Por que Inteligência Artificial e Aprendizagem de Máquina são matérias diferentes?

Question: Ao procurar cursos especializados de programação ou com demanda de mercado, dois deles se destacam:

IA - Inteligência Artificial (ou AI - Artificial Intelligence)
AM - Aprendizado de Máquina (ou ML - Machine Learning).

Ao meu ver, ML poderia ser uma subcategoria de AI. Então por qual motivo ele é um curso totalmente distinto? Teria a ver pelo motivo de serem assuntos muito complexos ou fazerem mais ou menos uso de algorítimos matemáticos?
Comment: @LuizVieira espero ansiosamente uma das suas magnificas respostas sobre o assunto haha
Comment: haha Obrigado pela consideração, @MarceloBonifazio. Mas as respostas já foram dadas (incluindo em comentários) pelos demais colegas. E a pergunta acabou de ser fechada (automaticamente, aliás). Eu gosto do assunto, mas acho o fechamento justo porque essa discussão é difícil (e bastante opinativa, na minha opinião rs). Por que Matemática e Estatística são matérias diferentes? Por que se estuda Lógica na Engenharia, na Computação e na Filosofia? Veja como essas perguntas são muito similares. Enfim, mesmo se não fosse opinativo, dificilmente acho que seria construtivo para este site.
Comment: Curiosamente, hoje o UOL publicou [um artigo sobre cientistas usando dados para prever de tudo](https://noticias.uol.com.br/ciencia/ultimas-noticias/redacao/2017/01/16/big-data-e-colaboracao-permite-prever-de-epidemias-a-ataques-terroristas.htm). Esse tipo de processo (em que dados são usados para se construir um modelo preditivo) certamente é parte importante da AM. Note como embora o artigo não cite uma única vez a IA, cita "modelos matemáticos", "modelo estatístico", e "[...] matemática e estatística são os ingredientes da receita do bolo perfeito".
Comment: Uma máquina que aprende não seria inteligente? E a inteligência de uma máquina, não seria artificial?
Comment: Não tenho grande conhecimento nesses aspectos, mas vejo que IA é uma disciplina muito abrangente, que a AM está dentro dessa disciplina, o AM é mais centralizado em teorias de como uma máquina aprende e os padrões que ela pode reconhecer.
Comment: Vixi, colega... acho que essa pergunta tende a ser baseada em opiniões, hein? *Na minha opinião* você tem razão, no sentido de que os assuntos são relacionados (e de que AM é, de certa forma, uma disciplina da IA). Mas pode haver quem discorde, talvez porque enxergue o conhecimento aplicado da AM mais como tendo origem na estatística, por exemplo. Já a escolha por ter um curso separado pode decorrer meramente da quantidade de assunto a ser tratado (já que ambas as áreas são *enormes*). Enfim, eu me pergunto sobre o quão construtiva vai ser essa discussão em particular. :/
Comment: @LuizVieira concordo que opiniões devem ser evitadas e respeitadas, entretanto nesse caso as evidências dos termos apontam para uma direção específica...https://pt.wikipedia.org/wiki/Journal_of_Machine_Learning_Research Não envio este link por ser wiki, mais pela editora...
Comment: Todas as respostas só me fizeram pensar que um curso vendido apenas como sendo de IA está errado. Deve se especificar quais tópicos da IA este curso aborda.
Answer:
Atenção: A abordagem deste post é apenas uma das formas de tratar um
  assunto totalmente amplo como a inteligência artificial. Ele deve ser
  entendimento como objetivamente e resumidamente didático e não deve ser interpretado
  como verbete fechado, verdade absoluta ou fonte primária. O
  StackOverflow em português é um site de perguntas e respostas
  objetivas, e não faz parte de seu escopo a elaboração de temas
  extensos. Para questões mais elucidativas, tratar no chat ou
  documentação específica do assunto!

Inteligência artificial é uma área multidisciplinar envolvendo psicologia,filosofia, computação, matemática, e como lembrado pela contribuição do membro Luiz Vieira, aprendidas também em outros cursos como o curso de economia.
Aprendizado de máquina é uma das matérias aprendidas dentro da disciplina inteligência artificial, que trata de abordagens de algoritmos de aprendizado computacional. Aprendizado é um dos comportamentos conhecidos do fenômeno da inteligência.
Acompanhe o seguinte raciocínio:

1 - Homens São feitos de átomos.
2 - Mulheres são feitas de átomos.
Conclusão - Homens e mulheres são do mesmo gênero sexual, pois são feitos de átomos.

Essa é uma pequena demonstração de falácia de composição, que pode induzir a raciocínios errados. Esse exemplo não se trata de dizer que o assunto do tópico se trata disso, ou que abordagens diferentes apontem para isso, mas uma advertência para que assuntos tão co-relacionados não caiam em falácia. Portanto, do ponto de vista conceitual semântico, Inteligência Artificial e Aprendizado de Máquina são conceitos diferente. O que não quer dizer que, dependendo da abordagem, em algum momento, possam significar a mesma atividade. Tudo depende de como é contextualizado. Espero ter contribuído e não ter dado a impressão de ser um assunto fechado.
Por fim, recomento o livro "Inteligência Artificial" de Peter Norvig e Stuart Russell. No Brasil é distribuido pela editora Campus. Pode encontrar pela Amazon.
É possível encontrar também esse livro em boas livrarias de renome.
Comment: Olá Paulo. Muitas das técnicas de AM são aprendidas *também* em outros cursos (principalmente de estatística e economia): [regressão linear](https://pt.wikipedia.org/wiki/Regress%C3%A3o_linear), [inferência bayesiana](https://pt.wikipedia.org/wiki/Infer%C3%AAncia_bayesiana), etc. Por isso, embora a sua resposta esteja certa, ela não é necessariamente canônica. Acho que vale editar para adicionar essa observação. Outra coisa é: a recomendação do livro está ok, mas a frase final pareceu propaganda. Eu removeria essa frase para evitar que a sua resposta seja caracterizada como SPAM.
Comment: Editei a parte final.
Mas queria uma sugestão de como editar a parte inicial para o autor da pergunta, e quem tiver a mesma dúvida, compreender que estes resumos não são verdades absolutas. Você tem privilégios de edição, poderia melhorar isso para mim? Se não for abuso da minha parte.
Comment: Você também pode editar amigo.
Comment: Eu sei, mas queria uma sugestão!
Achou que vou deixar simplesmente uma observação.
Comment: Vc diz editar na pergunta do AP? Acho que não precisa. Você pode colocar qualquer sugestão diretamente na sua resposta. Acho que faz parte da resposta mesmo.
Answer: Um adendo, talvez essa imagem seja mais explicativa:

Fonte da imagem: https://www.razorrobotics.com/artificial-intelligence
Machine Learning pode sim ser considerado um sub-item de Inteligencia Artificial, as duas matérias são intrinsecamente ligadas, muitos conceitos que aprende em IA são depois empregados com ML.
Podemos ainda fazer uma analogia com Calculo Diferencial e Integral, ou Matemática Discreta por exemplo que são sub-itens de Matemática, porém existem muitos conceitos diferentes do que se aprende em um módulo de Matemática puro.
As matérias são ensinadas em módulos diferentes porque existem muitas aplicações e conceitos distintos.
Lembro que na faculdade aprendi esse conceito, do qual acredito até certo ponto:
Inteligencia Artificial pode ser considerado qualquer sistema não humano que realiza determinada tarefa autônoma, sem necessidade de intervenção de uma inteligencia biológica. Qualquer algoritmo que sirva pra alguma finalidade pode ser considerado uma inteligencia artificial;

Por exemplo um sistema que receba X idades e calcule a mediana dessas idades é um tipo de IA. Não há intervenção humana para o cálculo da idade, a não ser em imputar as idades para a máquina fazer o calculo automaticamente, a isso se dá o nome de IA Fraca.

Aprendizado de Máquina funciona como um sistema que aprende qual comportamento deve seguir dependendo das iterações que o mesmo tiver. De inicio possui um comportamento padrão, mas que com o tempo, dependendo do que entrar e da saída esperada, pode ou não mudar esse comportamento.

Um exemplo utilizando essa magnifica biblioteca em js: synaptic.js, especializada em redes neurais. Neste exemplo é utilizado um algoritmo perceptron [que é uma sub-categoria de redes neurais, que pode ser ou não um tópico de ML dependendo da ementa de alguns cursos de IA] para treinar um algoritmo que consiga resolver sozinho um XOR, neste exemplo são usados 2 entradas, 3 camadas ocultas e uma saída, quando clicamos em iniciar treinamento ele mostra quantas iterações foram necessárias para que o sistema aprendesse sozinho o comportamento do XOR.
Comment: As matérias são ensinadas em módulos diferentes porque existem muitas aplicações e conceitos distintos. Obrigado!
Comment: Excelente resposta. +1
Answer: a visão de que ML é uma subcategoria de IA está correta, porém para ficar mais claro esse entendimento, é importante que você saiba que quando falamos de IA, estamos falando de um enorme variedade de matérias, algumas delas são:sistemas especialistas, aprendizagem de máquina, algoritmos de busca, etc.
Em geral as disciplinas de IA, se preocupam em apresentar uma visão geral dessas matérias, promovendo um entendimento do que existe e das possibilidades possíveis, e diante disso o aluno/pesquisador/engenheiro/programador poderá escolher qual a subcategoria vai investigar melhor. Isto pode ser feito através de disciplinas mais específicas, como a de aprendizagem de máquina, que busca  trazer um conhecimento mais profundo de técnicas, como: Aprendizado baseado em árvores de decisão,  Rede neural artificial, Algoritmos genéticos, Clustering.
Comment: Não sei quem negativou seu post, porque está correto. Achei uma boa abordagem. Tem o meu +1. Até complementa minha resposta!
Comment: Opa @PauloSérgioDuff, eu também não entendi, mas kkkkkk e você tem razão, o seu foi bem mais elaborado e de certa forma todos que comentaram foram complementado a resposta um do outro. Valeu pelo +1. :D
Comment: Eu ainda vou comentar lá no Meta sobre DownVoters! A boa notícia é que quem tiver a mesma dúvida e procurar no google, vai ter informações ricas e detalhadas.
Answer: "Então por qual motivo ele é um curso totalmente distinto?"
Essa pergunta independe de como realmente a máquina trabalha.
"Teria a ver pelo motivo de serem assuntos muito complexos ou fazerem mais ou menos uso de algorítimos matemáticos?"
Não existe computação sem algorítimos que utilizam de matemática... A quantidade ou o tamanho está relacionado com o algorítimo em si, depende do que ele vai fazer, mas tanto AI que irá definir toda uma gama de comportamentos e interpretações quanto o ML que irá absorver essa definições, vão utilizar uma quantidade razoável de complexidade.
Não tenho dúvida que são termos intimamente relacionados e que ML é uma sub-categoria de AI.
A diferença ao meu ver, já que afirmo que ML é sub-categoria de AI, é que AI está mais ligada a funções cognitivas inerentes ao ser humano, e que ML se utiliza desses conceitos para aprender e executar.
Ao meu ver é como se AI fosse a teoria e ML a prática.
Então respondendo a sua pergunta, "Por que Inteligência Artificial e Aprendizagem de Máquina são matérias diferentes?" ...
Não são matérias diferentes, são matérias complementares...
Aqui você pode ver que ML é sub-categoria de AI, claro que é wiki, mas pela lógica podemos concordar que sim...

A aprendizagem automática ou aprendizado de máquina (em inglês: "machine learning") é um sub-campo da ciência da computação que evoluiu do estudo de reconhecimento de padrões e da teoria da aprendizagem computacional em inteligência artificial.

E aqui pode ver o um pouco mais pela mente de um dos precursores da AI.
Comment: @LuizVieira não disse que vc discordava, só disse que o link que enviou de certa forma refutando a ideia é que é refutável(e foi refutado com essa imagem que se refere). Não acho que dependa de interpretação, e como eu disse não vejo como separar ML de AI, mas vejo AI sem ML... hehe mas entendo sua preocupação no que tange a utilidade, mas ai a pergunta seria outra,,, nussa parece que aprendi essa palavra hj (refutar)...kkkk.. Tem horas que a formalidade, me faz parecer mei bobo... Bom dia man....
Comment: Cara, como eu disse, eu não discordo. Mas é que isso depende muito da interpretação do indivíduo, principalmente sob a luz do problema que ele tá tratando. [Essa imagem](http://www.enterrasolutions.com/media/data-mining-Venn-diagram.png) (que é mencionada lá no link que eu referi) ilustra essa sua "lógica irrefutável". Só que ao mesmo tempo ela ilustra como isso tudo é tão multidisciplinar que eu me pergunto se ficar discutindo isso não é discutir o sexo dos anjos. Talvez seja mais útil discutir se determinada técnica pertence à área X ou Y (e ainda assim eu tenho as minhas dúvidas rs).
Comment: Ah sim. relendo pude entender melhor, mas a quantidade de algorítimo está ligada ao algorítimo em si, ambos vão usar uma quantidade considerável. Pelas respostas sobre AI e ML indicadas no comentário de sua pergunta, poderás ver que não é algo curto;
Comment: "Não tenho dúvida que são termos intimamente relacionados e que ML é uma sub-categoria de AI." Eu concordo, e até acho que a maioria das pessoas concorde. Mas [há quem discorde](https://www.quora.com/What-are-the-main-differences-between-artificial-intelligence-and-machine-learning): "*[...] Following this line of reasoning, Machine Learning is NOT a subset of AI. It really is the ONLY kind of AI there is.*"; e também "*Machine learning doesn't care about intelligent behaviour but accuracy and patterns.*".
Comment: Grande @MagicHat, apenas observar que eu disse "fazerem mais ou menos uso" e não "que não utilizem". Eu disse isso por que ao ver os requisitos desse dois cursos, um pedia uma nível mais avançado que outro.
Comment: @LuizVieira Entendo, refutar não só é valido como necessário,  entretanto acredito que usando da lógica minha afirmação se torna irrefutável, não creio haver ML sem o entendimento da AI, e creio que AI é um termo anterior...https://pt.wikipedia.org/wiki/Journal_of_Machine_Learning_Research ,  mas posso estar errado...


Feature selection for MLP in sklearn: Is using PCA or LDA advisable?

Question: I have a binary supervised classification problem with about 62 features, by eye about 30 of them could have reasonable discriminating power. Depending on the situation I have between 12,000 and 2,000 samples ( I consider a number of cases but the features are the same for all ).I am using sklearn and the MLP does not have a dedicated feature selection tool like decision trees do. My question is what is the recommended way to preform feature selection here? I have read in the sklearn documentation that LDA should not be performed in a binary classification problem and PCA is under the unsupervised methods on the sklearn website.
Does anyone have any experience with this that could suggest a method?
Edit: Added number of samples
Answer: Most probably, you do not need dimensionality reduction.
People do dimensionality reduction if the problem is intractable, but with 62 features, it is not the case.
People also sometimes reduce dimensionality because the number of observations is too small in comparison with the number of features. But if your sample is small, using neural network is a bad idea anyway - use logistic reression or SVM instead, as it is more robust.
Dimensionality reduction and feature selection are also sometimes done to make your model more stable. But you can stabilize it by adding regularization (parameter alpha in the MLPClassifier).
Dimensionality reduction and feature selection lead to loss of information which may be useful for classification. So if you don't have a very serious reason for this, do not use PCA or LDA fith MLP.
Comment: I edited my question for the number of observations I have, I currently set alpha doing a grid serach. I was asked to look into dimensionality reduction but maybe I am going a bit overkill here.
Answer: Well, you didn't say how many observations you have as @David pointed out.
Also it seems to me, you are a bit confused about supervised and unsupervised learning. The MLP you are using to build your classifier is indeed a supervised method. But feature selection does not have a "correct" answer. You can try to reduce the dimensionality with minimizing the loss of information hidden in the data, but that is still a problem for unsupervised method. How will the features look like? How many of them should there be? There isn't a single answer. PCA is indeed an unsupervised method, that is widely used for this and you can definitely try to apply it to your data. Also there are many ways to determine how many components should you retain. Check out the elbow diagram and proportion of variance explained for example.
Also it should be pointed out that PCA is not a feature selection method, but rather a dimensionality reduction method. It doesn't select some features from the original dataset, but transforms it into new features that are "ranked" on how much they contribute to the information.
Answer: My suggestion to go with LIME framework https://github.com/marcotcr/lime
This tool will help you in analyzing feature importance.
It will help you in analyzing features on sample level and won't provide any information on model level.
Comment: What is this tool?  How does it work to analyze feature importance?


Python list all submodules imported from module

Question: My code starts with the following:
from module import *

How can I get a list of all submodules imported from this module.
For example module has:
module.submodule
module.submodule2
module.anothersubmodule

I want to get after from module import *:
[submodule, submodule2, anothersubmodule]

(not strings with name of submodules, but a list with all submodules themselves)
UPD: I understood that I asked about XY problem.
So here's what i'm trying to achieve:
I have a folder called modules that will have a bunch of scripts following the same pattern. They will all have a function like main(). In my main script i want to import them all and iterate like that:
for i in modules:
    i.main(*some_args)

Comment: All information about imported modules can be found in `sys.modules`. Also don't use wildcard imports, they can be hard to debug and can cause one or the other surprise.
Comment: That somehow sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What's the higher level goal you are trying to achieve?
Comment: I `import *` because i want my script to have pluggable modules, so that i can just edit `__all__` in `__init__.py` and add submodules to modules folder. Then my script will handle all modules using that list.
Answer: Use the pkgutil module. For example:
import pkgutil
import module

modualList = []
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__):
    modualList.append(modname)

Comment: thanks! here is a somewhat simpler version:

`import pkgutil; [s[1] for s in list(pkgutil.iter_modules(some_module.__path__))]`
Answer: What about importlib?
import importlib
import os

directory = './module'

for filename in os.listdir(directory):
    filepath = os.path.join(directory, filename)
    if not os.path.isfile(filepath):
        continue

    modulename = os.path.splitext(filename)[0]

    args = [filename, filepath]

    module = importlib.import_module('module.{}'.format(modulename))
    module.main(*args)

With 3 differents Python files in ./modules, all like:
def main(*args):
    print('module one: {}'.format(', '.join(args)))

It gives:
module three: three.py, ./module/three.py
module two: two.py, ./module/two.py
module one: one.py, ./module/one.py


It's possible to block an url path with htaccess?

Question: Currently i'm getting a DDoS attack directly to this URL: myserver.com/?task=randompost, the "?task=randompost" doesnt exist anymore so they get redirected to the home webpage. Considering that they are attacking directly to that url path, its there any way to block all users that tries to enter that path??
Thanks!
Answer: This can be done with mod_rewrite:
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} =task=randompost
RewriteRule ^$ - [F,L]

This will ONLY work for example.com/?task=randompost request (will not work for example.com/index.php?task=randompost) and it needs to be placed in .htaccess somewhere at the top (before any other rewrite rules). If placed in virtual host context, the ^$ needs to be replaced by ^/$.
The [F] flag will instruct Apache to return 403 error immediately.


How many bit strings of length 7 exist if the string remains unchanged if it is reversed?

Question: How many bit strings of length 7 exist if the string remains unchanged if it is reversed ?
1 1 1 1 1 1 1 and 1 0 0 1 0 0 1 are an example that is unchanged if reversed.
0 0 0 0 0 0 0 and 0 1 1 0 1 1 0 would then also be unchanged..
Is there some way to calculate this? or do I have to find all the 128 bit strings and reverse them to see if they fit?
Comment: I didn't mean how many _symmetric_ 4-bit strings, I meant how may 4-bit strings in total. (I was hoping you could figure it out for yourself from there, but Doug Spoonwood has done it for you.)
Comment: @looooost, you have $4$ digits, for each digit you have $2$ options, either on, or off. so for the first digit you have 2 options, for the second 2 options, for the third 2 options, for the fourth 2 options, thats $2*2*2*2=2^4=16$. your answer (4^2) is correct only by coincidence.
Comment: How many bit strings of length $4$ are there? What do you get if you take a 4-bit string $abcd$ and reflect it about the fourth bit to make $abcdcba$?
Comment: of length 4, 4 exist 1 1 1 1, 0 0 0 0, 1 0 0 1 and 0 1 1 0.
Comment: total 4 bit strings are 4^2
Comment: No. it is not $4^2$. well yes, it is $4^2$, but only because $4^2=2^4$.
Comment: yeah sorry I meant 2^4, just typo :(, thank you
Answer: So consider a string

a b c d e f g.

If we reverse this string we have

g f e d c b a.

Now by hypothesis the first digit of 1. corresponds to the first digit of 2, the second digit of 1. to the second digit of 2 as follows:
<code>a b c d e f g
| | | | | | |
g f e d c b a
</code>
Thus, if and only if a bit string remains the same when reversed, then and only then a=g, b=f, and c=e.  So, if we figure out how many bit strings of length 4 exist, we'll have figured out the answer.  And more generally, if we have a bit strength of length x, then:
The number of palindromic bit strings of length x is equal to the number of bit strings of length
x/2 if x is even,
or the number of bit strings of length (x+1)/2 if x is odd.
Comment: You mean $(x+1)/2$, not $(x-1)/2$.


Show available languages in content-view

Question: in older-drupal-versions when content was translated to different languages, it was possible to indicate in which other languages that content is available and in which not.
Let's say I have en, de and fr as languages. Foo is translated to en and de and bar is translated to fr only.
In my contents index (/admin/content) I want to display that linked info as:
fooen, de, fr
baren, de, fr
Where clicking a non-striked text leads to the edit of the particular node and clicking the striked one will start a translation.
Is that, or something which gets close, possible in D8?
Answer: @CG-monroe is correct that there isn't anything out of the box, but you can still list the language for each node, edit the content view (defaults to /admin/structure/views/view/content) and add Translation language to the fields, you can also add the Original language field if that is useful as well.
Comment: And a language filter option to the filters so you can see specific language. I forgot this wasn't standard since the mod was made on my ML sites so long ago...lol
Comment: Good point, I usually end up adding a few additional filters to the content now, depending on what the site requires.
Answer: The content admin screen is now just a view.  AFAIK there is no view widget that will do that.
It probably would be possible to write a entity specific global widget for this.  Basically, you can get the list of installed languages from the language manager and then for each entity row use the getTranslations() method to find what has been translated.


Confusion regarding definition of similar triangles.

Question: I am confused with the definition of similarity two triangles.My textbook defines similarity as follows:

corresponding angles are equal.

corresponding sides are in the same ratio.

My question is that do we need to state both $1$ and $2$ because I think they are equivalent,so saying one would suffice.
Can someone give a proof of their equivalence?
Comment: Yes, they are equivalent.
Answer: Both definitions are necessary when defining similarity of two polygons. In the particular case of triangles, one can prove that weaker conditions are enough, called similarity criteria. For two triangles, your conditions 1. and 2. correspond to AA and SSS criteria.
But similarity criteria are theorems, not definitions: most textbooks use for triangles the same definition of similarity valid for a generic polygon.


How exactly tell the root of a song over a defined scale on ambiguous harmonic context?

Question: I play a song in either C major key or A minor key.
Usually I determine the root (C or A) taking into account clues like:

The happy or sad feel of it all
The first chord (C or Am)
Stereotypical tensions like G7-C or E7-Am

But I came up with a pretty jazzy baroque thing starting in C6 or Am7/C, does not feel exactly sad or happy, and does not have usual tensions.
How can I rationally infer the root? What would follow a pro?
How to tell whether the first chord is a I6 or a vi7 (Im7 or i7 in key of A). Despite of several notations Nashville, Roman, etc.
Comment: "Root" refers to the basis of a chord.  The term for the basis of a scale or key is "tonic"
Answer: You don't need to start on i or I on any piece of music and one chord alone will never tell you what key you are in. You need more context to actually know what's going on.
The rest of the progression will tell you what key you're in especially when you come across dominants chords and cadences. If you encounter a lot of E7 chords I'd expect it to be in A minor.  If you encounter a lot of G7 chords I'd expect it to be in C major. It is also possible for the piece itself to weave in and out of those two keys especially since they are very related.
C6 is a very common substitution for Cmaj7 so if I had to guess, I'd bet you were in C major over A minor.
Comment: Never come across C6 substituted for Cmaj 7. But it is another reincarnation of Am7. Ambiguity!! As I've no doubt quoted before - look at Fly Me To the Moon. C or Am? Who knows? Who cares?!!
Answer: Check your phrase ends/points of cadence, also your "roof" and "floor" (the successions of highest notes in the treble, lowest notes in the bass). Dom is quite correct that a lot of music doesn't start with the tonic. Starting deceptively has been a valid technique since at least C.P.E. Bach and Joseph Haydn.
Establishing a tonality is often an active process. Frequently when you are doing so, you are also establishing the opposing tonalities that will serve as large-scale dissonances (or tensions, if you want) in the piece. In the earliest sections of a piece, this is usually by suggestion: relative to the weight placed on the tonic, cadential progressions of secondary keys will tend to be "incomplete" in some way, either by occurring in rhythmically weak spots (midway through a phrase, for instance), or by using weak cadences (half-cadences, deceptive cadences, cadences with chord inversions) or both.
A lot of music in the major isn't conventionally happy; likewise a lot in the minor isn't conventionally sad. Most music, major and minor, exists in a continuum of Affekt between the two poles.
Answer: Patrx2 and Dom's answers are both very good. To add to them:

Usually I determine the root (C or A) taking into account clues like:
The happy or sad feel of it all

I think Patrx said it quite well, I would add that minor sounds darker to most people than major, but adding meaning and emotional content to the sound is the function of the artist, it is not dictated by the chords. Darker often gets associated with sadder, but to quote Van Gough "I often think the colors of the night are more vibrant and alive than those of the day."

The first chord (C or Am)

Is as mentioned is not a reliable indicator. However, in popular music the root of last chord will almost always be the root of the song. The chord quality may have been substituted (e.g. its not uncommon to write songs in minor keys and then substitute all the chords with major chords on built on the same root.)

Stereotypical tensions like G7-C or E7-Am

The tension and release provided by V7 to I (and the accepted substitutions for it e.g. tritone, common tone, etc.) is more than just a stereotype, its part of the structure of western music. Its just an inescapable part of how we are culturally conditioned to hear music. Regardless of how modal, atonal, avant-garde, or experimental a piece may be, it still exists in a world where it is specifically playing against the listeners expectation of a satisfying old school authentic cadence.
V7 to I is less of an indication that a key has been established, its simply how a key is established, when it is placed on strong beats in important parts of the songs overall form.
To use your example:

As I've no doubt quoted before - look at Fly Me To the Moon. C or Am? Who knows? Who cares?!!

I wish I had the recording, but assuming the chords on ultimate guitar are correct http://tabs.ultimate-guitar.com/f/frank_sinatra/fly_me_to_the_moon_ver5_crd.htm I would say the song is clearly in A minor. It ends on A-7 (starts on it as well), and is constantly going E7 to A-7. Of course those chords could be 100% wrong, I'm basing my call here on that specific link.
I feel your pain though, I distinctly remember that what the hell is going on here? feeling trying to figure out *God Only Knows" off the Pet Sounds CD.
Edit:
In Phil Smith's answer he points out that the last chord in Fly Me To the Moon is actually a C not an A-7 as it is transcribed on the link I referenced earlier. In which case I will stick to my theory and say if the last chord is a C, the song is in fact in C not in A minor. If the chords on the linked page were correct, the song would be in A minor, but apparently they are not correct.
Comment: Yeah. I didn't mention final cadences because I got the impression that OP was trying to figure out where to take an initial idea for a piece or song, but I agree with your observations, especially with regards to dominant relationships. A work's tonality (for a work of more than trivial complexity) is created by a hierarchy of tonal relationships and tonal assertions of varying strength, and it takes _all_ of the elements of music working together to create that hierarchy of strengths, _soit_ progressions, _soit_ beat placement, _soit_ dynamics, _soit_ registers.
Comment: Jay Sklyler, you very astutely wrote: >in popular music the root of last chord will almost always be the root of the song. but then you go on to say Fly Me To The Moon is in A minor when the last chord (excluding the turnaround) is C. Fly Me To The Moon is definitely in C. Or whatever key you're in. The song people always get wrong is Unforgettable. Assuming it's in the key of C, most people assume it's in G (all those F#s, you know). But if you analyze it in the key of G, it's totally complex. In the key of C, it's straightforward. The F to Fmin is just the standard IV-IVm of American Popular
Comment: Phil, I don't have the recording. like I said, I just analyzed the chords on the transcription I included a link to above. That transcription has the last chord of the song as an A-7.
Comment: I've always questioned 'Unforgettable'. Where does it stop feeling in C and feel like it's now in G?
Comment: The last C could well be a piccardy third :)
Comment: @user1352530 - the tierce de Picardie (Picardy third) makes the final chord in a piece in X minor play as X major. Referring to Fly Me to the Moon, it would be A major. Referring to Unforgettable, it's in major anyway.
Comment: Fly me to the moon is in the minor.  Whether or not they do a little switcheroo and modulate to the relative major at the end or not doesn't change the fact that the verses strongly pull to the minor as the tonic.  Where the song ends is a good way to "guess" for a pop song (because pop songs often stay where they begin), but what really matters is the actual way the harmony works, so the ending chord here is a moot point: you could easily arrange fly me to the moon to end on the major or the minor chord, and it would sound good!  But that wouldn't retroactively affect the rest of the song
Comment: The thing that tricks is the major 2-5-1  (D-7 G7 CΔ7)  on "in other words, baby kiss me".  And that can easily be used to modulate to C.  But normally, that's quickly brought back home with another 2-5-1 going back to the minor (so B-7 or Bø E7 A-)
Answer: A good way is to try and write a simple bassline, and see what sounds good.  It's easy to come up with note clusters higher up where the root note is ambiguous, but much harder (but not impossible) to hide from it lower down the pitch scale.
Also, make up a melody that fits your chords.  Then write a bassline that fits that same melody, and that could point you in a good direction.
Alternatively, this way is much more subjective, but it is honestly the way I would do it.  And that is just to try and work out what chord "feels" like home.  You've already talked about what chord a piece begins on, but if you wiggle around your chords to end on an Am, or the same for a C, which one feels properly resolved?
If you mentioned cadences.  So does E7->Am feel more like a resolution or a modulation (same with G7->C.)
IF that all fails, play with the parallel minor or major of your potential keys.  If you're in C and you modulate to C minor, it's a mood change, but not odd-sounding if you lead into it properly.  The same with Am to A major.  It's cheesy and you probably won't want to use it in your context (of jazzy baroqueness), but it will tell you where you're at.
Because (usually but not always, as is the disclaimer for most musical "rules")
C major -> C minor sounds a bit mysterious and odd
Am -> A major sounds a bit cheesy
C major -> Sounds like a modulation
Am - > Cm Sounds like seriously WTF just happened.
Also, minor=sad is often wrong.  ESPECIALLY with flat 7ths.
PROOF:


Infinite series of trigonometric ratios

Question: The question is to compute:
$$(1+\cos A)+2(1+\cos A)^2 + 3(1+\cos A)^3+\ldots = \sum_{k=1}^{\infty}k(1+\cos A)^k.$$
I tried by setting $1+\cos A=y$, then the serie becomes
$$y+2y^2+3y^3+\ldots = \sum_{k=1}^{\infty}ky^k$$
It's not a geometric progression as the coefficients are not in the series.
How can I go further?
Hints are welcome.
Comment: Differentiate the geometric progression $\sum_n y^n$ with respect to $y$.
Comment: $y+2y^2+3y^3+...=y(1+2y+3y^2+...)$ Now, what is inside parentheses ?
Answer: Using Ratio test,
$$\lim_{n\to\infty}\dfrac{(n+1)(1+\cos A)^{n+1}}{n(1+\cos A)^n}=\left(1+\cos A\right)\lim_{n\to\infty}\left(1+\dfrac1n\right)=1+\cos A$$
So, the series can only converge if $|1+\cos A|<1\iff 1+\cos A<1\iff\cos A<0$
For $|y|<1,$ let $$S_n=\sum_{r=1}^nr y ^r$$
$$yS_n=\sum_{r=1}^nry^{r+1}$$
$$(1-y)S=y+y^2+y^3+\cdots=\dfrac y{1-y}$$
Answer: Theorem:
$$1+2x+3x^2+4x^3+\dotsb=\frac1{(1-x)^2}$$
Proof:

Now, multiply everything by $x$ and let $x=1+\cos A$.
For more info see this thread.

Infinite series of trigonometric ratios


How can we draw a line between two distant points using a finite-length ruler?

Question: We want to join by a line two distinct points $A$ and $B$. We have only a ruler of length $l>0$ and a pen. If $AB>l$ how can we do this?
Comment: we don't have a compass?
Comment: Can I fold the paper?
Comment: No, we don't have a compass, and we cannot fold paper. It's a plane geometry problem. We want to find an exact method. I'm trying to solve this by DESARGUE THEOREM and PROJECTIVE GEOMETRY.
Comment: Also posted to MO, http://mathoverflow.net/questions/188471/how-can-we-join-two-points-with-a-small-ruler
Answer: This is one instance of Desargues' theorem:

Use the ruler to draw two arbitrary lines through $A$ in the general direction of $B$. You can extend them by simply shifting the ruler along the portion of the line you've already drawn. Once you're close to $B$, end the lines in points $C$ and $D$. On the line $CD$ choose a third point $E$, and through $E$ choose two more lines, one which intersects $AC$ in $F$ and $AD$ in $G$, the other which intersects $BC$ in $I$ and $BD$ in $H$. Now $GH$ and $FI$ intersect in a point on $AB$. If you have made the arbitrary choices in a suitable fashion, then all those lines could be drawn with your short ruler, and the resulting point $P$ will be closer to $A$ than $B$ was. Externd line $BP$ and it will reach $A$.
If any of the lines needed for this construction is too long, you may iteratively perform this whole construction there, or pick your points such that they lie closer together.
As an alternative, you might use Pappos' theorem instead of Desargues'. It requires one point and one line less, and on the whole looks somewhat more symmetric:

As before, you start by drawing lines $AC$ and $AD$ in the general direction of $B$. You choose a point $E$ on $BC$ and a point $F$ on $BD$. Then you intersect $FC$ with $AD$ to obtain $G$ and $ED$ with $AC$ to obtain $H$. $EG$ and $FH$ will intersect in $P$ which lies on $AB$. Externd $BP$ and it reaches $A$, as before.
Comment: Also, "repeat as required" is not necessary - once you have the point $P$, you can simply extend $PB$ by chunks until you reach $A$.
Comment: It is good when $AB-l$ is small, but when $AB>>l$ is a huge value, no one could guarantee that you can draw line as $BD$ or $CB$...
Comment: @Bogdan: If you notice your line $AC$ is too far away from $B$, then you can draw a new line closer to the actual line $AB$. Or you choose $F$ and $G$ arbitrarily, then draw their connections by recursively applying this whole idea until your ruler becomes sufficient. If you want to connect $A$ and $B$ using only one instance of Desargues' theorem, then you have to have points which connect to both $A$ and $B$. And I can't think of any way to add to Desargues' configuration which would help me avoid that problem.
Comment: A small typo: "the other which intersects $CD$ in $I$ and $BD$ in $H$" => "the other which intersects $BC$ in $I$ and $BD$ in $H$"
Comment: @Mario: Thanks for pointing out the typo. The "repeat as required" might still be needed in an iterative fashion, if the lines I described to perform the construction are still too long to draw directly.
Comment: What i have to do after getting point P
Comment: @Soham: extend $BP$. I just edited my answer to clarify this aspect.


Obter dados em JSON

Question: [
{
"ID": 1,
"ano": 5
}
]

Não sei como obtenho em JSON o valor de cada um dos campos, neste caso "1" e "5", tal como apresento acima.
Na obtenção dos dados em JSON tentei seguir algumas dicas que fui procurando, mas em vão.
Apresento em baixo o que estou a tentar atualmente, mas sem sucesso.
public class JSONTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentobject = new JSONObject(finalJson);
            JSONArray parentArray = parentobject.getJSONArray("");
            JSONObject finalObject = parentArray.getJSONObject(0);

            int id = finalObject.getInt("ID");
            int ano = finalObject.getInt("ano");

            return "id: " +id+ " ano: " +ano;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        System.out.println("Result: " + result);
        tvdata.setText(result);
    }
}

