O que o C++ pode fazer que o C# não pode?

Question: Sendo um programador .Net mas com uma antiga paixão por C++ (que cresceu desde o C++11), estive com essa curiosidade.
Eu sei que o .Net pode ser "extendido" com o C++/CLI, mas eu gostaria de saber o que o C# puro não consegue fazer, enquanto o C++ consegue.
Nota: Eu não quero opiniões aqui, e também não quero iniciar uma guerra das chamas. Eu quero fatos. Eu só quero saber o que o título da pergunta diz, não quero saber se você prefere uma linguagem ou outra porque é mais fácil fazer X nela.
Atualização: Depois de 4 respostas e algumas horas, estou julgando a do @utluiz como a que melhor respondeu a minha pergunta, portanto estou marcando como aceita. A do @FlávioGranato também é boa, mas achei a do @utluiz mais correta.
As duas outras respostas falam principalmente sobre o framework e a performance, que são óbvios para quem não é novato no assunto. Não estou dizendo que foram más respostas, só não foram respostas boas para essa pergunta. (Fora o fato que o framework é bem estável e performance não é um assunto crítico.)
Comment: pergunta aberta (não específica), muito suscetível a opniões, sujeita a tipos diversos de resposta. Voto pra fechar...
Comment: Talvez o principal seja rodar em ambientes não-MS-Windows.
Comment: @user2478690 Já ouviu falar do [Projeto Mono](http://www.mono-project.com/Main_Page)?
Comment: C++ pode te dar um salário de mais de quatro casas decimais.
Comment: Não é a resposta direta à sua pergunta mas é um adendo interessante: "C# é mais lento que C++ por que ele roda em uma máquina virtual e não na máquina nativa".
Comment: Como eu já disse, você está fazendo um tipo de pergunta que não está bem definida/descrita, portanto as respostas que aparecem são dispares, baseadas no que cada um entende da pergunta que está confusa, e não estou falando de vontade de dar uma opnião qualquer, o fato é que, não há como fugir disso, pois o próprio entendimento da questão está a escolha do leitor, e o próprio entendimento de respondido está da sua parte, e não uma coisa que se diga imparcial.
Comment: @Renan A piada foi boa, mas ainda acredito que o que faz o salário depende mais do programador do que da linguagem xD (e, infelizmente, depende mais do mercado do que do programador -- apesar de eu amar C++, quase não existe mais mercado pra ele)
Comment: @pepper_chico Negativo. Se olhar minha nota e atualização, vai ver que, se tem algo que não estou aceitando aqui, são opiniões. Antes de votar para fechar, veja como é a aceitação dessas perguntas no SOpt.
Comment: @alacerda O C# não é executado por uma máquina virtual. O código é compilado em código nativo no momento da execução por um compilador JIT.
Comment: @bigown Eu não tinha me atentado muito a sua resposta. Mas ela está perfeita.
Comment: Eu resolvi responder porque achei que nenhuma resposta passava nem perto do que você queria. Perfeito é exagero seu, mas tentei achar tudo o que é importante de diferente :)
Answer: Resumo:

Sistemas operacionais viáveis, drivers para sistemas operacionais existentes ou qualquer operação que precise acesso direto ao hardware.
Gerenciamento e otimização manual de memória inclusive permitindo aplicações real time.
Metaprogramação com templates e pré-processamento.
Herança múltipla.
Manipulação livre de ponteiros.
Uma série de pequenas funcionalidades sintáticas e semânticas.

Alguns já disseram que em tese pode-se fazer tudo. Claro que isto é verdade e é claro que há diferenças de como fazer e do resultado obtido. Algumas coisas são mais fáceis de fazer em uma linguagem do que eu outra. De uma certa forma, o pedido de não falar sobre o que é mais fácil elimina qualquer coisa que dê para falar da linguagem em si. Como eu acho que tem maneiras objetivas de falar das facilidades vou tentar responder.
Ambiente

Permite o uso em virtualmente qualquer plataforma enquanto que o C# essencialmente só funcionam em todas as plataformas mainstream, que são as que mais importam, os 3 principais desktops, os 3 principais mobiles e diversos servidores.
Roda sem a dependência de um runtime grande. As aplicações podem ficar bem enxutas. C# melhorou um pouco isso.
Não precisa JITtar o código antes de executar. Agora existe o .NET Native.
Acesso direto ao hardware e sistema operacional permitindo a criação de drivers, por exemplo.
Integração mais fácil com C.

Gerenciamento de memória

Tem controle absoluto sobre o gerenciamento de memória.
Permite controle total do layout e local de armazenagem das estruturas de dados. Dá para economizar até o último byte e colocar no local ótimo para a situação.
Liberação determinística de recursos como parte do objeto, impedindo que a liberação seja esquecida porque não colocou um using.
Permite a implementação de algum garbage collector.

Otimizações

Permite buscar otimizações que economizam o último ciclo do processador. E tem algumas otimizações mais agressivas no compilador.
Economia de memória em diversos aspectos.
Aplicações "totalmente" real time. Alguns games com main loop muito pesado sem folga para coleta de lixo só são viáveis em C++.
Se vale de comportamentos indefinidos para obter otimizações e capacidades de acordo com a plataforma.
Usa os dados numéricos básicos com o layout mais adequado para a plataforma.
Inclusão de código Assembly.
Ter implementações genéricas totalmente em tempo de compilação.
Economiza o overhead da vtable quando ela não é necessária.
Existem mais escolhas para otimizar códigos mantendo a semântica adequada (move semantics, inicializadores e constexpr por exemplo).

Sintaxe

Criar pseudo-sintaxe e utilizar outras "facilidades" do pré-processador.
Agrupar as declarações de membros por visibilidade sem diretiva #region.

Tipagem

Possui union apesar do C# ter uma forma limitada.
Tem a segurança que referências (não confundir com ponteiros) não contêm valor nulo. C# terá algo assim.
Liberdade para criar hierarquia de objetos como quiser, sem uma hierarquia básica pré-definida.
Utilizar tipos além de bool como resultado para desvio condicional.
Tem vários tipos string por padrão.
Tem mais controle sobre constância de valores, incluindo coerção da constância.
As funções podem ter o tipo de retorno inferido.

Recursos específicos

Tem funções independentes que não precisam ser membros de classes.
Herança múltipla de classes abstratas, não só através de interfaces.
Utilizar uma sub-linguagem com templates que é absurdamente mais poderosa que generics. Só este item pode se desdobrar em diversos outros.
Permite goto de forma um pouco mais livre.
Permite criar literais para os tipos.
Há mais operadores que podem ser sobrecarregados.
Há mais controle na forma de captura de variáveis em closures.
O throw permite lançar qualquer classe.
Os ponteiros são bem mais flexíveis e poderosos, permite acessos arbitrários à memória.

Miscelânea

Escolha de uma gama mais ampla de modelos de memória para tratar paralelismo e concorrência.
Pode explodir seu computador e colocar seu cérebro em parafuso (é só piada, ok?)

Algumas dificuldades do C#, principalmente as primeiras listadas podem ser solucionadas em breve com o .NET Native. Por isto é bom ter em mente que o a dificuldade muitas vezes está na implementação da linguagem e não na linguagem em si. Algumas destas limitações são minimizadas há tempos com o Mono.
Alguém poderia dizer que C++ permite criar um sistema operacional ou pelo menos que seria mais fácil. C# também permite e é até mais fácil. Claro que ele pode ter algumas limitações, mas é possível e de fato já foi feito. Pode até precisar de auxílio de outra linguagem (Assembly), mas C++ também precisa.
Alguns itens poderiam gerar vários detalhamentos. Tem tantas coisas que a lista pode crescer indefinidamente.
Ter todas estas capacidades não significa que o C++ é melhor. É diferente. Até porque algumas destas coisas que o C++ pode fazer facilmente é interpretado como desvantagem. E o C# também tem muitas coisas mais "prontas" ou mais poderosas que o C++. Apenas a pergunta não tem interessa nisto.
Coloquei no GitHub para referência futura.
Answer: O C++ permite:

herança múltipla contra interfaces em C#.
gerenciamento manual da memória contra GC em C#.
templates contra generics em C#.
inline assembly.
Possibilidade de desalocar explicitamente um objeto com delete.
Comment: Lembrando que código C++ "moderno" evita ao máximo usar new e delete; usa-se objetos em pilha e "smart pointers", e o pattern RAII abençoado pelo Stroustrup :)
Comment: @utluiz Foi mal. Anotado e aprendido.
Comment: @AndréLeria Relendo a pergunta eu achei que você queria algo em termos de resultado final e não recursos de linguagem. Mas se está bom para você, ótimo!
Comment: Gerenciamento manual de memória é possível em C# também. http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
Comment: @Renan Embora Você pode deletar um objeto, isso não é o mesmo que desalocar a memória, apenas ocorre que o objeto fica eligível para coleta. Tanto que no link que você postou, o tópico *"Explicit Release of Resources"* diz que para liberar recursos abertos imediatamente é recomendado usar um método `Dispose`.
Comment: Quando eu disse `deletar`, na verdade estava falando do "destrutor" ser ativado, por exemplo, removendo as referências de variáveis para o objeto. Quem possui o `delete` é o C++ e não o C#.
Comment: Na verdade, acho que isso não responde à pergunta. Alguém acha que devo excluir?
Comment: Herança múltipla é sempre polêmico, rs. Acho válido como parte da resposta, mas pouco abrangente. Mesmo assim, +1
Comment: Não exclua. C++ pode, C# não. Não é isso?
Comment: Resultado final depende mais do programador do que da linguagem. Por exemplo, se fosse C++ vs Java, valeriam Lambda Expressions (e, semelhantemente, Herança Múltipla).
Answer: Como linguagem, C# não fica devendo em nada, nem em performance.
O problema do C# é que implica num framework que é controlado pela Microsoft, embora haja a implementação livre, o Mono/Xamarin, do Miguel de Icaza. Cheguei a usá-lo em aplicativo "sério" que tinha de rodar em Mac/Linux/Windows e o desenvolvedor alocado preferiu usar C#.
Se você desenvolve código cuja "durabilidade" deva ser muito longa, tem de pensar duas vezes em que poste vai amarrar o burro. Amanhã o framework muda, depois de amanhã ele pode ser abandonado... Veja o que aconteceu com as software houses que apostaram suas fichas no Delphi. Troca a versão do Delphi, quebra tudo, tem muita gente por aí presa a versões paleolíticas do Delphi porque o programa e/ou componentes de terceiros são incompatíveis com as versões novas.
Agora, se você vai fazer algo que não tem de manter por décadas, e é voltado mais à plataformas Microsoft, vá em frente e use C#. Se estiver fazendo apps para Windows Phone, onde por definição você depende umbilicalmente do framework, não há o que discutir.
Comment: +1 por citar o Mono, inclusive o Xamarim (baseado em Mono) é uma solução boa para o problema de desenvolver multi-plataforma para mobile.
Answer: C++ é turing-completo, C# também, então com esforço computacionalmente pode ser feito o mesmo com ambas. As limitações aparecerão devido ao ambiente sob o qual elas serão submetidas e não a uma limitação da linguagem.
Comment: @Renan ["completude"](http://pt.wikipedia.org/wiki/Turing_completude)
Comment: +1 por mencionar a completice (essa palavra existe) de Turing.
Answer:
Acesso direto a endereço de memória. Mesmo sendo extendido com C++ a VM não lhe permite acessar diretamente os endereços de memória.
Escrever drivers de hardware
Comment: O acesso aos endereços não é permitido com o `unsafe`?
Comment: @AndréLeria sim, é permitido com o unsafe. Acredito que com isso também seria possível escrever drivers de hardware.
Comment: @Flavio Citation needed na afirmação número 2.
Comment: @Renan http://stackoverflow.com/questions/75886/c-sharp-driver-development
Answer: Nada.
Ambas as linguagens são turing-completas, como o pepper_chico falou. Isso significa que pode ser muito mais fácil fazer algumas coisas em uma ao invés de na outra, mas nada que uma faça é impossível de fazer na outra.
Em último caso, é possível escrever um compilador C++ em C# e embuti-lo no programa C#.
Answer: Depende da tarefa. Se for crítica em performance o C/C++ é o recomendado. Por exemplo, desenvolvi uma aplicação que roda como serviço, coletando contadores de performance de processos. Ele faz exatamente o que foi projetado, mas tem um custo altíssimo de consumo de recursos se comparado com a versão que foi refeita em C++. São dois fatores de alto custo: memória com picos de consumo grandes e custo computacional com picos de 25 % de consumo.
Em um ambiente onde os recursos computacionais devem ser direcionados ao objeto fim, custos para monitoração não devem superar 3% a 5% do todo.
A versão em C++ está na fase de homologação, mas já mostrou excelente desempenho com baixo consumo de memória.
Comment: A pergunta se refere a recursos da linguagem, e não performance / uso de memória.
Comment: @AndréLeria então descreva melhor sua pergunta e não deixe-a tão aberta e suscetível a ser fechada. Do jeito que tá, voto pra que feche, por que não é explicita em nada e diz que não busca opnião mas é o único tipo de resposta que se encaixa à forma como ela está.


Distributed transaction rollback with Spring-Boot

Question: I am learning distributed transaction rollback with Spring-Boot.
I am using spring-boot 2.2 with JPA and H2 database.
In my example, I have three micro-services which are running on different ports, with their own H2 database.
MicroserviceA  --- http://localhost:2222/savePersonBasicDetails
MicroserviceB  --- http://localhost:3333/savePersonAddress
MicroserviceC  --- http://localhost:4444/savePersonHobbies
From the MicroserviceA, I will get Person_Id, which I will send to the remaining two microservices along with their respective data. If any of the microservices fails, then I want to roll back the complete transaction.
Example:
save(PersonVO personVO) {
<code>Integer personId = microserviceA.savePersonBasicDetails(personVO);

microserviceB.savePersonAddress(personId, personVO);

microserviceC.savePersonHobbies(personId, personVO);//If it fails in microserviceC,

                                              //then the complete transaction should be rolled back.
</code>
}
I tried with @Transactional(rollbackFor = Exception.class) on the save() method, but the transaction is not rolling back.
Please suggestion.
Answer: You are mixing the terms. Distributed transaction is a term associated with RDBMS, not with webservices. There is a webservice standard for transactions over webservice WS-TRANSACTION relevant to soap webservices. But this standard is mostly unused.
The usualy therm used in context of web services is Transaction Compensation and you can search it. A very common pattern for compensation is the Try Cancel Confirm pattern, there are also different aproaches.
If you insist on using distributed transactions check out this link:
https://www.atomikos.com/Blog/TransactionalRESTMicroservicesWithAtomikos
Comment: Thanks for the answer. I tried giving upvote, but for that it requires 15 points reputation. I don't know how to accept the answer.


spring batch example check update if record exist otherwise insert

Question: Have 2 tables Table1 and Table2.
Have to read from Table1 and save data to Table2.
Before saving to Table2 have to check if the record exist in Table2 if exist then update otherwise insert.
I am new to spring batch and trying to use it. Not sure how this can be done. I see examples online are all flat file to database.
Didn't find that does something like above. Any help is appreciated.
Comment: need help with this please.
Answer: What you are looking for like below
How can you replicate Hibernate's saveOrUpdate in JPA?
It has noting to do with Spring Batch
Answer: Write a custom ItemWriter (just a pseudo code)
class ItemWriter implement ItemWriter<Table2> {
  public void write(List<Table2> l) {
    for(final Table2 d : l) {
      boolean exists = <Check if item 'd' exists in DB>
      if(exists) then <perform update>
      else <perform insert>
    }
  }
}

If you have a Table2DAO which implements a method performing update/insert you can use an ItemWriterAdapter (google for some example)


The 'OraOLEDB.Oracle' provider is not registered on the local machine

Question: estou com um problema que me está a limitar o trabalho, é o seguinte, criei um WebService com uma connection string para uma base de dados em oracle :
OleDbConnection con = new OleDbConnection("Provider=OraOLEDB.Oracle.1;Persist Security Info=False;DATA SOURCE=********;USER ID=******;Password=*******");

Os (*)'s são para esconder a informação, de qualquer das maneiras quando corro o programa para correr a minha query dá-me este erro:

"The 'OraOLEDB.Oracle1' provider is not registered on the local
  machine"

Conseguem explicar-me o porquê ?
Eu tenho o Oracle instalado no computador e já coloquei o Target CPU em x64 e x86 e de nada resolveu.
Comment: Para tentar ajudar: https://stackoverflow.com/questions/6649363/microsoft-ace-oledb-12-0-provider-is-not-registered-on-the-local-machine
Comment: Ele está a usar Ace.Oledb e não Oracle, o erro é diferente, mas obrigado de qualquer das maneiras ! :)
Comment: Saquei, e esse link aqui: https://social.msdn.microsoft.com/Forums/pt-BR/79350e20-35b1-4f01-9f2c-929b8247e83b/o-provedor-oraoledboracle-no-est-registrado-na-mquina-local?forum=504
Comment: http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
Answer: Você precisa registrar o driver OLEDB:
1 - Verifique a pasta que contém o arquivo OraOLEDB11.dll. ('oracle\product\11.2.0\client_64\BIN')
2 - Abra o cmd como administrador
3 - Navegue até a pasta onde contém a DLL. Ex: cd\oracle\product\11.2.0\client_64\BIN
4 - Execute o registro:
regsvr32 OraOLEDB11.dll

Se não houver a DLL no seu computador, deve estar faltando a instalação do Oracle Client
Comment: Tentei fazer isso e não resultou, uma coisa, o meu bin estava numa pasta chamada server e não "Client_64"
Comment: tente colocar essa dll dentro da pasta system32 ou syswow64


SLTwitterComposeViewController message sent to deallocated instance

Question: I'm working on a cocos2d project on iOS6 and it crash time to time while I'm trying to share something on twitter.

It only crashes on physical device (iOS 6.1.3)
It runs without any problems on simulator (iOS 6.1)
The problem arises when [twitterViewController addImage:] is used
I'm using ARC
Update: the problem is the \n character on body

When I call shareOnTwitter function, it opens the twitter share. I can close or post and it dismiss the view fine. But the second, third or even more times you press the button it crash with EXC_BAD_ACCESS.
With Enable Zombie Objects I get this error:

[SLTwitterComposeViewController respondsToSelector:]: message sent to deallocated instance

