Intuitive reason why jointly normal and uncorrelated imply independence

Question: It is well-known that if two random variables are jointly normal and uncorrelated, then they are independent. Does anyone have an intuitive reason why this is true? Explanation in terms of data is greatly appreciated.
Updates:
After seeing the answer by @kjetil b halvorsen, I feel I should give some more details. As far I know, that result (uncorrelated implies independence) is true if the variables are Bernoulli or they are jointly normal. I would like to stress that I completely understand the math behind the truthfulness of the mentioned result. When they are jointly normal, $\rho = 0$, so the joint density will factor into two, one a function of $x$ alone and another function of $y$ alone, hence independent. What I am looking for is some intuition why is this the case? For example, in case of Bernoulli, the only possible data are $(0,0), (0,1), (1,0), \text{ or } (1,1)$. So, if there is no linear relationship between them (uncorrelated), then there is none (independent)! I am just wondering whether there is anything like this?
Comment: I think you need to define your assumption wrt *uncorrelated*. The commonsense use of the word refers to Pearson correlation, a metric of strictly linear relationship. Many other measures of dependence are out there. So, two random variables may be *uncorrelated* wrt Pearson and still be highly dependent wrt other measures of association and dependence.
Comment: @DJohnson: I mean Pearson correlation. Please also see the edits. Thanks.
Comment: Any deep reason is unlikely to be forthcoming, simply because there exist a large number of other examples of this phenomenon.  Simply take *any* family $\{F_\theta\mid\theta\in\Theta\}$ of univariate distributions and embed that in a larger family of bivariate distributions $\{G_{\theta_1,\theta_2,\omega}\mid\theta_i\in\Theta,\omega\in\mathbb{R}\}$ for which $G_{\theta_1,\theta_2,0}(x,y)=F_{\theta_1}(x)F_{\theta_2}(y)$ and where $G_{\theta_1,\theta_2,\omega}$ for $\omega\ne 0$ has nonzero correlation coefficient.  By construction, uncorrelated implies independent in such a family.
Answer: Well, what intuition can there be? For a bivariate normal distribution (for $X$ and $Y$, say), uncorrelated means independence of $X$ and $Y$, while for the quite similar bivariate t distribution, with say 100 degrees of freedom, independence do not follow from correlation zero.  Plotted this two distributions will look quite similar. For both distributions all contours of the joint density function are elliptical.
The only intuition that I can see is algebraic, the joint density for the bivariate normal is a constant times an exponential function. The argument of the exponential function is a quadratic polynomial in $x,y$. When the correlation is zero, this polynomial will not include any cross terms $xy$, only pure quadratic terms $x^2, y^2$.  Then the property of the exponential function that
$$
   \exp(-x^2 -y^2) = \exp(-x^2)\cdot \exp(-y^2)
$$
kicks in  (of course the actual terms will be more complicated, but that does not change the idea).  If you try to do the same with the bivariate t distribution, everything is the same, except---the quadatic polynomial sits inside the argument of another function without that nice separation property of the exponential!  Thats the only intuition that I can see.


recursively loop over javascript object?

Question: I am trying to create a function which,
When given an object will output something like

 reason : ok
 status : 0
 AiStatistics : null
 CurrentSeasonArenaStatistics : null

  Player

   CampaignProgressCoop : CompletedLegendary
   CampaignProgressSp : PartialHeroic

    ReachEmblem

     background_index : 2
     change_colors : [0,7,2,0]
     flags : 0
     foreground_index : 49

 gender : male

How would i go about this?
This is my attempt:
function read_object(object){
  var $obj = $('
');
  for(var o in object) {
    $obj.append(o+' : ');
    if(typeof(object[o]) == 'object' and object[o] != null) {
      $obj.append(read_object(object[o]));
    }
    else
      $obj.append(object[o]);
  }
  return $obj;
}

Here is the  object i am using
{
  "reason":"Okay",
  "status":0,
  "AiStatistics":null,
  "CurrentSeasonArenaStatistics":null,
  "Player":
  {
    "CampaignProgressCoop":"CompletedLegendary",
    "CampaignProgressSp":"PartialHeroic",
    "ReachEmblem":
    {
      "background_index":2,
      "change_colors":[0,7,2,0],
      "flags":0,
      "foreground_index":49
    }
  }
}

Comment: That's the whole idea behind recursion Kieran. If you don't know the meaning of recursion yet, see the beginning of this sentence.
Comment: @Kieran
That is how recursion works.
You create something that just calls itself over and over again till it does not need to.
Comment: I am not taking the piss.. but is it good practice to call your method from inside your method? Shouldn't it be its own method maybe to return a string for your output?
Comment: ok, fixed, issue was me having $obj and $obj2 instead of var $obj and var $obj2
Comment: (looks up recursion...)cool recursion is pretty good.
Comment: FYI your object comparison uses the word "and" it should be &&. switching between python, apex, and javascript I had to pause for a couple minutes to adjust my brain to see it.
Answer: Separate the method out from the main call.

function read_object(object)
{
    //do some cool stuff to return a string
    return str;
}

function loopy(object)
{
    for(var o in object)
    {
        if(typeof(object[o]) == 'object')
        {
            read_object(object)
        }
        else
        {
            //output in some other way
        }
    }
}

Comment: No matter what you do you would end up with a recursive pattern.

In your example you would just end up calling loopy from read_object.
Comment: Yeah totally this would only work for one level of DOM. I had a read of recursion. Most people say that you dont really need to use it and can cause stack problems however it does save on code


Limit access to an EC2 instance from different instances

Question: I have an EC2 instance set up called Machine1. I specified the security group to be Group1. How can I allow access in Group1 to any machine that comes from an internal EC2 request? Do I have the specify the IP address of each machine?
Answer: Machines from the same security group can acces other machine in the same security group (by default). Usually this is the topmost rule in the INBOUND rules table like:
ALL sg-xxxxxxx (default) Delete

You can add like this other security groups to the rules, just check out the other groups sg-xxxxxx id on it's Details tab and then add it as the new rules source.


Can logistic regression be used to predict future classifications?

Question: I am trying to predict if a doctor is likely to switch from prescribing Drug A to Drug B.
Based on my understanding of logistic regression, you can use the independent variables to determine the probability of the dependent variable which can be used to classify binary outcomes.
So, I can create a logistic model, and feed it records of doctors who have been observed to switch from Drug A to Drug B. Then, I can apply the model to a broader dataset to estimate who has switched.
But I don't really care about who has switched. I already know that since I have the data. I want to know who is likely to switch in the future.
I am essentially trying to feed a model which will pop out a binary prediction that tells me if a doctor is likely to switch from writing Drug A to Drug B in the future.
Is logistic regression the way to go to do this?
Comment: Short answer: it can, long answer: There are lots of methods for predicting. What method you choose will largely depend on your data, and you will get barraged with a million opinions on what the _best_ way is. Logistic regression has the advantage that your coefficients give you odds ratios that are directly interpretable. This might also be preferable if you have only a few columns because it's not likely you'll get very good predictions, so you might prefer logistic regression which can be more informative. Also good for small datasets because its estimates have low variance.
Answer: There are many predictive models for binary classification, but yes, logistic regression augmented with a decision rule is one way to go about it. But it seems you have some slight misunderstandings with respect to how to apply it.

So, I can create a logistic model, and feed it records of doctors who have been observed to switch from Drug A to Drug B.

Yes, but you'll also want to feed it the records of doctors who have NOT switched. The model needs to learn what values of the independent variable are typically associated with switching and what values are typically associated with not switching.

But I don't really care about who has switched. I already know that since I have the data. I want to know who is likely to switch in the future.

You care about them in the sense that they will teach your model what switchers and non-switchers looks like, so that it can predict future outcomes
After you've trained the model on data with known outcomes, you can apply it to unknown cases, the model will spit out a probability, and then you can decide what to do with that probability. This is really where the logistic regression model ends. If you need to spit out a binary "will switch" or "will not switch", you're stepping outside the bounds of the probability model, but obviously people do it all the time.
So: data cleaning → model fitting → model diagnostics → (if model is good) apply to unknowns → make binary decision if you have to
Comment: Thanks for the response. Understood on your two comments about building the model. When I apply the model to a new set of data, lets say the model predicts a doctor is a switcher. I look at the data for said doctor and see that, they are NOT in fact a switcher. I'm trying to use that to say, well they haven't switched **yet** but they may in the future since they have similar characteristics to those who have switched. Basically I'm using the false positives as the ones I actually care about.  Sounds like this is not the intended use of logistic regression but could be done if I really wanted
Comment: I see. Sounds like a more complicated problem than can be handled by standard by logistic regression because there's an implicit longitudinal nature to it. If you're able to reframe your problem you might be able to do something like this: measure independent variables at time 0, then check N years later to see if doctor has switched ("yes/no"). This is your new dependent variable, and now you're examining with logistic reg. whether someone is likely to switch within N years given indep variables. If this isn't an option for you, maybe look at more complex models for longitudinal binary data.


Cluster Analysis Sample Size for Diss Proposal

Question: My psychology dissertation will be a cluster analysis with one grouping variable.  How do I know how many participants I need?  I imagine there should not be more than 5 clusters.  79 items make up 9 attributes that the participants will be clustered on.  I realize that power analysis is moot since cluster analysis is not inferential.  I have seen that for factor analysis it is 10 per item but cannot seem to find a guideline for cluster analysis.
Thanks for any help or insight you can offer.
Answer: You never know, before you have the data.
In particular with small sample sizes, it's easy to tweak parameters, preprocessing, algorithms etc. to get out whichever answer you like.
Do not assume that the output of a cluster analysis is "correct". There is no such thing as correct. Either the results lead to insights (which you should then verify in a second experiment) or not. Consider cluster analysis a tool to find out which questions to ask; but not as a means to prove that you have found anything.
Comment: Unfortunately this won't fly for my proposal.  Can I use G-Power and simply calculate for MANOVA?  Or use factor analysis recs of 10 per item?  And what would be the precedent for that? I am having NO LUCK finding anyone with recommendations.
Comment: You've got a recommendation: Don't do it!


Is there a Windows 7 64-bit printer driver out there for the Tally T2024/24 dot matrix printer?

Question: Is there a Windows 7 64-bit printer driver out there for the Tally T2024/24 dot matrix printer?
I've looked all over the place for the right driver, but it's got me stumped!
Thanks in advance! :)
Comment: I don't know this printer at all, but have you tried to use a generic Epson ESC/P printer driver? That's kind of working for many dot matrix printers like Star or NEC.
Answer: This isnt a direct answer to your question, but maybe it will help.
W7 appears to have a very limited supply of default printer drivers, unlike XP which seems to have very many.  To obtain many additional drivers, begin installing the printer, when it asks for the printer driver click 'use windows update' and see if that helps.  The result should be that W7 connects and downloads lots of printer drivers (you will be able to see these new drivers in the selection window)...and hopefully it will download one for your printer or one that will work.
Also, I have had luck recently using drivers for similar printers or even the generic text only driver in some cases.
I hope this helps.
Comment: Thanks for the suggestion, @cop1152.  Unfortunately, this device driver isn't in the [Microsoft Update Catalog](http://catalog.update.microsoft.com/), so the "use windows update" button doesn't find it :(.  I've since tried the Epson LQ-300 driver with limited success.


Number of ways to rank players in a tournament

Question: Six players play chess, and there's one two-way tie. How many distinct final arrangements are possible?

I think there are ${6\choose 2}$ ways to choose the two players who will tie. Then, there are $5!$ ways to rank the five players (we can think of the two people who tied as one person). So is the answer just ${6\choose 2} \cdot 5!$?
Comment: That seems like a reasonable interpretation of the problem and final answer, yes.
Answer: Yes, that's correct.
Another way to get the same result is to start with the $6!$ rankings of all 6 players, then declare which 2 players with neighbouring ranking are actually in the tie. That's 5 possibilities (1 and 2, 2 and 3, ... 5 and 6). Then we need to take into acccount that each tie is reached exactly 2 times (order "1,2,3,4,5 ties with 6" is reached from initial orders "1,2,3,4,5,6" and "1,2,3,4,6,5", for example).
This yields the same result
$$6!\times5\times\frac12 = {6 \choose 2} 5!$$


Adicionar uma seta ''pointer'' em efeito Tooltip

Question: Estou construindo um efeito Tooltip que exibe as definições de termos específicos, mas estou encontrando problemas ao ter que adicionar uma seta acima da pequena caixinha. Confiram o CSS do código logo seguido pelo HTML abaixo:
CSS
a.tooltip {
    position: relative;
    padding: 0;
    color: #000000;
    text-decoration: none;
    border-bottom: 1px dotted #133783;
    cursor: help;
    z-index: 25;
}
a.tooltip:hover {
    border: none;
    height: auto;
    background: transparent;
    color: #133783;
    z-index: 25;
}
a.tooltip span {
    display: none
}
a.tooltip:hover span {
    display: block;
    position: absolute;
    width: 290px;
    top: 2em;
    right-align: justify;
    left: 0;
    font: 12px arial, helvetica, sans-serif;
    padding: 5px 10px;
    border: 1px solid #133783;
    background: #E3E3E3;
    color: #000;
    font: 11px arial, verdana, helvetica, sans-serif;
}

HTML
HTMLHTML: É uma linguagem de marcação utilizada para produzir páginas na Web. Documentos HTML podem ser interpretados por navegadores.

Comment: Não entendi muito bem o que você precisa. Tem como demonstrar num desenho simples ?
Comment: Para ser mais específico, enviarei uma imagem: (http://i.imgur.com/Hsl44k3.png), confira a seta acima do efeito Tooltip, que exibe definições de termos.
Answer: Você pode usar um pseudo-element, como o before.
http://jsfiddle.net/13s7j1kd/2/
a.tooltip {
    position: relative;
    padding: 0;
    color: #000000;
    text-decoration: none;
    border-bottom: 1px dotted #133783;
    cursor: help;
    z-index: 25;
}
a.tooltip:hover {
    border: none;
    height: auto;
    background: transparent;
    color: #133783;
    z-index: 25;
}
a.tooltip span {
    visibility: hidden;
    position: absolute;
    width: 290px;
    top: 10em;
    text-align: justify;
    left: 0;
    font: 12px arial, helvetica, sans-serif;
    padding: 5px 10px;
    border: 1px solid #133783;
    background: #E3E3E3;
    color: #000;
    font: 11px arial, verdana, helvetica, sans-serif;
    opacity: 0;
    transition: all 0.3s ease;
}
a.tooltip:hover span {
    visibility: visible;
    opacity: 1;
    top: 3em;
}

a.tooltip span:before{
    content: "";
    position: absolute;
    left: 8px;
    top: -7px;
    width: 15px;
    height: 15px;
    transform: rotateZ(45deg);
    background-color: #E3E3E3;
    border: 1px solid #333;
}

a.tooltip:hover span:before{
    opacity: 1;
    z-index: -1;
}

Comment: Diego, agradeço pela resposta definitiva. Eu tinha esquecido que eu poderia ter utilizado a propriedade _transition_! Agora o código ficou completo. Abraço.
Comment: Diego, nem sei como te agradecer, o efeito está quase completo! Mas antes de encerrar o tópico, é possível deixar esse efeito mais lento e inserir links dentro da pequena caixa? Desde já agradeço.
Comment: Como assim inserir dentro ?
Comment: Diego, inserir uma **palavra linkada** dentro do efeito **Tooltip**, mas isso só funcionaria se modificarmos um pouco o CSS. E no que se refere ao efeito ficar **mais lento**, como posso fazer isso?
Comment: Atualizei o post Bruno. Mas não entendi ainda o esquema da palavra aí...
Answer: Simplesmente altere essa propriedade do css do a.tooltip:
a.tooltip {
    cursor: pointer;
}

exemplo: http://jsfiddle.net/ehg8vkj3/
caso não seja isso o que você queira, favor comentar antes de negativar.


Silverlight 5 MEF

Question: We are using MEF v1 with a Silverlight 5 application. We really need support for open generics. It's not clear to me whether this is possible with Silverlight 5.
The dilemma is that I know MEF 1 doesn't support open generics, but MEF 2 does (but MEF 2 is unreleased software still in preview and I don't see any silverlight .sln files when I download it - unlike MEF 1 sources on CodePlex). I know that MEFContrib does support it, but I'm not sure MEFContrib will compile with Silverlight 5.
Has anyone managed to get open generics working with Silverlight 5?
Answer: To answer my own question:
1) MEF v1 does not support open generics
2) In our project we attempted to use MefContrib to provide an open generics implementation, but we hit a road block with it because we use ExportFactory in our code which does not appear to be covered by any of the work in MefContrib
3) I read a recommendation from Glenn Block (MEF Architect and MefContrib contributor) that using an IoC as well as MEF is actually a reasonable thing to do. Glenn's article. This means you would use MEF to provide third party discoverability but use an IoC within the discovered code.
I personally know that both Castle and Unity have support for open generics. I will therefore recommend to my team that we adopt one of those two IoC's in conjunction with MEF as per Glenn's article.