Consigo obter todo o conteúdo junto, ou seja "[ { "ID": 1, "ano": 5 } ]" , mas encontro-me com dificuldades para obter determinados campos tal como mencionei.
Answer: Se a estrutura for exatamente como está na pergunta, você pode fazer desta forma:
String jsonString = "[{\"ID\":1,\"ano\":5}]";

JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = new JSONObject(jsonArray.get(0).toString());

System.out.println("ID: " + jsonObject.getInt("ID"));
System.out.println("ANO: " + jsonObject.getInt("ano"));

Também pode fazer assim:
String jsonString = "[{\"ID\":1,\"ano\":5}]";

JSONObject jsonObject = new JSONArray(jsonString).getJSONObject(0);

System.out.println("ID: " + jsonObject.getInt("ID"));
System.out.println("ANO: " + jsonObject.getInt("ano"));

Comment: Muito obrigada! @Diego Schmidt Resolveu o meu problema :-)
Comment: @Nokas Bom que deu... Coloquei outra forma que vc pode fazer.

Obter dados em JSON


How can I retrieve two entities that are associated with a connection entity, only under the name record2roleid?

Question: I have a connection that connects to the two entities "workorder" and "object" with a role name [record2roleid].
How can I check the connection between the two entities if they are just under the attributename [record2roleid]?
Comment: Show us what you have tried, atleast some SQL equivalent to convert into linq..
Comment: var connections = from c in ServiceContext.CreateQuery("connection")
                                  where c.GetAttributeValue("record2roleid").Name.Equals("x")
                                  select c;
