What type of test / research design is recommended for this analysis

Question: It is assumed that people are not seeking for help when they need to, therefore a program is implemented to teach them when to seek help. People can join the program voluntarily. I would like to study the effectiveness of the program one year after it implementation, i.e., is there any significant difference between two groups (those who joined the program and those did not) in the way they seek.
1) I am using quantitative causal-comparative research design. Am i correct?
2) I am not sure what type of analysis should be use for this design. Paired t-test? But I do not have pre-data.
Answer: Causal Comparative Research is common in educational and training/development studies to investigte the effectiveness training program. This design attempts to determine the impact of, say, a human resource development program. In your the case, the alternative hypothesis could be People joining the program are more effective seeking help when needed. So you are right with the first question.
As of the second question, you can use t-test, not paired obviously because you will not have paired cases.


Closure requires unique access to lambda function

Question: I'm learning Rust, and have implemented some simple code to experiment with closures - but am running up against an issue with the borrow-checker that I'm not sure how to resolve.
When compiling the following function
fn twice(x:int, f:|int| -> int) -> int {
    f(f(x))
}

I get the following error
closure requires unique access to `f` but it is already borrowed

I'm working through the guide and have a moderate understanding of why the borrow-checker doesn't like this - but I'm unsure how to resolve it.
I can work around it by assigning the results of the first call to a temporary variable first, and then calling f(..) again on this. However this feels inelegant.
Is there a cleaner/better way of writing f(f(x)), or some way to convince the compiler that this is safe?
Answer: The full error message is:
<anon>:2:7: 2:8 error: closure requires unique access to `f` but it is already borrowed
<anon>:2     f(f(x))
               ^
<anon>:2:5: 2:6 note: previous borrow of `f` occurs here; the unique capture prevents subsequent moves or borrows of `f` until the borrow ends
<anon>:2     f(f(x))
             ^
<anon>:2:12: 2:12 note: previous borrow ends here
<anon>:2     f(f(x))
                   ^

That is, the outer call is, in some sense, reserving f and preventing it from being used first. This is very similar to issue #6268, which concerns methods instead of closures.
As you say, using a temporary is a fix, and is the most reasonable fix.
fn twice(x:int, f:|int| -> int) -> int {
    let y = f(x);
    f(y)
}

Comment: @JamesDavies, mainly an edge case (e.g. see the issue I reference).
Comment: Thanks. Do you know if this is this intentionally part of the language, or an edge case in the borrow-checker that will we cleaned up at some point?
Comment: This certainly must be fixed.
Answer: In modern Rust, the original code compiles as-is:
fn twice(x: i32, f: impl Fn(i32) -> i32) -> i32 {
    f(f(x))
}

fn main() {
    twice(42, |i| dbg!(i));
}


Array só carrega último registro em PHP com PDO

Question: Estou gerando as informações, porem só preenche a ultima linha da query executada dentro do Array, mesmo tendo a certeza que está rodando todas as linhas no foreach. Alguem tem ideia como preencher todos os arrays com todas as informações?
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');

require_once('conexao.php');
$conexao = conexao();
$id_igreja = 1;

try{
$igreja = "1";
$sql = "SELECT descricao, data, hora FROM reuniao WHERE id_igreja = :igreja order by 2,3 LIMIT 1";
$stmt = $conexao->prepare($sql);
$stmt->bindParam(':igreja', $id_igreja);
$stmt->execute();
$dados = $stmt->fetchAll(PDO::FETCH_OBJ);

  foreach ($dados as $consulta){
    $arr = [
    'descricao' => $consulta->descricao,
    'periodo' => $consulta->data,
    'hora' => $consulta->hora
    ];
}
$json = json_encode($arr,JSON_PRETTY_PRINT);
$fp = fopen("reuniao.json", "a");
fwrite($fp, $json);
fclose($fp);
echo $json;
}
catch(PDOException $e) {
echo 'ERRO: ' . $e->getMessage() ;
}

?>

Answer: Você está sempre substituindo o valor do array. Por isso que só preenche a última linha. O certo é adicionar os valores que são resgatados no banco, assim:
$arr = [];
foreach ($dados as $consulta){
    // adiciona mais um registro no array $arr
    $arr[] = [
    'descricao' => $consulta->descricao,
    'periodo' => $consulta->data,
    'hora' => $consulta->hora
    ];
}

Se bem que talvez seja desnecessário, visto que o fetchAll já retorna um array. Logo, você poderia transformá-lo em json diretamente:
$dados = $stmt->fetchAll(PDO::FETCH_OBJ);
$json = json_encode($dados ,JSON_PRETTY_PRINT);


When / why to use a Fourier Transformation?

Question: I know Fourier Transformations only a little bit, I guess/hope, I understood the concepts, at least. One scenario is, e.g., describing a signal in the so-called time domain in the so-called frequency domain. This means, when observing a sound wave, you can decompose it into single frequencies it consists of.

Now, I'm trying to understand how it is possible to connect (local) slopes of a light wavefront to topology data. For a bit more understanding: Measure light that leaves an eye and the wavefront provides information about the cornea in terms of (gradients of) a topology.

This is actually done by a Fourier Transformation.
I don't see any time or frequency domain, here. Or are they? In case not, this leads me to a more general basic question: What exactly is Fourier Transformation doing? Not in technical matters but more like "What could be done with it?"
Comment: Since you have two spatial variables, you have two wavenumber variables which is how you end up with a 2D heat map.
Comment: https://en.wikipedia.org/wiki/Fourier_optics
Comment: The Fourier transform (and more generally an integral transform similar to the Fourier transform) works with conjugate variables. Time and (angular) frequency are one such pair, but another pair that is just as common is position and wavenumber (or momentum). I suspect they're using position-wavenumber analysis here, but it's hard to tell exactly. In digital signal processing, you're likely to work with time-frequency, but in quantum physics, geophysics, etc, you're more likely to run into position-wavenumber.
Comment: it's a 2d frequency domain. the FT is done on the image, so 2d intensity --> 2d frequency.
Comment: perfect, that was actually the question/answer. A (more elaborated) answer and I could accept it :)
Comment: The Fourier transform can be applied to a time-varying signal and returns amplitudes as a function of waveform frequencies. But you can also apply it to functions of space, giving results in terms of spatial frequencies. Nonlinear deformation of a regular grid will tend to spread and dampen the peaks corresponding to the grid frequency and multiples.
Comment: @user619894 Thanks, what does it mean, it is done on the image? For what? What is it doing?
Answer: Turning my comment into an answer:
The Fourier transform can be defined in a few different ways. In digital signal processing, one often works with time and (angular) frequency. In this setting, the Fourier transform takes the form
$$ \mathcal{F}f(\omega) = \int_{\mathbb{R}} \frac{1}{\sqrt{2\pi}} e^{-i\omega t} f(t)\,dt $$
depending on your Fourier transform convention (i.e. where you want your $2\pi$ to be).
In physics, geophysics, and elsewhere, you're likely to run into a slightly different notion of the Fourier transform: one that connects position with wavenumber. Since you can have multiple position variables ($x$, $y$, $z$, etc.), you have that many wavenumber variables to match ($k_x$, $k_y$, $k_z$, etc.). The Fourier transform takes the form
$$ \mathcal{F} f(\vec{k}) = \int_{\mathbb{R}^n} \frac{1}{(2\pi)^{n/2}} e^{-i \vec{k}\cdot\vec{x}} f(\vec{x})\,d\vec{x}. $$
In your case, you have a 2D image which means two spatial variables, so you have two wavenumber variables. The heat map is then generated by taking the modulus (possibly squared) of the Fourier transform to get rid of the imaginary part and only look at the magnitude.
For computational purposes, the $n$-dimensional Fourier transform can be discretized just like the 1D Fourier transform to give rise to DFT and FFT analogues.
As an aside to prevent any confusion: you can get a heat map, often called a spectrogram in digital signal processing, from a time-varying signal by way of what is called a short-time Fourier transform (taking the Fourier transform of your function with a moving window). What you have is not that as far as I can tell. You have a naturally 2D image from the fact that you have two wavenumber variables to match your two spatial variables.

As for when/why to use a Fourier transform, there's no one-size-fits-all answer. Sometimes Fourier transforms simplify a (partial) differential equation (e.g. the heat equation). Sometimes you want to remove or alter high/low frequency/wavenumber information from the data because it's not representative, e.g. removing a vocal miscue in a recording for a song or clearing out some ringing. Sometimes you want to attenuate certain frequencies/wavenumbers. Sometimes you want to identify certain phenomena that you can't see in the time or spatial domains. Short-time Fourier transforms offer a glimpse into both worlds simultaneously to help you identify (roughly) specifically when a frequency/wavenumber phenomenon happens.


Create Calculated Measure based on dimension filter condtion

Question: I am trying to create a new calculated measure in my cube based on a dimension attribute value. Fact and Dimension table looks like below.

So, far below MDX script is generated from the form view.
<code> SELECT NON EMPTY { [Measures].[FactCount] } ON COLUMNS
,NON EMPTY { ([DimDate].[Year].[Year].ALLMEMBERS * [DimDate].[Month Name].[Month Name].ALLMEMBERS
*
({FILTER(
[DimFilter].[Desc].[Desc],
[DimFilter].[Desc].CurrentMember.Name = 'F1')
})

) } ON ROWS
DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
FROM [FactTest]
CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS
</code>
However above script only returns for the dim filter value 'F1'
How can I get the other measure columns(output table from image) from the cube.
Any kind of help suggestion is appreciated and thanks in advance for your help!
Comment: I use SSRS to generate report.
Answer: You meant the following query?
<code>SELECT NON EMPTY { [Measures].[FactCount] } ON COLUMNS
    ,NON EMPTY { ([DimDate].[Year].[Year].ALLMEMBERS * [DimDate].[Month Name].[Month Name].ALLMEMBERS
    *
    {[DimFilter].[Desc].[F1],[DimFilter].[Desc].[F2]}

    ) } ON ROWS
    DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS
    FROM [FactTest]
    CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS
</code>


Theme suggestions for blocks in a region which has a dash in the name