Silverlight 5 MEF


Is there an $h$ such that $h = f/g$ is measurable, yet one of $f$, $g$, or neither are measurable

Question: I was trying to find an $h$ such that $h = f/g$ is measurable, yet one of $f$, $g$, or neither are measurable. Is it perfectly fine to choose $f^{-1}(D)$ such that $D$ is non-measurable and similarly for $g$ so that in total $h$ is just maps to $0$, thus making $h$ measurable?
Answer: Let $g$ be any non-measurable function which does not take the value $0$, and let $f$ be the constant $0$ function (which is measurable). Then $h=\frac{f}{g}=0$ is measurable.
Similarly, let $g$ be any non-measurable function which does not take the value $0$, and let $f=g$. Then $h=\frac{f}{g}=$ the constant $1$ function is measurable.
Comment: Is it possible to use similar arguments regarding integrable and non-integrable functions?


Especialização e generalização em banco de dados e desenvolvimento da aplicação

Question: Tenho uma tabela Livros e sei que a especialização/generalização de livros são Livros de Ficção, Livros de Drama e Livros de Suspense, por exemplo.
Porem, no modelo lógico, eu não sei se eu crio uma tabela Livros com relacionamento 1:N Tipos de livros com cada tipo cadastrado ou se crio uma tabela para cada especialização (livro_drama, livro_ficção)!
Sei que seria pouco viável criar uma tabela para cada Tipo, pois se eu precisasse de novos tipos de livros eu teria que criar sempre uma nova tabela. Mas se eu utilizar a outra forma, cada tipo de livro cadastrado teria suas regras de negocio especifica, mesmo cadastrando cada tipo, eu teria de programar as regras associadas.
Algo esta me incomodando em ambas as soluções! Como resolvo esse impasse?
Comment: Eu vejo assim: uma tabela para livros, e uma só contendo gêneros (suspense, drama, ficção científica, etc). Aí uma tabela associativa guardando a informação de que um livro pode ter um ou mais gêneros.
Comment: @Piovezan Exatamente isso que vi de inicio, mas com umas analises mais apuradas vi o seguinte caso: e se por exemplo os livros de suspense necessita-se de alguma regra especifica na aplicação, sendo ele um gênero? E os novos gêneros que fosse acrescentados ao sistema, eu constantemente teria que ficar remodelando o sistema com "possíveis" regras na aplicação.
Answer: Existe algum motivo para ter uma especialização? Se tiver, tem algum motivo para ter uma generalização? Pode parecer óbvio, mas uma das duas parecem estar erradas em modelagem relacional. Se está falando em especialização não tem porque falar de relação, são conceitos excludentes.
Não faça algo sem motivo. Pergunte-se qual o motivo de usar algo? Que problema isto está resolvendo? E quais estão sendo causados?
Você diz que que cada tipo de livro tem regras de negócio específicas. É mesmo? tem certeza? Vamos dizer que sim, e por que as regras de negócio estão no banco de dados? Vamos dizer que queira fazer assim, o que a pergunta já mostra que isto não é uma boa ideia, que solução vê a não ser separar cada tipo em uma tabela? Se o dado se comporta diferente precisa estar em tabela diferente. Eu só não faria assim, dentro da minha visão, pode ser que precise mesmo de algo fora do normal.
Uma solução é ter uma tabela só e algumas ações que dependem do tipo serem feitas de forma condicional.
Não tem impasse algum. Eu não vejo nada de especialização ou relacionamento aí, portanto não há dicotomia. Só tem regras de negócio diferentes que são programadas na aplicação. Ou no banco de dados se preferir assim. Mas não tem porque criar uma tabela nova se a estrutura é a mesma. Banco de dados não é aplicação, embora alguns achem que é.
Veja vantagens e desvantagens de por a regra de negócio no banco de dados.
Comment: É exatamente esta duvida que estou passando por não ter uma boa analise inicial da aplicação. Não só por culpa minha, mas por que me passa tais requisitos, talvez até por não conhecer certas partes do processo me obrigando a ter que advinha certo pontos e evitar o máximo de problemas de manutenção futura. Então ao seu ver, seria tipo: somente a tabela "Livros" com os tipos "enums" e com regras na aplicação ou somente a tabela "gêneros"? Entendi seu ponto de vista.
Answer: Eu tava pensando que suas especializações para livros fossem, por exemplo:

Livros digitais
Audiobooks
Livros impressos

nos quais a natureza da experiência da leitura fosse diferente, em cada caso. Daí faria sentido uma especialização.
No mais, quanto ao critério de usar várias ou uma tabela, vai de acordo com a sua vontade, ou de acordo com a vontade do arquiteto de dados, basicamente.
Comment: Gostei dessa visão, realmente faz sentido. Me reforça cada vez mais que o ideal seria "gêneros dos livros" mas se eu tivesse que colocar uma regra neste tipo, por exemplo "Suspense" que alguma coisa seria diferente aqui. Eu faria só uma consulta do gênero "suspense" e programaria estas regra? mas e se por algum motivo o campo for deletado, a regra na aplicação ainda estaria lá. Sempre teria essa preocupação entre a aplicação e o banco. Tem alguma maneira de controlar melhor isso. Controle de versão não gerencia o banco de dados.
Comment: Em bibliotecas, normalmente se usa um código denominado CDD, https://pt.wikibooks.org/wiki/T%C3%B3pico:Wikilivros_Discuss%C3%A3o:Biblioteca/Classifica%C3%A7%C3%A3o_e_categoriza%C3%A7%C3%A3o_dos_livros/resposta_(10) para classificar o assunto do livro, por isso, especializar o livro de acordo com o seu gênero seria supercomplicar o esquema de banco, eu acho!
Comment: Aqui: https://processotecnicoucs.wordpress.com/2011/09/14/classificacao-de-obras-literarias-ii/ também tem uma lista de classificação de gêneros literários por CDD/CDU.


How to render custom view mode in d7

Question: I'm trying to render nodes with a custom view mode, having another tab for each node in the same place than "Edit", "View", etc. So I have declared my custom view mode with hook_entity_info_alter, my new "tab" with hook_menu, with a page_callback pointing to a custom function that should return the node according to my custom view node.
It works great, but the node title is rendered too. How can I remove the node title ?
Here is the code. Thanks!
<code>   /**
   * Implements hook_entity_info_alter().
   */
   function test_custom_view_mode_entity_info_alter(&$entity_info) {
     $entity_info['node']['view modes']['another_teaser'] = array(
       'label' => t('Another teaser'),
       'custom settings' => TRUE,
     );
   }

   /**
   * Implements hook_menu().
   */
   function test_custom_view_mode_menu()
   {      $items['node/%node/another-teaser'] = array(
           'title' => 'Another Teaser',
           'page callback' => '_test_custom_view_mode_display_content',
           'page arguments' => array(1),
           'access arguments' => array('access content'),
           'type' => MENU_LOCAL_TASK,
       );

          return $items;
   }
   /**
   * Custom page callback hook_menu().
   */

   function _test_custom_view_mode_display_content($node) {
     $node_viewed = node_view(node_load($node->nid), 'another_teaser');

     return array(
              'content' => array(
                'node' => $node_viewed,
              ),
            );
   }