Answer: Try with this way
<code><fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="connection">
    <attribute name="record2id" />
    <attribute name="record2roleid" />
    <attribute name="connectionid" />
    <attribute name="record2objecttypecode" />
    <attribute name="record1objecttypecode" />
    <attribute name="record1roleid" />
    <attribute name="name" />
    <attribute name="record1id" />

    <link-entity name="connectionrole" from="connectionroleid" to="record2roleid" link-type="inner" alias="ad">
      <filter type="and">
        <condition attribute="name" operator="like" value="%Part%" />
      </filter>
    </link-entity>
  </entity>
</fetch
</code>
Comment: Thank you, I have found a solution but I will try your solution later, because I also want to learn Fetch-Xml.:)

thanks again !


Similar Matrices Formula

Question: I was confused by the formula for similar matrices. The book says $A = S^{-1} B S$ if $A$ and $B$ are similar. But I'm wondering if $S B S^{-1}$ makes a difference at all? Which formula should I stick to in general?
Answer: $S^{-1}BS=(S^{-1})B(S^{-1})^{-1}$, which is of the form $PBP^{-1}$, so without loss of generality we can assume $S^{-1}BS$.

Similar Matrices Formula


having trouble making popover view the correct size

Question: I am displaying a popover when user clicks into text field. The popover view has a picker view but I am having some trouble getting rid of some white space in the view popover .
This is what it looks like:

I think my popover size might be fixed because I display it like this when user begins editing textfield:
<code>[popoverController presentPopoverFromRect:textField.frame inView:self.view   permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
</code>
Any ideas on how to make the popover view smaller or for everything to fit in nicely?
I also played around with this line of code but no success:
<code>self.contentSizeForViewInPopover=CGSizeMake(360.0,220.0);
</code>
thanks in advance.
Answer: Are you sure you're setting the picker's origin to {0, 0}?
Comment: thanks I didn't think of that. I went to IB builder and moved my picker up to the origin and that fixed my problem.


Where is the best place to put prisma middleware on NestJs?

Question: My prisma.service.ts looks like this:
<code>@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}
</code>
According to Prisma docs I am supposed to put them outside the context of the request handler. That would be the app that I create on main.ts. Putting a middleware there before the app itself is defined looks wierd to me and doesn't work. I'd prefer to put it on the prisma.service.ts file itself
Comment: Ideally it would be inside `onModuleInit` in this case. Also make sure that `PrismaService` only has a single instance created in your entire application. Multiple instances would mean multiple middleware and that could cause issues.
Comment: what is "beest"? If it is not "best" (which you rejected as an edit), then what is it?
Answer: Not sure whether this is the "best" place to register them, but we do it in the constructor of the service along with the logging configuration and it works:
<code>import { INestApplication, Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { Prisma, PrismaClient } from "@prisma/client";
import { ConcurrencyErrorMiddleware } from "./concurrency-error.middleware";

@Injectable()
export class PrismaService extends PrismaClient<Prisma.PrismaClientOptions, "query"> implements OnModuleInit {
  private readonly logger = new Logger(PrismaService.name);

  constructor() {
    super({ log: [{ emit: "event", level: "query" }] });

    this.logger.log(`Prisma v${Prisma.prismaVersion.client}`);
    this.$on("query", (e) => this.logger.debug(`${e.query} ${e.params}`));

    this.$use(ConcurrencyErrorMiddleware());
  }

  async onModuleInit(): Promise<void> {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication): Promise<void> {
    this.$on("beforeExit", async () => {
      await app.close();
    });
  }
}
</code>
<code>// An example of such a middleware.
import { Prisma } from "@prisma/client";

export function ConcurrencyErrorMiddleware<T extends Prisma.BatchPayload = Prisma.BatchPayload>(): Prisma.Middleware {
  return async (params: Prisma.MiddlewareParams, next: (params: Prisma.MiddlewareParams) => Promise<T>): Promise<T> => {
    const result = await next(params);
    if (
      (params.action === "updateMany" || params.action === "deleteMany") &&
      params.args.where.version &&
      result.count === 0
    ) {
      throw new ConcurrencyError();
    }
    return result;
  };
}
</code>


Can a 2d shape have more vertices than edges?

Question: Can a 2 dimensional shape have more vertices than its edges, if there are no curved edges? For example, a hexagon has 6 edges, and 6 vertices. However, is there any shape, open or closed, where the number of vertices exceeds the number of edges?
Answer: Just draw a shape by its vertices. (I assumed a shape is a polygon here. Otherwise this is not true. For instance this does not hold when we draw a square with its diagonals.)

The first vertex will connect the first two edges. We now have one vertex and two edges.
Adding a new vertex will now add one edge (because one edge was already accounted for by the previous vertex). So for $m$ vertices we now have $m+1$ edges.
This will hold untill we draw the last edge. The last edge will connect two edges which are already acconted for.

Thus in the end we must have $n$ vertices and $n$ edges, for some $n$, by construction.
Answer: No, a 2d shape will always have the same number of vertices and edges.
In 3d, you have the Descartes-Euler formula $$s-a+f=2,$$ where $s$ is the number of edges, $a$ the number of vertices, and $f$ the number of faces.
Comment: A proof of some sort would be nice, I think...
Comment: How about 3 non-collinear points joined by 2 edges. And in general each planar graph that is a tree.


Cocos2d-x admob Integration

Question: Is there any good link from where I can integrate cocos2d-x admob in my app.
My Activity is extending CCLayer.
How can I approach integrating admob in that File.
Please let me know.
Thanks
Answer: You may choose Plugin-x for your project.Click here :)
Answer: http://rastergrid.com/blog/2013/03/admob-extension-for-cocos2d-x-android/
Here is an excellent tutorial to integrate admob in cocos2D-x (Android) step by step.
I had followed that tutorial and that works!
On iOS it will be very easy for you to intergrate admob because c++ and object-c can work together. What you need to do is make a bridge between c++ and admob iOS SDK code which is written in object-c
In fact I don't think that there would be a perfect cross-platform 3rd-party SDK integration solution. You may need to do separate implemention on each platform.
Comment: Hi ThankCreate, This is not working for me.
I have done all the steps but can't make it work.