Question: I have a Region in the theme called header-top. As you may notice this region has a dash in the name instead of an underscore.
This theme is a sub-theme of a master theme called Framework. I wanted to apply a certain template file to blocks in that region, so according to Drupal 7 Theme Hook Suggestions page I've created a template file called block--header-top.tpl.php and cleared the cache. After re-loading the page a few times, I inspect the HTML to see if this particular template file is being applied, but all evidence suggests that it's still using block.tpl.php. I've tried using template_preprocess_block and dpm-ing out the $variables and in there I see an array theme_hook_suggestions which has the following values: array(block__header-top, block__block, block__block__21). I've checked the existing template files and there's no template file named block--block.tpl.php or block--block--21.tpl.php. I've even tried to swap the dash with an underscore to be block--header_top.tpl.php but still no luck.
Finally I've switched the region name to become header_top and the renamed template block--header_top.tpl.php suddenly starts to take effect.
I'm wondering is there a certain naming convention for regions with dashes in the name? If so what would be the ways to try and find out what exactly the template name for this region should be? I'd like to not resort to renaming the region, as that may have a knock-on effect on modules and other template files which I may miss and mess up the production website.
Comment: Yeah you need to use underscores, per the docs you linked to: _"An example of a region-specific template would be "block--sidebar_first.tpl.php"."_
Comment: Did you clear the caches after changing the dash to an underscore? That method should work just fine
Comment: I've cleared the cache on every step. The dash in the region name just doesn't seem to work.
Comment: The dash wouldn't but the underscore does (in a standard install anyway). Do you have any contrib modules or an over-zealous theme installed that might be affecting it?
Comment: No as far as I know there aren't any. When I had the template file `block--header-top.tpl.php` it had `HEADER TOP` at the top of the file. Also I put `TEST` on top of `block.tpl.php` and before I renamed the region, I could only see `TEST` but after the region is renamed I see `HEADER TOP` being output. So the theming engine is definitely falling back to `block.tpl.php` in my theme folder. /scratches head
Comment: I just tried creating `block--sidebar_first.tpl.php` in a bare installation and that gets picked up as the documentation describes. It's got to be something your theme/site is doing differently
Comment: yea I think you misunderstood me @Clive, I'm having trouble with the opposite, ok with regions with underscores, but dashes seem to cause trouble with naming conventions when trying to create template files. Are dashes not allowed (or not recommended) in region names?
Answer: Per the Theme suggestion docs you linked to the format for region-specific block templates go like this:

An example of a region-specific template would be "block--sidebar_first.tpl.php"

It looks like Drupal flips _ and - in theme suggestions so

block__header-top

becomes

block--header_top.tpl.php