</code>
Comment: Thanks Clive ! I didn't thought about it.
I just add to template_preprocess_node this code snippet:
  `if($vars['view_mode'] == 'another_teaser') {
    $vars['title'] = '';
  }`
Comment: Are you sure it's the node title and not the page title (i.e. from page.tpl.php) that's showing?
Comment: Variable name $node_rendered is misleading as it has not actually been rendered at this point. Better would be $node_view or $node_render_array or something like that.
Comment: you're right, I changed it
Answer: I think you need to render send the element as html out put since there is no any theme function defined. See how this output process here.
So your return array should be:
<code> return array(
          '#markup' => $node_rendered
        );
</code>

How to render custom view mode in d7


1 bad phpfpm pool.d config causes disaster

Question: I noticed that if a pool config in pool.d has a bad path, then all the pools won't start when doing systemctl start php7.0-fpm.service - is there a way to make phpfpm gracefully continue?
I've tried to research phpfpm config details but I can't find anything related to a graceful continue if 1 pool is bad
Answer: php-fpm has a test flag you can use to test config files
  --test
  -t             Test FPM configuration file and  exit  If  called  twice
                 (-tt), the configuration is dumped before exiting.


Manter tabela com tamanho mínimo de altura

Question: Estou criando uma tabela usando o Datatables, mas gostaria de manter uma altura mínima mesmo quando tiver ao menos um registro.

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

e o JS
var nTrs = $('#example tbody tr');
if (typeof document.getElementsByTagName('td')[0] != 'undefined'){
    var iColspan = nTrs[0].getElementsByTagName('td').length;
}

var oTable = $('#example').dataTable({
    "columnDefs": [
        { "visible": false, "targets": 2 },
        ],
        "order": [[ 2, 'asc' ],[ 0, 'asc' ]],
    "orderFixed": [ 2, 'asc' ],
    "lengthChange": false,
    "scrollY": "200px",
    "scrollCollapse": true,
    "paging": false,
    "info": false,

    "drawCallback": function ( settings ) {
        var api  = this.api();
        var rows = api.rows( {page:'current'} ).nodes();
        var last = null;

        api.column(2, {page:'current'} ).data().each( function ( group, i ) {
            if ( last !== group ) {
                $(rows).eq( i ).before(
                    '
' + group + '
'
                    );

                    last = group;
                }
            });
        }
});

o exemplo pode ser visto aqui https://jsfiddle.net/53q66vrt/
Comment: Acho que você poderia tentar Style="height='????px';"
Comment: @MarceloDiniz por favor coloque como resposta a solução que encontrou
Comment: @Brunão simples assim, mas não cheguei a testar em vários navegadores para ver se o resultado será o esperado, deixei no css assim: `#example{height: 250px}`
Answer: Conforme foi dado como resposta nos comentários, segue resposta para a questão como solucionei.
No CSS eu coloquei #example{height: 250px} e com isso já resolveu o problema.
Segue exemplo no https://jsfiddle.net/33hqd5m1/


Partial exchangeability - Theory and results

Question: De Finetti has defined in 1938 the concept of partial exchangeability as a weaker form of exchangeability in order to deal with situations in which the symmetry among all observations is not desirable.
That's what I know and mere googling does not help this time because I've just found a bunch of papers that are a bit too advanced for me.
My questions are: what is the formal definition of partial exchangeability and does the results holding with exchangeability still holding (e.g. De Finetti representation theorem)? Can you give me an example of a situation in which partial exchangeability is meaningful?
Answer: This is described by Diaconis (1988; see also Diaconis and Freedman, 1980):

In 1938 de Finetti broaden the concept of exchangeability. Consider
  first the special case with two observations
  $X_1,X_2,\dots;Y_1,Y_2,\dots$. The $X_i$ might represent binary
  outcomes for a group of men and $Y_i$ might represent binary outcomes
  for a group of women. If it were judged that the observable
  covariate men/women did not matter, all of the variables would be
  judged exchangeable. Often, the covariate is judged as potentially
  meaningful, the $X_i$'s are judged exchangeable between themselves and
  the $Y_i$'s are judged exchangeable between themselves.
  Mathematically, the joint law must be invariant under permutations
  within the $X$'s and $Y$'s:
$$ \mathcal{L}(X_1,\dots,X_n;Y_1,\dots,Y_m) =
 \mathcal{L}(X_{\pi(1)},\dots,X_{\pi(n)};Y_{\sigma(1)},\dots,Y_{\sigma(m)})
 $$
This must hold for all $n$ and $m$, and permutations $\pi$ and
  $\sigma$.

You could check as well the original paper by de Finetti (1938) for discussion and multiple examples as he has very light and clear style of writing, what makes his papers easy to read.

Diaconis, P. (1988). Recent progress on de Finetti's notions of exchangeability. Bayesian statistics, 3, 111-125.
Diaconis, P., & Freedman, D. (1980). De Finetti's generalizations of exchangeability. Studies in inductive logic and probability, 2, 233-249.
De Finetti, B. (1938/1980). On the condition of partial exchangeability. Studies in inductive logic and probability, 2, 193-205.
Answer: To complete Tim's answer, from the useful references given there:
Suppose the quantities $\{X_i\} := \{X_1, X_2, \dotsc\}$ and $\{Y_j\}$ can have values $\{x\}$ and $\{y\}$ from two discrete sets. The assumption of infinite partial exchangeability for their joint probabilities means
$$
\mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m)
={}\\
\mathrm{P}(X_1=x_{\pi(1)}, \dotsc, X_n=x_{\pi(n)},\; Y_1=y_{\sigma(1)}, \dotsc, Y_m=y_{\sigma(m)}),\\
\text{for all $m,n$, and all permutations $\pi,\sigma$ of $\{1,\dotsc,n\}$ and $\{1,\dotsc,m\}$.}
$$
Then the probability above can be expressed in this integral form:
$$
\mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m)
={}\\
\iint \prod_{i=1}^n p_{x_i}\; \prod_{j=1}^m q_{y_j}\;
f(\mathbf{p},\mathbf{q})\;\mathrm{d}\mathbf{p}\,\mathrm{d}\mathbf{q},
$$
where $\mathbf{p} := \{p_x\}$ and $\mathbf{q} := \{q_y\}$ are distributions over the possible values $\{x\}$ and $\{y\}$, and $f$ is a probability density over all such pairs of distributions.
Another useful reference for partial exchangeability, with examples, is Bernardo & Smith's Bayesian Theory (Wiley 2000), especially § 4.6.


Least Required Number for Constructing n-dimensional Convex Hull

Question: Just had learn the concept of Convex set and Convex Hull.
At this point I had figured of my self regarding the question as following:
"Do I always need to have at least $n+1$ number of elements to construct a convex hull which is embedded in $\Bbb R^n$ space?"
This question is not fully elaborated with a commonly accepted terminologies because of lack of my experience in mathematics so will plot more examples to evade elusiveness.
First, If I have 2-dimensional space, which is correspondent to a sheet of paper , I need at least 3 different elements to construct a polygon which requires at least 2-dimensional space to be fully embedded in it(i.e. triangle would be convex hull which is fully embedded into the 2-dimensional plane with least number of elements).
Also, in a similar vein, If I have 3-dimensional space, which is correspondent to $\Bbb R^3$, I need at least 4 elements or points to construct a 3-dimensional object.
Upon this sense I would like to generalize this idea or notion into n-dimensional sense.
However, where do I have to start from to deal with more or equal to 4-dimensional space which is not visualizable to prove this generalization?
Any related concept or already-existing theorem or statement would be also appreciated.
Answer: There is such a thing as a simplex, a generalization of triangles, tetrahedra, and so on.  The $n$-simplex is the convex hull of $n+1$ points in $\mathbb R^n$.  There's a lot more to say about them, but...
Comment: thanks for the term
Comment: Let me mention one fact about simplices:  for any bounded polytope $P$  in $m$ space there is a simplex $S$ in some $n$ space, such that $P$ is the image of $S$ under an affine map.
Comment: ... which is the most well-introduced course or book for understanding your brief mention?
Comment: From this and that I assume you are a high school student or a university student just beginning to study mathematics? Maybe the *Convex Figures And Polyhedra* by iusternik is pitched right for you.  There is a book *Convex Polytopes* by  Grünbaum, the easier chapters might be accessible to you.  My library has a book *Convex Sets* by Valentine, which looks like a solid undergraduate treatment. (I apologize if I've misjudged your level.  It is hard to make sensible book recommendations without knowing something about the reader.)


SWIFT: touchesEnded not called in my tableViewController

Question: So I have a tableviewController called SettingsViewController, and it has the following touchesEnded function:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        print("yoyoyoyoyoyoyoyQVEWEVIWNE")
        let touchLocation = touch.location(in: view)

        // 290 because the width of the view is 414, and the SettingsViewController width gets set to 0.7 * the view width in SlideInTransition.  0.7 * 414 is 289.8
        if touchLocation.x > 200 {
            dismiss(animated: true)
        }
    }
}

I made the print statement to see if it was being called, which it is not. This view controller is presented with a 'menu-esque' slide in custom transition.  I have a suspicion that the bounds of the UIView is the problem somehow.  Here's the custom transition code:
class SlideInTransition: NSObject, UIViewControllerAnimatedTransitioning {

var isPresenting: Bool = false

func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return 0.5
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    // Make sure they exist

    // The view controller being transitioned from, using the context (ex: here it's the MapViewController)
    guard let fromViewController = transitionContext.viewController(forKey: .from),
    // The view controller being transitioned to, using the context (ex: here it's the SettingsTableViewController)
        let toViewController = transitionContext.viewController(forKey: .to) else {return}

    let containerView = transitionContext.containerView

    // Constants for appearance of SettingsViewController

    let vcWidth = toViewController.view.bounds.width * 0.7
    let vcHeight = toViewController.view.bounds.height

    if isPresenting {
        // Add SettingsViewController to container
        containerView.addSubview(toViewController.view)

        // Initial frame for view controller, off the screen to the left to start, that way it appears to slide in
        toViewController.view.frame = CGRect(x: -vcWidth, y: 0, width: vcWidth, height: vcHeight)
    }

    // Animate view controller onto the screen, sliding in from left
    let transform = {
        toViewController.view.transform = CGAffineTransform(translationX: vcWidth, y: 0)
        }

    // Animate back off screen
    let identity = {
        // .identity returns the vc to the initial frame, as created above in the isPresenting if statement
        fromViewController.view.transform = .identity
    }

    // Animation of the transition
    let duration = transitionDuration(using: transitionContext)
    let isCancelled = transitionContext.transitionWasCancelled
    UIView.animate(withDuration: duration, animations: {
        // If presenting, transform SettingsViewController (to) onto screen, otherwise set it back off the screen.
        self.isPresenting ? transform() : identity()
    }) { (Bool) in
        transitionContext.completeTransition(!isCancelled)
    }

}

}