If I have the library, i mean .so file already, and I dont want to comile CCAdView.h and CCAdView.cpp.
Will copy pasting that library work??

Cocos2d-x admob Integration


What instrument can an old guy learn if the main goal is to write music?

Question: At this old age I began, two years ago learning to write music. I write it using Sibelius and let the computer play it for me.
I have been strongly recommended to learn to play an instrument. I have two connected questions.
What instrument(s) would you recommend in my case. In my mind I imagine piano and violin are too difficult to begin this late. I suppose the instrument should at the same time be meaningful for music composition. My main purpose is to write music for me, but getting better at it is always good.
Now, I don't exactly understand completely the process by which learning to play an instrument   is so important for composing. I understand that knowing the sounds the different instruments can produce, the techniques to produce them, etc. is important. But I imagine that can be learned by listening to others play and reading about the techniques and listening to examples.
So my second question is: Is is really that important to build the physical dexterity required to play an instrument for composing music?  Or in other words. What aspects of knowing how to play an instrument are useful for composers that cannot be learned by seeing someone else play?
Comment: What instrument *can't* an old guy learn? – Another old guy.
Comment: When composing, it's a good idea to know the limits/ranges of each instrument so you don't write something they can't play! (it's happened to me)
Comment: Thanks. But I think that can be learned without knowing how to play. I have seen tables or diagrams showing the ranges of the instruments in an orchestra. I think Sibelius 7 (the software) also tells me that. If I put a note out of the range of an instrument Sibelius 7 simply doesn't have a sound sample for that note.
Comment: Meanwhile professional composers do this all the time. The David Stock violin concerto has French horns playing c# above high c. That said, please don't do this. ;)
Comment: There is a difference between learning about an instrument and learning to play it. Playing an instrument involves knowledge about the instrument but also physical dexterity. The latter is obtaining by practicing and practicing only. It is a reality that older brains tend to become less capable of assimilating new knowledge. Specially knowledge that can't be or shouldn't be rationalized. You can rationalize knowledge about an instrument, why one hand can't play a 12th interval in a piano for example. The knowledge involved for a hand playing quickly scales is of a different nature.
Comment: I might have used incorrect terminology. By 12th interval above I meant playing simultaneously two notes that are too far apart for a single hand.
Comment: Learn basic piano, because everyone agrees that this is the clearest way to understand how chords are put together, and the relationship between chord progressions and melody. Understanding chord progressions is the key to composing tunes.
Comment: @ABC: "I think that can be learnt with knowing how to play": most emphatically NO.  It's not just a matter of range.  Bach wrote four-part fugues for unaccompanied violin.  There is no real need to write fingerings in the score because there is only one fingering that will work anyway.  Mozart wrote some menuet where one note needs to get played with the nose, not because of range issues but because of reach.  I have accordion notes where some notes are only for chromatic button accordion (you can't trill with 4-5 a sixth above the thumb with a piano keyboard, but with CBA you can use 3-4).
Answer: I'd suggest the piano. While it takes many years to master, the piano is one of the easiest instruments to begin playing. Learning to play even the simplest chords or melodies on other instruments can take weeks, but a complete novice can use a keyboard.
The piano also lends itself well to composition because it has a wide range and it is easy to play polyphonic music. Since you're already using Sibelius, it's also worth noting that you could plug a keyboard straight into the computer and begin composing without having to worry about recording an acoustic instrument.
Comment: Completely agree. As a violinist myself who studied the piano for a while I recommend an instrument that lends itself to chords and counterpoint as well as the melodic line for composing. There are a handful of instruments that can do this somewhat (the guitar, for another) but the piano is the canonical choice.
Comment: +1 And don't be intimidated by the complexity of playing the piano. If you're learning in order to compose, your major goal is learning to pick out lines and try different kinds of things -- you're not trying to play a performance. (Unless of course you fall in love with the piano and start practicing a lot and performing!)
Answer: Traditionally speaking, composers throughout history have either been keyboardists of some sort or violinists.  The reason for this is that before the advent of technology, the piano was the primary source for playback for a composer - thus, if a composer wanted to hear what they wrote, they had to learn to play the piano.  As far as violin goes, I can only estimate that it is because its lineage (along with the rest of the string family) predates the large majority of other instruments.
That said, technology has in some ways replaced much of the old tradition.  Now, a composer doesn't have to be a competent pianist in order to write - the computer plays everything back - albeit a bit unrealistically.
Learning to play an instrument is beneficial for composing for a few reasons:
1.) You can play what you write for others!  You can share your passion and joy with those around you, and that is something that is very enjoyable in itself.
2.) It helps make your music more expressive.  It has been said that the music you write can only be as expressive as you yourself can be expressive on an instrument.  Learning an instrument for composition has more to do with learning how to express things musically than rigid technical mastery.
3.) It provides invaluable insight into the way instruments handle - how to write idiomatically for each instrument.  This is important for helping performers to sound their best while also making the music rewarding for both you and them as well.
4.) You don't have to master the instrument. Even just a basic understanding about how an instrument works - that is, how it produces sound, things it does / doesn't do well - can significantly improves a composer's writing quality.
5.) Talk to people who play instruments.  I love doing this and it is very helpful.  They've put in all the time and effort learning the instrument, and they can share their knowledge with you.  Going along with this, also have people play sections of things that you're working on.  This can give you a clear idea of the sounds you're looking for.
6.) Lastly, don't feel as though you have to pick a particular instrument.  Regardless of what you do, all that really matters is that you try to find an instrument that you enjoy playing - for the sole purpose of playing for simple enjoyment.

That all said, it is important to be realistic about your goals.  I'm definitely not suggesting that you should stop everything your doing, rush out, and purchase a really expensive instrument.  That's just silly.
You don't have to know how to play an instrument to write music - thousands of people do it every day.  I merely suggested it as a means to help you increase your writing ability.
Finally, I don't believe someone is ever "too" old to learn new things.  I just read an article today about an 87yr-old woman who earned a college degree.  Things like this are always inspiring and motivating.
I hope that helps.
Answer: What's that saying about old dogs and new tricks? Yeah, that one. It's a load.
I say, go out and get yourself a keyboard and/or a guitar. There are a wide variety of models at different pricepoints and feature levels; you should expect to pay at least $500 to get either a keyboard or a guitar that will be durable enough and sound good enough to last you a while.
The keyboard is going to be the more versatile of the two, and the easiest to start plunking around on, although as was said, it can take you several years to really get comfortable playing with all five fingers of both hands.
The guitar is going to be the easier one to start doing chord work on; you can learn the open chords and start playing along with basic chord charts in a matter of days. A lot of singer/songwriters of all ages do their composing on guitar, because that's the instrument they'll take out to the coffee shop (or the stadium) to perform those same songs.
On top of all that, I would invest in some music theory education. Just diving in and writing what you hear in your head is great, if you can, but not a lot of people can do that without any formal music education. I'd check the local community college; even if you're not planning on getting a music degree, the ability to sit down in a classroom and interact with a teacher who really knows this stuff is light-years ahead of most of the resources on the Internet, even including this site.
As far as knowing how to play an instrument before you start writing, there are good reasons but I wouldn't call it an absolute necessity. It's a good idea because:

First and foremost, you have to know the sounds you want when you're composing for an ensemble. You can get the basics by just listening to each different instrument, but each instrument is capable of a large array of subtle differences in tone and expression that you can utilize if you know what markings the instrumentalist will be expecting to see when you want him to do something.
Second, you have to ensure that your piece is within the technical ability of the instrument and the average instrumentalist. Most trumpet players are not Maynard Ferguson (though they may want to be). Just because someone can hit that high Z-flat doesn't mean it should be expected of everyone. There are resources that can tell you the expected range of the instrument given the skill level of the player.
For chorded instruments like the keyboard and guitar, you have to make sure that the instrumentalist has enough fingers to form the chord you want. For piano, for instance, if you expect two notes to be played at the same time on one hand, they can't be more than about an octave apart (and some really good pianists can't span an octave). For guitar, where the notes are laid out in two dimensions, a single hand is capable of "spanning" multiple octaves, but as there are a limited number of strings, there are fewer valid combinations of notes playable on a guitar as a chord. Therefore, you have the opposite problem; you have to ensure that the two notes you want played together can be played by fretting two different strings within about five frets on the fretboard. Minor and major seconds that don't include an open string's pitch are generally no-nos.
Third, even knowing the range of the notes, it's helpful to know what movements of notes would be considered difficult:

On wind instruments, large jumps (an octave or more) generally require crossing some sort of "break", such as changing partials, where there's more to changing between the two notes than changing fingerings.
Woodwinds additionally have a "native key" that can be played on the main fingerholes or pads; going more than two keys around the circle of fifths from that native key is going to be troublesome for all but the most skilled players.
On bowed strings, you can't usually expect a legato transition between strings more than one string apart (such as from the E to G); you can, however, still get away with some pretty big jumps, because the open strings are tuned a fifth apart and the span from the open string to octave is possible, if difficult, to span with one hand on a violin or viola (cello or bass, no way, but a good cellist can fake it remarkably well).
On plucked/strummed strings, the "shape" of the notes on the fretboard become important; it can be difficult to jump around in intervals that require the same finger to be in two different places very quickly.
On keyboards, lines that cause the two hands to merge or cross are generally to be avoided because it'll jam up the pianist; they generally like melodic runs that stay on one hand or that transition cleanly between two hands.
Comment: "For chorded instruments like the keyboard and guitar, you have to make sure that the instrumentalist has enough fingers to form the chord you want." I found this hilarious; it made me laugh for a couple of minutes! And it reminds me of Jon Schmidt's "All Of Me"; that piece contains a part that is played with the left forearm.
Answer: I agree with sjy that piano is probably one of the best choices for this. Then again, I don't really see why you would need it if you just want to compose. In the days before composition software with playback it was of course helpful to be able to actually hear what you wrote but other than that I can now only come up with these:

You might be able to try out different things, like melodies or harmonies or rhythms, quicker. For me it's faster to do it in my head, though, and then use the software to check how it really works. Also, if you're a beginning player this might just limit you since you can really only try simple things.
Even though the programs today can do some rubato and dynamics, and you can get pretty good-sounding samples, their playback still sounds very artificial. With a real instrument it could be easier to try out different nuances like good rubato or microdynamics, or what really sounds good on a real instrument. For this, too, you'll need to get above beginner level.
Knowing an instrument will also help you write "idiomatic" text for it. But again, if you don't get pretty advanced you might as well just study the instrument and its playing techniques theoretically. This is what composers do for most instruments anyway since there are way too many to play all of them.

So, these are some reasons but they all seem to require above-beginner level of skills, and on the other hand if you have a good "inner ear" you can do the first two without an instrument anyway.
Answer: I suggest a multi-pronged approach. I think to write music you need to be able to play basic tunes and chord progressions by ear on the following classes of instrument:

A keyboard-based instrument
A piano keyboard makes a lot of music theory explicit. When I explain transposition, keys, and other matters to do with relative pitch, I usually refer to a piano keyboard, even if the questioner is used to a different instrument.
So a keyboard helps you "see" pitches, and is particularly useful when transcribing music, because it's so explicit which notes you're playing.
For your purposes, a $30 toy electronic organ serves the purpose as well as a grand   piano. I imagine USB musical keyboard will be of use in Sibelius.
A chord-based instrument
... by which I mean an instrument in which (as one playing style) chords are the primary thing you "punch in" to the instrument. The prime example is a guitar, ukulele, banjo etc. - most players begin by learning to strum chords.
It's good to have an instrument like this to explore and experiment with chord progressions, without focusing all that much on individual notes.
Other possibilities for playing with chord progressions include autoharp (acoustic or electronic), or the auto-accompaniment feature on many electronic keyboards.
Or, of course, you could just play triads on a keyboard.
A diatonic instrument
By restricting you to a diatonic scale, an instrument like a harmonica, melodeon, certain    toy instruments, make it easy to improvise melodies in a Western tradition.
You can get the same effect by just playing the white notes on a piano. Experienced players of any instrument will have trained themselves to stay in a scale, but for beginners it's good to have "training wheels" like this.
Of course, sometimes you want notes that aren't in the diatonic scale -- at that point, switch to a chromatic instrument.
An instrument which doesn't distinguish between sharps, flats and naturals.
On a piano, you know if you're playing a sharp/flat because the key is black. On a guitar there is no special indicator. Sometimes it's nice to think in this style: a fifth is just five frets up, no matter where you start. This is good for thinking in tunes in terms of intervals, regardless of key.