(I knew it replaced _ with - but I didn't know it was the other way round too; there may be more to it than that).
Comment: It looks like if your region name has an underscore, then it doesn't seem to matter if you use a dash or an underscore in the template name they both work. However if your region has a dash, then it doesn't seem to matter what you use... the template doesn't get picked up.


Consumo de Web Service no padrão SOAP com envio de XML como parâmetro em PHP

Question: Estou desenvolvendo uma aplicação de integração entre a prefeitura da minha cidade e um sistema para uma empresa, para otimização da geração de NFS-e. Consiste em utilizar o Web Service da prefeitura para enviar, utilizando SOAP, arquivos XML para serem validados. Ou seja, o parâmetro passado será um arquivo XML.
Como nunca criei esse tipo de aplicação, estou com dúvida quanto a como fazer isso. Por exemplo:
Como utilizo os serviços disponibilizados (http://grphml.santacruz.rs.gov.br/thema-nfse-hml/) e faço a comunicação SOAP em PHP? Supondo que eu tenha o arquivo XML pronto e estruturado corretamente, como passo ele como parâmetro para os serviços do Web Service?
Não quero a solução de nada, somente dicas e exemplos que possam me ajudar.
Answer: Olá, na minha opinião este é um tópico bem complexo, se tratando de NFS-e é bem provável que vale a pena você usar uma API/biblioteca já pronta criada por outras pessoas, ou seja, não tente fazer tudo do zero...
Como utilizo os serviços disponibilizados (http://grphml.santacruz.rs.gov.br/thema-nfse-hml/) e faço a comunicação SOAP em PHP? ==> Usando as funções do cURL(), veja http://php.net/curl
Depois como sugestão veja os esforços já existentes da comunidade NFePHP, https://github.com/nfephp-org/sped-nfe (é a NF-e nacional mas tem iniciativas de NFS-e também).
Comment: Muito bom, obrigado pelas referências Fernando.


Vuejs Data Update

Question: I am trying to update highcharts data from a vuex-store, but the issue is that when the click event is triggered, the data in the vuex store state is mutated, but it only reflects in my highcharts component when i make some changes to the code and save the changes.
I am working on a dashboard using Vue and Highcharts.
<template>

    <vue-highcharts :options="options" ref="lineCharts"></vue-highcharts>
    <v-btn>{{parts}}</v-btn>

</template>

I want the data to be updated without making any changes to the code and saving it.
Comment: In where you are using your `series` array?
Comment: @SajibKhan I am using it for the highacharts
Comment: Could you reproduce your app/chart in online code editor like codesandbox or stackblitz?
Answer: You should use a computed to get the value with reactivity from the store, that way you don't need the created hook anymore. Also you should never access values from your store directly through the state, instead create a getter.
I'm not sure what are you trying to do, however this should be the right structure. If you only want to set this.options.series = this.$store.getters.parts. Like you are already doing with the Vue.set(this.options, 'series', this.$store.state.parts), in that case, add a watcher for the computed property and set the new property value.
{
  watch: {
    parts (updatedParts) {
      this.series.parts = updatedParts;
    }
  },
  computed: {
    parts () {
      return this.$store.getters.parts;
    }
  }
}

Vuejs Data Update


What is the difference between high impedance and low impedance microphones?

Question: Everywhere on the internet I would people stating the differentiating factor of "power" and how high impedance mics require an audio interface but nowhere I find anything regarding "sound quality".
Are high impedance microphones better in terms of quality than low impedance microphones (of course when pared with an audio interface)?
A detailed explanation would be much appreciated, in terms of how one out performs the other or is it just that they're basically the same other than the power requirements?
Answer: The simplest difference to grasp is 'intended use'.
In one sentence, professional vs consumer.
High impedance mics are cheap & cheerful, designed to plug straight into computer headset sockets. The computer's circuitry is equally cheap & cheerful. They go hand in hand. You can't plug a low impedance mic directly into a cheap computer headset/mic socket & expect it to work.
High impedance is much cheaper to manufacture, is lower quality & doesn't push signal so well. Signal loss soon becomes apparent.
Low impedance signals can be sent a long way, over balanced interference-free cabling.
There's a great beginner's article on MyNewMicrophone.com - Microphone Impedance: What Is It And Why Is It Important?
Extract…

Why Are There No Professional High-Impedance Microphones?
The only advantage of high-impedance microphones is the low cost of manufacturing. The disadvantages, however, are grave indeed! In fact, I'd argue that there's never an application for high-impedance microphones in any professional recording or sound system.
A good example of a high-impedance microphone would be a typical consumer karaoke microphone.
These karaoke microphones have a very high output signal level and therefore need a high-impedance output. This high output means no gain staging or amplifier within the mic, which drastically decreases manufacturing costs. These microphones don't need preamplifiers to bring their signals from mic to line level.
The big downside is that high-impedance microphones do not perform well over long cable runs. The longer the cable, the worse the result.
This is due to the inherent capacitance in a microphone cable. When a signal with high-impedance is sent through a microphone cable, a low-pass-filter is essentially created. The longer the cable, the lower the "filter cutoff" and the more muffled the sound.
To add insult to injury, the higher the impedance, the more susceptible the signal is to external noise and interference. Electromagnetic and radio interference worsens the signal-to-noise ratio of the signal and worsens the quality.

Even though that article goes into greater depth as regards load impedance & output impedance etc, in real terms you don't need to know or understand any of this. Microphone & pre-amp standards have reached a level of conformity that means "if it's got an XLR plug on both ends, it will work". All you need to know is whether or not it needs phantom power switched on - & even that's handled for you. A mic that doesn't need phantom won't be upset at all if the circuit does provide it, so long as the connection is XLR>XLR. It will just ignore it.
Comment: @Theodore - even regular condensers up to the 70s weren't always phantom. i have a set of 4 Calrecs [in storage, can't remember the model] that require their own totally non-standard transformer & special cables - & then come out at line level on mono jacks. You couldn't get it wrong & plug them up to a regular XLR, so there's no real danger.
Comment: Would phantom power upset any sort of mic - maybe ribbon mics? I have a nice old Beyer ribbon that I worry about using where there might be phantom power.
Comment: Any 'modern' mic will have a transformer which will discard any DC power like phantom. The issue is usually if it's hot-plugged or patched, getting a sudden hit to ground. I'd avoid it, just to be safe. 99 out of 100… is not zero odds;)
Comment: This one actually has a transformer, built into the jack. I guess because it's a jack, no phantom power would come through anyway. It's an M260 from the '60s, so hardly modern.
Comment: @Tim I know this is an old comment, but there were some older ribbon microphones with an output transformer that had a center tap that was grounded.  Applying +48 phantom to them would damage the transformer.
Comment: @Tetsujin Interesting, but not quite what I was talking about: I've heard some people [needlessly] fearing accidental application of phantom to *any* ribbon, when it's really just *certain* ribbons that could be harmed.
Comment: I was sure I'd already covered that - but perhaps not in clear terms. No modern mic of any type will be upset by phantom. Early mics had no fixed standards & ribbons would react the worst to inadvertent phantom, leading people to conflate information to this day.


Como uma classe é organizada na memória?

Question: Segundo esta definição do que é memória:

Em computação, memória refere-se aos dispositivos físicos utilizados
   para armazenar programas (sequencias de instruções) ou dados
   (informações de estado, por exemplo) em um programa de caráter
   temporário ou permanente para o uso em um computador ou outro
  dispositivo eletrônico digital.
fonte.

Seguindo esta definição foi gerado as seguintes dúvidas que serão abordadas no final da pergunta. Abaixo segue uma classe para servir de exemplo e ilustração.
public class Pessoa
{
    //Constante
    private const string caminhoFoto = @"C:\fotos";

    //Propriedades
    public string Nome { get; set; } = "";
    public int Idade { get; set; } = 0;

    public Pessoa(string nome, int idade)
    {
        Nome = nome;
        Idade = idade;
    }

    public Pessoa() { }

    //Metodos

    public List<String> Validar()
    {
        List<String> mensagemValidacao = new List<string>();
        //Metodo de "validação" para exemplificar.

        return mensagemValidacao;
    }

    public void Salvar()
    {
        //Metodo para "salvar no banco" para exemplificar.
    }
}

Exemplo de implementação da classe Pessoa:
Pessoa pessoa = new Pessoa("Jao", 21);
pessoa.Salvar();

Dúvidas
Seguindo a definição que está no início da pergunta, eu gostaria  que me esclarecessem as seguintes dúvidas:

Como é organizada na memória principal uma classe (após ser
instaciada) e suas caracteristicas como propriedades, constantes e
métodos?
Quem é responsavel por organizar os dados na memória, o compilador
da linguagem ou o sistema operacional?

Optei por usar a linguagem C# no exemplo, mas podem citar exemplo de outras linguagens também.
Answer: TL;DR
Na verdade, o objeto é só uma sequência de bytes equivalentes a seus campos de instância e é totalmente isolado do resto. A instância é só o objeto simples. O resto do que está na classe é algo separado e fica em uma área estática de forma única. O objeto (do seu exemplo), bem grosso modo, ficará assim:
|0A|B5|68|4F|00|00|00|00|
\-----------/\----------/
   string        int

Esse é o endereço (chutado) de onde fica o texto (sequencia de caracteres) e depois o número 0 como inteiro de 32 bits. Considerei que está usando arquitetura de 32 bits para saber o tamanho do ponteiro.
Introdução
Farei algumas simplificações, inclusive os detalhes podem variar dependendo da linguagem. Vou falar sobre linguagens estaticamente tipadas, as demais podem ter uma organização mais abstrata ainda. Algumas coisas são detalhes de implementação e podem mudar ou ser um pouco diferente do que falarei.
O assunto é complexo e importante para quem quer dominar a computação de forma mais profunda. Daria para escrever um livro aqui. Recomendo fortemente seguir os links da resposta e procurar novas informações por conta própria para se aprofundar e entender melhor alguns conceitos. Infelizmente nem tudo que precisa de mais detalhes tem resposta aqui no site. Cabem novas perguntas.
Vou me concentrar em C#. Java é muito parecido, mas faltam nela alguns recursos que falarei. C++ é diferente em poucos pontos: não há diferença entre struct e class, a instanciação define onde alocar, o cabeçalho do objeto varia conforme o alocador usado e não tem nada que facilite o garbage collector, travamento e polimorfismo (a não ser que o use, mas é fora da alocação), e faltam algumas facilidades que o C# tem. Outras linguagens, como D por exemplo, funcionam de forma bem semelhante. Não será muito diferente em Rust ou Go ou ainda Pascal.
A classe após ser instanciada é o objeto. Ele só tem estado, ou seja, só terá as dados das variáveis de instância. Os comportamentos não ficam na instância, mesmo que pareça estar junto. É ilusão.
Funcionamento do CLR
O C#, pelo menos na sua forma padrão, funciona com um runtime complexo que cuida do gerenciamento de memória, o JITter, controle de concorrência, segurança, entre outras coisas. Tem mais detalhes em O que é realmente o "runtime environment"?. O Java também, C++ possui um runtime muito, muito simples.
Isso vale para o .NET Core também. Ele é um pouco diferente, mas são detalhes. Também existe o .NET Native que não tem o JITter e é mais simplificado em alguns aspectos (o runtime do Mono pode funcionar parecido).
Entenda melhor sobre a "interpretação" do código binário.
O JITter pega o bytecode gerado pelo compilador e armazenado no que seria o executável e transforma em código nativo. Então todo código executável acaba ficando em uma parte do heap. Mesmo que eu fale de métodos em área estática, é um heap estático que é gerado em tempo de execução. Veja mais em Como funciona a execução de uma aplicação .NET?.
Não entrarei em detalhes sobre o heap, as suas 3 gerações do gerenciador de memória (garbage collector) e área de objetos grandes, nem do heap não gerenciado.
Leia O que são e onde estão a "stack" e "heap"?.
O CLR é responsável por toda organização da memória. Claro que ele precisa pedir permissão ao sistema operacional para começar trabalhar e alocar memória, mas a organização é basicamente dele, quando ele precisa ele pede para o SO para ajudá-lo em alguma coisa.
A organização pode ser vista aqui (imagem obtida de acordo com o link postado pelo Bruno Costa):

O .NET Core e Native não possuem domínios de aplicação.
Tem uma pergunta com um código C que pode ajudar entender como é criar uma função on-the-fly. Após o JITter fazer seu trabalho de pós-compilação, ele gera uma sequência de bytes e armazena no heap estático que falei antes.
As partes na memória
Métodos
É um engano as pessoas imaginarem que os métodos estão junto do objeto. Na verdade os métodos são simplesmente funções e residem em uma área estática. E existe apenas um método para a classe, as instâncias compartilham o que está lá, não existe nenhuma razão para ter um para cada instância. Após o JITter criá-lo ele é fixo (para otimizar mais é pode ser trocado por uma versão melhorado quando o JITter perceber que ele é muito usado e tem oportunidades de fazer uma otimização mais agressiva).
Pode parecer estranho, mas todos métodos na verdade são como se fossem estáticos, usando a terminologia que em geral os programadores C# conhecem. A diferença do método declaradamente estático e o método de instância é que o de instância tem um parâmetro oculto chamado this que recebe o objeto a ser manipulado. Sim, o que você manipula dentro do método está apenas manipulando o objeto normal recebido como parâmetro. Mesmo quando não precisa usar o this, o compilador coloca para você. Falo de algo sobre isso em Quando de fato preciso usar o operador this no Java? (não achei uma mais canônica).
As funções só possuem o código a ser executado. Os espaços para as variáveis locais das funções ficam na stack (uma por thread) e vão sendo acumuladas em pilha, como o próprio nome diz, de acordo com as chamadas. Na pilha só são colocados os valores básicos dos dados. Se for um tipo por valor o objeto estará ali, e se for um tipo por referência ali só terá uma referência para o objeto que estará no heap (em C#).
Importante notar que tipos por valor também podem ser alocados em registradores por causa de otimizações do JITter, ou no heap por estarem embutidos em outros objetos que estão lá.
Já escrevi mais detalhes sobre isso em Como funciona o gerenciamento de métodos na memória em C#?.
Todos os métodos (Validar(), Salvar(), os construtores, inclusive os 4 métodos que não parecem existir - veja abaixo) ficam em área estática, mas em um heap especial. Essas áreas são abstratas, não pense em uma separação bonitinha na memória.
A propriedade declarada criará dois métodos públicos para fazer o get e set das variáveis privadas então tem 4 métodos para criar (2 para cada propriedade) que não parecem óbvios. Mais detalhes em Nova funcionalidade do C# 6 "Auto-property initializers" é apenas um facilitador?. Ali não fala em detalhe, mas o código CIL abaixo demonstra que a inicialização de os campos das propriedades se dão na construção, em um método, ações (comportamento) só podem estar dentro de métodos. Falo sobre em Métodos e propriedades em C# - vantagens e desvantagens
Já falei que as funções, que na verdade são métodos de instância, recebem um parâmetro this. Um parâmetro não deixa de ser uma variável local e ela é que guardará "o objeto". Na verdade sendo uma classe o que a variável guarda de fato é uma referência (um ponteiro) para o objeto propriamente dito. Aparentemente o foco da pergunta é sobre esse objeto, mas é importante mostrar onde vão as outras coisas "constantes".
Constantes
A constante caminhoFoto fica em área estática. Note que essa variável em específico terá um ponteiro e separadamente o objeto com a sequência de caracteres em outra parte da área estática (por ser string).
Constantes ou qualquer coisa que sejam plenamente definidos em tempo de compilação ficam nessa área estática do código que acabará indo para a memória. Obviamente tudo que fica nessa área nunca será modificado, daí o nome estática.
O mesmo se dá com variáveis estáticas em geral (pelo menos seu valor). A diferença para uma constante é que essa última pode ser otimizada, ou seja, o seu valor pode usado nos códigos consumidores de forma direta. Pode copiar o valor, não precisa criar uma referência para ele como é comum em variáveis e nem precisa armazenar seu valor em algum lugar, não há indireção. Note que o valor de uma string de fato é o ponteiro para o texto efetivo, o texto teria que existir em algum lugar sempre.
Cuidado para não confundir constante com variável imutável. Variáveis não podem estar na área estática, nunca. Alguns objetos imutáveis até podem, é bem o caso de strings. Obviamente que strings construídas em tempo de execução não estarão nunca em área estática.
É bem comum todos os literais string ficarem na área estática, inclusive fazendo interning.
Em C# e Java até informações relevantes sobre a classe (ou qualquer outro tipo de dados) pode ficar nessa área. Esses são os metadados, a tabela de polimorfismo (vtable), entre outras coisas. A resposta do Bruno Costa tem um infográfico mostrando em detalhes.
Objeto
A alocação geral de um tipo por referência ocorre em partes: a referência, que pode estar em vários lugares (sempre em uma variável), inclusive por ter várias referências para o mesmo objeto; e o objeto mesmo. Nem tudo o que você vê ali está junto.
Um diagrama pode ajudar entender o que vai na stack (o que não é o objeto em si) e o que vai no heap (sem considerar as gerações). Vou falar do objeto propriamente dito.

Cabeçalho
Quando o objeto é instanciado com a estrutura definida na classe a alocação precisa dos dados inicializados, normalmente pelo construtor, e de dados de controle interno.
Nesse objeto, que é armazenado no heap, costuma ter um cabeçalho. Cada linguagem vai ser de um jeito.
Tem uma palavra (tamanho de um ponteiro) que indica de qual tipo aquele objeto é (TypeHandle). Esse ponteiro é importante por uma série de razões, desde ser usado pelo gerenciamento do coletor de lixo para saber o que fazer com aquilo, até reflexão (pegar os dados do tipo) e polimorfismo (vtable, a tabela virtual de métodos). Não vou entrar em detalhes sobre isso aqui, o assunto vai longe.
O tipo (um objeto complexo rico em informações (conforme o infográfico da resposta do Bruno) fica armazenado em algum lugar da área estática (como dito acima), portanto tem um endereço, é esse endereço que vai ali no cabeçalho.
O C# tem mais uma palavra (SyncBlock) para outros controle do garbage collector, travamento quando há concorrência, cache de hashcode e outras coisas. Leia mais em artigo em inglês.
É um pouco mais complexo que isso, mas essa é a base.
O objeto mínimo terá 12 ou 24 bytes (32/64 bits), mesmo que não existam dados nele (empty class). Uma palavra extra é reservada para esse caso, mas se tiver dados - o comum - essa palavra é aproveitada para eles. As alocações de objetos são sempre feitas em grupos de palavras, portanto em múltiplos de 4 ou 8 bytes. Se precisar ele faz um alinhamento (padding).
Dados do objeto
Depois o que vem nele é o objeto propriamente dito e variará de acordo com o que foi definido dentro da classe. O que terá ali é uma sequência simples de bytes que correspondem aos membros declarados na classe. Por isso que uma cópia, chamada bit a bit, copia todo o objeto de forma bem simples (essencialmente ele faz um memcpy() do C).
Para quem conhece bem C é fácil entender, já que é o equivalente a uma struct. Acho que já deu para entender que essas linguagens de mais alto nível só criaram novas abstrações em cima do que já existia.
Então se você tem uma string e um int, o objeto da classe exemplo na pergunta terá 8 ou 12 bytes (mas a alocação total dele será acrescida de 8 ou 16 bytes do cabeçalho).
A variável que é uma string ocupará o espaço de um ponteiro já que strings são por referência, portanto o objeto texto de verdade estará em outro lugar do heap (sim, haverá uma nova alocação com um objeto separado, a *string já é uma classe, embora poderá haver uma otimização a apontar para uma área estática da memória). Por isso não sei se o tamanho dele é 4 ou 8 bytes, dependerá se estiver em arquitetura 32 bits ou 64 bits.
O tipo int em C# sempre tem 4 bytes e é um tipo por valor, então o objeto já está ali mesmo, por que é como se fosse uma struct e não uma class.
Veja Qual a diferença entre Struct e Class?.
Campos das propriedades
O C#, nesse caso, cria membros com nomes internos que se assemelhará ao usado na propriedade (Ex.: <Nome>k__BackingField), na ordem que foram declaradas na classe, ou de forma reorganizada para dar melhor alinhamento na memória (juntar membros com menos que uma palavra para tentar alocá-los juntos em apenas uma palavra). Esses membros serão privados e eles serão o estado do objeto. Não é a propriedade, que é o conjunto desse campo privado com o par de métodos de acesso.
Quando o compilador precisa acessar uma variável privada, dentro da classe ou até do assembly (unidade de compilação), ele apenas calcula onde deve ser o acesso, ele não precisa saber o nome. É como nas variáveis locais, o nome existe mais para o programador entender, o compilador só precisa de endereços.
As variáveis que suportam propriedades normalmente só são acessadas indiretamente através dos seus métodos acessadores e modificadores, em tese só eles acessarão seus campos associados, mas nada impede que seja diferente internamente.
Acesso ao objeto
O acesso a esses campos é controlado internamente e determinado pelo compilador. Ele sempre será o endereço do objeto, que será armazenado em alguma variável da aplicação, mais o deslocamento do membro (é uma soma mesmo).
No caso, se for pegar a string o deslocamento é zero. Se fizermos uma analogia com um array é o elemento 0. Só não pode fazer a analogia por completo porque cada membro pode ter um tamanho diferente enquanto que no array o tamanho de todos elementos é igual.
A segunda variável de instância seria como o índice 1, então para acessá-la seria o endereço do objeto mais o tamanho do primeiro campo (4 ou 8 bytes).
Conclusão
Não falei de muita coisa, por exemplo não falei das condições especiais dos construtores, quando tem destrutores e finalizadores. Alguma coisa pode mudar no futuro, e posso ter simplificado tanto que posso ter escorregado em alguma coisa.
É complicado acompanhar tudo isso sem ver, e entender todo o processo de uma vez parece uma loucura. Mas se pensar bem, é muito simples. Não tem uma engenhosidade tão grande quanto possa parecer, um pouquinho tem :).
Livro recomendado.
Se quiser entender melhor como o CLR funciona e faz tudo isso tem o fonte disponível. Não é tarefa fácil :)
Se tiver interesse em conhecer o código da CIL que será gerado, pode ajudar enxergar algumas coisas que estou falando. Note que os métodos possuem informação do espaço que ele precisa reservar na stack que é gerenciado automaticamente pelo ambiente. O código é apenas uma representação textual (até com comentários) que um humano minimamente treinado consegue entender. Na verdade o código mesmo são apenas alguns bytes que indicam isso, os saltos dos números dos endereços entre as instruções dá uma ideia de quantos bytes cada uma ocupa.
.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static
        void Main () cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 22 (0x16)
        .maxstack 2
        .locals init (
            [0] class Pessoa
        )

        IL_0000: nop                  // Do nothing (No operation)
        IL_0001: ldstr "Jao"          // Push a string object for the literal string
        IL_0006: ldc.i4.s 21          // Push num onto the stack as int32, short form
        IL_0008: newobj instance void Pessoa::.ctor(string, int32) // Allocate an uninitialized object or value type and call ctor
        IL_000d: stloc.0              // Pop a value from stack into local variable 0
        IL_000e: ldloc.0              // Load local variable 0 onto stack
        IL_000f: callvirt instance void Pessoa::Salvar() // Call a method associated with an object
        IL_0014: nop                  // Do nothing (No operation)
        IL_0015: ret                  // Return from method, possibly with a value
    } // end of method Program::Main

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x2072
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: call instance void [mscorlib]System.Object::.ctor() // Call method indicated on the stack with arguments
        IL_0006: nop                  // Do nothing (No operation)
        IL_0007: ret                  // Return from method, possibly with a value
    } // end of method Program::.ctor

} // end of class Program