It does not crash on any particular line on my code.
Stack:
<code>libobjc.A.dylib`objc_msgSend:
0x3ad3b5a0:  teq.w  r0, #0
0x3ad3b5a4:  beq    0x3ad3b5e6                ; objc_msgSend + 70
0x3ad3b5a6:  push.w {r3, r4}
0x3ad3b5aa:  ldr    r4, [r0]
0x3ad3b5ac:  lsr.w  r9, r1, #2
0x3ad3b5b0:  ldr    r3, [r4, #8]    <-------- Thread 1: EXC_BAD_ACCESS
0x3ad3b5b2:  add.w  r3, r3, #8
0x3ad3b5b6:  ldr    r12, [r3, #-8]
0x3ad3b5ba:  and.w  r9, r9, r12
0x3ad3b5be:  ldr.w  r4, [r3, r9, lsl #2]
</code>
Code:
<code>- (void)shareOnTwitter {

    UIImage *renderedImage = ...;

    NSString *text = ...;

    SLComposeViewController *twitterViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [twitterViewController setInitialText:text];
    [twitterViewController addImage:renderedImage];
    [twitterViewController addURL:[NSURL URLWithString:kAPPURL]];
    [twitterViewController setCompletionHandler:^(SLComposeViewControllerResult result){

        switch (result) {
            case SLComposeViewControllerResultCancelled:
                break;
            case SLComposeViewControllerResultDone:
                break;
            default:
                break;
        }

        [[CCDirector sharedDirector] dismissViewControllerAnimated:YES completion:nil];
    }];

    [[CCDirector sharedDirector] presentViewController:twitterViewController animated:YES completion:nil];
}
</code>
Thanks for your help!
UPDATE:
The problem is solved when I comment the line that adds the image:
<code>//[twitterViewController addImage:renderedImage];
</code>
Which made me doubt about my render image function, so I replaced the line with:
<code>[twitterViewController addImage:[UIImage imageNamed:@"email@example.com"]];
</code>
And the problem is noticeable once again. Weird right?
Comment: which line does it crash? call stack? ARC or MRC?
Comment: @LearnCocos2D I updated the post with more details. I'll create a new project to test this later, maybe I'm missing something somewhere.
Answer: Finally I got it! The problem was a return character on the message text. The most weird is that it seems to only occurs with certain text lenght and parameters sets.
Took me few hours to close up the problem and make an example that produces the app crash. It crashes in only certain circumstances. For example, with the text I'm providing, if you comment addURL it will not crash.
Pay attention to setInitialText in the following code, almost at the end of the text there is a \n character. That is the tiny problem...
<code>[twitterViewController setInitialText:@"########################## ###########? ########### ########: #######\n## #######"];
[twitterViewController addURL:[NSURL URLWithString:@"http://google.com"]];
</code>
Now, if you replace this lines on the same code that is in the question, the application will crash after some twitter view dismisses.
I created a new project and paste this same lines... it crashes. It may be a bug on SLComposeViewController


Fabric.js - How to select a specific object by type

Question: I'm trying to figure out how to grab a fabric object and change its properties when its moving. I have three different shapes. A fabric.Rect, fabric.Circle and fabric.Triangle. They all have different property values so if anyone knows how to change them accordingly that would be greatly appreciated.
This is how I tried doing it with no success.
canvas.on('object:moving', function(e) {
  var activeObject = e.target;
  activeObject.shadow = null;

   if (e.target = fabric.Rect){
    activeObject.height = 40;
    activeObject.width = 40;
    };

    if (e.target = fabric.Circle){
     activeObject.radius = 20;
     };

    if (e.target = fabric.Triangle){
     activeObject.height = 40;
     activeObject.width = 35
     };

});

Answer: function onObjectSelected(e) {
  console.log(e.target.get('type'));
}
canvas.on('object:selected', onObjectSelected);

Comment: I see what you did. Unfortunately, I have to have the event listener "object:moving." This is because I have a clone of the selected object. So instead could I not do this:

`canvas.on('object:moving', function(e) {

      var activeObject = e.target;
      var name = e.target.get('type');
      activeObject.shadow = null;

        if (name = circle{
         circle.radius = 20;
        };

    });`
Comment: yes, its fine. As long as you got what you want its good! Main was to get your object, that i was trying to convey you. [e.target.get('type')]
Comment: Thank you for your help. Unfortunately I am running into a RefferenceError as circle is not defined. Apparently it's not as it appears in the log.


Partial derivative of a function their variables depend on each other

Question: if    $z=F\left(x,y\right)$ and   $y$=$\phi \left(x\right)$
Then is it correct to say that $z$ is just a function of a single variable which is $x$ ?
and if we try to compute $\frac{\partial z}{\partial x}$ it will be equal to $\frac{dz}{dx}$ because the function $z$ will be affected only by the variable $x$ and it's nonsense in computing $\frac{\partial z}{\partial x}$ to treat $y$ as a constant because it changes as $x$ changes ?
Note:I watched the multivariable course presented by Herbert Gross by MIT and in the lecture of partial derivatives he emphasized that in order to do partial derivatives the variables of the function must be totally independent in order to compute it
Answer: Your function $F$ is a function defined on some subset of $\mathbb{R}^2$ mapping onto $\mathbb{R}$. $\frac{dF}{dx}$ tells us, how the function $F$ changes, when we change $x$ "just a bit". Since the set your function is defined on is open, we can always moove $x$ "just a bit", in both directions. The same holds true for y. Keep it mind that $F$ is a completely different function than $F(x,\phi(x))$. The latter is a curve, the argument can only move in one dimension, the first one is not.
For the "treating y as a constant part" it is important to keep in mind that y is not a free variable, we can not choose values for y, they are determined by $x$.
$\frac{d}{dx} F(x,\phi(x)) = DF(x,\phi(x)) \cdot \frac{d}{dx}(x,\phi(x))^t= F_1(x,\phi(x)) \cdot 1 + F_2x,\phi(x))\cdot \phi^{\prime}(x)$.
Comment: so this means that z is a function of a single variable which is x
Comment: ''Keep it mind that $F$ is a completely different function than $F(x,ϕ(x))$. The latter is a curve, the argument can only move in one dimension, the first one is not.''

are you refering to the diffrence between $F(x,y)$ and $F(x,ϕ(x))$ the first one there nothing to indicate that $y$ and $x$ are denpendent on each other so we treat them as two independent variables but the second one is not ,am I right ??
Comment: I got what you are saying
$F(x,y)$ is a function of $2$ independent variables unless we say that $y$$=$$\phi(x)$
if we say that $y$$=$$\phi(x)$ then our original function become a function of a single variable which is $x$
Comment: Yes, that means $z$ is a function of $x$.
Comment: Exactly, and this new functions only has 1 variable, thats why it does not make sense to differentiate for the second one.
Comment: is my last comment what you meant to say ?
Comment: Yes, they are independet, since $F$ is a function over the plane we can "moove" its arguments in 2 dimensions, where as we can only "move" in 1 dimension for the curve.


Dell R720 Memory Configuration

Question: I have an R720 with 2x E5-2650 v2, 8x8Gb Single Rank RDIMMs and 8x8Gb Dual Rank RDIMMs. I´m not sure how to install the DIMMs I´ve read that single ranks are faster than dual ranks so should I dedicate the 8 single rank dimms to CPU 1 and the other 8 dual rank to  CPU 2? Or should I populate CPU 1 with 4 single rank and 4 dual rank?
Answer: (Legally required notice - I work for Dell)
Regarding Surviving on Stack Exchange Sites
I'm not entirely sure what's wrong with your initial question other than asking about home builds is discouraged and the R720 is out of production.
However on your answer: If you're looking to survive the initial rep grind of any Stack Exchange site, removing emotion or extraneous comments from your answers goes a long way. We have a phrase we used to use in my military days, "Calling fire on one's own position." Saying, "Asked ChatGPT and the answer was very specific and without any arrogance." is very much a comment that falls into the category of "Calling fire on one's own position." Would avoid that as it's a one way ticket to downvote town.
Regarding Your Answer
ChatGPT appears to have lied and I suspect your usage of ChatGPT is part of the reason you're getting downvoted. While ServerFault does not have an official policy, there is a reason SO does ban ChatGPT: https://stackoverflow.com/help/gpt-policy. It is a fantastic tool, it's important to know how generative AI works. The TLDR version is it's just summarizing things it has seen before and there is no guarantee it is fully accurate as is the case here. Here is the R720's channel organization:

The chart in the manual is formatted strangely so here it is a bit more clearly. A slots go to proc one and B slots go to proc 2.

Processor 1
Channel 0
Channel 1
Channel 2
Channel 3

Slots
A1 (white), A5 (black), A9 (green)
A2 (white), A6 (black), A10 (green)
A3 (white), A7 (black), A11 (green)
A4 (white), A8 (black), A12 (green)

Processor 2
Channel 0
Channel 1
Channel 2
Channel 3

Slots
B1 (white), B5 (black), B9 (green)
B2 (white), B6 (black), B10 (green)
B3 (white), B7 (black), B11 (green)
B4 (white), B8 (black), B12 (green)

Taking a look at part of what you have in your answer: you put dual ranked DIMMs in slot A1 which is on processor 1 channel 0 and a single ranked DIMM in slot A5 which is also on proc 1 channel 0.
To understand why this is problematic read the next section.
Necessary Background
What's important here is to understand how memory works. For starters, what is a memory channel? It's the physical line going out to the bank. I'm guessing whatever proc you have in there is either Sandy Bridge or Ivy Bridge in which case they have 4 channels per proc with three DIMMs per bank as described here
Note: I'm going to explain this next part at a comparatively high level. In reality, it gets more complicated the further down you go, but this is generally how it works.
The reason the processor family matters is that you have to know how it is actually going to push data out to your DIMMs. Assuming you haven't changed the behavior in the BIOS, it should by default interleave the data between the DIMMs. I'm not sure on a server that old, but usually there will be an interleave size - let's call it 128 bytes. This means that if you're going to write 512 bytes of data what the memory controller would actually do is first write 128 bytes to channel 0, then 128 bytes to channel 1, channel 2, then channel 3. This happens so that when you go to retrieve that 512 bytes you can do a single access against each channel and there is no contention on any one channel.
So what really matters is the access patterns and memory requirements of your specific workload. If you have no idea what your application workload looks like then you would default to balancing the config.
The Answer
This brings us to what is wrong with what you're suggesting in your answer. What the manual says is a bit different than what you have, "In a dual-processor configuration, the memory configuration for each processor should be identical. For example, if you populate socket A1 for processor 1, then populate socket B1 for processor 2, and so on." That is to say, the memory configuration should be balanced.
Let me say that no one is ever going to recommend mixing dual and single rank DIMMs in a production environment. Given that the server in question is old I assume this is probably a personal project in which case it's fine.
The problem is your configuration is balanced but it mixes differently ranked DIMMs in the same channel. Interleaving works independently for each channel but when you mix ranks in the same channel wonky things start to happen. The exact behavior varies by processor but in general, interleaving performance will degrade because it's going to have to deal with the incongruity in the ranks within the same interleave access. Different ranks typically means different access latencies, plus the corresponding difference in size, which causes problems because generally interleaving will stripe the data across the DIMMs in the bank.
So there are multiple correct answers here, but whatever you do, you should make sure that both procs are identical, and that in any given channel that channel has DIMMs with the same rank.
TLDR Me
There are multiple correct answers here, but whatever you do, you should make sure that both procs are identical, and that in any given channel that channel has DIMMs with the same rank.
Comment: I undeleted the question because this is such a good answer.

Dell R720 Memory Configuration


Drawing a dot grid

Question: I'm new to graphics programming.  I'm trying to create a program that allows you to draw directed graphs.  For a start I have managed to draw a set of rectangles (representing the nodes) and have made pan and zoom capabilities by overriding the paint method in Java.
This all seems to work reasonably well while there aren't too many nodes.  My problem is when it comes to trying to draw a dot grid.  I used a simple bit of test code at first that overlayed a dot grid using two nested for loops:
int iPanX = (int) panX;
int iPanY = (int) panY;
int a = this.figure.getWidth() - iPanX;
int b = this.figure.getHeight() - (int) iPanY;

for (int i = -iPanX; i < a; i += 10) {
    for (int j = -iPanY; j < b; j += 10) {
        g.drawLine(i, j, i, j);
    }
}

This allows me to pan the grid but not zoom.  However, the performance when panning is terrible!  I've done a lot of searching but I feel that I must be missing something obvious because I can't find anything on the subject.
Any help or pointers would be greatly appreciated.
--Stephen
Answer: I think re-drawing all your dots every time the mouse moves is going to give you performance problems.  Perhaps you should look into taking a snapshot of the view as a bitmap and panning that around, redrawing the view 'properly' when the user releases the mouse button?
Answer: Use a BufferedImage for the dot grid. Initialize it once and later only paint the image instead of drawing the grid over and over.
private init(){
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    // then draw your grid into g
}

public void paint(Graphics g) {
    g.drawImage(image, 0, 0, null);
    // then draw the graphs
}

And zooming is easily achieved using this:
g.drawImage(image, 0, 0, null); // so you paint the grid at a 1:1 resolution
Graphics2D g2 = (Graphics2D) g;
g2.scale(zoom, zoom);
// then draw the rest into g2 instead of g

Drawing into the zoomed Graphics will lead to proportionally larger line width, etc.
Comment: Thanks, performance has increased massively!  There are a few quirks that I'll have to iron out but overall it is much improved.

The solution you offer for zooming isn't ideal as this increases the size of the grid which I would prefer to keep as single pixels.  Do I update the grid img on a zoom to accomodate?
Comment: yeah, that occurred to me afterwards. It depends on how often you  expect the zoom to change. I think you should update the grid image with every zoom change. And in paint(g) you could draw the grid at a 1:1 zoom and then set the scaling factor for the rest of the objects to paint. I think i'm going to update that in my answer.

Drawing a dot grid


E-mail com cópia JavaMail

Question: Tenho um sistema que envia e-mail, funciona normalmente, quero inserir um campo para enviar copia do e-mail, um CC ou CCo. segue abaixo um trecho do meu código.
Entidade
    private String destino;
private String titulo;
private String mensagem;

Método enviaEmail
 public static void enviaEmail(Ordens ordens) throws EmailException {
     Email email = new SimpleEmail();
     email = conectaEmail();
     email.setSubject(ordens.getTitulo());
     email.setMsg(ordens.getMensagem());
     email.addTo(ordens.getDestino());
     String resposta = email.send();
     FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "E-mail enviado com sucesso para: " + ordens.getUsuario().getLogin(), "Informação"));
 }

Front

 <h:panelGrid columns="2">
 <h:outputText value="Para: "/>
 <h:inputText value="#{ordensControle.ordens.destino}" size="48"/>
 <h:outputText value="Título: "/>
 <h:inputText value="#{ordensControle.ordens.titulo}" size="48"/>
 <h:outputText value="Mensagem: "/>
 <h:inputTextarea value="#{ordensControle.ordens.mensagem}" cols="88"
 rows="10"/>
 </h:panelGrid>

Biblioteca Ultilizada , commons-email
Comment: Coloque em sua pergunta a biblioteca de email que você utilizou, acredito que seja a apache commons email
Answer: Utilize o método addBcc() para copia oculta e addcc() para copia segue a referencia abaixo.
BCC: https://commons.apache.org/proper/commons-email/apidocs/org/apache/commons/mail/Email.html#addBcc(java.lang.String)
CC: https://commons.apache.org/proper/commons-email/apidocs/org/apache/commons/mail/Email.html#addCc(java.lang.String)
No seu código poderia ficar da seguinte maneira para CC.
Entidade
private String destino;
private String titulo;
private String mensagem;
private List<String> cc;

Método enviaEmail
public static void enviaEmail(Ordens ordens) throws EmailException {
     Email email = new SimpleEmail();
     email = conectaEmail();
     email.setSubject(ordens.getTitulo());
     email.setMsg(ordens.getMensagem());
     email.addTo(ordens.getDestino());
     for(String cc : ordens.getCc()){
         email.addCc(cc);
     }
     String resposta = email.send();
     FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "E-mail enviado com sucesso para: " + ordens.getUsuario().getLogin(), "Informação"));
 }

Comment: Cara ótimo, vou editar a pergunta pra ver se vc pode me ajudar no Front-End como vai ficar dai.

E-mail com cópia JavaMail


How to build a Winsock2 (WS2_32.lib) application targeting Windows XP with Visual Studio 2017

Question: I have an application written in C++ that uses socket (Winsock2.h). It has been developed on Windows 10 and it builds and runs fine on Windows 10. There is an old XP machine on which that application has to run (the machine cannot be upgraded as it contains legacy code that does not run on newer systems), but when I try to run the application on it I get the error: "The procedure entry point WSAPoll could not be located in the dynamic link library WS2_32.dll".
I tried the following:

I downloaded Visual Studio Express 2010 on a XP box and tried to build the application on it:

The code does not compile, because it uses libpqxx library (I suspect that libpqxx uses some c++11 code, that is not fully supported by VS2010);

I downloaded the XP toolset (v141_xp) for Visual Studio 2017 and built the application on Windows 10 (I have also downloaded and installed on XP the Microsoft Visual C++ Redistributable for Visual Studio 2017);

I got the same "The procedure entry point WSAPoll could not be located in the dynamic link library WS2_32.dll" error.

I tried to use winsock.h and link the application to wsock32.lib:

I got the same entry point error on WS2_32.lib (probably VS links the application to WS2_32.lib even if I specified to use wsock32.liB).

Is there a way to build on VS2017 using the xp toolset an application that uses Ws2_32.lib targeting XP?
EDIT 2019-05-03 10:30
As noticed by cprogrammer and Remy Lebeau WSAPoll does not exist in XP. The point is that I do not use WSAPoll in my code. So I followed the suggestion of Retired Ninja and I wrote from scratch an application using WinSock2 starting from the very basic and adding functions step by step(*). Well, all of my code worked well. The point is that I included also another library - libpqxx - and probably it uses WSAPoll.
Ok, I still have a problem, but at least I know where it is
(*) By the way, I already tried the same in the part of my code that uses WS2_32.lib, but as the problem was in another library I still got the error, so the suggestion to start from scratch really helped.
Comment: I would create a new project targeting XP and add Winsock2 to it. It should be simple, just WSAStartup and WSACleanup. If you can get that to work then you should be able to make your larger app work. That's assuming you don't actually use WSAPoll, because that was first introduced in Vista.
Comment: Instead of using winsock.h , just simply use  and  , it has the same functions , except 1 thing , WSAStartup and WSADATA isn't on it.
Comment: @SkillerDz those headers are not available on Windows
Comment: @RemyLebeau They are available on my  pc which use Windows.
Answer: Accortding to docs, for WSAPoll, the minimum supported client is Windows 8.1, Windows Vista [desktop apps | UWP apps]
Cannot be used for applications targeting Windows XP.
Answer: Your app (or one of its dependancies) is static linking to WSAPoll(), which simply does not exist on XP, it was introduced in Vista.  Whatever code your app uses that utilizes WSAPoll() will have to be rewritten for XP.  For instance, by using GetProcAddress() to access WSAPoll() dynamically instead of statically, and using a fallback (select(), WSAAsyncSelect(), WSAEventSelect(), etc) when WSAPoll() is not available.
Actually, the code should be rewritten - period, since WSAPoll() is broken and even Microsoft has gone on record saying that WSAPoll() will not be fixed and should not be used.
Comment: @cprogrammer your suggestion falls under the "code should be rewritten - period" portion of my answer. Just don't use `WSAPoll()` at all, use another approach.
Comment: I personally disagree with this solution because you will have two brances of code (that are hard to debug enyway) that will also depended on the platform. If you need to target XP, just use fallback method. Will work on Vista+.


Why Wolstenholme's theorem is not true for p=2, 3

Question: Theorem 5.25 in Apostol's Analytic Number Theory book (Wolstenholme's theorem) states that the following holds for any prime $p \ge 5$ : $$\sum_{k=1}^{p-1} \dfrac{(p-1)!}{k} = 0 \mod p^2.$$ I read and read the proof but I never found somewhere when $p=2, 3$ are invalid. That is, in the process of proof there is nowhere when the proof fails for $p=2, 3$. However, the statement does not hold for $p=2, 3$ and holds for $p=5$. Perhaps in order for $S_1$ to appear in $g(x)$, $p=2$ has been put aside, but $S_{p-2}=S_1$ for $p=3$ still is valid. So how is the proof valid for $p=2,3$ as well but the Wolstenholme's identity is not valid for $p=2,3$?
Comment: Just take $p=2$ or $p=3$ and go through the proof line by line until it breaks down.   In either case the sums (or binomial symbols, or factorials) will all be very simple.  In the [Wkipedia proof](https://en.wikipedia.org/wiki/Wolstenholme%27s_theorem#A_proof_of_the_theorem) of an equivalent version, at some point there is an explicit division by $3$, for instance.  Without seeing the proof you have in mind, there's not a lot more to say.
Comment: In [this proof](https://math.stackexchange.com/questions/325491/proof-of-wolstenholmes-theorem) the problem comes from the sum of squares formula, which has a $6$ in the denominator.
Answer: The issue is just before the end of the proof, where an equation is taken modulo $p^3$. If $p \ge 5$, then this will cancel all terms except $-S_{n-1}p$, but if $p=3$, then $p^{p-1} = 9$ is not divisible by $p^3 = 27$ and will not be cancelled either.
In that case, you get $3S_1 \equiv 3^2 = 9$ mod 27, so $S_1 \equiv 3$ mod 9, which is confirmed by the actual sum being $S_1 = 3$.


Strong consistency in quantum estimation problem

Question: I'm reading the paper: Strong consistency and asymptotic efficiency for adaptive quantum estimation problems by Akio Fujiwara.
In this paper, describes the next adaptive scheme of estimation:
"Consider a sequential design problem that allows us at each stage an experiment $E$ to be taken from an experiment space $\mathcal{E}$. The observed data $x_n \in \mathcal{X}$
at time $n$ have probability density $f(x_n ; \theta, E_n )$, with respect to some $\sigma$ -finite measure $\mu$ on $\mathcal{X}$, which depends on both the parameter $\theta \in \Theta$  and the experiment $E_n \in \mathcal{E}$ selected at stage $n$. It is
assumed that $E_n$ is measurable with respect to the natural filtration $\mathcal{F}_{n−1} := \sigma(X_1 , . . . , X_{n−1} )$,
that is, $E_n$ is chosen according to the information of the past data $X_1 , . . . , X_{n−1}$ . The likelihood function is therefore given by
$$L_n(\theta) := \prod_{i=1}^{n} f (x_i ; \theta, E_i ).$$
In a quantum estimation problem, $\mathcal{X}$ is a finite set (with $\mu$ the counting measure), and $\Theta, \mathcal{E}$ are both compact. "
Also, they claim that under the next regularity conditions they can obtain the strong consistency for the Maximum likelihood estimator. The regularity conditions are

$f(x; \theta, e)$ is positive for all $(x, \theta, e)$, and is continous in $(x, \theta,e)$
$\mu(\left\{x; f(x; \theta, e) \neq f(x; \theta', e)    \right\})>0 $ for any $\theta \neq \theta'$ and $e \in \mathcal{E}$.

However, I don't have a good measure theory background. Then I have a couple of questions,
My questions are:
¿What means the second regularity condition, is it the identifiability for each probability density?
¿If any of the conditions is not holds, the Maximum likelihood estimator could be consistent?
Thanks for any help.
Comment: Yes the second condition is identifiability.  If a model is not identifiable there are several values of $\theta$ with the same likelihood, and the maximum likelihood estimator might not be uniquely defined. See https://en.wikipedia.org/wiki/Maximum_likelihood_estimation#Consistency
Answer: The definition of identifiability is this: a family of densities or p.m.f. $f_\theta$ is identifiable if and only if $\theta_1\neq\theta_2$ implies $f_{\theta_1} \neq f_{\theta_1}$; that is, saying that a family is identifiable is the same as saying that different parameters cannot give you the same density.
In your case, for each fixed experiment $e$, the family $f(\cdot;\theta,e)$ is identifiable if and only if $\theta_1\neq\theta_2$ implies that $f(\cdot;\theta_1,e)$ and $f(\cdot;\theta_2,e)$ are different functions, i.e.,  it cannot be true that for all $x\in\mathcal{X}$ $f(x;\theta_1,e) = f(x;\theta_2,e)$. When $\mathcal{X}$ is finite and discrete, the equation
\begin{equation}
\mu(\{x|f(x;\theta_1,e)\neq f(x;\theta_2,e)\}) > 0
\end{equation}
reads literally as "there must be at least one element in $\mathcal{X}$ that can make $f(\cdot;\theta_1,e)$ and $f(\cdot;\theta_2,e)$ evaluate to different values". This is the same as saying that $f(\cdot;\theta_1,e)$ and $f(\cdot;\theta_2,e)$ must be different functions. So yes, the second condition is equivalent to saying that the family of densities for each experiment $e$ must be identifiable.
Without the identifiability condition, there cannot be any guarantees that the MLE $\hat{\theta}_n$ will be (weakly) consistent. To see this without going too technical, for simplicity let all the experiments $e_n$ be the same, say, $e_n=e$ for all $n$ and let's imagine $\theta_1$ and $\theta_2$ are two different parameters such that $f(\cdot;\theta_1,e)$ and $f(\cdot;\theta_2,e)$ are the same function. Notice that whichever one of $\theta_1$ and $\theta_2$ were the truth, your observations $x_1\cdots x_n$ will be drawn from the same density; therefore $\hat{\theta}_n$, which is a function of $x_1\cdots x_n$, would also be drawn from the same density no matter which one of them were the truth. If $\hat{\theta}_n$ were consistent, by the definition of weak consistency, the density of $\hat{\theta}_n$ needs to become more and more concentrated around the true $\theta$; but both possible $\theta$'s give rise to the same density for $\hat{\theta}_n$, so now which one of $\theta_1$ or $\theta_2$ should density of $\hat{\theta}_n$ converge in probability to? It cannot converge in probability to both, so the consistency idea is broken in this situation.


SearchView shows only one & same record from listView with CustomAdapter but searchView works fine with ArrayAdapter. Here's my adapter

Question: import com.example.mis_internee.atendence_app_android.R;

    public class EMP_LEAVE_ADAPTER extends ArrayAdapter<String> {

        private final Activity context;
        private final String[] itemname;

        public EMP_LEAVE_ADAPTER(Activity context, String[] itemname) {
            super(context, R.layout.mylist, itemname);
            // TODO Auto-generated constructor stub

            this.context = context;
            this.itemname = itemname;

        }
        public View getView(int position, View view, ViewGroup parent) {
            LayoutInflater inflater=context.getLayoutInflater();
            View rowView=inflater.inflate(R.layout.emp_leave_adpater_layout, null,true);

            TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
            ImageView image=(ImageView)rowView.findViewById(R.id.icon);

            txtTitle.setText(itemname[position]);
            return rowView;

        };
    }

Comment: where is search filter method in your code?
Comment: SearchView is in Activity , its is working when i write " arratAdapter.getFilter().filter(newText);" but when i use this adapter " ELA.getFilter().filter(newText);" it shows only first row of list
Comment: that's why i am asking you created custom adapter for search so you have to implement filter method for filter text.
Comment: public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.viewaprovedlist, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.action_search);
    searchView = (SearchView) searchMenuItem.getActionView();

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);

    return true;
}
Comment: public boolean onQueryTextSubmit(String query) {
        return false;
    }
    @Override
    public boolean onQueryTextChange(String newText) {
        ELA.getFilter().filter(newText);
//
//        if (TextUtils.isEmpty(newText)) {
//            listView.clearTextFilter();
//        }
//        else {
//            listView.setFilterText(newText.toString());
//        }

        return true;
    }
Comment: posted in comment
Comment: @KamranIjaz please edit your question with the code instead of commenting
Answer: You have to implement filter class in your custom adapter and call this method from your class, have look
in your adapter :
 public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<String> list = originalData;

            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }
}

Now in your activity where  edittext  is defined :
editTxt.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        System.out.println("Text ["+s+"]");

        mSearchableAdapter.getFilter().filter(s.toString());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

change according to your requirement, hope it will help you!!
Answer: You need to return different view and also you need to recycle the view manually as follows:
 public View getView(int position, View view, ViewGroup parent) {
 ViewHolder viewHolder;
 if(view == null) {
   viewHolder = new ViewHolder();
   LayoutInflater inflater=context.getLayoutInflater();
   View rowView=inflater.inflate(R.layout.emp_leave_adpater_layout, null,true);

  viewHolder.txtTitle = (TextView) rowView.findViewById(R.id.item);
  viewHolder.image=(ImageView)rowView.findViewById(R.id.icon);
  view.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) view.getTag();
    }
  viewHolder.txtTitle.setText(itemname[position]);

  return viewHolder;
};

public class viewholder {

 public TextView txtTitle;
 public ImageView image;
}

Comment: Hi, thanks for response , i used adapter for text and image , it is showing fine but when i add searchView and search with name it shows only that name which is on top, and if search text out of list then no row shows
Comment: you want to hide rows when there is search text out of list right..?
Comment: no i just want to show that row which i search like if is search "A" from list
A
B
C
D
it Will show "A" but when i Search "B" it shows again A but when i search "XYZ" which is not in list it shows nothing.
Comment: ok. once you get response from API, update the arraylist data/ and refresh the adapter using adapter.notifydatasetchanged(). Add null check for preventing refresh, if there is no results..


Converting polar equation to rectangular equation

Question: I'm doing exercises of converting polar equations to rectangular. I would like to check if what I'm doing is right.

$$\frac{\sin^2(\theta)}{\cos(\theta)}=\frac{1}{r}$$
$$r\sin^2(\theta)=\cos(\theta)$$
$$r\cdot r\sin^2(\theta)=\cos(\theta)\cdot r$$
$$r^2\sin^2(\theta)=r\cos(\theta)$$
$$(r\sin(\theta))^2=r\cos(\theta)$$
$$y^2=x$$

Is this right? Do I have to take the square root on both sides?

$$r=\frac{\theta}{\sin(\theta)}$$
$$ \sin(\theta)\cdot r=\frac{\theta}{\sin(\theta)}\cdot \sin(\theta)$$
$$r\sin(\theta)=\theta$$
$$y=\theta$$

I have my doubts here because I think $\theta$ must disappear.
Answer: For the first one you are correct:
I am assuming you are using the following identities:
$$x=r\text{cos}(\theta)\hspace{4mm}y=r\text{sin}(\theta)\hspace{4mm}r=\sqrt{x^2+y^2}$$
As for if you have to take the square root to the equation $x=y^2$ not that the ordered pairs $(x,y)$ that satisfy this equation are the same if  you consider $y^2=x$ or $y=\pm \sqrt{x}$ with the later being  more customary. What you do have to  be mindful of is since there is no restriction on $\theta$ are we accounting for all the quadrants of our graph. Note that $y^2=x$  falls in quadrant I and IV. The polar equation $r=\frac{\cos(\theta))}{\sin^2(\theta)}$ is in quadrant I and IV so all is good.
Comment: ok. thanks. what about the second one? it is possible to make disappear the theta from there?
Comment: As was stated  below  since  $\frac{y}{x}=\tan(\theta)$ then $\theta=\arctan(\frac{y}{x})$ which i believe  cannot be separated but  can  consider the order pairs  $(x,y)$ being mindful to not consider  the  combinations that result in  $2\pi k=\arctan(\frac{y}{x})$  where $k\in \mathcal{Z}$  since this will result in a division  by zero in original polar equation.
Answer: As $y=r\cos\theta,x=?$
$\dfrac yx=\tan\theta$
$\theta=\arctan\dfrac yx$ where we need to consider general values of $\arctan$
as $\theta$ can assume any finite and real value


How do you order Models with M2M relationship to avoid NameSpace errors?

Question: I can't figure out how I'm supposed to order these models that have a M2M relationship.
When I try to syncdb, I can't because the Model related model is not in the namespace yet, so I get:

NameError: name 'FavoriteQuestion' is not defined

If I switch places, I get:

NameError: name 'UserProfile' is not defined

class UserProfile(models.Model):
    """User Profile customizations"""
    user = models.ForeignKey(User, unique=True)
    favorite_questions =  models.ManyToManyField(Question, through=FavoriteQuestion,
                                                 related_name='favorited_by')
    badges = models.ManyToManyField(Badge, through=Award,
                                    related_name='awarded_to')

class FavoriteQuestion(models.Model):
    """A favorite Question of a User."""
    question      = models.ForeignKey(Question)
    user          = models.ForeignKey(UserProfile, related_name='user_favorite_questions')
    added_at = models.DateTimeField(default=datetime.datetime.now)

Here is the TraceBack:

$ python manage.py syncdb
    Traceback (most recent call last):
      File "manage.py", line 11, in <module>
        execute_manager(settings)
      File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 439, in execute_manager
        utility.execute()
      File "/usr/local/lib/python2.6/site-packages/django/core/management/__init__.py", line 380, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv
        self.execute(*args, **options.__dict__)
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute
        self.validate()
      File "/usr/local/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate
        num_errors = get_validation_errors(s, app)
      File "/usr/local/lib/python2.6/site-packages/django/core/management/validation.py", line 28, in get_validation_errors
        for (app_name, error) in get_app_errors().items():
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 131, in get_app_errors
        self._populate()
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 58, in _populate
        self.load_app(app_name, True)
      File "/usr/local/lib/python2.6/site-packages/django/db/models/loading.py", line 74, in load_app
        models = import_module('.models', app_name)
      File "/usr/local/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
        __import__(name)
      File "/Users/Bryan/work/APPNAME/forum/models.py", line 434, in <module>
        class FavoriteQuestion(models.Model):
      File "/Users/Bryan/work/APPNAME/forum/models.py", line 437, in FavoriteQuestion
        user          = models.ForeignKey(UserProfile, related_name='user_favorite_questions')
    NameError: name 'UserProfile' is not defined

Answer: You don't need to create the favourite_question field on the UserProfile.
As long as each FavouriteQuestion has a user associated with it the model instance API will give you access to a list of favourite questions for a user.
Answer: Instead of passing in the the Class to the field constructor, pass in the string of the class name. Django will do the leg work of figuring out how to hook up the models without relying on the class definitions to exist at the point in the module where the other class is being defined. I would actually do this for all of your relations you define:
class UserProfile(models.Model):
    """User Profile customizations"""
    user = models.ForeignKey('User', unique=True)
    favorite_questions =  models.ManyToManyField('Question', through='FavoriteQuestion',
                                                 related_name='favorited_by')
    badges = models.ManyToManyField('Badge', through='Award',
                                    related_name='awarded_to')

class FavoriteQuestion(models.Model):
    """A favorite Question of a User."""
    question = models.ForeignKey('Question')
    user = models.ForeignKey('UserProfile', related_name='user_favorite_questions')
    added_at = models.DateTimeField(default=datetime.datetime.now)


Comparing SVD of orthogonal matrix $(\sqrt{W}A)$ and matrix $A$ in order to find the singular values of A

Question: I have a diagonal matrix W and another matrix A. I also have that $(\sqrt{W}A)$ is an orthogonal matrix.
I have that the SVD of $$\sqrt{W}A=U\Sigma V^T=(\sqrt{W}A)II$$ where I is the identity matrix. So, the singular values of $(\sqrt{W}A)$ are all $1$.
I am trying to figure out what the SVD of just $A$ would be so I can find the singular values of A. I tried to say that it is $$A=\sqrt{W}^{-1}\sqrt{W}AII=AII$$ but this isn't an SVD since A is not orthogonal.
I was also thinking that maybe it would be $$A=(\sqrt{W}A)\sqrt{W}^{-1}II$$ but I don't think that $\sqrt{W}^{-1}$ will commute in that way.
Any help would be much appreciated. Thank you.
Answer: Since $\sqrt{W}A$ is unitary,
$$ I = (\sqrt{W}A)(\sqrt{W}A)^* = \sqrt{W} AA^* \sqrt{W}^*$$
First note that $\sqrt{W}$ has to be full rank since $\sqrt{W}A$ is full rank. Therefore $\sqrt{W}^{-1}$ exists and, assuming $W$ is real,
$$ AA^* = \sqrt{W}^{-1}\sqrt{W}^{-1} = W^{-1} $$
Now think about how the singular values of $AA^*$ are related to $A$, and how $W^{-1}$ is related to $W$.
Comment: Yep! Another way to think about this problem is geometrically. A unitary matrix maps the unit ball to the unit ball/ Applying $\sqrt{W}^{-1}$ to the image of $\sqrt{W}A$ will stretch the unit ball in some way. The amount it stretches will give you the singular values of $A$.
Comment: Thank you very much for the help. It seems like from what you said that the singular values of A are the positive square root of the eigenvalues of $W^{-1}$. Since $W$ is a diagonal matrix, the eigenvalues of $W^{-1}$, and therefore the singular values of $A$, are the positive square roots of the reciprocal of the diagonal of $W$? Does that sound right? Thank you again.
Comment: Thank you very much. I really appreciate it. :)


Violation of PRIMARY KEY constraint in Entity Framework Core

Question: I have a .NET5 Blazor Server application using EFCore5.
I have two entities that have a many-to-many relationship with each other.
Let's call them 'Books' and 'Tags'.
EFCore provides the BookTag join table.
On my page, I have a form that is populated with the book details and has a multi select box for the tags.
I include the tags when I get the book:
context.Books.Include(x=>x.Tags);
In debug mode, I see the Book item has several tags. But when I update some details of the book and save the form, calling context.Books.Update(book); I get an error because of duplicate keys in the BookTag join table.
It seems EFCore tries to insert entries in that table, but it should do a merge or insert/update.
I've read numerous articles about the many-to-many but all of them just show how to retrieve data. I can't find an example of how to update.
Edit:
I'm using the GenericRepository as explained by @carl-franklin in his excellent BlazorTrain series.
Edit2:
Here is some relevant code, I'm now not using the GenericRepo:
Startup.cs
services.AddDbContextFactory<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
ApplicationDbContext.cs has only the DbSets.
Book.cs
[Key]
public string Code { get; set; }
public string Name { get; set; } = "";
public virtual ICollection<Tag> TagCollection { get; set; }

Tag.cs
[Key]
public string Code { get; set; }
public string Name { get; set; } = "";
public virtual ICollection<Book> BookCollection { get; set; }

Book.razor.cs
[Inject] private IDbContextFactory<ApplicationDbContext> contextFactory { get; set; }
private ApplicationDbContext context { get; set; }
protected IEnumerable<Book> BookList;

protected override async Task OnInitializedAsync()
{
    context = contextFactory.CreateDbContext();
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

    BookList = await context.Books.Include(x => x.TagCollection).ToListAsync();
}

private async Task UpdateBook(Book book)
{
    // Called after submitting form
    context.Books.Update(book);
    await context.SaveChangesAsync();
}

Even if I don't change anything, just update I get the duplicate error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_BookTag'. Cannot insert duplicate key in object 'dbo.BookTag'
In UpdateBook() I see the book has tags, as expected. It looks like EFCore is inserting them in the join table without checking if they already exist.
Comment: When you initially read data from database, add `.AsNoTracking()`.
Comment: Thanks Ergis. I'm already doing that. In fact I'm doing it on the context level: `context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;`
Comment: Show us your code.
Comment: Thanks @RobertHarvey I've updated my post and added relevant code.
Comment: `Violation of PRIMARY KEY constraint 'PK_BookTag'. Cannot insert duplicate key in object 'dbo.BookTag'` -- Kinda says it all.  Not sure why you're turning off change tracking; that's what makes all this work.  `Update` does not mean `Upsert` or `Merge`.
Comment: Change tracking was turned off in the GenericRepo I got from BlazorTrain. When in my extracted code I don't turn it off my problems disappear and I can add the tags without errors. As expected. @RobertHarvey If you turn your comment into an answer I'll accept it.
Answer: Change tracking must be turned on for this to work.  Otherwise, you have to track the changes yourself; Entity Framework thinks you're adding a new record, but the key is the same as an existing record, which is why you're getting the error.


Delete user in transaction

Question: I'm having trouble figuring out why the following code isn't working in Drupal 7. _queue_processor is a cron queue processor function:
function _queue_processor($uid) {

    $transaction = db_transaction();

    watchdog('debug', 'transaction created'); // This will not be called.

    try {
      user_delete($uid);
    }
    catch (Exception $e) {
      // A problem occurred. Rollback transaction.
      $transaction->rollback();
      throw $e;
    }
    // Rollback intentionally.
    if (variable_get('some_var', FALSE)) {
      $transaction->rollback();
    }
}

The code never makes it past the $transaction = db_transaction(); line. However, if I remove the transaction and try/catch, user_delete() is called just fine, and the transaction that user_delete_multiple() creates within itself works as well.
Is there something wrong with putting user_delete() within a transaction? I know it already uses one, but I need to be able to run the deletion and then conditionally rollback afterwards, and I'd rather not do this by throwing an exception in an implementation of hook_user_delete() to force rollback.
I am using MariaDB.
Answer: As far as I know, this can only be done using exceptions. Here is a minimal example. Note that the module in the code example is called module.
function module_queue_processor($uid) {
  try {
    // Delete user.
    user_delete($uid);
  }
  catch (DebugException $e) {
    // Catch custom exception. The inner transaction has been rolled back.
    // @todo The exception is still logged to watchdog in user_delete().
  }
}

/**
 * Implements hook_module_implements_alter().
 */
function module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'user_delete') {
    // Remove node_user_delete() to ensure nodes are not deleted.
    unset($implementations['node']);

    // Move module_user_delete() to the beginning of the list.
    // This ensures that custom processing is done first.
    // This may not be necessary, but it's a good idea.
    $group = $implementations['module'];
    $implementations = ['module' => $group] + $implementations;
  }
}

/**
 * Implements hook_user_delete().
 *
 * This hook is called before all others.
 */
function module_user_delete($account) {
  $uid = $account->uid;
  $name = $account->name;

  // Prevent deletion of anonymous and root users.
  if ($uid == 0 || $uid == 1) {
    watchdog('module', 'Cannot delete user with UID @uid.', array('@uid' => $uid), WATCHDOG_ERROR);
    return;
  }

  // It is not necessary to pass the transaction object to functions. The
  // transaction will automatically be committed when all open transaction
  // objects go out of scope.
  // For more information: https://drupal.stackexchange.com/a/285032
  $transaction = db_transaction();

  try {
    // Temporarily use strict error handler to throw exceptions for warnings and
    // notices. Without this, warnings might cause content to be not deleted
    // without a rollback of user deletion.
    set_error_handler('module_custom_error_handler');

    ...
  }
  catch (Exception $e) {
    // Rollback the transaction.
    $transaction->rollback();

    // Log the exception.
    $message = '%type while deleting user %name with UID %uid. Transaction not committed. !message in %function (line %line of %file).';
    $variables = array(
      '%name' => $name,
      '%uid' => $uid,
    );

    watchdog_exception('module', $e, $message, $variables);

    // Throw the exception again to halt user deletion.
    throw $e;
  }
  finally {
    // Restore the pre-existing error handler.
    restore_error_handler();
  }

  // Rollback intentionally.
  if (variable_get('module_dry_run', FALSE)) {
    $transaction->rollback();

    // Trigger transaction rollback inside user_delete_multiple().
    throw new DebugException($message);
  }
}

/**
 * Custom error handler used to make non-errors into exceptions.
 *
 * @link https://stackoverflow.com/questions/1241728/can-i-try-catch-a-warning
 */
function module_error_handler($errno, $errstr, $errfile, $errline) {
  // Error was suppressed with the @-operator.
  if (error_reporting() === 0) {
    return FALSE;
  }

  throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

/**
 * Custom exception used to trigger transaction rollback for dry run.
 */
class DebugException extends Exception {}

Delete user in transaction


Testing the Central Limit Theorem with the Shapiro-Wilk test on dice rolling simulations

Question: Rolling a single dice repeatedly will result in a uniform distribution. But if we roll multiple dice the sum would be the Normal distribution due the Central Limit Theorem (CLT).
To verify this, simulated multiple dice rolls number of times to get a distribution and then used the Shapiro-Wilk test to calculate p-value.
What seems strange is that if we increase the number of rolls, the histogram becomes smoother and apparently closer to normal by p- value tends to decline until it stays below 0.05 for any number of repetitions.
Both Python and R gives the same results. Below are two pieces of code in Python. One plots p value vs. the number of rolls. The other repeats the experiment 1000 times and calculates the percentage of results supporting the null hypothesis with p > 0.05.
E.g., with 20 dice, the percentage for 100 rolls is about 94; 700 rolls - 75%, 1500 rolls - 11%, 2000 rolls - 0%.
How can we explain this phenomenon?
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

def shapiro_p(n_dice, n_throws):

    rng = np.random.default_rng()
    throwing = rng.integers(1, high=6, size=(n_throws, n_dice), endpoint=True)
    X = np.sum(throwing, axis=1) / n_dice
    shapiro_test = stats.shapiro(X)

    return shapiro_test.pvalue

n_dice = int(input('Input the number of dice '))
n_max = int(input('Input the number of rolls '))

x = [n for n in range(3, n_max + 1)]
y = [shapiro_p(n_dice, n) for n in range(3, n_max + 1)]

figure_title = 'Number of dice: {0}'.format(n_dice)

plt.plot(x, y)
plt.hlines(0.05, 3, n_max + 1, colors='red')
plt.xlabel('Number of rolls')
plt.ylabel('p')
plt.title(figure_title)
plt.grid(True)
plt.show()

The second piece of code:
from scipy import stats
import random

dice = [i for i in range(1, 7)]

def shapiro_p(n_dice, n_rolls):
    sampl = [sum(random.choices(dice, k=n_dice)) for j in range(n_rolls)]
    shapiro_test = stats.shapiro(sampl)
    return shapiro_test.pvalue

n_dice = int(input('Number of dice '))
n_rolls = int(input('Number of rolls in each test '))
# n_tests =  int(input('Number of tests '))
n_tests = 1000

null_h = 0
for n in range(n_tests):
    if shapiro_p(n_dice, n_rolls) >= 0.05:
        null_h += 1
print('Percentage of tests supporting the null hypothesis: ', 100*null_h/n_tests)

Comment: Thank you! It appears counterintuitive as histograms become smoother, but increasing power explains the results. I also see that increasing the number of dice delays the p-value fall off.
Comment: @COOLSerdash - That shold be an answer - the answer.
Comment: Are you testing against the standard normal?
Comment: Aksakal, shapiro test in scipy tests for normality, not necessarily against the standard normal distribution.
Answer: The CLT is an asymptotic result valid for $n\rightarrow \infty$. Namely, it says for iid random variables $X_i$ with mean $\mu$ and variance $\sigma^2<\infty$ with the following definition:

$$ S_n = \frac{1}{\sigma\sqrt{n}}\sum_{i=1}^{n}(X_i-\mu) =
> \frac{\sqrt{n}(\bar{X}_n-\mu)}{\sigma} $$ Then $S_{n} \xrightarrow{d}
 Z\sim \operatorname{N}(0, 1)$ as $n\rightarrow \infty$.

The CLT says nothing about finite $n$ but the Berry-Esseen theorem gives bounds on the error of the approximation.
The distribution of the (appropriately scaled) sum is never exactly normally distributed at finite $n$, except when the $X_i$ have a normal distribution to begin with. For example: The support of the sum of $m$ d6 dice throws is $[m, 6m]$ whereas the normal distribution has support $(-\infty, \infty)$. So we'll expect the $p$-value of the Shapiro-Wilk test to increase with increasing number of dice, because the sum (or scaled sum) will approximate the normal distribution better.
The second effect that you observe is that the power of the Shapiro-Wilk test to reject deviations from a normal distribution increases with increasing number of rolls. Hence, with a fixed $m$ (number of dice), the $p$-value of the Shapiro-Wilk test will get smaller with increasing number of rolls. That's what you see in the graph resulting from the first piece of your Python code.
Comment: Thank you! I do not have enough reputation yet to upvote your answer, can only thank you in the comment.
Comment: I am not sure that I agree with that last sentence. Wouldn't the power of the test depend on how many times you draw samples of size $n$, rather than on $n$ itself? In the extreme, consider rolling a billion dice, but only once. How do you test the central limit theorem to the sum when you only have one sum?
Comment: @Dave I think you're right. I used $n$ ambiguously for the sample size and for the number of dice. I will revise my answer.
Comment: @COOLSerdash (+1) Great answer. Reference to Berry-Esseen theorem is not that well known. Nice that it is discussed here.


Why was this answer converted to a comment?

Question: I added an answer to a question yesterday which has since been converted to a comment, but to me the answer was perfectly valid and didn't need to just be a comment.
Magento CE 188.8.131.52 downloadable product does not open uploader
The error message posted, though not in English clearly refers to Adobe Flash, and hence my answer was for the user to check they had flash installed and it was up to date.  For whatever reason Marius considered this not to be a valid answer, but why?  It feels like rather heavy handed moderation...
Answer: Because you've wrote it in the form of question. For me it looked like clarification request.
I just have undeleted, edited your answer and cleaned up comments.
Comment: Ok thanks for that.


Python 3.1 and MySQL?

Question: I've been trying to get MySQL working with Python, but I haven't been able to find any scripts that work with it :(
I can't find a 3.1 compatible setuptools, easy_install or MySQLdb package. What should I be using?
Comment: You should also be using Python 3.2.x. Python 3.1 is obsolete and no longer maintained; plus, Python 3.2 contains many, many fixes and performance improvements over 3.1.  Also, `setuptools` has been superseded by the `Distribute` package, which also provides `easy_install`.
Comment: SQLAlchemy, what about trying to use ORM? Isn't sqlalchemy released for python 3+ yet?
Answer: Looks like PyMySQL is working with 3.1 with the right build options, but I haven't tried it myself yet:
https://github.com/petehunt/PyMySQL/#python-3-0-support
Answer: In case you aren't using windows, you can use mypysql
http://mypysql.sourceforge.net/

Python 3.1 and MySQL?


Ajax sem enviar o action

Question: Boa tarde, tenho esse código ajax onde utilizo para fazer um update no meu formulário, acontece que quando dou o submit ele vai para a página php, e eu  não quero isso, quero apenas o retorno dela.
segue o código:
function alterProduct(obj){
    var form = $(obj);
    var dados = new FormData(obj);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: dados,
        processData: false,
        cache: false,
        contentType: false,
        success: function( data ) {
            if ( data == 'OK' ) {
                alert('Dados enviados com sucesso');
            } else {
                alert(data);
            }
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }
    });

    return false;
}

meu form:
<form method="post" enctype="multipart/form-data" class="update-product" onsubmit="alterProduct(this)" action="ajax/update_product.php">
    <input type="text" name="id" value="<?php echo $a->current()->id; ?>" hidden>

        Nome do Produto
        <input type="text" name="name" value="<?php echo $a->current()->name; ?>" class="form-control" placeholder="Digite o nome do seu produto">

        Preço
        <input type="text" name="price" value="<?php echo $a->current()->price; ?>" class="form-control money" placeholder="Digite o valor do seu produto">

        Quantidade
        <input type="number" name="qtd" class="form-control" value="<?php echo $a->current()->qtd; ?>" placeholder="Digite a quantidade a ser cadastrada">

    <input type="submit" name="update" class="btn-action" value="Alterar">
    <button type="button" class="btn-outline" data-dismiss="modal">Fechar</button>
</form>

Answer: Por conta de como você está chamando a função, precisa de mais um return por fora:
... onsubmit="return alterProduct(this)" ...

Comment: Obrigado pela ajuda.

Ajax sem enviar o action


Using Gaussian process regression with non Gaussian data

Question: I have a question about practical implementation and interpretation of the Gaussian process regression model given by Rasmussen & Williams.
The regression problem is defined as follows:
Let $x_i\in \mathbb R^{5}$ be an input vector and $y_i\in \mathbb R$ be its corresponding target. The set of $M$ inputs are arranged into a matrix $X=[x_1,\ldots,x_M]^⊤$ and their corresponding targets are stored in a matrix $Y=[y_1,\ldots, y_M]^\top.$
I wish to train a GPR model $G={X,Y,\theta}$ using the squared exponential function:
$$k(x_i,x_j)=\alpha^2\exp\left(\frac{−1}{2\beta^2(x_i−x_j)^2}\right)+\gamma^2\delta_{ij}, $$
where $\delta_{ij}$ equals 1 if $i=j$ and 0 otherwise. The hyperparameters are $\theta=(\alpha,\beta,\gamma)$ with γγ being the assumed noise level in the training data and $\beta$ is the length-scale.
To train the model, I need to minimise the negative log marginal likelihood with respect to the hyperparameters:
$$−\log p(Y∣X,\theta)=\frac{1}{2}\operatorname{tr}\left(Y^\top K^{−1}Y\right)+\frac{1}{2}\log∣K∣+c, $$
where $c$ is a constant and the matrix $K$ is a function of the hyperparameters
<code>covfunc = @covSEiso;
likfunc = @likGauss;
sn = 0.1;
hyp.lik = log(sn);
hyp2.cov = [0;0];
hyp2.lik = log(0.1);
hyp2 = minimize(hyp2, @gp, -100, @infExact, [], covfunc, likfunc, X1, Y1(:,n));
exp(hyp2.lik)
nlml2 = gp(hyp2, @infExact, [], covfunc, likfunc, X1, Y1(:, n));
[m s2] = gp(hyp2, @infExact, [], covfunc, likfunc, X1, Y1(:, n), XT);
YT(:, n) = m;
</code>
X1,Y1 are the training inputs/targets
XT are the test inputs, YT are the target predictions.
My question is about the use of [m,s2] as predictions for Y (the second to last line of code). If the original sample Y are not normally distributed is the predictive distribution given by the values in [m,s2] stil valid? For example is it valid to say that for a test value $x_{*i}$ the distribution of the prediction for the target $y_{*i}$ is $N(m,s2)$, or am I misinterpreting the implementation of this model?
Comment: @AngusCampbell I believe that GPy in Python does.
Comment: In Gaussian process regression (GPR) we assume that our function is a realization of Gaussian process. Almost any function is close to some Gaussian process realization. In particular, GPR can fit the training data perfectly i.e. pass through the all sample points. I have encountered no discussion regarding testing of Gaussian nature of data while using GPR.
Comment: The assumption in GPR is that the noise is Gaussian. The sample Y will not typically be, but the residuals after you've applied your model should be if the model is well-specified. This is illustrated in the figure below, somewhat. There are cases for which the noise is truly non-gaussian so that even with a well-specified model the residuals will be non gaussian or heteroskedastic. In these cases, something like Warped Gaussian Processes by Snelson/Ghahramani can be used. There is much literature on the topic, they provide a few good references towards the end of the paper.
Comment: @DavidKozak are there python or R packages that can be used to implement warped gaussian processes?
Answer: For a gaussian process, the evaluation of the gaussian processes of an input value $(x+1)$ is the output $y(x+1)
$ obtained by
$$\mathord{\buildrel{\lower3pt\hbox{$\scriptscriptstyle\frown$}} \over y}  = {K^y}(\mathord{\buildrel{\lower3pt\hbox{$\scriptscriptstyle\frown$}} \over x} ,x)*{\left( {{K^Y}} \right)^{ - 1}}*y
$$
in your code, this is expressed by $m$ ,the mean value is the value of higher probability. For each value that you want to evaluate, you need to calculate $${K^y}(\mathord{\buildrel{\lower3pt\hbox{$\scriptscriptstyle\frown$}} \over x} ,x)
$$ and then you apply the equation for the mean value to obtain your output value.
You can see a gaussian process as a sum of gaussian distributions over a specific path.


how to remove backslashes and double quotes in json string

Question: I am trying to pass string to json object, and it works. However there are some backslashes and double quotes in the json! How can I remove them?
I am using c# Web API. This is my code.
public string jsonvalues()
{
    var x = new
    {
      status = "Success"
    };
    var javaScriptSerializer = new
    System.Web.Script.Serialization.JavaScriptSerializer();
    var jsonString = javaScriptSerializer.Serialize(x);
    return jsonString;
}

When I return this function in controller, I get the result like this

"{\"status\":\"Success\"}"
Comment: where does your observed value , `"{\"status\":\"Success\"}".` come from ? did you observe this in the debugger, or did you log / output it somewhere ?
Comment: Visual studio (assuming you are using this as an IDE) adds the slashes, but if you use something like fiddler to view the response, then you would see that there are no slashes, etc.
Comment: @FabioSalvalai: this is the output displayed on the browser
Comment: Shown in the browser, there are surrounding quotes as well ?
Comment: Isn't this same question as http://stackoverflow.com/questions/33094739/how-to-convert-a-string-to-json-object-in-c-sharp/33095011?noredirect=1#comment54007512_33095011
Answer: This is happening because you are serializing the data to JSON manually (in code) and when you return the data from controller, the framework serializes the same thing again, which is already a json formatted string!
To solve that, simply do not serialize it, let the MVC/Web API framework do its job and create a JSON out of your object.
If you are using Web API use like this
[HttpGet]
public object jsonvalues()
{
    var x = new
    {
        status = "Success"
    };
    return x;
}

If you are using MVC, use like this
[HttpGet]
public ActionResult jsonvalues()
{
    var x = new
    {
        status = "Success"
    };
    return Json(x, JsonRequestBehavior.AllowGet);
}

Both will return

{ status: "Success" }
Comment: :but i cant able to return 'x' directly,it shows an error ''Cannot implicitly convert type '' to 'string'.
Comment: @hakkeem see the methods I have shown as example, you **do not** return `string` from your web api controller method, return `object` instead.
Comment: what namespace does Json live in?


Check if stream from HttpServletResponse was download by client - JAVA

Question: Basically, my system generates url's to download files from my server. I make this using Struts with a result of type 'stream'. This work great.
Now I want to notice for each file downloaded, if it was FULLY downloaded.
I've been searching for a while but really don't know how to continue. I'm a beginner with this.
**
New Action:
**
  public String download(){
  try {
            String path = Init.getWebInfPath() + UploadManager.getInstance().getProperty("UPLOAD_DIR") + content.getZipFile();
            file = new FileInputStream(new File(path));
        } catch (Exception e) {
            return ERROR;
        }

        Long overallSize = null;
        try {
            overallSize = file.getChannel().size();
        } catch (IOException e) {
            e.printStackTrace();
        }

        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=\""+content.getZipFile()+"\"");
        response.setHeader("Content-Length", String.valueOf(overallSize));

        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            int read;
            read = file.read();
            while (read>0){
                sos.write(read);
                read = file.read();
            }
        } catch(Exception e){
          return ERROR;
        }

        return NONE;

}
**
New xml:
**
<struts>
     <package name="content" namespace="/content" extends="default">
    <action name="download" class="com.tictapps.adserver.web.content.ContentAction" method="download">
        <result name="none"/>
    </action>
</package>
</struts>

Comment: The code looks fine.
Answer: Once you return the stream result, you've no more control on the OutputStream.
The first ways coming to my mind to ensure that the file is completely downloaded are:

Write directly to the OutputStream, and return the result NONE (that is mapped to nothing) instead of SUCCESS (that you've mapped to Stream). You will have full control on the response, but will lose some of the framework automatisms. This works, I've did it in the past.
Create a custom result based on the Stream result's source code, eg.  StreamWithConfirm, and add the logic you need in it.
You could probably do it in a custom interceptor (in the post-invocation part, obviously), but I'm not sure and BTW this would be the hardest of the three for a newbie.

The n. 1 (adapting the code from the linked answer) should be what you need.
Comment: AWESOME. It worked! Also I was reading from fil while>0 (it had to be !=-1). Final question: if sos.close line is reached, you can assure that the file was delivered correctly?
Comment: Ok, thanks, I tried to make number 1, but don't know how to continue. Please check the new info.
Comment: 1. Close the ServletOutputStream (better in a finally{} block); 2. How to continue ? When you reach `return NONE;`, the file has been fully downloaded! Do what you need to do the line before that return ;) Also remember to upvote and accept the answer when you'll be comfortable with it.
Comment: I'm sory but this way I always download a 5 bytes file (invalid). The download appears in the Chrome bar when sos is closed, but it only starts to download after return line.
Comment: And after that I get this error:
org.apache.struts2.dispatcher.Dispatcher error
GRAVE: Exception occurred during processing request: No puedo llamar a sendError() tras llevar a cabo la respuesta
java.lang.IllegalStateException: No puedo llamar a sendError() tras llevar a cabo la respuesta
 at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:450)
 at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:150)
 at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
 at ...
Comment: Then you're doing something wrong. Please update your code with the latest additions
Comment: Well, 1) you are NOT flushing and closing any `sos`, and 2) you are still mapping "none" to something. You don't need to map it to anything, returning Action.NONE means *"don't return any result"*. Use an empty (or self closing) action in struts.xml
Comment: You can assure that *everything has been sent and no error has been thrown*, that I guess is enough for what matters to you. Other than that, I'm not sure when an error is thrown, eg. what happens if the file is downloaded in a damaged section of the hard drive, but that's OS-dependent. For example in DOS when you copied files with "copy foo.txt bar.txt", foo were copied into bar without checks, and you'd discovered that the bar file was corrupted only after opening it


Relacionar inputs dinamicos com datalist a outros inputs dinamicos

Question: sou novo por aqui e curioso na programação, então desculpe se falar besteira, mas preciso de ajuda.
Tenho um formulário com a opção de inserir inputs dinamicamente.
Sempre que se adiciona um "item", são adicionados dois inputs, o "foo" e o "bar".
Todos os "foo" se relacionam com o datalist "list".
Todos os "bar" são inativos e seu valor deve ser alterado sempre quando o valor de "foo" for alterado.
HTML INPUTS:

    <input name="foo[]" list="dList" type="text">
    <inpu name="bar[]" disabled="" type="text">

    <input name="foo[]" list="dList" type="text">
    <inpu name="bar[]" disabled="" type="text">

<datalist id="dList">
  <option label="Item 1" datavalue="1" value="Item 1">
  <option label="Item 2" datavalue="2" value="Item 2">
</datalist>

A única maneira que encontrei de pegar os inputs (dinamicos) foi:
input = $('#listaServicos').find(':input'); // array de inputs
// aqui tereis tanto os _"foo"_ quanto os _"bar"_

E depois fazer um for trabalhando com eles:
valores = [[1,3000],[2,5000],[3,4000],[4,10000],[5,10000]];

for (i = 0; i < input.length; i++) {
  name = input[i].name;
  console.log("name: "+ name);
  if(name.indexOf('foo') > -1){
    // aqui preciso pegar o atributo _"datavalue"_ do datalist
    // correspondente, comparar com a key array valores
    //e preencher o _"bar"_ com o valor
  }
}

O problema maior esta em relacionar o "foo" com o datalist, pois o "foo" e o "bar" estarão sempre no mesmo subarray.
Desde já agradeço por qualquer ajuda quer vier
Answer: Segue uma alternativa de implementação do que entendi do problema, com certeza existem maneiras melhores de implementar, o código está bem auto-explicativo mas segue uma breve descrição do que ele faz:
Primeiramente coloquei a função .on('input') do jquery que é acionada sempre que o input for alterado, logo em seguida pego o valor selecionado e procuro ele no datalist(dList) através do seletor jquery, com o valor de fato procuro pela chave correspondente no array de valores[], após encontrar simplesmente atribuo o valor no input bar com o siblings jquery.
*Nota que o código só funciona nesse formato do array valores, tentei alterar mínimo possível, qualquer dúvida comenta ai, espero que ajude.

//input = $('#listaServicos').find(':input'); // array de inputs
// aqui tereis tanto os _"foo"_ quanto os _"bar"_

valores = [
  [1, 3000],
  [2, 5000],
  [3, 4000],
  [4, 10000],
  [5, 10000]
];

$('input').on('input', function() {
  var value = $(this).val();
  var chaveSelecionada = $('#dList [value="' + value + '"]').data('value');
  var valorDaChaveNoArray = procuraPorChave(chaveSelecionada);
  $(this).siblings("input").val(valorDaChaveNoArray);

});

function procuraPorChave(id) {
  for (var i = 0; i < valores.length; i++) {
    for (var j = 0; j < 2; j++) {
      if (valores[i][j] == id) {
        return valores[i][j + 1];
      }
    }
  }
}

    <input name="foo[]" list="dList" type="text">
    <input name="bar[]" disabled="" type="text">

    <input name="foo[]" list="dList" type="text">
    <input name="bar[]" disabled="" type="text">

<datalist id="dList">
  <option label="Item 1" data-value="1" value="Item 1">
  <option label="Item 2" data-value="2" value="Item 2">
</datalist>
Comment: Grande resposta!!!
Grato pela ajuda, não esperava uma resposta tão precisa e rápida!
Comment: Adicionalmente, toda vez que um input é adicionado, tenho que REexecutar o trecho "$('input').on('input', function() {....}" para que funcione nos novos inputs.


How to initialize variables that contains list of tuples in tensorflow?

Question: I am trying to work through this guide.
for this line of code, I get error:
model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)

FailedPreconditionError: Attempting to use uninitialized value Variable_2
     [[{{node Variable_2/read}} = Identity[T=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Variable_2)]]

How do I initialize a list of tuples in tensorflow?
I tried to change this line of code from:
training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

to:
training_y = tf.global_variables_initializer([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

but get error:
TypeError: global_variables_initializer() takes 0 positional arguments but 1 was given

what am I doing wrong to initialize the variable?
entire code:
import tensorflow as tf
from tensorflow import keras

model = keras.Sequential()

input_layer = keras.layers.Dense(3, input_shape=[3], activation='tanh')
model.add(input_layer)

output_layer = keras.layers.Dense(1, activation='sigmoid')
model.add(output_layer)

gd = tf.train.GradientDescentOptimizer(0.01)

model.compile(optimizer=gd, loss='mse')

training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])
training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)
# model.save_weights('demo_model.h5')
# model.load_weights('demo_model.h5')

text_x = tf.Variable([[1, 0, 0]])
test_y = model.predict(text_x, verbose=0, steps=1)

print(test_y)

Updated code:
import tensorflow as tf
from tensorflow import keras

model = keras.Sequential()

input_layer = keras.layers.Dense(3, input_shape=[3], activation='tanh')
model.add(input_layer)

output_layer = keras.layers.Dense(1, activation='sigmoid')
model.add(output_layer)

gd = tf.train.GradientDescentOptimizer(0.01)

model.compile(optimizer=gd, loss='mse')

sess = tf.Session()  #NEW LINE

training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])
training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

#init_op = tf.initialize_variables([training_x, training_y])
init_op = tf.initializers.global_variables()

sess.run(init_op)  #NEW LINE

model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)
# model.save_weights('demo_model.h5')
# model.load_weights('demo_model.h5')

text_x = tf.Variable([[1, 0, 0]])
test_y = model.predict(text_x, verbose=0, steps=1)

print(test_y)

Comment: Your code isn't the same as is on the tutorial which you've linked. Please show your actual code - it's impossible for us to tell you why this is happening but it's clear that 1) the variables aren't being initialized, and 2) `global_variables_initializer()` takes no arguments.
Comment: @IanQuah I added the entire code
Comment: Where is `var_list` coming from?
Comment: @IanQuah that was my attempt to initalize the variables I removed it in the above example
Answer: sess = tf.Session()  #NEW LINE

training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])
training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

init_op = tf.initialize_variables([training_x, training_y, test_x, test_y])  #NEW LINE

sess.run(init_op)  #NEW LINE

model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)
# model.save_weights('demo_model.h5')
# model.load_weights('demo_model.h5')

text_x = tf.Variable([[1, 0, 0]])
test_y = model.predict(text_x, verbose=0, steps=1)

print(test_y)

Hopefully that gets your through your "uninitialized variables" issue.
Basically, the issue you're running into is that TF is a wrapper around C++. So, to handle some optimization stuff, they require you to 1) define all the variables, 2) initialize them BEFORE doing any operations. Hence, you faced the issue of
model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)

giving you the "uninitialized variables" error.
Hope this helps!
Comment: I removed `test_x` and `test_y` from `init_op` line. Still getting same error as above.
Comment: Also tried changing `tf.initialize_variables` to `tf.variables_initializer`, still same error.
Comment: Try [global initializer](https://www.tensorflow.org/api_docs/python/tf/initializers/global_variables) - it's probably because now even though the variables are initialized, the models layers are not
Comment: I commented out `tf.initialize_variable` and tried `tf.initializers.global_variables()`. It got through `1/1000` epoch, but then gave me this error `FailedPreconditionError: Attempting to use uninitialized value Variable
  [[{{node Variable/read}} = Identity[T=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Variable)]]`
Comment: After you've replaced it can you copy-paste your code into your original question?
Comment: Hmm, when I run the pasted code I get a different error. it has to do with `model.fit`, and stuff about the dimensions, not that it's uninitialized. `AttributeError: 'Variable' object has no attribute 'ndim'`
Comment: Thats very weird, Ive restarted my kernal multiple times and its still the same error.
Comment: Try pasting into a text file and running that- no kept sessions or whatever
Comment: Sorry, I don't know how to help you beyond that. I will say that now since you've done the global initializer as long as you don't define any tf variables after it, all your variables should be initialized
Comment: I fixed it! change the `tf.Variable` to `np.array`. I will accept your answer if you change it.