Clearly there are overlaps here; your example of piano and violin covers all those categories -- piano for 1,2,3 violin for 4. But you could pick another set of instruments that allow those styles of thinking.
Answer: In my experience, learning an instrument makes coming up with individual voices in a song much easier, because you can press "play" on your Sibelius song and solo/jam along to it until you produce something you like. This helps when you're at a particular measure in a song and you find yourself lost or falling back on the same songwriting tropes.
Piano is a good choice for a composer, since it allows you to realize rhythm and lead at the same time, even at a beginner level. It's harder to do that with an instrument like guitar or violin.
Comment: (Edited my answer to make "it" clearer.) Well think about it - by learning an instrument, you can improvise along with the song, playing whatever happens to flow from your fingers. You can often "discover" new ideas for your song this way (either by accident or by accessing ones lying dormant in your subconscious) that you otherwise wouldn't have thought of. How would you replicate such a thing in Sibelius with a static music sheet staring you in the face at all times? Unless you hear the music in your head already, you're feeling in the dark.
Comment: I think this answer has some good content but I am not clear what it refers to. When you say, 'Another thing to mention is that it makes coming up ...' What is the 'it' referring to?
Comment: Are you saying that composing on Sibelius may somehow make me tend to restrict myself in some particular cliches? If this is what you are saying I kind of agree with you. That happens to me. Now, I am not completely sure if to blame Sibelius or my creativity and my experience, the lack of it.
Comment: This is a very good point. I feel this when composing in Sibelius. It is more rigid than when I fool around with some friends' keyboards. In Sibelius you can input notes using the keyboard of the computer, A,B,C,D... but since accidentals require more key combinations they are only added a posteriori.
Answer: I also tend to suggest the piano. One new argument for it is, that digital pianos are available which may directly provide MIDI input for any decent composition software. While there are a few other midi-enabled instruments, like Yamaha WX5, which may be easier to master in real-time, the restricted range will make things unnecessary complicated. Dynamics are much easier simply recorded than written and to speed up, what you played, to the tempo you imagine is also easy.
Answer: In addition to the suggestions here, working on your singing may be helpful; being able to sing what you are trying to write, by itself, or over top of your playing (or computer playback) can be a way to rapidly test ideas.
Answer: A viable choice I see underrepresented here is the Autoharp.
It has the advantage over other instruments that the keys are labeled with chord names. If it's songs you're trying to write, words + music, this could get you going pretty quick.
For an even lower lo-fi approach, the autoharp can be simulated on a zither or hammered dulcimer by using the left hand to mute unwanted strings much as the mutes on the autoharp function.
The zither is a diatonic instrument, (cf. Slim's category 3).
This instrument drives home the term key-change. You literally have to leave the key hanging on the instrument and grab it and change it.

Having listened to some music from your link. I have another quirky suggestion, for antiques-mall entusiasts. The electric organ. It's like an enormous harmonica with an electric bellows. But it gives you expression in the timing, and shrieks like a banshee. Glorious noise.
Comment: It is more like this kind of music (http://www.youtube.com/user/franklinvp?feature=mhee). Not really songs, but it could be songs some time. But it is good. First time I hear about this instrument.


Mapeamento OneToOne JPA 2.2 Unidirecional

Question: Olá, pessoal.
Estou utilizando JPA + hibernate 4 em cima da estrutura da base de dados (MySQL 5.6) abaixo. Estou em dúvida no relacionamento @OneToOne.
O que está acontecendo:
A entidade BodyPart tem uma relação @OneToOne com BodyPartHit com carregamento EAGER. Na outra entidade, BodyPartHit, eu gostaria de ter apenas o id de BodyPart, conforme já está mapeado nas entidades abaixo. Ao persistir a entidade BodyPart, ela não persiste BodyPartHit mesmo estando com marcada com CascadeType.All. Daí tive que fazer da forma que geralmente é feito, persistindo a entidade pai e setando o id na entidade filha e funciona. Ao recuperar um objeto BodyPart, não é realizado o carregamento preguiçoso de BodyPartHit.
O que eu gostaria se possível:
Manter o mapeamento das entidades abaixo, ter apenas o idBodyPart na entidade BodyPartHit e na entidade BodyPart ter uma referência @OneToOne para BodyPartHit com CascadeType.All, usando fetch = FetchType.EAGER.
O que eu tentei pra solucionar o problema:
Eu verifiquei um post do UaiHebert falando um pouco sobre esse tipo de mapeamento, porém ele usa a anotação @PrimaryKeyJoinColumn que não necessita de um id na entidade filha (BodyPartHit no caso) pois a chave da entidade pai (BodyPart) é migrada para a filha, mas o problema deu utilizar essa abordagem é que tenho um id na tabela filha.
A base de dados (MySQL 5.6) está estruturada da seguinte forma:
CREATE TABLE IF NOT EXISTS `body_part` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `description` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE IF NOT EXISTS `body_part_hit` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `id_body_part` INT NOT NULL,
  `perc_damage_hit` DECIMAL(4,2) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_body_part_hit_1_idx` (`id_body_part` ASC),
  CONSTRAINT `fk_body_part_hit_1`
    FOREIGN KEY (`id_body_part`)
    REFERENCES `body_part` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

@MappedSuperclass
public abstract class BaseEntity<ID> implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // get and set
}

Entity
@Table(name = "body_part")
@XmlRootElement(name = "bodyPart")
public class BodyPart extends BaseEntity<Integer> {
    private static final long serialVersionUID = 1L;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "id", unique = true, nullable = false, updatable = false)
    private BodyPartHit bodyPartHit;

    private String description;
    // get and set
}

@Entity
@Table(name = "body_part_hit")
@XmlRootElement(name = "bodyPartHit")
public class BodyPartHit extends BaseEntity<Integer> {
    private static final long serialVersionUID = 1L;

    @Column(name = "perc_damage_hit")
    private BigDecimal percentDamageHit;

    @Column(name = "id_body_part)
    private Integer idBodyPart;

    // get and set
}

Answer: Não há como fazer.
Do jeito que você mapeou a classe, estaria correto se o lado que levasse a chave fosse o BodyPart, que não é o caso. Para conseguir fazer o relacionamento bidirecional, vc precisa mapear BodyPart em BodyPartHit, e então utilizar o mappedBy em BodyHit. JoinColumn é para ser usada na entidade que leva a chave, e não na que tem a chave transportada.
Veja esse post: https://stackoverflow.com/questions/11938253/jpa-joincolumn-vs-mappedby
Ficaria dessa forma
@Entity
@Table(name = "body_part")
@XmlRootElement(name = "bodyPart")
public class BodyPart extends BaseEntity<Integer> {
    private static final long serialVersionUID = 1L;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "bodyPart")
    private BodyPartHit bodyPartHit;

    private String description;
    // get and set
}
@Entity
@Table(name = "body_part_hit")
@XmlRootElement(name = "bodyPartHit")
public class BodyPartHit extends BaseEntity<Integer> {
    private static final long serialVersionUID = 1L;

    @Column(name = "perc_damage_hit")
    private BigDecimal percentDamageHit;

    @OneToOne
    @JoinColumn(name = "id_body_part", unique = true, nullable = false, updatable = false)
    private BodyPartHit bodyPart;

    // get and set
}

Comment: Isto não responde à pergunta. Quando você tiver [reputação](http://pt.stackoverflow.com/help/whats-reputation) suficiente, você vai poder deixar [comentários em qualquer post](http://pt.stackoverflow.com/help/privileges/comment) mas, até lá, escreva apenas resposta que não [dependam de mais informações de quem perguntou](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/86765)
Comment: Discordo, amigo.
Comment: Mesmo antes da edição não necessitava informações adicionais. Construção de conhecimento é mais importante que pontos, abraço.
Comment: @LeonardoLana Desculpe-me se a sua recepção ao StackOverflow em português foi um pouco turbulenta. Mas não desanime, sua contribuição é bem-vinda.
Comment: @LeonardoLana caso eu não consiga encontrar uma solução no contexto que expliquei na pergunta irei implementar dessa forma. Contudo, como utilizo essas entidades em uma resposta JSON, poderá ocorrer um problema de recursão infinita o qual há soluções que são/podem ser explanadas em outros tópicos.
Comment: Neste caso você anotaria, na classe BodyPart, o atributo com JsonManagedReference, e no Hit com Jsonbackreference
Answer: Para solucionar o problema, basta fazer uso da annotation @PrePersist, além de inverter o mapeamento das entidades (o @OneToOne deve estar na classe BodyPartHit.java)
BodyPartHit.java
@Entity
@Table(name = "body_part_hit")
@XmlRootElement(name = "bodyPartHit")
public class BodyPartHit {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "perc_damage_hit")
    private BigDecimal percentDamageHit;

    @OneToOne
    @JoinColumn(name = "id_body_part", unique = true, nullable = false, updatable = false)
    private BodyPart bodyPart;

    @Column(name = "id_body_part", insertable = false, updatable = false, nullable = false)
    private Integer idBodyPart;

    // equals, hashCode, toString, getters and setters
}

BodyPart.java
@Entity
@Table(name = "body_part")
@XmlRootElement(name = "bodyPart")
public class BodyPart {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "bodyPart")
    private BodyPartHit bodyPartHit;

    private String description;

    @PrePersist
    public void prePersist() {
        if (bodyPartHit != null) {
            bodyPartHit.setBodyPart(this);
        }
    }

    // equals, hashCode, toString, getters and setters
}

Desta forma, quando o JPA persiste a entidade filha (BodyPartHit) via cascade, ele já irá possuir o id da entitdade pai (BodyPart).
Espero ter ajudado.
Segue um projeto exemplo que subi no github: https://github.com/enikolas/jpa-one-to-one-cascade
Comment: obrigado Nikolas, vou dar uma olhada depois, se der certo dou resolution na sua resposta.
Comment: @diegohsi por nada, aguardo o feedback em ver se isso resolve seu problema.


Comparing emmeans to ggeffect - default weights

Question: For a model estimated in glmmTMB with a zero-truncated negative binomial distribution, I am trying the following to probe an interaction:

emmeans() to estimate marginal means
pairs(emmeans()) to estimate pairwise comparisons
ggeffect() to prepare the marginal means for plotting

It looks like the marginal means are different across the emmeans and ggeffects package due to different default weights. In emmeans(), weights = "equal" is the default, whereas I need to specify weights = "proportional" in emmeans() to have the results match ggeffect().
The pairwise comparisons for the "equal" and "proportional" marginal means yield different results. The estimates are similar, but the SEs and resulting p values are different. How should one determine which weighting to use if the original design is unbalanced?
Answer: It depends on a lot of things. But let's start with...

How many factors are there?
Are interactions included in the model?
If not, should interactions be included? E.g., have you even tried it, and looked at whether any of them are significant.
Have you looked at residual plots?

If interactions are playing a role here, it is quite possible that you shouldn't even be considering marginal means -- in which case the question of weights becomes moot.
Once you have a defensible model, the next step is to plot the predictions, e.g., using emmip().
Sometimes questions like those above seem annoying. But often, I see people racing for the finish line when they haven't even tied their shoes yet.
Comment: Thanks for your response. Yes, there are interactions in the model and we have plotted the predictions. I am probing an interaction between 2 binary variables following this example: https://stats.idre.ucla.edu/r/seminars/interactions-r/#s5a. It is from creating a publication-ready plot with ggeffects that I have noticed discrepancies between predicted values between packages, and am trying to determine how to resolve the discrepancies. When I specify weights = "proportional" in emmeans, the predicted values match across packages, but this changes the significance of the simple effects.
Comment: I think the choice of weights is related to the sampling model. If you have experimental data, then equal weights are probably preferred. If these are observational data, and you want to estimate what is true marginally, then one of the other weighting schemes may be preferable. But it depends on what factors truly are "nuisance" factors, etc. I'd be very cautious with this as I don't think it is straightforward or routine. You might also consider other models that exclude unneeded interactions.


How to prove that f/g is bounded variation?

Question: I am trying to prove that when $f$ and $g$ are of bounded variation on $[a, b]$, $f/g$ is of bounded variation on [a, b] if there exists an $\varepsilon\gt 0$ such that $|g(x)|\ge \varepsilon$ for $x\in [a, b]$.

Let $\Gamma$ be a partition of $[a, b]$ by $\Gamma=\{x_0, x_1, \cdots, x_m: x_0=a, x_m=b\}$.
Let $\displaystyle S_\Gamma[f; a, b] = \sum_{i=0}^m \left[f(x_i)-f(x_{i-1})\right]$.
Let $\displaystyle V[f; a, b] = \sup_{\Gamma} S_\Gamma[f; a, b]$.
\begin{align}
S_\Gamma[f/g; a, b] &= \sum_{i=1}^m \left|\frac{f(x_i)}{g(x_i)}-\frac{f(x_{i-1})}{g(x_{i-1})}\right|\\
&=\sum_{i=1}^m \left| \frac{g(x_{i-1})\left(f(x_i)-f(x_{i-1})\right)-f(x_{i-1})\left(g(x_i)-g(x_{i-1})\right)}{g(x_i)g(x_{i-1})} \right|\\
&\le\sum_{i=1}^m \left|\max(g)\right|\left|\frac{f(x_i)-f(x_{i-1})}{g(x_i)g(x_{i-1})}\right| - \sum_{i=1}^m \left|\max(f)\right|\left|\frac{g(x_i)-g(x_{i-1})}{g(x_i)g(x_{i-1})}\right|\\
&= \left|\max(g)\right| \left|\frac{S_\Gamma[f; a, b]}{\sum_{i=1}^m g(x_i)g(x_{i-1})}\right| - \left|\max(f)\right| \left|\frac{S_\Gamma[g; a, b]}{\sum_{i=1}^m g(x_i)g(x_{i-1})}\right|\\
&\le \left|\max(g)\right| \left|\frac{V_\Gamma[f; a, b]}{\sum_{i=1}^m g(x_i)g(x_{i-1})}\right| - \left|\max(f)\right| \left|\frac{V_\Gamma[g; a, b]}{\sum_{i=1}^m g(x_i)g(x_{i-1})}\right|
\end{align}
I proved until here but I can't proceed more.
I don't know whether $\left|\frac{A}{B}\right|$ is less than or equal to, or greater than or equal to $\frac{\left|A\right|}{\left|B\right|}$
I have the following conditions from the proposition: $$V[f; a, b] < \infty \\ V[g; a, b] < \infty$$
Moreover, the other problem is when $\varepsilon$ become smaller and smaller, the value of $\frac{1}{g}$ become bigger and bigger.
Can someone give me the way to prove this proposition?
Answer: Hints:
It may be easier to show separately that $f,h \in BV([a,b]) \implies fh \in BV([a,b])$ and $g \in BV([a,b]) \implies 1/g \in BV([a,b]).$
For $g$ we have
$$\sum_{k=1}^n \left|\frac{1}{g(x_k)} - \frac{1}{g(x_{k-1})} \right| = \sum_{k=1}^n \left|\frac{g(x_k) - g(x_{k-1})}{g(x_k)g(x_{k-1})} \right| \\ \leqslant \frac{1}{\epsilon^2} \sum_{k=1}^n \left|g(x_k) - g(x_{k-1}) \right|$$


Bounds or a nice form of the the partial sums of $\sum_{n=1}^\infty \frac{1}{n^2}$

Question: I do know that $\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}$, but so far I have not been able to found is either nice closed form for the sums $\sum_{n=K}^M \frac{1}{n^2}$ where $M > K \geq 1$, or alternatively some tight bounds, maybe in terms of $M$. By nice I mean that sure, you could expand each of the terms by hand, but then you would end up with a quite messy formula having a sum of products in the numerator and a quite clean product in the denominator.
So I am asking for a reference/sketch for a nice exact sum (if such even exists) or alternatively some tight upper and lower bound, preferably with some explanation. Thanks!
Edit: I feel dumb for not including this initially, but I was reading an algebra proof which used the bound $\sum_{i=N+1}^{M}\frac{1}{i^2} < \frac{1}{N^2}$ I got interested in knowing more about the bounds of the series in general. This means, unfortunately, that my specific question is a bit loose. Therefore my title could be: "What cool bounds/asymptotic connections do you know for the partial sums of the series $\sum_{n=1}^\infty \frac{1}{n^2}$?
Comment: There is no exact formula but asymptotics can be computed to all orders. The tool you want is called Euler-Maclaurin summation: https://en.wikipedia.org/wiki/Euler%E2%80%93Maclaurin_formula
Comment: Are you familiar with the technique of partial summation? Look at this: https://lc.mt/talks/lecture-1-notes.pdf#page=11
Comment: The only thing is:If $n\leq k$ then $n^2\leq k^2$ impliess that $\frac{1}{k^2}\leq \frac{1}{n^2}$ then $\sum_{n}^k \frac{1}{j^2}\leq \frac{k-n}{n^2} $ right?
Answer: Using partial summation, it's not hard to see that
$$\sum_{n=1}^M \frac1{n^2}=\frac{\pi^2}6-\frac1M+\frac1{2M^2}+O\bigg(\frac1{M^3}\bigg).$$
Is this the sort of thing you were after?

If you want the lower-limit of the sum to be $n=K$, you can do
\begin{align*}
\sum_{n=K}^M\frac1{n^2}&=\sum_{n=1}^M\frac1{n^2}-\sum_{n=1}^{K-1}\frac1{n^2}\\[5pt]
&=\frac1K-\frac1M+\frac1{2K^2}+\frac1{2M^2}+O\bigg(\frac1{K^3}\bigg).
\end{align*}
Comment: To you question, perhaps with Klaus' comment. I feel dumb for not including this initially, but I was reading an algebra proof which used the bound $\sum_{i=N+1}^{M}\frac{1}{i^2} < \frac{1}{N^2}$ I got interested in knowing more about the bounds of the series. This means, unfortunately, that my specific question is a bit loose.
Comment: @EpsilonAway That bound is incorrect.
Answer: For a very elementary bound, observe that $$\frac{1}{n^2} < \frac{1}{n(n-1)} = \frac{1}{n-1} - \frac{1}{n}.$$
Therefore, by telescoping sum,
$$\sum_{n=K}^M \frac{1}{n^2} < \sum_{n=K}^M \left(\frac{1}{n-1} - \frac{1}{n} \right) = \frac{1}{K-1} - \frac{1}{M}.$$
Similarly,
$$\sum_{n=K}^M \frac{1}{n^2} > \sum_{n=K}^M \left(\frac{1}{n} - \frac{1}{n+1} \right) = \frac{1}{K} - \frac{1}{M+1}.$$
Answer: Not sure if this is what you want, but it is too long for a comment, so here we go: You can write it in terms of the derivative of the digamma function, i.e. the second derivative of $\log \circ \Gamma$. For this note that
$$f(z) := (\log \circ \Gamma)''(z) = \frac{\mathrm{d}}{\mathrm{d}z}\frac{\Gamma'(z)}{\Gamma(z)} = \frac{\Gamma''(z)\Gamma(z) - \Gamma'(z)^2}{\Gamma(z)^2}$$
so that
\begin{align*}
f(z+1) &= \frac{\Gamma''(z+1)\Gamma(z+1) - \Gamma'(z+1)^2}{\Gamma(z+1)^2}\\
&= \frac{(2\Gamma'(z) + z\Gamma''(z))z\Gamma(z) - (z\Gamma'(z) + \Gamma(z))^2}{z^2\Gamma(z)^2}\\
&= \frac{z^2\Gamma(z)\Gamma''(z) - z^2\Gamma'(z)^2 - \Gamma(z)^2}{z^2\Gamma(z)^2}\\
&= f(z) - \frac{1}{z^2}
\end{align*}
Thus, since $f(1) = \frac{\pi^2}{6}$, we have
$$\sum_{n = 1}^M \frac{1}{n^2} = \frac{\pi^2}{6} - f(M+1).$$
That is, $f(M+1)$ is actually equal to the tail of the series. For $\sum\limits_{n = K}^M \frac{1}{n^2}$ you can then get
$$\sum\limits_{n = K}^M \frac{1}{n^2} = f(K) - f(M+1),$$
of course.


Is there a & (BASH) equivalent for DOS Batch files?

Question: I'm thinking not since that violates the principle of batching.  So what are my options if I want to launch two apps in windows in one script.
Answer: https://stackoverflow.com/questions/298562/windows-xp-or-vista-how-can-i-run-a-batch-file-in-the-background-no-windows-dis
In short, "start /b" is the dos solution, but there are a few other options depending on your environment.


New Cart after Order Completes

Question: I have an ecommerce solution where when an order is completed, I would like the user to be able to go to cart and see that it is empty.  Previously I destroyed the cart, but that isn't advised so as per some recommendations I added a column to cart that is
:active, :boolean, :default true

My cart controller looks like this
def show
  @cart = Cart.find_by_id(session[:cart_id])
end

# GET /carts/new
def new
  @cart = Cart.create
    session[:cart_id] = @cart.id
    @cart
    redirect_to @cart
end

I have a method in my application controller that looks like this for creating carts.
  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end

after an order goes through, I have the :active column change from true to false.  How could I make it so that if the current_cart.active? is false, it creates a new cart?
I've tried
   def current_cart
     if Cart.find(session[:cart_id]).active? ==false
      cart = Cart.create
      session[:cart_id] = cart.id
     end
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end

but I seemed to have two carts working at a time..
Update
Tried
    def current_cart
     if Cart.find(session[:cart_id]).active? ==false
      reset_session
     else
      Cart.find(session[:cart_id])
    end

No avail..
Answer: The code you tried does not return a Cart object if the one returned by Cart.find is not active - it returns the cart.id. The simplest fix would be to return the created cart (like you do in the rescue clause):
def current_cart
  cart = Cart.find(session[:cart_id])
  unless cart.active?
    cart = Cart.create
    session[:cart_id] = cart.id
  end
  cart
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end

You should also DRY it up - to something like:
def current_cart
  begin
    cart = Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = nil
  end
  unless cart && cart.active?
    cart = Cart.create
    session[:cart_id] = cart.id
  end
  cart
end

If you don't want to actually create a cart in the new scenario, use new instead of create:
def current_cart
  cart = Cart.find(session[:cart_id])
  unless cart.active?
    cart = Cart.new
  end
  cart
rescue ActiveRecord::RecordNotFound
  cart = Cart.create
  session[:cart_id] = cart.id
  cart
end

Comment: the goal here is that after I complete an order and go back to cart, it should say your cart is empty.  My cart is persisting with this code.
Comment: I'm having an unknown problem, not sure how to figure it out.  Your code should work, it doesn't... maybe it would be best to delete the session associated iwth the user and cart... on order completion.. is it bad practice to delete session data? I have tons in a DB already.
Comment: @Peege151 - wouldn't it be simpler to check if the Cart is active in the _view_? Simply _show_ an empty cart if it is not active...
Comment: It should be, I'm not sure why it's not working.  I confirm that the cart is NOT active in the view (order already took place) but it shows the same cart.  Any ideas?
Comment: @Peege151 - my suggestion is simply to _ignore_ the cart if it is not active - draw the page as if there is no cart...
Comment: Sometimes the obvious thing to do is so far away.  Thanks, this works -- as when a user adds items to a cart it creates a new one from here.

New Cart after Order Completes


RadioButton in ListView

Question: I want to create a ListView with a RadioButton in every row.
I'm using a CursorAdapter and I'm binding it in the right way, but I cannot manage correctly the RadioButton.
I want that at any moment only one RadioButton to be checked (so when I check one, I would like the one that was checked before to uncheck).
Furthermore, when I put the RadioButton on the row, I cannot manage anymore the setOnItemClickListener.
Do you know any tutorial that will work for me? Or can you give me any info?
Answer: Sorry for the previous ans I was sleepy I guess. Try the following
<code>setListAdapter(new ResourceCursorAdapter(this, android.R.layout.simple_list_item_single_choice, cursor));

listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
</code>
Comment: you could handle the logic yourself by putting an extra column in your table, not sure if that would be too expensive though.

RadioButton in ListView


Como Salvar itens da Datagridview dentro de uma coluna?

Question: Estou criando um formulário de Orçamentos, parecido com este da foto:

Como podem ver, no botão Novo, gero uma nova linha no banco com o número do orçamento no campo Código e o cliente no campo NomeCliente. Porém, na hora de adicionar as peças e serviços, não tenho ideia de como faço. Eles estão no datagrid com vários campos Código da peça, Nome, unidades, valor unitário, Desconto e valor total.
Ao terminar de adicionar todos os itens na datagrid através do formulário de produtos e serviços, não consigo inserir as linhas dentro do banco, para quando consultar novamente o orçamento elas aparecerem na própria datagrid.
Alguém puder me dar uma ajuda com ideia de como fazer? Estou ainda para começar o projeto.
então me vem a dúvida:
Qual banco usar? Teria alguma maneira de fazer isso com Access 2003, ou alguma versão mais recente? Ou devo inserir uma base de dados em SQL Server?
Grato.
Answer: Este é um caso clássico de mestre-detalhe. Há uma explicação bastante rica de como fazer isso aqui, mas podemos esmiuçar um pouco mais a resposta.
Access nunca é muito recomendável para um banco de dados, a não ser que haja um ótimo motivo pra isso (legado, por exemplo). A alternativa mais interessante ao Access é o SQL Server LocalDb, que é praticamente um SQL Server portátil, e cujo arquivo de dados pode ser importado em uma instância do SQL Server de forma transparente.
Comment: iria usar Access pois sera uma aplicação pequena , apenas de 1 usuario , e apenas para orçamentos , obrigado pelas dicas.
Answer: Olá, Cigano Morrison Mendez! Comecei a fazer um sistema para 1 usuário também. A princípio estava acessando o Access mesmo, mas agora que você aconselhou estou buscando outras opções... Você pode me dizer porque o Access não é muito recomendado? Agradeço desde já!


wic card not recognised - cisco 2821

Question: I've installed a new ADSL2+ supporting HWIC1 card in a cisco 2821 router but its not being recognised. Any ideas why it might not be seeing it?
%GT96K_FEWAN-1-UNKNOWN_WIC: NM slot 0, wic card has an unknown id 4C8
Thanks
Comment: What version of IOS is that router running?  What is the model number of the HWIC?
Comment: What IOS is the router running?  Can you include "show version" output?
Answer: Where did you get the WIC card from?
Was it brand new, or grey-market from eBay?
I only ask, because there's a growing trade in fake cards, manufactured overseas which look like genuine WICs, but don't have the correct firmware to actually make them usable.
Also, it could be that that WIC isn't supported by the IOS version on the router.
Comment: Thanks, I think it is because of the ios version, i'm running ROM: System Bootstrap, Version 12.4(13r)T - flash:c2800nm-advsecurityk9-mz.124-3i.bin
Comment: Yes Cisco documentation indicate the HWIC-1ADSL was first supported in 12.4(4)T.  124-3i in the file name would indicate 12.4(3) mainline and not have the updated support added to the T train releases.

wic card not recognised - cisco 2821