.class public auto ansi beforefieldinit Pessoa
    extends [mscorlib]System.Object
{
    // Fields
    .field private static literal string caminhoFoto = "C:\\fotos"
    .field private string '<Nome>k__BackingField'
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = (
        01 00 00 00 00 00 00 00
    )
    .field private int32 '<Idade>k__BackingField'
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = (
        01 00 00 00 00 00 00 00
    )

    // Methods
    .method public hidebysig specialname
        instance string get_Nome () cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x207b
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldfld string Pessoa::'<Nome>k__BackingField' // Push the value of field of object (or value type) obj, onto the stack
        IL_0006: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::get_Nome

    .method public hidebysig specialname
        instance void set_Nome (
            string 'value'
        ) cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x2083
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldarg.1              // Load argument 1 onto the stack
        IL_0002: stfld string Pessoa::'<Nome>k__BackingField' // Replace the value of field of the object obj with value
        IL_0007: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::set_Nome

    .method public hidebysig specialname
        instance int32 get_Idade () cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x208c
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldfld int32 Pessoa::'<Idade>k__BackingField' // Push the value of field of object (or value type) obj, onto the stack
        IL_0006: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::get_Idade

    .method public hidebysig specialname
        instance void set_Idade (
            int32 'value'
        ) cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x2094
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldarg.1              // Load argument 1 onto the stack
        IL_0002: stfld int32 Pessoa::'<Idade>k__BackingField' // Replace the value of field of the object obj with value
        IL_0007: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::set_Idade

    .method public hidebysig specialname rtspecialname
        instance void .ctor (
            string nome,
            int32 idade
        ) cil managed
    {
        // Method begins at RVA 0x209d
        // Code size 43 (0x2b)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldstr ""             // Push a string object for the literal string
        IL_0006: stfld string Pessoa::'<Nome>k__BackingField' // Replace the value of field of the object obj with value
        IL_000b: ldarg.0              // Load argument 0 onto the stack
        IL_000c: ldc.i4.0             // Push 0 onto the stack as int32
        IL_000d: stfld int32 Pessoa::'<Idade>k__BackingField' // Replace the value of field of the object obj with value
        IL_0012: ldarg.0              // Load argument 0 onto the stack
        IL_0013: call instance void [mscorlib]System.Object::.ctor() // Call method indicated on the stack with arguments
        IL_0018: nop                  // Do nothing (No operation)
        IL_0019: nop                  // Do nothing (No operation)
        IL_001a: ldarg.0              // Load argument 0 onto the stack
        IL_001b: ldarg.1              // Load argument 1 onto the stack
        IL_001c: call instance void Pessoa::set_Nome(string) // Call method indicated on the stack with arguments
        IL_0021: nop                  // Do nothing (No operation)
        IL_0022: ldarg.0              // Load argument 0 onto the stack
        IL_0023: ldarg.2              // Load argument 2 onto the stack
        IL_0024: call instance void Pessoa::set_Idade(int32) // Call method indicated on the stack with arguments
        IL_0029: nop                  // Do nothing (No operation)
        IL_002a: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::.ctor

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x20c9
        // Code size 27 (0x1b)
        .maxstack 8

        IL_0000: ldarg.0              // Load argument 0 onto the stack
        IL_0001: ldstr ""             // Push a string object for the literal string
        IL_0006: stfld string Pessoa::'<Nome>k__BackingField' // Replace the value of field of the object obj with value
        IL_000b: ldarg.0              // Load argument 0 onto the stack
        IL_000c: ldc.i4.0             // Push 0 onto the stack as int32
        IL_000d: stfld int32 Pessoa::'<Idade>k__BackingField' // Replace the value of field of the object obj with value
        IL_0012: ldarg.0              // Load argument 0 onto the stack
        IL_0013: call instance void [mscorlib]System.Object::.ctor() // Call method indicated on the stack with arguments
        IL_0018: nop                  // Do nothing (No operation)
        IL_0019: nop                  // Do nothing (No operation)
        IL_001a: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::.ctor

    .method public hidebysig
        instance class [mscorlib]System.Collections.Generic.List`1<string> Validar () cil managed
    {
        // Method begins at RVA 0x20e8
        // Code size 13 (0xd)
        .maxstack 1
        .locals init (
            [0] class [mscorlib]System.Collections.Generic.List`1<string>,
            [1] class [mscorlib]System.Collections.Generic.List`1<string>
        )

        IL_0000: nop                  // Do nothing (No operation)
        IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() // Allocate an uninitialized object or value type and call ctor
        IL_0006: stloc.0              // Pop a value from stack into local variable 0
        IL_0007: ldloc.0              // Load local variable 0 onto stack
        IL_0008: stloc.1              // Pop a value from stack into local variable 1
        IL_0009: br.s IL_000b         // Branch to target, short form
        IL_000b: ldloc.1              // Load local variable 1 onto stack
        IL_000c: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::Validar

    .method public hidebysig
        instance void Salvar () cil managed
    {
        // Method begins at RVA 0x2101
        // Code size 2 (0x2)
        .maxstack 8

        IL_0000: nop                  // Do nothing (No operation)
        IL_0001: ret                  // Return from method, possibly with a value
    } // end of method Pessoa::Salvar

    // Properties
    .property instance string Nome()
    {
        .get instance string Pessoa::get_Nome()
        .set instance void Pessoa::set_Nome(string)
    }
    .property instance int32 Idade()
    {
        .get instance int32 Pessoa::get_Idade()
        .set instance void Pessoa::set_Idade(int32)
    }

} // end of class Pessoa

Coloquei no GitHub para referência futura.
Comment: @DiegoFarias sim, todo objeto por referência tem isso antes do dado propriamente dito. Isto é usado para controle interno do *runtime*. Na verdade em qualquer plataforma precisa de um cabeçalho pelo menos para informar o tamanho do objeto. A única forma de evitar esse custo é ter arenas separadas para cada tamanho que pode alocar, o que é virtualmente impossível de alcançar em muitas situações e tem várias desvantagens. Faria uma bela bagunça na memória e destruiria a performance.
Comment: Foi um excelente *peek-view* do `CLR`.
Comment: Quer na minha pergunta quer na sua falta uma referencia obrigatória para o [ECMA](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf). Fica aqui para quem estiver interessado em ver em todo o detalhe o `CLI`
Comment: É bem útil sim.
Comment: Não entendi direito essa questão de cabeçalho do objeto. No caso o objeto tem um cabeçalho que é inicializado quando o objeto é instanciado ?
Answer: Quais são as zonas de memória
Para responder a esta pergunta creio que é uma boa ideia voltar ao velhinho assembly.
Num programa (que ultimamente consta em instruções assembly), existem várias zonas de memória, entre as quais:

BSS e Data (dados não iniciados e iniciados, respetivamente, partilhados com outras aplicacoes.)
Stack
Heap

Fonte
Como é que estas zonas de memórias são usadas em C#
Em C# as seguinte operações resultam nas consequentes zonas de memória

new de uma classe é sempre alocado no heap
sempre que você chama um função, você aumenta o stack
dentro das funções new de uma struct ocupa o espaço no stack do tamanho dessa struct. Enquanto new de uma classe ocupa apenas o tamanho de um ponteiro no stack

Em C# não existe conceito de dados não iniciados, todos os dados são iniciados com valores por omissão, tudo a 0, ou null, por isso o BSS pode não ser usado.
É simples imaginar que constantes possam ir parar à zona Data.
Quais são os responsáveis por especificar as zonas de memórias e de as gerir
De certa forma pode-se dizer que não existe um único responsável por organizar os dados nestas zonas. Em vez disso pode-se dizer que cada um trata de coisas diferentes

O programa especifica qual a quantidade de cada tipo de memória (em tempo de compilação só é importante saber a memória Data e BSS)
O sistema operativo trata de guardar essas zonas de memórias em seccoes diferentes da memória RAM
Cabe ao programa fazer gestão do heap

O stack é normalmente gerido automaticamente, em linguagens que não sejam de baixo nível (ou seja, praticamente em todas as linguagens que não o assembly)
Como é que os métodos sao guardados
Em C# todos os tipos tem metadata, esta é a mesma metadata que pode ser obtida através da API de reflexão.
Dentro dessa metadata, existe uma tabela para os métodos virtuais, uma tabela para as implementações explicitas de Interface, nota que esta tabela contém apenas um ponteiro para os métodos e não o seu código.
O código é guardado na dll, no Java é compilado para bytecodeenquanto noC# o código é compilado para IL (que é também um bytecode mas tem um formato diferente do Java). O bytecode é depois compilado para assembly com o compilador JIT (just-in-time).

Fonte
Como é que objeto é representado em memória
Esta imagem mostra informações bastante interessantes. Pode observar que um objeto ocupa pelo menos 8 bytes em 32 bits, ou 16 bytes em 64 bits.
Isto porque todos os objetos armazenam um ponteiro que tem informação sobre os monitores (os monitores são objetos de sincronização), assim como um ponteiro para o seu tipo.
A isto acresce memória por cada membro da sua classe. Normalmente também é feito padding para que o processador tenha o trabalho facilitado a obter a informação da instância da memória.
Como isto tudo se mostra no seu exemplo
Quando você cria uma instância de Pessoa
var pessoa = new Pessoa("Jao", 21);

Um objeto é criado com a seguinte estrutura:

Já o caminhoFoto é armazenado na secção Data e não faz parte da informação do objeto.
Pode usar a imagem que tem a tabela de métodos para saber qual é a estrutura do seu tipo Pessoa. E como os seus métodos e interfaces estão organizados.
Comment: Um link melhor para a primeira imagem seria o seguinte https://web.archive.org/web/20150515023057/https://msdn.microsoft.com/en-us/magazine/cc163791.aspx. Esse link tem também muita informacao relacionada ao assunto.
Comment: Ainda ficou umas coisinhas que pode dar uma interpretação errada, mas nada que a minha também não tenha. Vou apagar aqui o que não é relevante mais.
Answer: Na memória, tudo é armazenado no formato "endereço" = "valor". Não é armazenada nenhuma informação com relação a tipo ou finalidade para aquele valor. Quem cuida da checagem da validade de cada valor (como tipagem) e validade de cada operação (como validar soma entre dois números e invalidar soma de número com caractere no caso de um compilador de uma linguagem estritamente tipada) é o compilador.
Respondendo:

Na memória, as variáveis serão armazenadas no formato "endereço" = "valor".
O sistema operacional é responsável por selecionar o local na memória e alocar o valor atribuído. O compilador é responsável por validar todas as operações do programa a ser compilado e providenciar o controle (instruções de leitura na memória para a CPU, onde especifica quantos bytes para cada tipo de dado) entre as variáveis a serem utilizadas e os endereços selecionados pelo SO em tempo de execução (dentre mil outras coisas).


Is there an analytic solution to this equation? $a+b\sin(x)+c\tan(x)=0$

Question: Here is the equation which should be solved for $x$:

$$
a+b\sin(x)+c\tan(x)=0
$$
where $a$, $b$, and $c$ are constants.
Is there an analytic solution, or at least an algorithm to approximate it for any given set of constants?
Answer: Using the universal substitution $t=\tan(x/2)$ gives
$$
a+b\cdot\frac{2t}{1+t^2}+c\cdot\frac{2t}{1-t^2}=0
$$
So you just need to clear denominators and solve the quartic.  (OK, the last link is a joke.  You should solve it using the algorithm from Galois theory instead of a single nasty formula.)
Comment: @Somos: you get a quartic: $(1-t^2)(1+t^2)=1-t^4$ will appear with the $a$.


Delete a webform file by clicking on its name

Question: I added a file field to a webform. Everything works fine but I need to style the file submissions differently.
This is what I should get: the file name is displayed with an icon that allows you to delete it directly.

However, on webform, we have a checkbox next to the name of the file that must be checked and then click on the submit button so that the file is deleted.

I am able to modify this functionality but I still have a problem. In js, when we click on the file name, I check the checkbox and simulate a `mousedown on the submit button. It works fine but after the 2nd click. The first does cause an ajax call but the file is not deleted.
Do you have any idea how I could handle this?
$('.js-form-managed-file span.file').mousedown(function (event) {
              $(this).closest('label.option').prev('input[type="checkbox"]').prop('checked', true);

              if ($(this).closest('label.option').prev('input[type="checkbox"]').prop('checked')) {
                  $('.js-form-managed-file .js-form-submit').mousedown();
              }

});

Answer: I managed to create this functionality where the user directly clicks on the name of the file he sent to delete it. With css, I was able to add a delete icon next to the file name.
The error comes from the sumit button selector (the one used to delete files after checking the checkboxes) which was targeted. By doing a console.log(settings), I could see in
_triggering_element_name

that the trigger element was not ($('.js-form-managed-file .js-form-submit').mousedown(); but $("button[name='shop_files_remove_button']")
So here is the working code. You have to adapt with the name of your button :
(function ($, Drupal, once) {

  Drupal.behaviors.Contact = {
    attach: function (context, settings) {
      once('contact', '.js-form-managed-file').forEach(function (element) {

        $('.js-form-managed-file span.file').mousedown(function (event) {
          $(this).closest('label.option').prev('input[type="checkbox"]').prop('checked', true);
        });

        var checkboxes = $('.js-form-managed-file .form-checkbox');
        checkboxes.change(function () {
          if (checkboxes.is(':checked')) {
            $("button[name='shop_files_remove_button']").mousedown();
          }
        });
      })
    }
  }

})(jQuery, Drupal, once);


Android wheel on Samsung Galaxy S2 ICS

Question: In our app we use Android wheel lib. Problem is on Galaxy SII. The wheel works only when user touch it, move his finger on the side (out of the wheel) and then scroll up or down. Have anyone this problem too and possible solution?
Answer: This is a bug of the kankan android-wheel library. In WheelView.java on line 611 change the switch statement to the following:
<code>switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: //added to fix problem
    case MotionEvent.ACTION_MOVE:
        if (getParent() != null) {
            getParent().requestDisallowInterceptTouchEvent(true);
    }
    break;

    case MotionEvent.ACTION_UP:
        if (getParent() != null) { //added to fix problem, this may be uneeded
            getParent().requestDisallowInterceptTouchEvent(false);
        }

    if (!isScrollingPerformed) {
        int distance = (int) event.getY() - getHeight() / 2;
        if (distance > 0) {
            distance += getItemHeight() / 2;
        } else {
                distance -= getItemHeight() / 2;
        }
        int items = distance / getItemHeight();
        if (items != 0 && isValidItemIndex(currentItem + items)) {
                notifyClickListenersAboutClick(currentItem + items);
            }
    }
    break;
}
</code>

Android wheel on Samsung Galaxy S2 ICS


The convergence of a power series (Radius of Convergence)

Question: Find the radius of convergence of the following power series $$\sum_{n=1}^\infty  \frac{(-1)^n z^{n(n+1)}}{n}$$
Here's my working
$$\lim_{n\to \infty}|  \frac{(-1)^{n+1} z^{(n+1)(n+2)}}{n+1} \frac{n}{(-1)^nz^{n(n+1)}}|$$
$$=\lim_{n\to \infty}\big|  \frac{(-1)^n(-1) z^{(n^2+3n+2)}}{n+1} \frac{n}{(-1)^nz^{n^2}z^n}\big|$$
$$= \lim_{n\to \infty}\big|  \frac{ -z^{3n}z^2}{n+1} \frac{n}{{}z^n}\big|$$
$$=\lim_{n\to \infty}\big|  \frac{ -nz^{2n}z^2}{n+1}\big|$$
I am stuck after this. Is the limit greater than 1 since anything raised to the power infinity is very huge? How do I do this? Also what happens if z=i?
Answer: As so often straightforward comparisons will give the result.
The series $\sum z^n$ has radius of convergence $1$. The series $\sum (n+1)$ diverges.
(a) For $|z|<1$ we have that
$$\left|\frac{(-1)^n}{n}z^{n(n+1)}\right|\leqslant |z|^n$$
so by the Comparison Test our series converges for $|z|<1$ and so $R\geqslant 1$.
(b) For any $a>0$ we have that
$$
\left|\frac{(-1)^n}{n}(1+a)^{n(n+1)}\right|\geqslant\frac{1+n(n+1)a}{n}\geqslant (n+1)a
$$
and so by the Comparison Test our series diverges at $1+a$, and so $R\leqslant 1$.
Answer: Use the fact that$$\lim_{n\to\infty}\left|\frac{-nz^{2n+2}}{n+1}\right|=\lim_{n\to\infty}\frac n{n+1}|z|^{2n+2}=\begin{cases}0&\text{ if }|z|<1\\1&\text{ if }|z|=1\\\infty&\text{ if }|z|>1.\end{cases}$$So, your series converges if $|z|<1$ and diverges if $|z|>1$. Therefore, its radius of convergence is $1$.
Answer: You could try to do the following to see your series as a "usual" power series:
$$\frac{(-1)^n z^{n(n+1)}}n=a_mz^m\;,\;\;\text{when}\;\;a_m=\begin{cases}0,&m\neq2,6,12,...,k(k+1)\\{}\\\cfrac{(-1)^m}m,&m=k(k+1)\end{cases}\;,\;\;k\in\Bbb N$$
From here, using Cauchy-Hadamard theorem:
$$\frac1R=\limsup_{n\to\infty}\sqrt[n]{|a_n|}=\lim_{n\to\infty}\frac1{\sqrt[n]n}=1$$
so $\;R=1\;$ .
It's important to note that the series could be not considered a power series per dry definition (depending on the author), but it is possible to turn it into one as above.
Comment: Please do not use the same variable twice, set $m=n(n+1)$, or $n=m(m+1)$.
Comment: @I've no idea what you'rse saying: the coefficient $\;a_m\;$ is defined in terms of $\;m\;$ which, is defined in terms of $\;n\;$ . What isn't clear? The coefficient for the degree $\;m\;$ is $\;a_m\;$ , which is defined there for every case of (natrual, of course) $\;m\;$ .Probably could be cleare to define it as function of $\;k\;$ and not $\;n\;$ itself...but I think it's sufficiently clear now
Comment: The coefficient for the term with degree $m=n(n+1)$, that is, for the term $a_mz^m=a_{n(n+1)}z^{n(n+1)}$ is $a_m=\frac{(-1)^n}{n}$. This does not change the overall result, as $|a_m|\sim \frac1{\sqrt{m}}$ also gives radius of convergence equal to one, but in the detail your formula is wrong.
Comment: @LutzLehmann Again, you're focusing in indexes.: what you say at the beginning of your last comment is *exactly* what I wrote from the beginning (repeating the index $\;n\;$ , which I corrected). The formula (CH) is correct, whether you use $\;n,m, t\;$ or any other natural index.
Comment: No, you claim in your first formula that the monomial $z^{n(n+1)}$ is identical to the monomial $z^n$.
Comment: @DonAntonio: the expression for $a_m$ in your answer is not quite correct.
Comment: This is now over-corrected. The coefficient for the degree $m=n(n+1)$ is $a_m=\frac{(-1)^n}{n}$. One could solve $m+\frac14=(n+\frac12)^2\implies n=\sqrt{m+\frac14}-\frac12$.
Answer: The series in the posting can be expressed as
$$
\sum^\infty_{n=1}\frac{(-1)^n}{n} z^{n(n+1)}=\sum^\infty_{m=0}a_mz^m$$
where $a_m=0$ unless $m\in\{n(n+1):n\in\mathbb{N}\}$, in which case $a_m=\frac{(-1)^n}{n}$, where $n=\sqrt{m+\frac14}-\frac12$.
Then by the root test criteria, the series converges for all $z$ with $|z|<R$ and diverges for all $|z|>R$, where
$$\frac{1}{R}=\limsup_m\sqrt[m]{|a_m|}=\lim_m\frac{1}{\Big(\sqrt{m+\frac14}-\frac12\Big)^{1/m}}=1$$
As can be seen from the fact that $\lim_{k\rightarrow\infty}\sqrt[k]{k}=1$.


Groups $G$ of order $8$ so that $U(\mathbb{Z}/n\mathbb{Z})\cong G$ for some $n$.

Question: I cant solve this exercise.
Find all groups $G$ of order $8$ so that $U(\mathbb{Z}/n\mathbb{Z})\cong G$ for some $n$.
I need a little help here. thanks!!!
Answer: Hints
First, we know the group is abelian, and there are only a few abelian groups of order $8$.  How many?
Second, the order of $U(\mathbb{Z}/n\mathbb{Z})$ is equal to $\varphi(n)$, Euler's totient function.  There are only finitely many numbers $n$ for which $\varphi(n)=8$ ($5$ I believe), and they aren't too hard to find.  You could just do a brute force calculation of $U(\mathbb{Z}/n\mathbb{Z})$ for all such values.  I can't think of another way to do this.
Comment: I need to know if I am right. There are 3 abelian gruops of order $8$. Then my answer to the problem have to be $3$ or less gruops, right? I friend told me that the number of grups are $5$,I think him is counting the non abelian groups
Comment: yes, I was right... your help was very useful!
Comment: Yes, there are only 3 abelian groups of order 8.  There are 5 groups of order 8, the other two nonabelian groups being the quaternions and the dihedral group of order 8.  The answer to the problem should be 2 groups.  There is one abelian group of order 8 that is not realized as the group of units of $\mathbb{Z}/n\mathbb{Z}$.
Comment: yes, my answers are the same. thank you


What is the difference between a probability measure and a probability density function?

Question: During my research, I have repeatedly come across the terms probability measure and probability density function (pdf). I am familiar with the concept of a pdf, but I am not entirely sure how probability measures relate to pdfs, or where exactly the differences lie in theoretical terms. I have since combed StackExchange (such as this and this question), and visited the Wikipedia article for probability measures, but I still cannot see the difference, so I imagine I must be missing a nuance.
Hence my question: Could you check my understanding, and - if necessary - correct it?
To provide an example for context, let us consider the continuous-valued example of human body height. Let us denote the height of a person in meters as a random variable $X$, which maps a person's physical height to a corresponding real value $x$. In that case:

we could define a probability density function $p(x)$ over all theoretically possible heights $x$. The pdf must be non-negative for all $x$, i.e. $p(x)\geq0 \; \forall \; x$, and it must integrate to $1$, i.e. $\int_{-\infty}^{\infty} p(x) dx=1$. We can integrate $p(x)$ over subintervals to learn the probability that a person's height is in this interval.

the definition of a probability measure seems related. Let us denote the set of all possible body heights $x$ as $S_1$. Based on this set, we design another set $S_2$ which contains $S_1$ and all possible subsets of $S_1$. The probability measure then assigns values between $0$ and $1$ to each entry in $S_2$, with the condition that the entry $\{\text{all }S_1\}$ in $S_2$ is assigned $1$, $\{\}$ is assigned $0$, and certain additivity properties are met (see the image below, taken from Wikiedpa)

Concerning my understanding of the difference: A pdf $p(x)$ can assign values $\geq1$ to $x$, as it describes a density and only requires that the integral over all $x$ be equal to $1$. The limitation of probability measures to values below $1$ would probably correspond to a role more similar to integrating (vanishingly small) sub-intervals of $p(x)$. Is this the distinction between pdfs and probability measures? Why is this distinction important? Am I missing or misunderstanding something?
Comment: PDFs, by definition, exist only for measures absolutely continuous with respect to a reference measure (usually Lebesgue).  https://stats.stackexchange.com/questions/298293 is relevant.
Answer: A probability density function induces a probability measure with Reimann-Stiljes integration, but the space of probability measures is bigger. Take, as an example, the Cantor distribution which has no probability density function, but whose distribution function, the Cantor function, meets criteria of a probability measure, (i.e. it is cadlag, tends to 0 as $x \rightarrow -\infty$ and tends to 1 as $x \rightarrow \infty$). The Cantor function is an intuitive and elementary example in measure theory of a function that is continuous measurably everywhere, has derivative of 0 measurably everywhere, but is not constant.
Comment: Or just take the singular point mass at zero for the sure event.
Comment: (+1) he Cantor distribution has density uniformly equal to one wrt the Cantor measure!


Compile files from URLs in table as zip

Question: I've got a Views table with a column displaying links to files (images, pdf's etc.). I've got a button below the table that exports the entire table. I need another button that should start a .zip download of all images currently shown in the table. The table has a filter on it, so it's important that only the files from the filtered results are downloaded.
I haven't been able to find a module or similar use case, so I hope there's someone here that can point me in the right direction.
Cheers,
Answer: Enable the PHP input filter and add a text area to the footer of your view, then use something like the following to build an array of all of your files (taken from this tutorial):
<code><?php
function views_get_current_view_result() {
  $view = views_get_current_view();
  return $view->result;
}
?>
</code>
And then use that array to build the zip according to download multiple files as zip in php
This would be a lovely idea for a views display handler plugin module, which many would probably find useful.

Compile files from URLs in table as zip


Is it always true that $\operatorname{Mat}(L)^n = \operatorname{Mat}(L)\operatorname{Mat}(L)\cdots (n\text{ times}) = \operatorname{Mat}(L^n)$?

Question: Is it always true for a matrix of a linear transformation that $$\operatorname{Mat}(L)^n = \operatorname{Mat}(L)\operatorname{Mat}(L) \cdots (n\text{ times}) = \operatorname{Mat}(L^n) \text{?}$$

$\operatorname{Mat}(L)$ is the equivalent matrix expression of a linear transformation $L$ in $\mathbb{R}^n$.
$L^n$ means $n$-times function composition of function $L$.
Comment: I think it might be better to say it is equal to $L\circ \cdots \circ L$, where $\circ$ denotes composition. Unless of course your notation $L^n$ is indeed shorthand for repeated composition.
Comment: @CameronWilliams Doesn't matrix multiplication equal function composition? This question also sort of concerns, whether it actually does.
Comment: It does. I was just taking a little issue with the notation $L^n$ since it is slightly ambiguous. Some people mean $f^n(x)$ to be $f(x)^n$; others mean $f^n(x)$ to be $(f\circ \cdots \circ f)(x)$. At any rate, $\operatorname{Mat}(L)^n = \operatorname{Mat}(L\circ\cdots\circ L)$.
Answer: Yes. Given a basis, the map, which sends a linear map to the matrix w.r.t. this basis is a $K$-algebra isomorphism, in particular the claim in your question holds.
Of course its important, that we use only one basis and not two different bases (The identity map is idempotent, but a base change matrix of two bases, which is just the matrix of the identity map w.r.t. these bases, is not).


How to count the number of calls to a rest service?

Question: I created a rest service which every user on the site calls from a product we are selling.
How do I count the number of calls for every user so I can generate a report of this.
D8
Answer: Do your REST service needs authentication?
If yes, you just log each access attempt by users:
One attempt per one record per user or one record per user and updating the count column always.
If there is no authentication, you will have harder time to achieve this.
It would be also good to know HOW they are making this rest calls (eg: clicking on a button which resolves into a rest call?).
You could still try to check session and find out which user made the requeset.
Comment: The rest service is called from by a VBA script in a excel sheet which we make as well. There is no authentication (besided the fact how to arrange that :-) but if that's part of the solution we will created that. The script is calling this url, we return josn data or [] that's it.
Comment: Well if you have no authentication, and the rest call is also no made from on the webpage, where you could have had the user session, currently there is no way to determine who made the request!
Comment: Ok how to add authenciation and to count then?
Answer: You can create a new Content Entity. With this entity you can save all calls on the rest service (p.e. user, url or product, time, ...).
Drupal creates a database table for each entity and with the ContentEntityBase it is easy to save new entries, read all entries, read part of the entries, search or whatever you want to do.
There exists a big introduction & documentation
Addition
When you save all the calls you can easy read the calls out with the entity. And based on the informations you have saved, you can count the number of calls to your rest service and you can generate the report.
Code Examples

Create the module-folder example_module in modules/custom
Add the info-file:

modules/custom/example_module/example_module.info.yml
name: EXAMPLE MODULE
description: YOUR DESCRIPTION
package: YOUR PACKAGE

type: module
core: 8.x

Add the Class to create your entity

modules/custom/example_modules/src/Entity/ExampleEntity.php
<?php
namespace Drupal\example_module\Entity;

use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Defines the Example Module entity.
 *
 * @ingroup example_module
 *
 * @ContentEntityType(
 *   id = "example_entity_name",
 *   label = @Translation("Example entity"),
 *   base_table = "example_entity_name",
 *   entity_keys = {
 *     "id" = "id",
 *     "user_id" = "user_id",
 *   }
 * )
 */
class ExampleEntity extends ContentEntityBase {

  /**
   * {@inheritdoc}
   *
   * Define the base fields.
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the entity.'))
      ->setReadOnly(TRUE);

    // Save user_id as a string
    $fields['user_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('User'))
      ->setDescription(t('The associated user.'))
      ->setSettings([
        'max_length' => 255,
        'text_processing' => 0,
       ]);

    // You can replace the fields or add more. Feel free!

    return $fields;
  }
}

Enable the module: $ drush en example_module
Use the entity to save or load content. For example in a Controller of the rest service.

// Somewhere above the Controller
use Drupal\example_module\Entity\ExampleEntity;

// Create a new entry
$user_id = Drupal::request()->get('user');
$entityContent = array(
  'user_id' => $user_id,
);
$exampleEntity = ExampleEntity::create($entityContent);
$exampleEntity->save();

// Load entries by user_id
$entityTypeManager = Drupal::entityTypeManager();
$exampleEntityStorage = $entityTypeManager->getStorage('example_entity_name');
$entries = $exampleEntityStorage->loadByProperties($entityContent);
// Now you can count the entries.

Be careful, there are different ways to work with Drupal and different ways where to place your own code. Without seeing your code base I can only help with this "default way".
Comment: You didn't mention anything about the solution. I don't know how is your answer relevant in any way.
Comment: If I misunderstood the question (How to count the number of calls to a rest service?), sorry!

I understood that @Justme wants to count the number of calls. So probably the solution could be to save each call (with a new Content Entity) and after that you can count them by reading out of the new Entity.

Probably the question is not really clear, I see that we (@ssibal and me) have different understandings about it's content.
Comment: @btemperli, I don't know if you misunderstand me. The only thing I see is that is for me not clear how to implement your solution. I understand the idea but how to do it is for me not clear. Sorry for this.
Comment: @Justme I added now an example where you can see how to do it. Does this helps for you?


Converter string para data

Question: Preciso fazer com que uma função incremente X dias a uma data. O problema é que a data está vindo como string nesse formato: dd/mm/yyyy e na hora de atribuir o X dias a essa data, diz que não reconhece a var que será incrementada em X dias, como: var_tal is not a function. Como eu procedo? aqui está o exemplo no fiddle.
Dessa forma não funciona:
var dt_exclusao = '26/11/2015';
var periodo = 60;
var nova_data = new Date(dt_exclusao);
    //alert(dt_exclusao.setDate(dt_exclusao.getDate() + periodo));
    alert(nova_data);
    alert(periodo);
    nova_data.setDate(nova_data.getDate() + periodo);
    alert(nova_data);

Mas assim funciona, isso quer dizer que é o formato passado que reside o problema:
var dt_exclusao = '2015-11-26T00:00:00';
var periodo = 60;
var nova_data = new Date(dt_exclusao);
    //alert(dt_exclusao.setDate(dt_exclusao.getDate() + periodo));
    alert(nova_data);
    alert(periodo);
    nova_data.setDate(nova_data.getDate() + periodo);
    alert(nova_data);

No fiddle funcionou, mas na página não. A função na página está assim:
function montaDataSubstituicaoPrestador(dt_exclusao, periodo){

    var arrData = dt_exclusao.split('/');
    var novaData = new Date(arrData[2] + '-' + arrData[1] + '-' + arrData[0]);

    alert(arrData);
    alert(dt_exclusao);
    alert(periodo);
    alert(novaData);
    novaData.setDate(novaData.getDate() + periodo);
    alert(novaData);
}

A grande diferença é que fiddle eu coloco na mão o dt_exclusao e na função eu recebo. A data montada em novaData vem assim: NaN. O arrData está correto, tipo: 26,11,2015, mas a montagem dá erro NaN.
Comment: Não adianta passar `dd/mm/yyyy` para `new Date()`. Você já achou um formato alternativo que é aceito, por que não usá-lo?
Comment: No seu fiddle, não há objeto Date, não irá funcionar mesmo.
Comment: Não? O Pedro Camara Junior explica exatamente como fazer.
Comment: Mas aqui tem o fiddle funcionando: http://jsfiddle.net/ivanferrer/8hz20pkL/
Comment: @bfavaretto, a data já vem de uma outra função que pega do banco nesse formato `dd/mm/yyyy`todo o meu problema é que eu não estou conseguindo transformar de um formato`(string - dd/mm/yyyy)` para o aceito. Esse é o motivo do post.
Comment: Quebre o valor com split como sugeriu o Pedro
Comment: Em realidade essa é outra pergunta, ainda que para a mesma função. Aqui eu pergunto com relação a como passar de string para data, logo não foi respondida ainda.
Comment: Não tinha visto a discussão aqui, está funcionando agora @pnet ?
Answer: O construtor new Date() com string deve ser no formato mm-dd-yyyy ou mm/dd/yyyy ou pode ainda utilizar o construtor com inteiros new Date(yyyy, mm, dd)
Referência: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date
No teu caso, você precisa converter a string para um desses formatos, pode fazer isso utilizando o split(), e depois acessar os valores do array gerado para utilizar no construtor que prefirir.

Nota: Quando usar construtor com inteiros, o mês começa em 0, por isso adicionei no construtor -1.

var dataExclusao = '26/11/2015';
var arrDataExclusao = dataExclusao.split('/');

var stringFormatada = arrDataExclusao[1] + '-' + arrDataExclusao[0] + '-' +
  arrDataExclusao[2];
var dataFormatada1 = new Date(stringFormatada);
var dataFormatada2 = new Date(arrDataExclusao[2], arrDataExclusao[1] - 1, arrDataExclusao[0]);

console.log('Data formatada 1: ' + dataFormatada1);
console.log('Data formatada 2: ' + dataFormatada2);

dataFormatada1.setDate(dataFormatada1.getDate() + 60);
dataFormatada2.setDate(dataFormatada2.getDate() + 90);

console.log('Data formatada + 60 dias: ' + dataFormatada1);
console.log('Data formatada + 90 dias: ' + dataFormatada2);
Answer: O construtor Date (bem como o método Date.parse) é bem restrito no formato aceito. O formato é esse que você citou:
YYYY-MM-DDTHH:mm:ss.sssZ

O Z refere-se ao fuso horário UTC. Tem browser que até aceita outros formatos, mas como eles não são mencionados na especificação, é melhor usar esse mesmo.
Uma alternativa a esse formato é passar as partes da data como parâmetros separados:
var hoje = new Date(2015, 10, 26);

Converter string para data


Web Service/WCF Newbie: Create WCF Proxy Client/Object against Java-based SOAP Web Service

Question: I have a .Net web application that needs to interact with a Java-based system via SOAP.
I have not worked with web services other than some basic WCF and would appreciate any guidance on this.
Basically, I was thinking about creating a WCF proxy client to connect to the SOAP web services. The system is a 3rd party Java-based system that provides a SOAP interface.
The sample code provided used wsdl to generate the proxy, but isn't that before the times of WCF?
UsernameToken aToken = new UsernameToken("root", "root", PasswordOption.SendPlainText);

MetadataService.MetadataService aMetadataService = new MetadataService.MetadataService();

SoapContext aContext = aMetadataService.RequestSoapContext;

aContext.Security.Tokens.Add(aToken);

String aXmp = aMetadataService.s_getXmpFromRecordID(wAssetId.Text);

Any suggestions?
Thank you!
Answer: The WSDL is all you need to generate a client proxy for the web service. And no, this is not before the times of WCF. WSDL was designed specifically for this purpose.
The simplest solution is to use svcutil to create the code.
You call svcutil with the WSDL of the web service and you get back the client code along with the configuration for it.
You then call the operations of the web service as methods on the client instance. It's as simple as that!
For example, lets consider a basic web service like this one: http://www.startvbdotnet.com/web/sample2.asmx (it's basic math exposed as a web service which I found by google-ing).
To generate a client for this I would use svcutil like so:
svcutil http://www.startvbdotnet.com/web/sample2.asmx?wsdl

This command will generate the Sample.cs and output.config files (the code and configuration for the client).
You add these to your project (along with needed assemblies like System.ServiceModel and System.Runtime.Serialization) and now you can call the web service with code like this one:
using (SampleSoapClient proxy = new SampleSoapClient())
{
    Console.WriteLine(proxy.Add(6, 2));
    Console.WriteLine(proxy.Substract(6, 2));
    Console.WriteLine(proxy.Divide(6, 2));
    Console.WriteLine(proxy.Multiply(6, 2));
}

WCF makes things easy. Adding security is also simple with use of proper configuration or attributes on the service classes.


Change $\sigma$ to $\log \sigma$ in Normal Distribution

Question: I would like to Change $\sigma$ to $\log \sigma$ in Normal distribution,
$$
P(x) = \frac{1}{{\sigma \sqrt {2\pi } }} \exp \left\{{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right.} {2\sigma ^2 }}} \right\}.
$$
I know so far the transformation of random variables such as $f_{X,Y}$ to $f_{U,V}$ where $X\sim {\rm beta}(\alpha, \beta), \ Y\sim {\rm beta}(\alpha + \beta, \gamma)$, $U=XY$ and $V=X$.
But if I want to transform the parameter, such as $\sigma$ above, how should I deal with it?
Answer: You can just replace $\sigma$ in
$$ P(x) = \frac{1}{{\sigma \sqrt {2\pi } }} \exp \left\{{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right.} {2\sigma ^2 }}} \right\}$$
with $\exp{\ln{\sigma}}$, thereby yielding the following
$$ P(x) = \frac{1}{{\exp{\ln{\sigma}} \sqrt {2\pi } }} \exp \left\{{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right.} {2(\exp{\ln{\sigma}})^2 }}} \right\}$$
which can be further rewritten as follows
$$ P(x) = \frac{1}{{\sqrt {2\pi } }} \exp \left\{{{{ - \left( {x - \mu } \right)^2 } \ln{\sigma}\mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right.} {2\exp{(2 \ln{\sigma})} }}} \right\}.$$
Since $\sigma$ here is a fixed parameter rather than a random variable, no further details are necessary. However, should $\sigma$ be a random variable with probability $P(\sigma)$, and should you want to use $\ln \sigma$ there, namely $P(\ln \sigma)$, then you should change $P(\sigma)$ accordingly.
Is that what you want? Does this helps? If not, could you reformulate the question? Thanks.
UPDATE:
It seems to me that what they are doing in that post is analogous to the following $$\int{f(x) P(x|\sigma) P(\sigma) d\sigma dx}$$ and that they tried to compute this but directly replacing $\sigma$ with $\ln{\sigma}$. In order to obtain the same results, the integral must be expressed as $$\int{f(x) P(x|\ln{\sigma}) P(\ln{\sigma}) \frac{1}{\sigma} d\sigma dx} $$, that is, by taking into account that changing $\sigma$ into $\ln\sigma$ also changes the differential within the integral. The result would be perhaps clearer is we write $\sigma=\ln{u}$. In that case, the integral would read $$\int{f(x) P(x|\ln{u}) P(\ln{u}) \frac{1}{u} du dx}. $$ I may be wrong about what they tried to do in that post, but this may hopefully help you anyway.
Comment: If you multiply $X$ by $\frac{\log(\sigma)}{\sigma}$ then the new variance will be $\log(\sigma)^2$. However $\mu$ becomes $\frac{\log(\sigma)}{\sigma}\mu$. Is the the latter fact the one that disturbs you?
Comment: I was looking at [this post](http://stats.stackexchange.com/questions/261768/make-a-standard-deviation-always-positive-in-metropolis-hastings/261786#comment500945_261768) which says we need to consider the Jacobian of the transformation. That's why I'm confused.


Compound (double) inequality

Question: Just want to understand why we have a specific approach to solving double inequalities for example separating the statement $-6 < 2x-4 < 12$ into two components. Working left two sides first and then the right two sides etc.
What is troubling me is this. The following statement is true.
$1 < 2 < 3$
In words, 3 is greater than 2 which is greater than 1. Let x = 2 therefore:
(x-1) < x < (x+1)
The standard approach doesn't work anymore (I think) so if you work from left hand side,
x - 1 < x
x - x < 1
and whilst 0 is less than 1 which is true, there is no x variable to work with. Shouldn't this somehow return something like x > (0, 1, or any number less than 2) and x < (10, 20, or any number greater than 2)?
Why is that?
Or what am I doing wrong?
Thank You.
Comment: Can you explain what you are doing on both sides?
Comment: When you eliminate a variable... well, you eliminate a variable.  $x-x < 1$.  What don't you understand about that?
Comment: Thank you for your comments. Sorry for the confusion caused.

If I told you x was equals to 2, $(x-1) < x < (x+1)$ would become $1 < 2 < 3$ which is true. But what if I didn't tell you x was equals to 2, how would you find out what x might equal to just by looking at $(x-1) < x < (x+1)$ ?
Answer: Well, in your case, you assumed
$(x-1) < x < (x+1)$
is true when $x=2$, but you also have to consider that $(x-1) < x < (x+1)$ is true for all real values of $x$, therefore it has no definite value which you can 'return' to.
You can try:
$x=1: 0 < 1 < 2$
$x=100: 99 < 100 < 101$ and the list goes on
And, as a side note, we can see that the $x$'s cancel each other out, just like in an equation. For example, in
$x + y = x + 3$
$x$ can take on any value and the equation will remain solvable over $y$.
So: $(x-1) < x < (x+1) \rightarrow  -1 < 0 < 1$
Comment: I really appreciate your response. And yes, you are right in saying that any real value of x would satisfy the statement $(x−1)<x<(x+1)$.

Thanks a lot.
Answer: I believe you are fundamentally misinterpreting how you are using variables in your example. In order to explain why, you must first understand what you are claiming. To say

Shouldn't this somehow return something like x > (0, 1, or any number less than 2) and x < (10, 20, or any number greater than 2)?

is the same as saying
$x > 0, 1, 1.5, 1.9, 1.99, ...$
and
$x < 100, 10, 5, 2.5, 2.1, 2.01, ...$
We can equivalently say that $x \geq 2$ and $x \leq 2$. When you take these two inequalities together, you get $x = 2$.
However, $x-1 < x < x+1$ is a different claim altogether. Yes, $x = 2$ is one solution to this set of inequalities, but there are infinitely many other solutions. For example, if $x = 7$, then $6<7<8$.
Therefore, you can play around with the inequalities, but you are not going to find the single solution $x = 2$ because the inequalities have more solutions, infinitely more in fact.
Comment: Thank you for your time. I should have experimented with a range of values to see how the results might differ.

Compound (double) inequality


What is the strongest possible statement of the idea that "the tangent line is the best linear approximation"?

Question: For instance, I've just checked that that if you take the best linear approximation (in the $L^2$ sense) to a sufficiently nice function $f$ on the interval $[-\varepsilon, \varepsilon]$, and then let $\varepsilon \to 0$, you get $f(0) + x f'(0)$.
Surely we could make this stronger -- I imagine the analogous statements should hold for, say, the $L^1$ norm as well, or for most reasonable norms.  Can we go farther, though?
Question: What is the strongest precise definition we can give the word "best" so that we have a statement of the form "the tangent line is the best linear approximation to a differentiable function"?  (Feel free to replace "differentiable" with, say, $C^2$ or something if it makes for a more interesting answer.)
(Note: I'm aware of similar-sounding questions here, such as In what sense is the derivative the "best" linear approximation?, but the answers there don't answer my question.)
Comment: $\mathcal C^2$ is stronger than differentiable.
Comment: @gperez By "weaken" I meant "state a weaker *result*," e.g. one that's only valid for $C^2$ functions and not arbitrary differentiable functions.  But maybe that's not in line with common usage.  I've edited to remove any possible ambiguity.
Comment: @mattbiesecker: Yes, but that doesn't *a priori* rule out that your best approximations in various norms could converge to the same thing as $\varepsilon \to 0$.  Or do you have an example where you get something other than the tangent line in this scenario?
Comment: Forget common usage, [logic has an answer](https://math.stackexchange.com/questions/167016/stronger-condition-lead-to-weaker-result). So you were right, I just didn't see that you were referring to the result. So Differentiable is a weaker hypothesis than $\mathcal C^2$, but a result on Differentiable functions is stronger than one on $\mathcal C^2$ functions. Nice duality.
Comment: @DanielMcLaury There are weighted norms where it fails but I don't know of a counterexample for the $L^p$ norms.   I may very well be true (it seems to be true for any polynomial $f(x)$)
Comment: How do you define "best"? Anything close to "best fitting curve" technique? E.g. http://web.iitd.ac.in/~pmvs/courses/mel705/curvefitting.pdf
Comment: @rtybase: The question is about how we can define "best."  That said, I'm not sure I see how you can make a meaningful statement here involving linear regression that's not just strictly weaker than the $L^2$ thing I mentioned above.
Comment: @mattbiesecker: Can you give an example of a weighted norm where it fails?
Comment: @DanielMcLaury.  I retract my earlier conjecture about weighted norms.   I check enough examples (oddball weighted norms, sobolev norms)  to believe it is plausible your $L_2$ result my indeed be= true  for any norm  (at least for  $f \in C^1$)
Answer: If $f$ is differentiable at $0$ the the same statement holds with uniform approximation instead of $L_2$.
Proof:
Let $T(x) = f(0) + xf'(0)$.
By the definition of differentiability we have
$$ f(x) - T(x) = \mathcal o(|x|) $$
and thus
$$ \sup_{|x|\le\varepsilon} |f(x) - T(x)| = \mathcal o(\varepsilon).$$
So this would also be satisfied by the best approximation on interval $[-\varepsilon, \varepsilon]$ say $g_\varepsilon$.
In particular, for any mapping $\varepsilon\mapsto x_\varepsilon \in [-\varepsilon, \varepsilon]$ we have
$$ |f(x_\varepsilon) - g_\varepsilon(x_\varepsilon)| \le \sup_{|x|\le \varepsilon} |f(x) - g_\varepsilon(x)| \le \sup_{|x|\le \varepsilon} |f(x) - T(x)| = \mathcal o(\varepsilon).$$
Hence, we have
$$g_\varepsilon(0) = f(0) + \mathcal o(\varepsilon)$$
and
$$ g_\varepsilon' = \frac{g_\varepsilon(\varepsilon) - g_\varepsilon(-\varepsilon)}{2\varepsilon} = \frac{f(\varepsilon) - f(-\varepsilon)}{2\varepsilon} + \mathcal o(1) \to f'(0).$$
For $L_p$ average, $1\le p < \infty$:
Fix some $p\in [1,\infty)$.
For any measurable $\phi$ denote its average $L_p$ norm by
$$N_\varepsilon \phi = \sqrt[p]{\frac{1}{2\varepsilon} \int_{-\varepsilon}^{\varepsilon} |\phi(x)|^p\,dx}.$$
Let $g_\varepsilon$ be a $L_p$ best approximation on $[-\varepsilon, \varepsilon]$. Then, we also have
$$ N_\varepsilon (f - g_\varepsilon) \le N_\varepsilon (f - T) = \mathcal o(\varepsilon). $$
and
$$ N_\varepsilon (g_\varepsilon - T)
\le N_\varepsilon (f - g_\varepsilon) + N_\varepsilon (f - T) = \mathcal o(\varepsilon). $$


Autoplay YouTube video (privacy-enhanced mode) in fancybox 3

Question: It is possible to autoplay a regular YouTube video in fancybox by appending ?autoplay=1 to the video URL:
video

… and …
$(document).ready(function(){
    $("a.lightbox").fancybox();
});

Unfortunately in some browsers (Chrome, Safari) this doesn't work if the "privacy-enhanced mode" is enabled (youtube-nocookie.com):
privacy-enhanced mode video

The option autoplay=1 is not fully supported on youtube-nocookie.com.
How can I still have the video automatically played in the lightbox with privacy-enhanced mode?
Edit (Mar 23):
Firefox, Chrome and Safari start playing the video immediately on https://www.youtube.com/embed/zRwBVYjUBOc?autoplay=1 (also without fancybox – just open the url). I found out that Firefox still starts to play the video on https://www.youtube-nocookie.com/embed/zRwBVYjUBOc?autoplay=1 , only Safari and Chrome don't.
Comment: Could this be cause of the issue? - https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Comment: @Janis I don't know if Google's decision has something to do with this. I guess it may be related to the european General Data Protection Regulation. A solution to my issue might be something via `afterLoad : function() {}` of fancybox. The user has already clicked on a link to open the video in fancybox, so this is no autoplay on load, but on click.
Comment: @Ben maybe I misunderstood your issue but this is a working example with the two modes: codesandbox.io/s/y0kmrk51lj
Comment: @Fraction Thanks! I first tried it with Safari: my first click on "privacy-enhanced mode video" opened fancybox, but the video did not start playing. After closing fancybox and clicking on the same link again, it worked: Fancybox opened and the video started to play. In Firefox it worked immediately on first click. Thanks to your example I found out that the ?autoplay=1 parameter works in Firefox, when I open the URL https://www.youtube-nocookie.com/embed/zRwBVYjUBOc?autoplay=1 , but not in Chrome or Safari.
Comment: If you open the link in a new tab (middle click the link with your mouse) it works. If you open it in the same tab, it doesn't work... I'm in Chrome
Comment: @Rojo: I can't repoduce this. Openening this Link ...
https://www.youtube-nocookie.com/embed/zRwBVYjUBOc?autoplay=1
... in a new tab (chrome, either regular or incognito mode) does not start playing the video.
Comment: @Ben just add an answer yourself saying it's impossible and mark it as correct so other people don't come and add other random answers
Comment: @Rojo I'm not sure if it really is impossible and still try to find a solution.
Answer: Not entirely sure how this youtube-nocookie is supposed to work but you can surely trigger a click with javascript...
$('video').click();

If the video is in an iframe, you should still be able to do this;
$('iframe').contents().find('video').click();

Comment: No, I perfectly understood the question. You have misunderstood the answer. "Triggering" a "click" means, doing it by code without a user interaction.
Comment: I think you misunderstood the problem. I don't want the user to click in the video. When the user clicks on the the link this opens a lightbox and generates an iframe with the video. I would like to start playing the video immediately without any further user interaction.
Comment: Sorry. You're right, it was me who misunderstood it. I tried your example, but it does not work (Safari and Chrome):  https://codesandbox.io/s/jnzwqr6q7w
Comment: I just found out that the initial problem does not affect all browsers. See my edit above.
Comment: Can you setup a fiddle with fancybox and you're video - I'll have a look.


Analytic characteristic function convergence

Question: This feels a bit silly, but I can't seem to find a nice reference. I have a weakly converging sequence of random variables $X_n \Rightarrow X$. The characteristic functions $\phi_n(s) := \mathbb{E}[e^{isX_n}]$ are analytic in a fixed complex neighborhood $N$ of $0$ and converge uniformly on compact subsets of $N$ to an analytic function $\psi(s)$ on $N$.
By Levy continuity, $\phi(s) := \mathbb{E}[e^{isX}] = \psi(s)$ for $\mathbb{R} \cap N$. I want to conclude that
$$\psi(s) = \mathbb{E}[e^{isX}] \qquad\text{for all }s \in N.$$
Can I do so? Moreover, is it written down somewhere? It just seems like such a natural thing to want, but none of the sources I've looked at (e.g. Billingsley) talk about it, so I'm probably looking in the wrong places.
Answer: This follows from Lukacs, Characteristic Functions, 2nd Edition (1970), Thm. 7.1.1 and the discussion preceding it (p. 191-193). As you would expect, Lukacs shows that if a characteristic function agrees with an analytic function in a neighborhood of the origin, then $\mathbb{E}[e^{izX}]$ agrees with that analytic function in a strip $-\alpha < \mathrm{Im}(z) < \beta$, which is exactly my desired conclusion.