I made my touchesEnded code so that when the user touches outside the viewController, it dismisses, (the view controller only 70% the width of the screen) but it simply doesn't get called, regardless of where on the screen I tap.  Any idea why? Thanks.
Answer: https://developer.apple.com/documentation/uikit/uiresponder/1621084-touchesended
«If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events, even if your implementations do nothing.»
This would be a start.
Comment: how do I call it with super? Not sure where to put the 'super'
Comment: override func touchesEnded(_ touches: Set, with event: UIEvent?) {
super.touchesEnded(touches:touches, event: event)
Comment: Thanks cora, but putting this in the touchesEnded function hasn't changed it. If you have any other ideas, lmk. thanks
Comment: Well, then I recommend these links for you.
Comment: https://www.youtube.com/watch?v=Fj-08kQmcY4 - TableView with diffable datasource, which has built in previews and menus.
Comment: https://stackoverflow.com/questions/22127451/touches-ended-not-being-called - Answers to similar problem which involves adding a gesture recognizer.


Combining json files without created a new list of objects every time

Question: I have a dynamic amount of .json files being generated in a folder, that I would like to combine to one final json file.
This is my current code:
import json
import glob
import os

read_files = glob.glob(save_dir + "page_data*.json")
read_files.sort(key=os.path.getmtime)
output_list = []

for f in read_files:
    with open(f, "rb") as infile:
        output_list.append(json.load(infile))

with open(save_dir + "table_data.json", "w+") as outfile:
    json.dump(output_list, outfile)

So with above, I look for all my the generated .json files in my folder, and combine them into one final file called: table_data.json.
In this example, two files have been appended:
[
    [{
        "0": "Text",
        "1": "More text",
    }, {
        "0": "Yes",
        "1": "No",
    }],
    [{
        "0": "Text from another file",
        "1": "Yes",
    }, {
        "0": "Second file",
        "1": "Text",
    }]
]

As you can see, for each file, a new [] set is created.
How can I combine the json files dynamically, but without creating a new json list object [] every time? I only want one list of objects, like so:
[{
    "0": "Text",
    "1": "More text",
}, {
    "0": "Yes",
    "1": "No",
}, {
    "0": "Text from another file",
    "1": "Yes",
}, {
    "0": "Second file",
    "1": "Text",
}]

Comment: Use `output_list.extend` instead of `output_list.append`
Answer: It's easier than you might expect! Just change one word in your code:
for f in read_files:
    with open(f, "rb") as infile:
        output_list.extend(json.load(infile))

Using output_list.extend instead of append will add elements one by one, instead of adding the entire json object as one list element.


"independence" in definition of complex Gaussian distribution

Question: From Wikipedia

the family of complex normal distributions characterizes complex
  random variables whose real and imaginary parts are jointly normal,1
  i.e., normally distributed and independent.

The definition in the same article is

Suppose $X$ and $Y$ are random vectors in $\mathbb{R}^k$ such that $vec[X Y]$ is a $2k$-dimensional normal random vector. Then we say that the complex random vector
  $$
    Z = X + iY \,
$$
  has the complex normal distribution.

Does "independent" mean independence between random variables $X$ and $Y$, or linear independence between vectors $X$ and $Y$ in vector space $\mathbb{R}^k$ ?
If the former, why  doesn't the definition require $X$ and $Y$ to be independent?
Thanks!
Answer: It means the random variables are statistically independent.
Comment: Yes.  Looking at the history of that page, the comment about independence was added well after the rest of the page was written.
Comment: If it means s the random variables are statistically independent, why doesn't the definition require X and Y to be independent?
Comment: The page considers several different cases.  In some cases, X and Y are independent, and in other cases they are not.  I  would say that the first sentence on that page is misleading.
Comment: " the first sentence is misleading", do you mean the definition of complex Gaussian distribution shouldn't require independence between X and Y?


Dump a Java HashMap to XML and back

Question: does anyone know of a good library or method of converting the contents of a HashMap to XML and then parsing this to reconstruct the HashMap?
Answer: The XStream library is what you want. http://x-stream.github.io/
It has a HashMap converter, and a tutorial on how to use convertors.
Comment: +1. XStream is the only thing that lets me stomach XML in Java.
Comment: @seanhodges I didn't know this lib, does it have any advantages compared to jaxb?
Comment: @stacker I'm not too experienced with JAXB outside of Axis WS, but my understanding is that it generates Java code based on a schema. XStream lets you use objects based on your own Java classes. Not sure on other factors like performance or J2EE compliance though.
Comment: @stacker From the XStream FAQ: http://xstream.codehaus.org/faq.html#Other_Products_JAXB JAXB and XStream are two completely different approaches
Answer: Java Architecture for XML Binding (JAXB)
allows Java you to map Java classes to XML representations. JAXB provides two main features: the ability to marshal  Java objects into XML and tunmarshal XML back into Java object
Where to start? Pick a tutorial from these:

http://en.wikipedia.org/wiki/Java_Architecture_for_XML_Binding
http://jaxb.java.net/
http://java.sun.com/developer/technicalArticles/WebServices/jaxb/

In 15 minutes your done!
Comment: This requires you to define a XSD beforehand which might not fit in with what Aly is working with at all.

Dump a Java HashMap to XML and back


Inverting the infinite matrix $+\mathbf{I}$ with entries $\mathbf{P}_{ij}={i-1\choose j-1}$

Question: Let $ \mathbf{P}$ denote the "infinite matrix"
$$ \left[ \begin{array}{ccccc}
1 & 0 & 0 & 0 & \dots \\
1 & 1 & 0 & 0 & \dots \\
1 & 2 & 1 & 0 & \dots \\
1 & 3 & 3 & 1 & \dots \\
\vdots & \vdots & \vdots & \vdots & \ddots \\
\end{array} \right]$$
with entries $ \mathbf{P}_{ij} = \dbinom{i-1}{j-1}$ and let $ \mathbf{I}$ denote the "infinite identity matrix."  Compute the inverse of $ \mathbf{P} + \mathbf{I}$.
This was not the initial attempt. I couldn't think of anything at first. But after some nudges, I tried to compute the $n\times n$ matrix $\mathbf{P}_n$. Now my first observation was $\det \mathbf{P}_n=1$. Now if I could show that the invertibility of $\mathbf{P}_n$ would be efficient. So we expand $\mathbf{P}_{n+1}$ by the last row, then it is obvious
that $\det \mathbf{P}_{n+1}=\det \mathbf{P}_n=1$. So invertibility is meaningful. But when I inverted for small values, I couldn't find any pattern. I can't think of a method to cook up the solution. Can someone help me? I see my method of thinking should have been presented and I apologise. I will add them later on.
How to compute an inverse of an infinite matrix? And even if I can, what to do with it? Thanks for any help.
Comment: It looks like $P_{ij}^{-1}=(-1)^{i+j}P_{ij}$.
Comment: Why do you want to compute the inverse? Who told you there is something you can do with it?
Comment: My teacher gave me this problem. He said he has done it. I hope this satisfies your queries? @JonasMeyer Thanks. Now could you help me out here? Thanks again.
Comment: @shadow10 It seems like there was a rather obvious pattern emerging right at the start, which I think is what g.kov was mentioning. Did it break down on some row? As I mentioned, there's no point in talking about determinants for an infinite matrix. If you find a formula for the entries of the inverse, then you can just check the matrix multiplication directly to see if it is something like the Kronecker delta function.
Comment: It's possible the teacher just wants you to discover some pattern in the inverse, then prove that this pattern holds for the whole matrix. It looks like this matrix contains Pascal's triangle, although I don't know for sure.
Comment: @rschwieb: Yes, it is Pascal's triangle for sure.
Comment: You are telling me to consider the $n \times n$ truncated submatrix? I didn't think of that, but the determinant could go to infinity as $n$ becomes large, then dividing by it becomes meaningless. Am I out of line here? Please tell me. Thanks.
Comment: @shadow10 While the determinant probably becomes meaningless for infinite matrices, the inverse certainly does not. Infinite dimensional linear transformations can have inverses, and they're perfectly well defined. Expressing them might become a little bit harder because you have to find a formula for entries, though, rather than write out the complete matrix.
Comment: @shadow10 As for my hint, I was suggesting something like this. Obviously, the first row of the inverse (picture it on the right) is $(1,0,0,\ldots)$. The second row would clearly be $(-1,1,0,0,\dots)$. Then the third row would be $(1,-2,1,0,0,0,\ldots)$. Maybe a pattern eventually emerges.
Comment: I don't see the pattern actually, but I see that the $\det $ is $1$. I have checked for $n\le 7$. But nothing is coming out to me. And even if I find a pattern, can you help to prove it? I tried to induct and prove the $\det \mathbf{P} =1$ but I am failing miserably. Thanks for the hint.
Comment: Well, I still don't see a pattern emerging, another thing, I seem to have misled g.kov by talking about $\mathbf{P}$, see the matrix I want to find the inverse of is $\mathbf{P}+\mathbf{I}$. So please note that. And after adding to $\mathbf{I}$ the matrix is pretty weird, I don't see any pattern. And is there any general method to do it? Suppose $\mathbf{A}$ is an infinite matrix, and $\det \mathbf{A_n}\ne 0$ for each $n$, where we consider the truncated matrix, then can we compute $\mathbf{A}^{-1}$?
Comment: Just found these two articles from [2002](www.jstor.org/stable/2695500) and [2005](www.emis.de/journals/HOA/IJMMS/Volume2006/90901.pdf), both of which address this problem (inversion of the 'Pascal matrix' plus one). The first is behind a JSTOR firewall, but the second should be freely available. Executive summary: Inverting $\mathbf{P}$ is elementary, but the elements of $(\mathbf{P}+\mathbf{I})^{-1}$ are evaluations of polylogarithms.
Comment: If you might be able to observe that $P*V(x)=V(x+1)$ where $V(x)=$columnvector$(1,x,x^2,x^3,...)$ (for instance by simple pattern-detection, or even more clever, by the binomial theorem), then you're getting the key. Consider $(P+I)^ {-1}=I-P+P^2-P^3+P^4-...+...$ then $(P+I)^{-1} \cdot V(x)=V(x)-V(x+1)+V(x+2)-...+...$ .This leads you to the alternating (infinite) sum of powers of x, and after that to the Hurwitz-zeta and Bernoulli-polynomials and much more. Goggle for "helms" and "pascalmatrix" for more to find a couple of articles of mine about it.
Comment: The most appropriate search might be the link http://go.helms-net.de/math/pascal/bernoulli_en.pdf
Comment: @g.kov : the pattern is not difficult to recognize. for $r \ge c$ it is $(-1)^{r-c} \cdot \binom{r}{c} \cdot \eta(-(r-c)) $ where $\eta(x) $ is the alternating zeta-function and we find it for the nonpositve arguments having $1/2,1/4,0,-1/8,0,1/4,...$. The matrix-indices go from zero to infinity and $r$ is the row and $c$ is the column index.
Comment: @semiclassical: I mixed the adress for my comment making it pinging at g.kov; sorry.  Rereading the thread I see it was you who wrote about polylogarithms. So please see my previous comment.
Answer: For now, let's focus on inverting $\mathbf{P}$. (The method below should work for $\mathbf{I}+\mathbf{P}$ as well but I didn't want to start there). First, note that the elements of $\mathbf{P}^{-1}$ satisfy
$$(\mathbf{P}\cdot\mathbf{P}^{-1})_{ik}=\sum_{j} \mathbf{P}_{ij}(\mathbf{P}^{-1})_{jk}
=\sum_j \binom{i-1}{j-1}(\mathbf{P}^{-1})_{jk}=\delta_{ik}.$$ Note that this is still a linear algebra problem, albeit with an infinite number of variables and constraints.
I'll attack it with a generating function approach: Multiplying the LHS by $x^i$ and summing over all integers produces
\begin{align}
\sum_{ij} \binom{i-1}{j-1}(\mathbf{P}^{-1})_{jk}x^i=\sum_j (\mathbf{P}^{-1})_{jk}\sum_i\binom{i-1}{j-1}x^i = \sum_{j=1}^\infty (\mathbf{P}^{-1})_{jk}\left(\frac{x}{1-x}\right)^j.
\end{align}
To justify the last equality, shift the index of summation of $i\mapsto i+j$:
$$\sum_i\binom{i+j-1}{j-1}x^{i+j}=x^j\cdot \sum_i\binom{i+j-1}{i}x^{i}=\dfrac{x^j}{(1-x)^j}$$ since the last summation is a (negative) binomial series. If we repeat this on the RHS we simply get $x^k$ since the Kronecker delta kills the rest of the terms.
We then let $y=\dfrac{x}{1-x}$ and equate the RHS and LHS to obtain
$$ \sum_{j=1}^\infty (\mathbf{P}^{-1})_{jk}y^k =\left(\frac{y}{1+y}\right)^k=(-1)^k\left[\frac{(-y)}{1-(-y)}\right]^k=(-1)^k\cdot \sum_j\binom{j-1}{k-1}(-y)^j$$ with the last equality following from the prior equation. Identifying coefficients on both sides then finally gives $\boxed{(\mathbf{P}^{-1})_{jk}=(-1)^{j+k} \binom{j-1}{k-1}}$. Comparing with our original equation, this implies the summation $\sum_j (-1)^{j+k} \binom{i-1}{j-1}\binom{j-1}{k-1}=\delta_{ik}$; this almost certainly admits a counting proof via inclusion-exclusion.
So we may take $\mathbf{P}^{-1}$ as known, and can now focus on $(\mathbf{I}+\mathbf{P})^{-1}$. Something like the binomial inverse theorem should come in handy; I'll see if I can find a simple route.
Answer: Let $V$ be the vector space of polynomials (or polynomial functions if you prefer that).
Let us look at the transpose of $P$ instead of $P$. We see immediately that $P^T$ is the matrix of the linear transformation $S:p(x)\mapsto p(x+1)\in GL(V)$ with respect to the natural basis $\{1,x,x^2,\ldots\}$. Therefore the inverse of $P^T$ is the transpose of the matrix of the inverse transformation $S^{-1}:p(x)\mapsto p(x-1)$. This proves the observation/conjecture in a comment by g.kov: $P^{-1}_{ij}=(-1)^{i+j}P_{ij}$.
The matrix $I+P^T$ corresponds to the transformation
$$
\begin{aligned}
R:p(x)\mapsto & p(x)+p(x+1)\\
=&p(x)+p(x)+Dp(x)+\frac{D^2}2p(x)+\cdots\\
=&(1+e^D)p(x).
\end{aligned}
$$
Therefore its inverse is
$$
R^{-1}=\frac1{1+e^D}=\frac12+\frac12\cdot\frac{1-e^D}{1+e^D}=\frac12(1+\tanh\frac D2).
$$
The Taylor series of the hyperbolic tangent is too scary for me, so may be I stop.
Comment: You might find the two links I posted above in comments earlier interesting for comparison with that last result. (I'll admit, once I saw those two papers I gave up on there being a simple approach.)
Comment: @Semiclassical: Thanks. I did miss those links. My main point was to give a simple argument for $P^{-1}$.
Comment: The series begins with $ 1/2 + 1/4 D - 1/48 D^3 + 1/480 D^5 - 17/80640 D^7 + 31/1451520 D^9 $ $ - 691/319334400 D^{11} +...  $.     The numbers $17,31,691$ in connection with the index in steps of 2 should ring some bell in direction of Bernoulli-numbers, or even better, of Euler numbers (see wikipedia). The remaining seems to be not too difficult...


pandas merge dataframes on a condition

Question: lets say I have a parent df:
parent_df:
id

11.0_A
121.0_B
433.0_A
32.0_A
12.0_B

and I have two other dataframes df_A and df_B.
df_A:
id, name
.
.
11, abc
433, xyz
32, jkl

df_B:
id, name
.
.
121, mno
12, pqr

I wish to merge parent_df with the appropriate df_A or df_B depending on the rows.
expected result:
parent_df
id,        name

11.0_A,     abc
121.0_B,    mno
433.0_A,    xyz
32.0_A,     jkl
12.0_B,     pqr

How do i achieve this?
I know to merge two df i could simply do:
parent_df = parent_df.merge(df_A, on=['id'], how='inner')

but this is not the case, I need to handle a condition perhaps split the id after .0_ as well.
Any help would be appreciated!
Answer: You can use split and explode, followed by a merge with the concatenation of df_A and df_B:
df_res = parent_df.merge(
    pd.concat((
        pd.concat((df_A, pd.DataFrame(['A' for _ in range(len(df_A))], columns=['AB'])), axis=1),  # add a column with 'A'
        pd.concat((df_B, pd.DataFrame(['B' for _ in range(len(df_B))], columns=['AB'])), axis=1),  # add a column with 'B'
    )),  # concatenate df_A and df_B, enriched by 'AB' column
    how='left',
    left_on=['AB', 'id_AB'],
    right_on=['AB', 'id'],
    suffixes=('_x', '_y'),
)[['id_x', 'name']].rename(columns={'id_x': 'id'})

Assuming that parent_df, df_A and df_B are the followings:
import pandas as pd

parent_df = pd.DataFrame(
    data=[
        ['11.0_A'],
        ['121.0_B'],
        ['433.0_A'],
        ['32.0_A'],
        ['12.0_B'],
    ], columns=['id']
)

df_A = pd.DataFrame(
    data=[
        [11, 'abc'],
        [433, 'xyz'],
        [32, 'jkl'],
    ],
    columns=['id', 'name']
)

df_B = pd.DataFrame(
    data=[
        [121, 'mno'],
        [12, 'pqr'],
    ],
    columns=['id', 'name']
)

df_res is:
        id name
0   11.0_A  abc
1  121.0_B  mno
2  433.0_A  xyz
3   32.0_A  jkl
4   12.0_B  pqr

Comment: `KeyError: "['id_y'] not found in axis"`

pandas merge dataframes on a condition


sqlite date comparison

Question: I have column of type date time and values are getting stored in format 10-29-2011 08:25.
I would like to find out the rows only which are less then current date-time. What will be the condition for date comparison for current date and this date-time column field?
Thanks.
Comment: see http://stackoverflow.com/questions/1975737/sqlite-datetime-comparison
Comment: but how to compare with current date-time?
Answer: you could use the datetime function
SELECT * FROM mytable
WHERE mydate > datetime('now')

you can even make date operations
SELECT * FROM mytable
WHERE mydate > datetime('now','-15 days')

sqlite date comparison


Question about finite/infinite intersection

Question:
$A= \bigcap_{i \in \mathbb{N}} (-1+\frac{1}{i}, \frac{1}{i})$

$B= \bigcap_{i=1}^{n} (-1+\frac{1}{i}, \frac{1}{i})$ with $n<\infty$

In case of $A,$ I think the intersection should be empty.
but I am unsure about $B$
the first few intervals would look like this
$i=1: (0,1)$
$i=2: (-1/2,1/2)$
$i=3: (-2/3, 1/3)$
$\vdots$
$i=n: (\frac{1-n}{n}, \frac{1}{n})$ $n<\infty$
so the value on the left would get smaller and 0 would be included in all intervals, but how about the right side?, the last value $\frac{1}{n}$ would be the smallest of all, could I just say the finite intersection would be $B=(0,\frac{1}{n})$?
Comment: @galaxy-- I think Quantum mean that maybe is $i$ instead of $n$?
Comment: You might want to notice that everything in the infinite intersect must be in the finit intersection as well and so $\cap^{\infty} \subset \cap_{m=1}^n$ and as $\{0\}\not \subset (0, \frac 1n)$ your two answers can't both be correct..... You might also want to notice that $-1 +\frac 11 = 0$ and $0\not \in (-1+\frac 11, \frac 11)= (0, 1)$ ....(endpoints are *not* in the intervals)... if you think about that, I am *certain* you will be able to figure this out on your own.  Otherwise your reasoning is perfectly correct.
Comment: You might want to look at the indices of your first set.
Comment: @QuantumSpace: Zero is not included in our definition of $\mathbb{N}$ if that is what you meant?
Comment: I agree with your aim for $B$, galaxy--!
Comment: @Quiet_waters: thank you :)  I edited it now.
Comment: @galaxy--, welcome, however I do not agree with your aim for $A$. Note that $0$ is not on intervals, so I think the intersection is empty
Comment: @Quiet_waters: oh you are right, we are open on both sides, so A would be empty and does my solution to the second look correct?
Comment: @galaxy-- yes, good studies
Answer: As $0 \not \in (-1 +\frac 11, \frac 11)= (0,1)$ we can't have $0$ in any of either the finite or infinite intersections.
If $r > 0$ then there is an $m > \frac 1r$ and $\frac 1m < r$ so $r \not \in (-1 +\frac 1m, \frac 1m)$ and so $r$ will not be in any intersection that includes an index $m > \frac 1r$.  As the infinite intersection includes that index, no $r>0$ will be in the infinite intersect.
As for whether $r$ is in the finite intersection, we'll get to that in a moment.
If $r < 0$.... then $r < 0 = -1 + \frac 11$ so $r \not \in (-1 +\frac 11, \frac 11)=(0,1)$ so $r$ is not in any of the intersections finite or infinite.
So there is no values that are in the infinite intersection.  So $\bigcap_{m\in \mathbb N}(-1+\frac 1m, \frac 1m) =\emptyset$.
And if $\bigcap_{m=1}^n (-1+\frac 1m, \frac 1m) \subset (0,\infty)$.
Okay.... back that that observation that if $m > \frac 1r$ then $r\not\in (-1+\frac 1m, \frac 1m)$.
Well..... let's step back.   If $0< r < \frac 1n$ then $r < \frac 1n < \frac 1{n-1} <....$ and $r < \frac 1m$ for all $\frac 1m$ (and, of course, $r > 0 \ge -1+\frac 1m$) so $r\in (-1+\frac 1m, \frac 1m)$ for all $m \le n$ so $r$ is in the finite intersection.
But if $r\ge \frac 1n$ then $r\not \in (-1+\frac 1n, \frac 1n)$ and $r$ is not in the finite intersection.
So $\bigcap_{m=1}^n (-1+\frac 1m, \frac 1m) = (0, \frac 1n)$.
=======
Here's a slicker way to view it.
Consider $r \in \cap_{\alpha \in A} (a_\alpha, b_\alpha)$.  Then $r $ is in every interval $(a_\alpha, b_\alpha)$ so $r > \max a_\alpha$ if a maximum element exists and $r \ge \sup \max a_\alpha$ if a maximum element doesn't exist.
And the same reasoning to conclude $r < \min b_\alpha$ if a minimum element exist or $r \le \inf b_\alpha$ if it doesn't.
ANd thus the intersection can be determined by considering whatever interval can be made from $\max,\sup a_\alpha, \min,\inf b_\alpha$.
(If $\max,\min$ exist that side of the interval will be open and not include the $\max, \min$; otherwise it will be closed and will include the $\sup, \inf$; If $\max,\sup  a_\alpha > \min,\inf b_\alpha$ then the intersection will be empty; and if $\sup a_\alpha = \inf b_\alpha$ it will be the single point.
So $\max_{m\in \mathbb N} (-1+\frac 1m)=\max_{m\le n}(-1+\frac 1m) = (-1+\frac 11)=0$.
And $\min_{m< n}\frac 1m = \frac 1n$. So $\cap_{m=1}^n (-1+\frac 1m,\frac 1m) =(0,\frac 1n)$.
And $\min_{m\in \mathbb N}\frac 1m$ does not exist and $\inf_{m\in \mathbb N}\frac 1m = 0$.
So if $r\in \bigcap_{m\in \mathbb N}(-1+\frac 1m,\frac 1m)$ then $r > \max -1 + \frac 1m = 0$ and $r \le \inf \frac 1m = 0$.  So $0 < r \le 0$ which is impossible.  So  $ \bigcap_{m\in \mathbb N}(-1+\frac 1m,\frac 1m)= \emptyset$.
Comment: Why does someone with a reputation over 100000 write $\cap_{m=1}^n(-1+\frac 1 m,\frac 1 m)$ instead of $\bigcap_{m=1}^n(-1+\frac 1 m,\frac 1 m) \text{ ?} \qquad$
Comment: @fleablood thank you so so much, for writing that in such a detailed manner.


Altering markup of language switcher

Question: I want to lightly alter the language switcher block's markup by adding additional classes, among others "clearfix" to clear the floats. I cannot however pin down where the markup is created.
This link http://drupal.org/node/1369090 (last post) suggests using template.php but again, I cannot see how I would alter the wrapper div's markup.
Is there any way to achieve this?
Answer: In D7, the language switcher block is created in locale_block_view():
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

You can use hook_block_view_alter() to modify the markup of the block.
If you want modify the output of the links, you can override the theme_links() function in your theme using THEME_links__locale_block() in the template.php file.
Comment: Could you expand on the "you can use hook_block_view_alter" part?  I've tried implementing this a few ways and its now working.

Altering markup of language switcher


MaxEnt with given variance (but mean unknown)

Question: The MaxEnt distribution of $x \in (-\infty,\infty)$ with given mean and variance is the Gaussian. What happens when the mean is unknown? What is the MaxEnt distribution of $x\in(-\infty,\infty)$ with given variance (but unknown mean)?
Answer: This is not correct. The normal distribution is the MaxEnt distribution for given variance, irrespective of the value of the mean (this is because differential entropy is "translation-invariant", it does not depend on location).
Note that the issue here is not whether a moment is "known" or "unknown", but rather whether we need to compare distributions that have the same value for that moment.
So, among distributions with the same variance and possibly different means, the normal is the MaxEnt distribution.
PS: The wikipedia table for MaxEnt distributions is therefore wrong in showing the Normal to be Max Ent for given variance and mean.
Comment: So a consequence of this is that "the" maxent distribution with given variance, but unknown mean is not unique! there are infinitely many different distribution with the same maximizing entropy.
Comment: @kjetilbhalvorsen How did you arrive at this conclusion? I don't follow.
Comment: @kjetilbhalvorsen Ah, maybe you treat two normal distributions with different mean as different distributions... this is correct, but I have the impression that the whole MaxEnt framework is about finding the distribution _family_.
Comment: Well, say that you want maxent distribution on $(-\infty, \infty)$ with variance one and some unknown mean. Using your result, then for example $\text{N}(-13,1)$ or $\text{N}(107, 1)$ or ... all have the same maximizing entropy. Otherwise I misunderstood your claim?
Comment: Why is it about finding the distribution family? Jaynes used maxent to choose a prior distribution fulfilling some restraints. If the restraints do not give me a unique distribution I dont understand how that may be useful to me?
Comment: @kjetilbhalvorsen No, you're correct, they both are MaxEnt distributions compared to any other distribution outside the normal family. As for your second comment, you can always fix the mean if you like, and declare that the normal is the MaxEnt for given common variance and mean. It is just the case it is also MaxEnt for just the variance as common, irrespective of whether this is useful or not.


Override of commerce-order-receipt.html.twig template not working?

Question: My theme is using Bootstrap barrio theme (bootstrap_barrio) as a base theme. I'm trying to override Drupal commerce template modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig and it's not working for me. Even I copied that file to drupal/web/themes/my_theme/templates ,cleared the cache, Commerce is still using original template file from commerce module.
What puzzles me is that base Barrio theme also has that template and it's also not used?!?
Do I have to set somewhere what theme should be used for email templates or something? Overriding other modules templates (including commerce templates) works fine. Documentation says "The email can be customized by overriding the Twig template in your theme just as you would any other template".
Answer: Figured out what was the problem. I had to select my theme for sending emails on
Configure the Mail System admin page.
/admin/config/system/mailsystem
Other way some other theme is used.
Comment: Thanks @MilanG. That's already the second problem you asked about and helped me out :)


How can a single Green's function be used in both the inhomogeneous and homogeneous versions of a differential equation?

Question: Consider the differential equation $$\frac{d^2}{dx^2}=f(x)$$ with boundary conditions $y(0)=0$ and $y'(1)=0$. If we then let $f(x)=0$ we have a homogeneous differential equation. Then we know that the Green's function will be $$G(x,x')=Ax+B, x<x'$$ $$G(x,x')=Cx+D, x>x'.$$ Using the given boundary conditions, the boundary condition that $G(x,x')$ must be continuous at $x=x'$ and the boundary condition that the derivative with respect to $x$ of $G(x,x')$ must be discontinuous at $x=x'$ then it can be shown that $b=0$, $c=0$, $a=-1$ and $d=-x'$. Then Green's function is $$G(x,x')=-x, x<x'$$ $$G(x,x')=-x',x>x'.$$ Choose now $f(x)=x$ with the same boundary conditions so that our differential equation is inhomogeneous. Using $$y(x)=\int_0^1G(x,x')f(x')dx'$$ it can be shown that the solution to the inhomogeneous differential equation is $$y(x)=\frac{x^3}{6}-\frac{x}{2},$$ which is clearly the correct solution. The Green's function found from the homogeneous differential equation can be used to find the solution to any inhomogeneous equation of this same form, i.e. $f(x)\ne0$.
How can this work? I don't understand how this single Green's function found from a homogeneous differential equation can be used to solve any inhomogeneous differential equation of the same form as the original homogeneous one.
Comment: Green's function is not found by solving homogeneous equation. Instead, it's the general solution. In physics, you can think of it as solving for continuum basis(deltas).
Comment: Yes, that is generally how we think of it in physics. I am a physics student and our interpretation is that the Green's function provides a response to an impulse (i.e. the delta function) at x=x', and thus integrating gives the response across impulses at all x=x'.
Answer: When finding the Green's Function for the operator $\mathscr{L}=\frac{d^2}{dx^2}$, with the prescribe boundary conditions $y(0)=y'(1)=0$, we are not finding the solution to
$$\mathscr{L}\{y(x)\}=0 \tag 1$$
with those boundary conditions.  The solution to $(1)$ with those boundary conditions is simply $y(x)=x$.  And $G(x,x')\ne x$.
Rather, if we extend the analysis to include Generalized Functions, or Distributions, then the Green's Function $G(x,x')$ is a solution to
$$\mathscr{L}\{G(x,x')\}=\delta(x-x') \tag 2$$
with $G(0,x')=G_1(1,x')=0$, where $\delta(x)$ denotes the Dirac Delta, which I discussed in THIS ANSWER and THIS ONE.
Then, $(2)$ can be written as
$$\mathscr{L}\{G(x,x')\}=0,\,\,\text{for}\,\,x\ne x'$$
with the continuity condition and discontinuity of the first derivative condition provided by
$$\begin{align}
\lim_{\epsilon \to 0^+}\left.\left(G(x,x')\right)\right|_{x=x'-\epsilon}^{x=x'+\epsilon}&=0\\\\
\lim_{\epsilon \to 0^+}\left.\left(\frac{\partial G(x,x')}{\partial x}\right)\right|_{x=x'-\epsilon}^{x=x'+\epsilon}&=1
\end{align}$$
As already established in the OP, we find $G(x,x')=-\min(x,x')$.  Note, that while classically $\frac{d^2}{dx^2}G=0$ almost everywhere, in the context of distributions, $\frac{d^2}{dx^2}G=\delta(x-x')$.
To see how this reconciles classically, note that the solution to
$$\frac{d^2y(x)}{dx^2}=f(x)$$
with $y(0)=y'(1)=0$ is given by
$$y(x)=\int_0^1 G(x,x')f(x')\,dx'\tag 3$$
Taking the first derivative of $(3)$ yields
$$\begin{align}
y'(x)&=\frac{d}{dx}\left(\int_0^x (-x')f(x')\,dx'+\int_x^1 (-x)f(x')\,dx'\right)\\\\
&=-xf(x)+xf(x)-\int_x^1f(x')\,dx'\\\\
&=-\int_x^1 f(x')\,dx'
\end{align}$$
Proceeding to take a second derivative reveals
$$y''(x)=f(x)$$
as expected.  The reason why we cannot simply interchange the order of the integral with the derivatives is that the Green's Function does not have a continuous partial derivative.  And it is precisely that discontinuity that gives rise to Dirac Delta contribution.
Comment: Mark, out of curiosity, is this a standard way of describing continuity of a function (I mean any function not just a Green's function), or is this definition of continuity particular to Green's functions.?


Non-parametric test for comparing means of 2 or more dependent variables in R?

Question: I have a matched paired dataset (student survey before a topic was taught and student survey after the same topic was taught) where I compare the means of their answers (answers are given in Likert scales).
I use the Wilcoxon signed rank test (as opposed to the rank sum test) to compare scores of individual questions to see if they are significant, where my code is
<code>wilcox.test(score ~ time, data = "question 1", paired = TRUE)
</code>
I want to test and see if let's say previous experience in the topic was a contributing variable in creating a significant jump in mean from before to after in a group of questions (etc. questions 1-4). But I am stuck on which method of analysis to use in this situation.
I initially used a Kruskal Wallis test, then performed a post hoc Dunn test with Bonferroni adjustment, which gave results such as "test scores of students with no previous experience in a topic were significant from before to after" and "test scores of students with previous experience in a topic were not significant from before to after". But I realized K-W is only appropriate when the variables are independent. So my question is, are my variables dependent because the students are from the same sample and the data are matched this way, or are they independent because my matched data is being compared to previous experience which is an independent variable?
Comment: Welcome to Cross Validated! Do you have a sense of how you would do it parametrically?
Answer: First, a side note: There are no nonparametric tests for comparing means.  A mean is an inherently parametric thing.  Nonparametric tests primarily test whether responses in one group tend to be larger than responses in another group (stochastic ordering; concordance probability).
A second side note: Regarding the Wilcoxon signed-rank test.  This test, unlike the unpaired Wilcoxon-Mann-Whitney two-sample rank test, yields different answers depending on how you transform Y.  The rank difference test solves this problem.
But you have come up against a problem.  We have flexible ordinal regression models for the unpaired situation, and we have the rank difference and signed-rank tests for the paired situation where there are no covariates to adjust for.  But we are lacking in methods for robustly analyzing paired data where other variables need to be considered.
The only approach I can think of, and for which feedback would be much appreciated, is this.  Let X be the pre response value and Y be the post response, and Z be another covariate such as previous experience.  Fit an ordinal model such as the proportional odds model that generalizes the unpaired Wilcoxon and Kruskal-Wallis methods.  Symbolically the model is Y ~ X + Z, which can be extended to Y ~ f(X) + Z + g(X)Z where linearity of X is relaxed by expanding X to multiple columns using spline functions f and g, noting that this would require more data but allows Z to modify how the pre relates to the post.  This is an analysis that is conditional on pre.  Then from the fitted model we estimate Pr(Y > X | X, Z) for a variety of X and Z values.  Thus we are estimating the probability that the post exceeds the pre for all values of pre.  Probabilities above 0.5 would indicate increases in Y in going from pre to post.
Another thing to consider: Conditional logistic regression is a generalization of the McNemar test for paired binary data, and may somehow come into play.
Comment: I agree with the intuition that means are in some sense "parametric," but this term doesn't feel quite right. There *are* nonparametric tests for means.  For instance, consider the family of all symmetric distributions of finite mean and apply any nonparametric test of medians (which coincide with their means).  Although "symmetric" is the kind of strong condition we feel is needed to test means, it's still nonparametric.
Comment: Yes there's undoubtedly better terminology than nonparametric.  I should have left it at "we don't have a nonparametric test of means".  A test that assumes symmetry would not quite qualify as _nonparametric_ in this setting.  On a slightly related matter  empirical likelihood and bootstrap do not work well for means with highly skewed distributions.
Answer: Conversely to the other persons who already answered you, I am not an stats expert (just an applied researcher). Therefore, my answer will probably be less valuable and more simplistic than those you already have. However, I give it in case it could be useful.
I feel that the analyses you could use depend on how "previous experience" is defined:
-If previous experience is a binary factor (having previous experience vs. no having previous experience) perhaps you could just use a Yuen's test to compare the trimmed means of the experienced/non-experienced groups on a difference score (post-pre survey scores).
If you do not like the idea of the difference score, you could also compare the trimmed means of the experienced/non-experienced groups using robust between x within analogs of ANOVA that do not make any distributional assumption. These methods are described in section 8.6 of Wilcox, R.R. (2022) "Introduction to robust estimation and hypothesis testing". 5th edition. Springer.
-If experience is not defined as a binary factor but as a continuous variable, you could probably use robust ANCOVA-like methods that do not make distributional assumptions and can handle curvature. These methods are described in chapter 12 of Wilcox, R.R. (2022) "Introduction to robust estimation and hypothesis testing". 5th edition. Springer.


Can Netbeans(MinGW compiler for c/c++) call on arbitrary C/C++ DLLs(compiled in VS'05)?

Question: AS above, i encountered a "undefined reference error imp_ZN12classNameC1Ev" when using JNI to call upon class functions in arbitrary provided DLL. I am wondering if name mangling incompatibilty for the 2 different compilers is the source of error?
To be exact, can a code compiled by MinGW(gcc/g++) call another code's class function compiled by visualStudio?
Answer: Compiling is not exactly the problem. The problem is at linking. If you have C++ interfaces then name mangling will definitively make you trouble. Each compiler has its own name mangling scheme. Too bad, they should have standardized maybe this too in the C++ standard...
One way to workaround the problem is to create a small C wrapper API around the C++ Dll you have (which must be compiled with MSVC) and use this C API from Netbeans. (Eventually making some C++ header-only wrapper for the classes in the c++ dll to make it appear like the original Api. That's two level of wrapping but I have no idea if this can be solved in an easier way.


Proving the derivative of a certain point using the sequence definition

Question: Using this derivative definition

If $f$ is a function and has derivative $f'(c)$ at the point $c$ in the domain of $f$ means that if ($a_n$)$_{n=1}^{\infty}$ is any sequence converging to $c$ such that $a_n$ $\not= c$is in the domain of $f$ for all $n \in \mathbb{N},$ then: $$(\,\frac{f(x_n)-f(c)}{x_n-c}) \,_{n=1}^{\infty}$$converges to $f'(c)$

prove that $f'(c)=-6,$ where $f(x)=x^2 +2$
I feel like this should be fairly straight forward, but I'm having trouble.
My attempt:
Plugging in $a_n$ for $x,$ and using $f(c)=f(-3)=11,$
$(\,\frac{f(x_n)-f(c)}{x_n-c}) \,_{n=1}^{\infty}$<=> $\frac{[(a_n)^2+2]-11}{a_n-3}$<=>$\frac{(a_n)^2-9}{a_n-3}$<=>$a_n-3$
Because we are using sequences, I'm not sure if this is a correct approach, and I am not sure how to complete the proof. Do I need to choose a certain epsilon to show that this sequence converges to $f'(c)$?
Comment: So you have two convergences in this problem: the sequence $\{a_n\}\to c$ and $\frac{f(x)-f(c)}{x-c}\to f'(c)$ (as $x->c$) you can thus bound $|a_n-c|<\epsilon_1$ for $n>N_1$ and $|\frac{f(x)-f(c)}{x-c}-f'(c)|<\epsilon_2$ for $|x-c|<\delta$. Can you see how to combine these bounds to get a proof that the difference quotient sequence converges?
Comment: Are you allowed to use the fact that $\lim_{n \to c}(a_n + b_n) = \lim_{n \to c}a_n + \lim_{n \to c}b_n$
Comment: @wgrenard Yes, I have already proven that theorem!
Comment: @Twis7ed So that would involve a proof using the sequential definition of limits and the delta-epsilon definition?
Answer: What you have done is fine, and you don't have to get into any business with $\epsilon$ because you already know that $\lim_{n \to \infty}a_n = -3$
Since $\lim_{n \to \infty}a_n$ exists and is finite, and clearly $\lim_{n \to \infty} 3 = 3$ so it also exists and is finite, you can conclude that
$$
\lim_{n \to \infty}(a_n - 3) = \left( \lim_{n \to \infty}a_n \right) - \left ( \lim_{n \to \infty} 3 \right) = -3-3 = -6
$$
Comment: So I would not be using that n approaches infinity?
Comment: Oops, you are right. I made the appropriate changes
Comment: No worries! And we know $a_n$ converges to -3 from the definition I gave?
Comment: @Mathgirl correct. It is assumed that $a_n$ is a sequence converging to $c$.


Complete solution for a system of polynomial equations

Question: A research question led to the following system of polynomial equations.
\begin{align*}
  & x^3 - x^2y + x^2z + x^2 - xy + xz + y^2 - yz - y = 0 \\
  & x^3z - 3x^2y + 3xy^2 + xz^2 - y^3 + y^2 - 2yz = 0 \\
  & x^4 - x^3y - 2x^3z + x^3 + x^2yz - x^2y + x^2z + xy^2 + xyz - xy - xz^2 - yz^2 = 0 \\
  & x^4z + x^4 - x^3y + x^2yz - x^2y + 2x^2z^2 + x^2z - x^2 - xy^2z + xy^2 + xy - y^2z + z^3 - z = 0
\end{align*}
I used the poly_system function in SymPy (a Python library for symbolic mathematics) to solve this system, and it returned the following solutions:
$$[(-1, 0, 0), (0, 0, -1), (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0), (1, 2, 1), (2, 3, 0), (3, 6, 1)]$$
This was better than I had hoped, but I am concerned that the function may fail to find all solutions. How can I be certain that no other solutions exist?
Comment: Are you only interested in integer solutions? Either way this approach appears quite hopeless.
Comment: @orlp : This is also the solution set over the complexes.  So unless he was working over something unusual, ... ?
Answer: Using Maple, I took a "plex($x,y,z$)" Groebner basis of the ideal generated by the left sides of your equations.  The result was
$$ \eqalign{&{z}^{5}-{z}^{3}
,\cr
&y{z}^{3}-y{z}^{2}
,\cr
&{y}^{2}{z}^{2}-{z}^{4}-{y}^{2}z-y{z}^{2}+yz+{z}^{2}
,\cr
&{y}^{3}z-7\,{z}^{4}-8\,{y}^{2}z+5\,y{z}^{2}+7\,yz+7\,{z}^{2}
,\cr
&{y}^{4}-18\,{z}^{4}-4\,{y}^{3}-23\,{y}^{2}z+27\,y{z}^{2}+3\,{y}^{2}+21
\,yz+18\,{z}^{2}
,\cr
&-3\,{z}^{4}+6\,x{z}^{2}+{y}^{3}-4\,{y}^{2}z+7\,y{z}^{2}-3\,{z}^{3}-4\,
{y}^{2}-yz+3\,{z}^{2}+3\,y+3\,z
,\cr
&6\,{z}^{4}+6\,xyz-{y}^{3}+{y}^{2}z-7\,y{z}^{2}+3\,{z}^{3}+4\,{y}^{2}-2
\,yz-6\,{z}^{2}-3\,y-3\,z
,\cr
&2\,x{y}^{2}-{y}^{3}+{y}^{2}z-{z}^{3}-2\,xy-2\,xz+y+z
,\cr
&3\,{z}^{4}+12\,{x}^{2}z-2\,{y}^{3}+5\,{y}^{2}z-11\,y{z}^{2}+6\,{z}^{3}
+8\,{y}^{2}-7\,yz-3\,{z}^{2}-6\,y-6\,z
,\cr
&6\,{x}^{2}y-{y}^{3}+{y}^{2}z+2\,y{z}^{2}-3\,{z}^{3}-6\,xy-6\,xz-2\,{y}
^{2}+4\,yz+3\,y+3\,z
,\cr
&-{z}^{4}+4\,{x}^{3}-{y}^{2}z+5\,y{z}^{2}-4\,{z}^{3}+4\,{x}^{2}-8\,xy+y
z+{z}^{2}+4\,z
\cr
}$$
From the first basis element, all solutions must have $z \in \{-1, 0, 1\}$.
If $z = -1$, the second basis element tells us $y=0$, and then the sixth gives us $x=0$.
If $z = 0$, the fifth basis element tells us $y \in \{0,1,3\}$.  If $y=0$ we get $x=0$ or $x=-1$ from the 11th basis element.  If $y=1$ we get $x=0$ or $x=1$ from the 10th basis element.  If $y=3$ we get $x=2$ from the 8th basis element.
If $z=1$, the fourth basis element gives us $y = 0$, $2$ or $6$.  If $y=0$, the 6th basis element gives us $x=0$.  If $y=2$, the 6th basis element gives us $x=1$.  If $y=6$, the 6th basis element gives us $x=3$.
Thus the listed solutions are the only ones.
Answer: It looks like I can answer my own question. SymPy reports that the ideal generated by these polynomials has the following Gröbner basis.
\begin{align*}
& 2xyz^2 + 2xyz - 2y^2z + 2xz^2 - yz^2 \\
&  y^2z^2 + 2xyz - 2y^2z + 2xz^2 - yz^2 \\
& 2xz^3 - yz^2 \\
& yz^3 - yz^2 \\
& z^4 + 2xyz - y^2z + 2xz^2 - yz - z^2 \\
& 4x^3 + 2xyz - 2y^2z + 2xz^2 + 5yz^2 - 4z^3 + 4x^2 - 8xy + 4z \\
& 2x^2y + 2xyz - 2y^2z + 4xz^2 + 3yz^2 - 2z^3 - 2xy - 2y^2 - 2xz + 2y + 2z \\
& 2xy^2 + 6xyz - 6y^2z + 12xz^2 + 7yz^2 - 4z^3 - 2xy - 4y^2 - 2xz - 4yz + 4y + 4z \\
& y^3 + 6xyz - 7y^2z + 12xz^2 + 7yz^2 - 3z^3 - 4y^2 - 4yz + 3y + 3z \\
& 4x^2z + 2xyz - 2y^2z + 6xz^2 + yz^2 - 4yz
\end{align*}
The Wikipedia article on the Gröbner basis has the following statement.

Given the Gröbner basis G of an ideal I, it has only a finite number
  of zeros, if and only if, for each variable x, G contains a polynomial
  with a leading monomial that is a power of x (without any other
  variable appearing in the leading term). If it is the case the number
  of zeros, counted with multiplicity, is equal to the number of
  monomials that are not multiple of any leading monomial of G. This
  number is called the degree of the ideal.

Since the above condition is satisfied, we know that the system has exactly nine solutions.
Answer: Assuming you are working over a field of characteristic zero, ...
Computing a Groebner basis for your system, which I duplicate so you can verify that I am working on the same system,
\begin{align*}
x^3 &-x^2 y+x^2 z+x^2-x y+x z+y^2-y z-y = 0 \\
x^3 z &-3 x^2 y+3 x y^2+x z^2-y^3+y^2-2 y z = 0 \\
x^4 &-x^3 y-2 x^3 z+x^3+x^2 y z-x^2 y+x^2 z+x y^2+x y z-x
   y-x z^2-y z^2 = 0 \\
x^4 z &+x^4-x^3 y+x^2 y z-x^2 y+2 x^2 z^2+x^2 z-x^2-x y^2 z+x y^2+x y-y^2 z+z^3-z = 0,
\end{align*}
we get (with variable order $x > y > z$) \begin{align*}
&z^5-z^3, \\
&y z^3-y z^2, \\
&y^2 z^2-y^2 z-y z^2+y z-z^4+z^2, \\
&y^3 z-8 y^2 z+5 y z^2+7 y z-7 z^4+7 z^2, \\
&y^4-4 y^3-23 y^2 z+3 y^2+27 y z^2+21 y z-18 z^4+18 z^2, \\
&6 x z^2+y^3-4 y^2 z-4 y^2+7 y z^2-y z+3 y-3 z^4-3 z^3+3 z^2+3 z, \\
&6 x y z-y^3+y^2 z+4 y^2-7 y z^2-2 y z-3 y+6 z^4+3 z^3-6 z^2-3 z, \\
&2 x y^2-2 x y-2 x z-y^3+y^2 z+y-z^3+z, \\
&12 x^2 z-2 y^3+5 y^2 z+8 y^2-11 y z^2-7 y z-6 y+3 z^4+6 z^3-3 z^2-6 z, \\
&6 x^2 y-6 x y-6 x z-y^3+y^2 z-2 y^2+2 y z^2+4 y z+3 y-3 z^3+3 z, \\
&4 x^3+4 x^2-8 x y-y^2 z+5 y z^2+y z-z^4-4 z^3+z^2+4 z
\end{align*}
The first tells us $z \in \{-1,0,1\}$ for any solution.
Taking $z=-1$ and simplifying the original system, the Groebner basis is $\{x, y\}$, meaning the only solution for this $z$ is $(0,0,-1)$.
Taking $z = 0$ and simplifying the original system, the Groebner basis is
$$  \left\{x^5-2 x^4-x^3+2 x^2,-x^3-x^2+2 x y,-x^4+x^2+2 y^2-2 y\right\}  \text{.}  $$
The first tells us $x \in \{-1,0,1,2\}$.  Trying each of these, we get the solutions $(-1,0,0)$, $(0,0,0)$, $(0,1,0)$, $(1,1,0)$, and $(2,3,0)$.
Taking $z = 1$ and simplifying the original system, the Groebner basis is
$$  \left\{x^3-4 x^2+3 x,y-2 x\right\}  \text{.}  $$
The first tells us $x \in \{0,1,3\}$ and for each of these, the second gives us $y$ in $(0,0,1)$, $(1,2,1)$, and $(3,6,1)$.
And there are no further solutions (over a field with characteristic zero).


How to upgrade ram in arduino?

Question: I have an Arduino Uno which has 16MB RAM. I want to upgrade its ram (e.g 128 MB ) to store larger programs. Is this possible?
Actually I have tried storing datas in an external SD cards but using ram boosts the performance.
Answer: So I start by supposing you are talking about the flash memory size and that you are actually meaning kilobytes not megabites.
The ram and storage are actually built in the microprocessor so you cannot "upgrade them" but you can swap it out with an equivalent with just more ram like the ATmega1284P which is basically the same but it has 128 KB of programmable flash and 16 KB of ram.
A different solution could be to add ram chips outside and access the through the code.

How to upgrade ram in arduino?


Django: How to create an user and set its related field

Question: I've extended the user data using another model (OneToOne relation) and when a user is created, its profile is also created. I'd like to update the field mailing when the user is created without a query.
models.py
class Profile(models.Model):
    user         = models.OneToOneField(User, on_delete=models.CASCADE)
    mailing      = models.BooleanField(default=False)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

views.py
def register(request):
    ...
     if user_form.is_valid() and profile_form.is_valid():
        user = user_form.save(commit=False)
        user.mailing = profile_form.cleaned_data['mailing']
        user.save() #The user is created but mailing is not set
        return redirect('login')

profile_backend.py
class ProfileBackend(ModelBackend):
    def get_user(self, user_id):
        UserModel = get_user_model()
        try:
            return UserModel._default_manager.select_related('profile').get(pk=user_id)
        except UserModel.DoesNotExist:
            return None

I can set the variable taking the user as object but this imply using an extra function.
Answer: @receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        profile_id = uuid.uuid1().hex #for unique id if any
        Profile.objects.create(user=instance,profile_id=profile_id)
    instance.profile.save()

This is one of my sample code. This may help you out.
Comment: Same problem, data is not being saved. Is `user.mailing = True` correct or should I actually modify it?


sigsuspend(), replace set or add?

Question: As per the man page of sigsuspend(), it will replace the current signal mask set with its 1st parameter. In APUE, I saw an example as follows. The code maybe a little too long but I don't want to miss anything.
int pr_mask(char *s)
{
    sigset_t sigset;

    sigprocmask(0, NULL, &sigset);

    printf("%s: ", s);

    if(sigismember(&sigset, SIGINT)) printf("SIGINT ");
    if(sigismember(&sigset, SIGQUIT)) printf("SIGQUIT ");
    if(sigismember(&sigset, SIGUSR1)) printf("SIGUSR1 ");
    if(sigismember(&sigset, SIGALRM)) printf("SIGALRM ");
    /* ..... */

    printf("\n");
    return 0;
}

void sig_quit(int signo)
{
    pr_mask("in sig quit");
}

int main()
{
    sigset_t new, old, tempset;

    signal(SIGQUIT, sig_quit);

    sigemptyset(&tempset);
    sigaddset(&tempset, SIGINT);

    sigemptyset(&new);
    sigaddset(&new, SIGQUIT);
    sigprocmask(SIG_BLOCK, &new, &old);

    pr_mask("in critical section");
    /* critical section */

    sigsuspend(&tempset);
    pr_mask("after return form sigsuspend");

    sigprocmask(SIG_UNBLOCK, &new, NULL);
    pr_mask("program exit");

    return 0;
}

Output is:
in critical section: SIGQUIT
in sig quit: SIGINT SIGQUIT
after return form sigsuspend: SIGQUIT
program exit:

The problem is the second line. The SIGQUIT is still in the signal mask set.
Should it be only SIGINT as sigsuspend has already replaced the signal mask with tempset, which is set to SIGINT only?
Answer: While executing the SIGQUIT handler, SIGQUIT itself is blocked.  This is to avoid re-entering the handler by accident...
From the POSIX spec for sigaction (which you really should use instead of signal):

When a signal is caught by a signal-catching function installed by sigaction(), a new signal mask is calculated and installed for the duration of the signal-catching function (or until a call to either sigprocmask() or sigsuspend() is made). This mask is formed by taking the union of the current signal mask and the value of the sa_mask for the signal being delivered, and unless SA_NODEFER or SA_RESETHAND is set, then including the signal being delivered.

The POSIX spec for signal is a little less specific:

When a signal occurs, and func points to a function, it is implementation-defined whether the equivalent of a:
signal(sig, SIG_DFL);
is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed.

So it is legal for the OS to simply add the signal to the mask for the duration of the signal-handling function, and apparently that is what Linux does.
Comment: However the OS does not reset the signal mask to the old one after the signal handling function is done. Is there a way to avoid this ?
Answer: because the output "in sig quit: SIGINT SIGQUIT " is printed while executing the SIGQUIT handler.it would add the SIGQUIT to the signal mask, that means the current mask become the union of &tempset and the SIGQUIT.

sigsuspend(), replace set or add?


Inserir dados de uma tabela em outra

Question: Galera, eu estou quebrando a cabeça com esse problema já tem um tempo e queria a ajuda de vocês. Eu tenho um código que insere dados na tabela venda:
<?php
        if(isset($_POST['send'])){
        $venda = $_POST['num_venda'];
        $data = $_POST['data_venda'];
        $placa = $_POST['placa'];
        $km = $_POST['km'];
        $produtos = $_POST['produtos'];
        $servicos = $_POST['servicos'];

        include ('banco.php');

        mysql_query("INSERT INTO venda(id_venda, num_venda, data_venda, placa, km, produtos, servicos)
        values(
            NULL,
            '{$venda}',
            '{$data}',
            '{$placa}',
            '{$km}',
            '{$produtos}',
            '{$servicos}'

                        )
        ");

        header("location:listadevendas.php");

    }

    ?>

E eu tenho outras tabelas venda_produto(id, id_venda, produtos) e venda_servico(id, id_venda, servicos). Eu queria inserir os dados da tabela venda nelas, que seriam (id_venda e produtos ou servicos). Li em alguns lugares para usar triggers mais não consegui e outros pra usar inner join mas também não consegui. Será que alguém pode me ajudar?
Answer: Já tentou utilizar o insert..select?
INSERT INTO venda_produto (id, id_venda, produtos)
  SELECT venda.id, venda.id_venda, venda.produtos
  FROM venda;

Comment: "não deu certo" é meio vago. Precisa ver onde está errando, em vez de ficar mudando o jeito até dar sorte.
Comment: opa , fiz algumas ediçoes aki e deu certinho , muito obrigado vc me tiro uma dor de cabeça enorme ;)
Comment: eu tentei assim mas tbm nao deu certo , sera que nao tem outro jeito ?
Comment: @MatheusGoes qual erro ocorreu na execução? você editou corretamente as tabelas/colunas da query?
Comment: disponha fera! :)
Answer: Sua pergunta não ficou clara o suficiente, mas vamos lá. Faça uma tabela relacionada da seguinte forma:

No modelo acima, será criado uma linha nas tabelas venda, venda_produto e venda_servico sempre que algo for cadastrado. Esse modelo foi feito seguindo suas instruções. Se os produtos e serviços já estão pre-definidos no sistema, seria interessante um outro modelo que cadastrasse uma nova linha apenas na tabela venda e fizesse a relação dela com os produtos pre-definidos.
Código SQL pra gerar essas tabelas (altere conforme suas necessidades):
-- MySQL Script generated by MySQL Workbench
-- 12/01/15 15:16:18
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Table `venda_produto`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `venda_produto` (
  `id` INT NOT NULL,
  `produtos` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = MyISAM;

-- -----------------------------------------------------
-- Table `venda_servico`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `venda_servico` (
  `id` INT NOT NULL,
  `servicos` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`))
ENGINE = MyISAM;

-- -----------------------------------------------------
-- Table `venda`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `venda` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `numero` INT NOT NULL,
  `data` DATETIME NOT NULL,
  `placa` VARCHAR(8) NOT NULL,
  `km` INT NOT NULL,
  `produtos` INT NULL,
  `servicos` INT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_venda_venda_produto_idx` (`produtos` ASC),
  INDEX `fk_venda_venda_servico1_idx` (`servicos` ASC))
ENGINE = MyISAM;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

Faça conexão com o banco de dados usando MySQLi (a função MySQL é obsoleta)
$link = mysqli_connect($host, $username, $password, $database) or die(mysqli_connect_error());

mysqli_set_charset($link, 'utf8') or die(mysqli_connect_error($link));

Antes de montar o INSERT, faça escape em todos os dados passados por $_POST para dificultar ataques de SQL Injection.
foreach ($_POST as $key => $value) {
    $key    = mysqli_real_escape_string($link, $key);
    $value  = mysqli_real_escape_string($link, $value);
    $data[$key] = $value;
}

Faça INSERT na tabela venda e pegue o ID gerado
$query = "INSERT INTO `venda`(`numero`, `data`, `placa`, `km`, `produtos`, `servicos`)
    VALUES ('" . $data['num_venda'] . "', '" . $data['data_venda'] . "', '" . $data['placa'] . "', '" . $data['km'] . "');";

mysqli_query($link, $query) or die(mysqli_error($link));

//Pega o ID

$insertID = mysqli_insert_id($link);

Faça INSERT nas tabelas de venda_produto e venda_servico e UPDATE na tabela de venda com o ID para as outras tabelas.
$query = "INSERT INTO `venda_produto`(`id`, `produtos`) VALUES (" . $insertID . ", '" . $data['produtos'] . "'); INSERT INTO `venda_servico`(`servicos`) VALUES (" . $insertID . ", '" . $data['servicos'] . "'); UPDATE `venda` SET `produtos`=[" . $insertID . "],`servicos`=[" . $insertID . "] WHERE id = " . $insertID . ";";

mysqli_query($link, $query) or die(mysqli_error($link));

É isso.
Comment: +1 pela ênfase no MySQLi. MySQL não existe mais mo PHP 7 e desde o PHP 5.5+ estava deprecada.

Inserir dados de uma tabela em outra