Utilizar muitas interfaces é uma má prática de programação?

Question: Sou estudante em Sistemas de Informação e estou modelando um jogo, um pet virtual que tem suas necessidades e conversa com seu dono, abaixo segue a modelagem das classes e interfaces.
Mostrei para um amigo formado em Ciência da Computação, ele achou que tem muitas interfaces, que não era necessário, eu argumentei que caso no futuro eu poderia dar manutenção e implementar pets da forma que eu quisesse sem muito esforço, podendo criar um pet híbrido entre animal e robo, e atribuindo a ele seus comportamentos através das interfaces, mas enfim ele veio com argumentos de desempenho da aplicação.
Minha dúvida é se minha modelagem (que não está pronta, apenas um esboço) com tantas interfaces é uma má prática de programação? Quando devo utilizar uma interface?

Link da imagem
Answer: Quando vamos modelar um sistema orientado a objetos, uma das coisas mais importantes que devemos fazer é atribuir a cada tipo (seja interface, classe, estrutura, enumeração ou delegado) um conjunto de conceitos e responsabilidades.
Você está fazendo praticamente uma interface para cada método importante dos seus pets. Praticamente todo animal dorme e come, por exemplo. Você poderia criar uma única interface para agrupar essas funcionalidades. Isso ajuda bastante a manter o trabalho simples porque:

se você tiver que adicionar mais uma funcionalidade aos animais, basta trabalhar em uma única interface. Não precisa ir a cada classe e fazer ela implementar mais uma interface nova;
se você tiver que mudar a assinatura de algum método, você não vai ter que rodar por todos os seus animais pra ver quais são afetados, i.e.: fica bem mais fácil controlar quem é afetado por uma mudança de uma interface específica.

Outra coisa, vários sons de animais possuem interfaces próprias na sua implementação. Uma abordagem mais comum é ter um único método (novamente, esse vai na interface geral para animais). Você poderia chamar o método de "talk" ou "speak". Daí, se o animal vai latir, berrar, miar ou chamar o juiz pra reclamar de falta fica a cargo da implementação do método na classe que for utilizar a herança.
Finalmente, você pergunta: tá, juntei todos os métodos numa única interface chamada Pet. Mas e se eu tiver algum animal que não usa alguma funcionalidade? Por exemplo, uma lesma jamais daria salto mortal pra trás. Nesse caso, você tem várias opções:

Tratar isso em um método abstrato e dar alguma indicação de que a lesma não pode dar salto mortal pra trás;
Ser um bastardo e lançar uma NotImplementedException;
Ser um duplo bastardo e deixar o método vazio.

Em todos os casos, documente bem o que estiver fazendo ;)
Note que não há necessidade de classes específicas para dinossauros e cachorros se você pensar assim. A quantidade de funcionalidades em comum entre ambos é simplesmente grande demais para justificar tal especialização.
Você poderia ter alguma necessidade de especialização, se você fizesse algo do tipo:

Uma única interface chamada Pet, que pode por exemplo evoluir e se mover;
Três "sub" interfaces: animal, planta e robô;
Daí você atribui a cada "sub" interface apenas aquilo que é específico dela. Robô não cresce (eu acho), planta não fala e animal não solta raio da morte.

Good luck and happy coding!
Comment: +1. Eu incluiria: "Ser um triplo bastardo e mentir, retornando True mas ignorando."
Comment: @BrunoAugusto Até existe motivos para ter interfaces com apenas um método (ou poucos), isto não chega ser um grande problema mas não faz sentido você separar comportamentos que estão relacionados. Eu até entendo o que você está dizendo, há motivos para fazer desta forma (eu explico na minha resposta) mas no momento ele não está fazendo isto. Quando ele mudar o *design* e poderá postar outra pergunta para ajudarmos na nova configuração. Aí talvez algumas interfaces sejam úteis de verdade. Seria legal e fazer isto. Para ver se ele pegou o jeito ou ainda precisa de mais orientações.
Comment: Concordo com o ponto da implementação do método *speak()*, mas não sei, de certa forma, separar cada ação em uma interface própria até que faz sentido porque facilitaria e muito a criação de interfaces secundárias. Imaginem dois tipos de "animais", *Automaton* e *Android*. Os dois são do tipo *Robot* (interface) que por sua vez é um *Pet*, mas cada um é mais específico que o outro.
Comment: Um Autômato seria qualquer máquina com um ou mais propósito(s) único(s), ao passo de um Androide poderia falar e "dormir". E com métodos específicos em interfaces separadas do jeito que está você pode facilmente atingir esse objetivo sem prejuízo do polimorfismo pois ao s olhos da Aplicação todos serão *Pet*.
Comment: @BrunoAugusto regra geral: especializar demais nas interfaces é um tiro no pé. Basta ver como são usadas interfaces em grandes frameworks como Java ou .NET. Em geral, as interfaces são as mais abrangentes possíveis. Case in point: [ICollection](http://msdn.microsoft.com/en-us/library/system.collections.icollection(v=vs.110).aspx).
Comment: Não estou dizendo que está certo, não tenho domínio tão profundo no assunto pra bater o martelo com tanta força assim. Tampouco estou afirmando que todas essas interfaces são realmente essenciais, que não existe mesmo nenhuma possibilidade de ampliar a abrangência de uma ou outra. Mas que faz um certo sentido, faz.
Comment: @Renan (shut up and take my +1!) é uma pena que não podemos favoritar respostas, uma das melhores que eu já li aqui na SO-pt.
Comment: @Renan Um objeto não deveria publicar um método que não seja um comportamento dele. Se uma lesma não pode dar salto mortal para trás, por que ela tem um método para acionar este comportamento impossível? Se a lesma publica este método estamos diante de um erro de design.
Comment: No caso da lesma, o melhor seria ter ao menos um interface separando esse comportamento (ou comportamentos), caso contrário você estaria realizando uma quebra de contrato. O [Princípio da substituição de Liskov](http://pt.wikipedia.org/wiki/Princ%C3%ADpio_da_substitui%C3%A7%C3%A3o_de_Liskov) fala sobre isso.
Comment: Acredito que seja bem nesse ponto que eu tentei chegar, @Caffé. De novo, não estou dizendo que a modelagem do diagrama está correta MAS, tendo cada ação numa interface diferente, é como chegar num shopping, naquelas lojas de doces, e dizer "eu quero esse, esse, aquele e um pouquinho daquele outro" e cada vez vai sair uma coisa diferente, que faz mais ou menos coisas que o anterior sem sobrecarregar ninguém, sem publicar métodos desnecessários e etc.
Comment: +1 pelo humor! hauahuahuahua
Answer: Classe Abstrata X Interface
Você começou criando a classe Pet com propriedades comuns entre as classes derivadas. Há algum motivo para não continuar fazendo isto para os métodos e eventos? Se passar estes membros comuns para a Pet já simplifica muito. O Renan sugeriu juntar tudo em uma interface chamada Pet. Mas você já tem esta interface. Uma classe abstrata é ao mesmo tempo uma classe e uma interface. A classe abstrata Pet é sua interface.
Generalize o que puder
Siga a recomendação do Renan e transforme os métodos de emissão de som dos Pets em algo genérico. Lembre-se que a emissão de som é a ação única, o jeito que os sons são emitidos é que vai variar, ou seja, a implementação varia. O que você fez foi exatamente o que está descrito no link fornecido pelo Josué Eduardo.
Provavelmente você ainda não entendeu bem a conceituação do que seja a interface. Ela declara ações e não o mecanismo (normalmente, mas não vamos fazer do mecanismo sendo usado de outras forma, nem toda linguagem faz isto), a implementação destas ações. Entenda que interfaces e métodos abstratos de classes abstratas definem comportamento, mas não implementam este comportamento. Só classes concretas podem implementar os comportamentos. Quando você trata um latido ou um relincho sem a abstração da capacidade dos animais emitirem sons, está deixando de lado uma das vantagens da orientação a objeto que é a abstração real (ter uma abstração de latido para implementar um latido é uma abstração artificial).
Talvez todas estas emissões de sons já estejam contempladas no método Talk() e apenas as implementações diferentes sejam necessárias. Neste ponto discordo do Renan que cada tipo de Pet não precisa de classes específicas. Precisa para poder fazer as implementações específicas nestas classes. A solução sugerida só funcionaria se todas emissões de sons fossem iguais.
Se o Talk() serve para outra coisa, você pode criar outro método genérico para denotar a ação de emissão de sons dos pets, Speak() talvez?.
Quando fizer isto, todas as interfaces, individualmente, serão implementadas apenas em uma classe cada. Você consegue dizer porque isto é necessário? Se tiver um bom motivo, ok, se não tiver, acabe com elas. Em geral uma interface só é interessante quando é usada em pelo menos duas classes. Utilização futura não é um bom motivo. Se no futuro precisar, aí sim você cria as interfaces. Não há problemas em criar uma interface e colocar em uma classe já existente desde que o design da classe esteja certo. Uma classe existente pode assumir uma interface nova se ela já possui o comportamento desejado. Isto não fere nenhum princípio e não cria problemas.
Digo mais. Se conseguir abstrair os pares de métodos (não force a barra, só faça se for o melhor a fazer), Eat e Recharge, Sleep e Maintenance, Poop e OilLeak, talvez descubra que são a mesma ação com implementações diferentes.
Implementação futura
Se um dia precisar em um HybridPet que implemente alguns métodos (e eventos obviamente) exclusivos do AnimalPet E também alguns métodos exclusivos do RoboticPet, aí você cria a IAnimalPet que será usada na classe AnimalPet e na HybridPet e a IRoboticPetque será usada na RoboticPet e HybridPet. Isto se realmente elas ajudarem alguma coisa. Só precisará de duas interfaces.
Conclusão
Notou que você precisa de zero interfaces? No seu caso, você tem muitas interfaces. Na modelagem atual, uma interface é muito.
Não se esqueça que em classes abstratas, ao contrário das interfaces você pode dar uma implementação padrão nos métodos se elas coincidirem para alguns tipos de pets.
Não se preocupe com o futuro neste caso. Se você tiver dificuldade em criar uma interface consistente no futuro é porque seu modelo estava errado, não porque você deixou de criar a interface antes.
Eu acho seu caso bem simples e não precisa fazer a gambiarra de tornar uma especialização uma exceção (e provavelmente gerar uma exceção em runtime neste caso) como sugerido pelo Renan.
Se melhorar a modelagem e ainda tiver dúvidas poste nova pergunta para continuarmos ajudando com o novo problema.
Coloquei no GitHub para referência futura.
Answer: Neste caso é má prática porque você está escrevendo código inútil. Crie apenas as interfaces que são necessárias agora.
Deixe para criar no futuro as interfaces que serão necessárias no futuro. Isso não vai aumentar em nada o teu esforço - a IDE cria interfaces automaticamente para você e já altera o código que referencia a implementação para que passe a referenciar a interface, e mesmo que a IDE não fizesse isso o esforço não seria mais que um "pesquisar e substituir".
Ao contrário do que seu amigo disse, o desempenho da aplicação não vai mudar em absolutamente nada, mas seu código ficará mais simples, o que, dentre outros benefícios, diminui o desperdício.
Comment: É o famoso princípio [YAGNI](http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it)
Answer: Cara se você tem uma interface para uma implementação, não vejo utilidade alguma ter a interface. Muita gente usa como argumento: "se você precisar um dia estender a classe é mais fácil", mas esse dia nunca chega.
Se você tem mais de uma implementação para a interface, ok... mas porque o uso da interface ? do ponto de vista prático, ela é necessária ?... não inche seu código só pra ficar "arquiteturalmente bonito" quanto mais simples melhor.
Te aconselho a dar uma olhada nesse blog do Adam Bien, e também procure por alguns workshops dele. Apesar de ser voltado a Java, ele tem alguns conceitos muito interessantes sobre OO, que se aplicam a qualquer linguagem.
Comment: @BrunoAugusto OCP e interfaces não se relacionam. Mesmo que você não tenha uma interface **hoje** não significa que a classe não possa ser estendida. Você pode adicionar uma interface quando quiser sem causar nenhum problema (se causar, o design estava errado, não era a falta da interface). Claro que para não modificar a classe, a interface nova em classe existente deverá ser em cima de algo já implementado (ou definido em caso de classe abstrata). Você estaria apenas dizendo que algo existente agora passa ser parte de uma interface. Criar antes viola o YIAGNI ou mesmo o KISS, que é pior.
Comment: @BrunoAugusto Mas não precisa mudar o "consumidor" (como você diz), você não vai mudá-lo. Precisa incluir a interface, não a implementação. OCP tem a ver com **implementação**. Tanto que uma das mais conhecidas técnicas de *refactoring* é o *Extract Interface* que é feito à partir da implementação já existente. Adicionar uma interface nova a uma classe existente não muda a implementação da classe, muito menos quebra qualquer contrato de compilação ou *runtime*.
Comment: *Aham...* E o OCP que se exploda, né? Do jeito que essa modelagem se encontra hoje, num futuro, seja ele próximo ou não, ele pode facilmente criar um novo animal completamente novo, com características únicas, muito provavelmente (vai depender da implementação) sem sequer tocar no código que faz o animal comer, dormir, falar...
Comment: Como deu pra notar nos outros comentários eu vejo por outro ângulo, talvez errado, mas OCP é para os fortes :p. Penso que se existe uma interface própria através do qual a Aplicação executa, sei lá, uma ação de comer, qualquer recurso que possa de fato comer pode ser criado a qualquer tempo sem necessidade de modificar a Aplicação consumidora. Se você tem outras tantas interfaces no mesmo sentido você pode fechar a Aplicação consumidora para modificações pois através do polimorfismo proporcionado pela interface *Pet* qualquer classe seria aceita e teria sua ação de comer realizada com sucesso.
Comment: Eu sempre tive uma grande dificuldade em entender alguns dos paradigmas assim, só na base teórica. E o fato de material de qualidade sobre assunto relacionado com a linguagem de que eu gosto não existir ou ser bem escasso não contribui em nada. O que me dá mais raiva é que você tá explicando, tá explicando e eu não consigo visualizar do mesmo jeito que você(s). Acho que eu preciso de um café. >.<
Comment: @BrunoAugusto ,acredito que o bigown e eu compartilhamos de um mesmo ponto de vista: o prático. Sempre que for pensar em arquitetura / estrutura se pergunte o "porque preciso?","pode ser mais simples ?". Outra coisa que o bigown sitou que eu aprovo 100%. é a questão de classe abstrata no lugar das interfaces, para ter um comportamento padrão.
Comment: Pois é, eu sei bem disso. Mas como eu não programo profissionalmente posso "me dar ao luxo" de considerar esse tipo de cenário como viável.
Answer: Respondendo a sua pergunta: Não é má prática. Mais você deve seguir alguns princípios na hora de fazer a modelagem, segundo o princípio YAGNI você não precisa criar interfaces para todas as suas classes pelo simples fato de que você nunca irá utilizar, mas se você está com dúvidas na hora de modelar certa classe sugiro a criação de uma interface, principalmente se você está desenvolvendo um pacote ou utilizando e quer um baixo nível de acoplamento.
Answer: Apenas utilize Interfaces se utilizar Design by contract (DbC).
Se não usa DbC, mantenha seu código enxuto sem utilizar interfaces.
Isto é "o melhor" a partir dos valores do Lean Software Development pois elimina desperdícios. Obviamente, a partir de outros valores, este "melhor" pode ser diferente.
Eu acredito que o uso de uma interface serve para garantir que um objeto possui propriedades requeridas no momento em que será utilizado, forçando a execução disto com Tipagem. Se não preciso desta garantia, logo a criação e implementação de interface é um esforço em vão. Se espero um objeto Logger, espero que ele tenha um método que me permite registrar uma string, portanto digo que o objeto Logger que receberei deverá ao menos possuir um método foo(string) e assim terei certeza que a aplicação funcionará. Mas isto é válido apenas se as possibilidades de injeção de Logger forem mais que uma, como por exemplo, quando você desenvolve uma biblioteca que grava logs, mas espera que o Logger seja injetado pela aplicação que usará sua biblioteca.
Comment: Por que isto é o melhor a se fazer?
Comment: ok, mas qual a vantagem? Que desperdício? Se eu preciso tomar banho não estou desperdiçando água? Se deixo o chuveiro ligado e vou fazer outra coisa é que estou. Porque a interface é não é desperdício c/ DbC mas é se não usá-lo? Acredito que tenha alguma sustentação no que você disse mas como é algo que parece ir contra tudo o que é estudado sobre o assunto, não podemos simplesmente confiar na sua afirmação. Dê alguma informação adicional para aprendermos algo novo.
Comment: @bigown, isto é "o melhor" a partir dos valores do Lean Software Development pois elimina desperdícios. Obviamente, a partir de outros valores, este "melhor" pode ser diferente.
Comment: Entendo. Editarei minha resposta e você me dá sua opinião.
Comment: Melhorou bastante mas ainda não entendi a relação com o DbC. Tudo isto que você explicou é necessário independente do DbC ser usado. A não ser que você tenha uma definição de DbC diferente da que eu tenho. O compilador recusar compilar algo que não seja do tipo adequado (não tem a interface requerida) para você é DbC?
Comment: Vejo que o fato de não compilar é apenas um detalhe técnico, mas sim a arquitetura planejada para a orientação ao contrato e Dependence Injection é o que realmente importa isto se aplica também para linguagens onde não compilamos uma build.
Answer: Usar interface pra tudo é uma péssima prática pois dificulta muito saber onde realmente a interface está sendo utilizada de forma útil (se é que alguma está sendo), isto é, voltada para a finalidade que ela foi criada.


2-5-1 Jazz progression and modes

Question: I am classically trained and just started looking into jazz theory.
I understand that the 2-5-1 progression is a good place to start.
My basic understanding is to play the above progression with arpeggios 1-3-5-7 combinations for improvisation.
I also understand that 2 "types" of jazz are possible: modal or chord based.
My first question is:
If I am in C Ionian mode, my progression is Dm, GM, CM or any variations of these basic chords( I guess??)
However, if I am in the Dorian mode(or any modes), does it change from D,G,C to E,A,D and so on through the modes?
Basically, should I always think of it as 2-5-1 based on the scale, mode... I wish to use?
My second is:
Can modal and chord based jazzed be "blended", used together for improvisation?
Comment: Then, your next step is to transcribe jazz masters and see how they approach this. As to the scale/chord approach, I'd say that both are useful and complementary. "Chord based" means "target notes", "Scale based" is more about which non-chord notes to play. Classical training is useful in this respect, but not the end of the story in the jazz style.
Comment: Anyway, this kind of stuff is easier to learn by listening and transcribing solos. This way, you acquire "jazz vocabulary" and everything becomes clearer.
Comment: You can have a look at Kent Hewitt's youtube channel, where there are some beginner stuff about learning improvisation over II/V/Is -- a good approach is to "target" important notes of the chords. As you grow a technique, you can target more interesting notes than the root, third or fifth. See eg. https://www.youtube.com/watch?v=wsDMOgLjCXA
Answer: The ii-V-I progression is a great place to start.

If I am in C Ionian mode, my progression is Dm, GM, CM or any variations of these basic chords( I guess??)

Exactly right. ii, V, and I are what are called Roman numerals, and uppercase Roman numerals mean a major chord (while lowercase means minor). So ii is the minor triad built on the second scale degree, which in this case is D, and thus Dm. GM and CM are the major triads built on scale-degrees 5 and 1.

However, if I am in the Dorian mode(or any modes), does it change from D,G,C to E,A,D and so on through the modes?

The Dorian scale is what you play above the ii chord in the ii-V-I progression. The tonic of the Dorian scale is the root of the ii chord. So in this case you'll play a D Dorian scale while the ii chord is playing.

Now, let's go one step further with this: above the V chord, you'll play a Mixolydian scale (here, G Mixolydian). And above the I chord, you'll obviously just play a C major scale (or C Ionian). If we look at those three scale collections, they contain the exact same pitches: C D E F G A B.
This means that, if you ever see a ii-V-I progression, you can just play around with the major scale built on I throughout all three chords. You'll want to emphasize different pitches and ignore others depending on what chord is playing at the time, but this is a super fast way to start improvising above ii-V-I progressions.
Comment: 1357 as a base to learn seems fine. You might also consider basing the modes off of their parent scales. For instance, when you learn C major, also practice D Dorian, E Phrygian, F Lydian, G Mixolydian, A Aeolian, and B Locrian, because these are all the same pitches, they just started on a different scale degree.
Comment: As far as "changing the scales you use," we sort of aren't. Although we switch from D Dorian to G Mixolydian to C Ionian in a ii-V-I, they're all the same scale collections, just beginning on different pitches. So I hesitate to say we're "changing scales."
Comment: Ok. I understood it right. As the mode changes, I need to stick to the Roman numerals to stick to the progression. What about the use of the 1-3-5-7 notes of the scale used as a base to learn? Also, are you saying you can change the scales you use, as long as they are closely related, like C,G,F  and relative minors as well as using symmetrical diminished scales or super Locrian scales?
Comment: Ok. I think I missed something here. Are you saying I theoretically should be playing notes starting from D or Dm when playing the ii chord and Starting with C when playing the I chord? Or are any combinations ok?
Comment: You can play any notes, it's just that D Dorian uses the exact same pitches as C Major; it's just that the D Dorian scale begins on D, whereas C Major begins on C. When improvising, you don't need to start on those pitches, but it terms of practicing the scales themselves, you *should* start on those pitches (because that's what distinguishes D Dorian from C Major). Hopefully I understood your question correctly!
Answer: In addition to the fine answers already posted, I'll add this: the two ways of thinking about it (modes vs. chords) are exactly the same.
Imagine the chord progression is Dmin7-G7-CMaj7. Someone tells you, "solo over the Dmin chord using the 3-5-13." What numbers is this person referring to? The notes of the D dorian minor scale.
Or imagine that you're transcribing a solo. You take a short lick that occurs over the Dmin7 chord and you want to learn to play it in all 12 keys. So you write out the lick out as numbers: 2-3-4-5-7-5-6-4-3-1. What do the numbers refer to? The degrees of the dorian minor scale. (E-F-G-A-C-A-C-B-G-F-D)
We can think of chords as being built from underlying scales. Modes are the scales from which chords like Dmin, G7, and many more are built. If not for modes, we would have to talk about the tones of a Dmin chord by referencing the notes of the C Major parent scale: the note D would simultaneously be (a) the root of the Dmin chord and (b) the 2nd scale degree of the C Major scale. This would obviously be untenable. Having scales that start on the same note as the chord's root unifies our theory so that (a) the scale degree and (b) the chord degree both refer to the same number.
So, the two approaches are equivalent because the numbers refer to the exact same thing.
When learning to improvise, arpeggios are a good place to start. Even better is mixing arpeggios with other techniques. For example, Jamey Aebersold has great patterns for beginning improvisers where you play up the arpeggio (1-3-5-7) and then down the scale/mode. For example, over Dmin (the ii chord), you could play:

D-F-A-C - B-A-G-F (1-3-5-7-6-5-4-3) or
F-A-C-E - D-C-B-A (3-5-7-9-8-7-6-5)

But you can also reverse the order: descend down the arpeggio and then play up the scale. Pairing two techniques in this way opens a lot of doors for creative practice.
Your question asks: "If I am in C Ionian mode, my progression is Dm, GM, CM or any variations of these basic chords." But there's an issue with how you've phrased this. The chords Dmin-G7-CMaj aren't in C ionian--they're in the key of C Major. Only the CMaj chord pairs with C Ionian. The Dmin chord pairs with D Dorian minor and the G7 chord pairs with G Mixolydian. Referencing these scales (Dorian minor, Mixolydian, and Ionian) is a modal approach because you are drawing on three modes that all come from the same C Maj parent scale. It would be weird, though, to play the entire progression thinking only of a C major scale. To illustrate why this sounds weird, go to your piano, and in your left hand play a Dmin chord while playing a C major arpeggio in your right hand. Improvisation sounds good when the chord tones are emphasized. This is not possible when thinking of the entire ii-V-I progression as being C major. Rather, it will sound better to think in terms of the specific chords/modes belonging to each measure.
Instead of playing a major key, we could play in a minor key. For example, instead of playing a ii-V-I in C Maj, you could play a ii-V-i progression in the key of C minor. Now, the chords would be Dø7-G7alt-Cmin where the first chord is a half-diminished chord (flatted 3rd, flatted 5th, and flatted 7th) and the second chord has alterations on the 9th, 5th, and/or 13th. There are a few choices of scales to use over this progression, but one nice set of scales is: D locrian #2 (the 6th mode of the F melodic minor parent scale), G altered (the 7th mode of the Ab melodic minor parent scale), and C melodic minor. This is again a modal approach because, for each chord, we're pairing a scale that starts on the root of that chord. But this time, the three modes aren't all coming from the same parent scale.
Hopefully these examples elucidate what a mode is, how it is used, and why it is used. That said, when you're improvising, it's really helpful to think about groups of notes. (This sort of technique is called "chunking" in psychology and allows us to store more information using less working memory.) Thinking about the scale in terms of the chord tones can be really beneficial and can have two positive effects: (a) this can help you emphasize the strong tones from the underlying scale and (b) this can help you reduce the amount of working memory you must expend when thinking about which notes to play.
Answer: Just to add that, as in classical music, there are lots of ways in jazz to embellish a ii-V-I progression. E.g. D minor 9 (containing the notes D F A C E), G with a sharpened ninth  (containing G B D F A sharp), C maj 7 (C E G B).
It's also common to substitute the V with either a flat II or a flat VII. So, instead of the above G chord you could use, say, D flat with an augmented 11 (D flat F A flat B E flat G) or B flat 13 (B flat D F A flat C G).
Comment: Hi there - if you meant this as an addition or comment on another post you now have enough rep to do that.
Answer: lots of good answers here, but I think the heart of your question is missed.
Yes, you can play lead over the key of C Major using the different modes of the scale (C Ionian, D Dorian, E Phrygian etc..), but none of these modes contain notes outside of the C major scale.
If you want to take your lead to the next level you can also use any mode that uses C as its tonic. That includes not only C Maj but C Nat Min (aka the "C" Aeolian Mode), C Harmonic Min, & C Melodic Minor & C Dorian (essentially any of the seven modes of C + Harmonic & Melodic Minors). This will give you notes to play that are outside the Diatonic C Major Scale. Try experimenting by playing the G Major scale over a CMaj7 chord. Since G is the V of C major, this is called the C Lydian Mode. In this mode, you'll be using a F# instead of the standard F (from the perspective of C this will be considered a #IV - or the vii degree of G maj).
Here is the best demonstration of modes for guitar that I've come across: https://www.youtube.com/playlist?list=PLF6kSoxb4mMvhKDfsZo2xymEFGWc-zAOc
Extra Credit:
You are not limited only to playing LEADS borrowed from other modes - you can also write CHORD progressions borrowed from other modes. To elaborate on the above example - instead of playing the V7 chord (G7) you could try the VMaj7 (GMaj7)(borrowing that F# from the key of G - aka C Lydian). You haven't technically modulated keys here because C is still the tonic of C Lydian (the mode where the GMaj7 belongs..)
..unless of course you wanted to modulate to another key. This would be a great way to transition into the key of D by following that up with CMaj7 - GMaj7 - A7 - D. The borrowed F# in GMaj7 serves as a great pivot point from the key of C into the key of D.

2-5-1 Jazz progression and modes


Methods for monitoring and alerting data issues when dealing with complex dependencies

Question: In this hypothetical example, we have a data flow across multiple engineering teams in an ecommerce company. These teams deliver services, produce data, and consume data at different points of the flow.
For example;

'Team Orders' maintains the Orders database and interfaces
'Team Traffic' generates web traffic data
'Team Warehouse' maintains the data warehouse
'Team Traffic' depends on 'Team Order's service to retrieve order data and associate it with web traffic
'Team Warehouse' depends on 'Team Traffic's data to build DW tables

Imagine that 'Team Orders' hits a db issue (load, latency, whatever) - Their monitoring system alerts an engineer who starts investigating the db issue.
In the meantime, 'Team Traffic' has also been alerted, as they see a spike in bad responses. They start investigating, and quickly realise the issue is with 'Team Orders's service, and raise a ticket to 'Team Order'
Downstream from all of this, 'Team Warehouse' is receiving bad data. Their DW monitoring alerts them to this variance, so they start looking for root cause.
The problem is, we now have at least three engineers investigating the same issue, and they might not even be aware that other teams are doing the same thing.
An important point is that all three teams are using different monitoring and alerting systems; Team Orders is monitoring for db server issues, while Team Warehouse is looking for variances in record counts.
There are other approaches; alerting at the top of the pipeline only (blocking downstream escalations) or alerting at the bottom of the pipeline to upstream systems.
Are there any best practises, white papers, or engineering solutions I can research to understand the different ways to alert and escalate data issues across multiple eng/support teams?
Answer: Highly recommend The Practice of Cloud System Administration, goes over some of this in great detail. Here we have 3 levels of monitoring

End to End (oh crap something is wrong)
Per service/API (oh crap member of SQL cluster is down, API is responding slow or with something other than a 200/300 HTTP code etc)
APM - What piece of code etc is slow, error rates for specific services etc.

These + the logs give us most of what we need to know what's going on, the generally we have a single person responsible for seeing that the issue is fixed - the coordinate the fix but they do NOT do the technical work, that is farmed out to others. The coordinater's job is to make sure we don't step on each other's toes fixing the issue.


How do I limit the number of images displayed in a teaser?

Question: I have a site with an image field that allows for unlimited images. I want the first image in the field to be shown in the teaser (for both listing and views). Is there a configuration option that will let me do this?
I'd rather not put in a self-written module (as it means I have to maintain it myself).
Answer: Try using this module http://drupal.org/project/field_multiple_limit
It allows you to go into the display settings for your content type and configure the teaser settings to display only a certain amount of values. You can even make it skip vales, for example if you want it to display values 2 to 5.
Comment: It works! Now I don't have the galleries blowing up all over!


How is 4 a quadratic residue of 7?

Question: On Wolfram's dictionary, it shows that the quadratic residues of 7 are 1,2,4.
It shows that the quadratic residues of 5 are 1,4.
I tested 1 and 4, and as you can see:
$$1^2 = 1 \pmod 5$$
and
$$ 4^2= 16 \pmod 5 = 1 \pmod 5$$ since 5*3 = 15
If $4^2 = 16 \pmod 7 = 2 \pmod 7$
Doesn't this mean it would fail the criterion that a quadratic residue must be congruent to a perfect square modulo p (here, p = 7) ?
Doesn't it need to always be congruent to $1 \pmod p$ ?
Comment: $\;2^2=4=4\pmod 7\;$...in fact, $\;4\;$ (and any other natural square) is a quadratic residue modulo *any* prime...though not always a *non-zero* one.
Comment: Right, just realized that any time you get another perfect square as the remainder then the number that yielded that is a quadratic residue
Comment: I believe you mean "$4$ is a quadratic residue mod $7$." This means that there is an $x$ so that $x^2\equiv4\pmod7$.
Answer: In short, $2^2 \equiv 5^2 \equiv 4 \pmod 7$. Since $4$ appears as a square, we see that $4$ is a quadratic residue.
In fact, $4$ is always a square mod primes. When looking mod $2$, we see that $4$ is zero (so it's the trivial square). Otherwise, $4$ will always appear as the square of $2$, regardless of whatever prime we are modding by.
Answer: It does not fail the criterion (actually, the definition) for a quadratic residue.
In fact you've just shown that it does not: $2\equiv4^2\pmod7$, hence $2$ is (by definition) a quadratic residue modulo $7$ because it is congruent to the square $4^2$.
The fact that $2$ itself is not a square does not mean it can't be a quadratic residue.

How is 4 a quadratic residue of 7?


Fast Insert of raw binary data from multiple files to access database

Question: I'm looking for the fastest method to read from multiple binary files and write everything inside single MS Access database within multiple tables. SQL Server or any other database are not an option. I'm using C#.
Let's say I have only one file containing 1 GB of data.

File starts with header (containing column names code) followed by  more than 700 000 blocks of  measurement data. Header is less than 100 byte long. One data block is 1500 bytes long ( 372 x single float + 12 bytes for date and time)
first 84 single values must be inserted in first database table
remaining 288 single values are divided equally in 9 tables, 32 values each
every table row has time and date as first column

For now, I'm using binary reader. I'm reading block by block and executing INSERT statement (ADO.NET) 10 times per block. That would be more than 7 millions of INSERT.
Execute time for 1.5MB is about 1 minute - 1GB would be more than 10 hours.
Is there any way to do this much faster? What do you think is possible to expect?
Answer: You should use the SqlBulkCopy Class
See. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
Comment: I must write data to Access database.The SqlBulkCopy class can be used to write data only to SQL Server tables.
Answer: You are probably committing on every insert. It is better to begin a transaction, process some fixed number of data blocks, say 100 or 500, and then commit the transaction and begin another. Keep a text file log of which records have been committed so that if you need to restart for some reason, you know where to start.
You could try changing the Jet engine properties for sycing but it would be better to simply begin an SQL transaction on the connection, and then commit after a large chunk of records. You will also need to turn of Auto Commit as in this VB example.
In addition, if you specified sorted keys then undo that. Use ADOX to make them index keys after you load all the data.
Comment: Thanks for replay, but I didn't found StartTrans either.

I have read all my data and wrote it inside DataTable. Now I have large DataTables ready to be inserted inside mdb file. I've found few threads suggesting use od Microsoft DAO 3.6 Object Libary or some other COM.
Comment: You can always do the transactions inside SQL statements as shown here http://stackoverflow.com/questions/2078432/do-we-have-transactions-in-ms-access
Comment: I've just tried Inserting with ADODB. I got 2x better execution time, but that is still too slow. I tried using BeginTrans/CommitTrans but it looks like there's no effect. After BeginTrans I'm Executing Insert statement for each row in  DataTable. Execute method takes to long (90% of processing time) regardles of BeginTrans I declared. Commit is executed in 100 ms, so there is no point of starting new transaction.
Comment: The advice in the cited URL to change registry settings is very bad advice. These settings, ImplicitCommitSync and UserCommitSync be set to OPPOSITE settings because they apply to different things. See this post for a full explanation of what those settings apply to: http://stackoverflow.com/questions/4562973/whats-the-difference-between-jet-oledbtransaction-commit-mode-and-jet-oledbuse/4581122#4581122


Searching for a Python lightweight IDE (or text-editor)

Question:
Possible Duplicate:
What IDE to use for Python?

Hi all,
I'm looking for either a lightweight IDE or a text-editor (with plugins, of course) for writing Python code. Some of the features I'd like the software to provide are as follows:
1) Auto-complete/suggest
2) Multi-tab
3) Auto-format (on save if it is possible)
4) Syntax highlighting
5) Easy navigation between .py code (in Eclipse, if you use F3, you can jump to the Class/Interface file)
6) Expand/Collapse (more known as Folding?)
7) Integrate with code-checking specific to Python (code analysis, unit-test tools, etc)
8) [Optional] Source tree (browsing/navigation)
I prefer to use keyboard to navigate around because I'm using a laptop (with limited display size as well) and I'd like to avoid using mouse.
Update: Please list the plugin names as well if the out-of-the-box doesn't provide them.
Thanks
Answer: You mention Eclipse - what about PyDev, a Python IDE for Eclipse?
edit - also, this question has an incredibly comprehensive list of Python IDEs, sorted by feature. Might be worth a look.
Comment: I believe Eclipse doesn't comply with the question main requirement: A "lightweight" editor
Comment: With regards to nowadays personal computer's performance, pydev for Eclipse is a good option.
Just follow the instructions here to download Eclipse, and install pydev. http://www.pydev.org/manual_101_install.html
Answer: Wingware's Python IDE fulfills all of your requirements, and I do consider it to be the best Python IDE around. That being said, it's a commercial product and not available free of charge, though Wingware offers noncommercial/open-source licensing.
Comment: Well there's a workaround to that if you're an active open source project, but it's a bit difficult to get approved for it
Comment: Yep, I just remembered that, too and edited it in.
Answer: There is python.el (written by Emacs community) and python-mode.el (written by Python community) for Emacs.  Also, rope, ropemacs, and a few more.  Look at EmacsWiki, you will find something for sure if you are open to use Emacs.
Answer: If you're on Windows, I would suggest you give Python Tools for Visual Studio. Might not be lightweight, but it sure is nice.
Cruder look, but very lightweight and extremely powerful: you could look at using Vim as a Python IDE.
Comment: Looks to me like all of the requirements can be matched by Vim, not out of the box though. Still Vim is worth the effort since it pays off manyfold.


Calling COM module from node.js

Question: We have a closed COM engine we need to call from our node.js server.
Is there a package I can use to call this engine from node.js?
Answer: One way to do this is to build your own C++ extension to node.js.
This extension can use your COM component. However It looks complicated and time consuming to build an extension for node.js.
Check here fro more info http://nodejs.org/api/addons.html
Comment: ya, I know I can do it, but I expected someone would develop some bridge.

Calling COM module from node.js


I don't know how to deal with the trills in Bach's Fugue in D Minor

Question: (Included from comment: the fugue is from well-tempered clavier, vol. 1 BWV 851)
All research I do gives me a different answer. One example said to use the auxiliary note first - more in keeping with the Baroque era, "G" has the trill over it, so then it would be " AGAGAG" but to exclude the returning note of "F" which is aligned with the semiquavers in the Right Hand.
I am using the Peters Edition and this includes the lower note "F"
Comment: @AndyBonner I would further suggest that Mary Scriven identify _which_ fugue in D minor it is.  There is indeed a long trilled G in each hand in BWV 565, but there could also be G trills in other fugues in that key.
Comment: It is Fugue number V1  851 from WTC book 1
Comment: If you're really interested in authenticity, work with an edition that doesn't make these kinds of interpretive assumptions for you (but be aware that you'll still have to make them for yourself). [IMSLP](https://imslp.org/wiki/Toccata_and_Fugue_in_D_minor%2C_BWV_565_(Bach%2C_Johann_Sebastian)) has the *Bach-Gesellschaft Ausgabe*, which isn't too invasive, and several versions typeset recently. Also, be aware that this piece has a long and complex history. There's substantial evidence that it wasn't even written by Bach. It's been such a huge hit through...
Comment: ...through the last couple of centuries that there's a lot of tradition that you can't totally escape from. Even if you do the most historically appropriate performance, the Phantom of the Opera hovers over your shoulder. Also note that how to interpret trills in baroque keyboard music—even limiting it to Bach—is a very long subject, and will often come down to choices based on context.
Comment: And finally, please post an image or reference a measure number so we can know the surrounding notes; I'm not sure any meaningful answer can be given without that.
Answer: Since Bach published his own table of ornamentations (Henle blog is a German page but shows facsimile and as well as a new rendering, but you should easily find an English explanation - if required - easily), I would try that one first. If your edition uses a modified notation, it should also bring its own table.


Only front page works

Question: I am trying to set up a local server to try out drupal 8.1.3 and so far I was able to set up my profile and website but I cannot go to any pages other than the first page. (Welcome page, front page)
I have used the following link to install Drupal:
https://www.howtoforge.com/tutorial/how-to-install-drupal_8-with-apache-and-ssl-on-ubuntu-15-10/
Few things to note:

I'm not sure if I have CleanURL, tried to fix this issue but couldn't succeed I believe.
I have tried  multiple different approaches to fix issues like CleanURL, SSL connection, Apache2 (AllowOverride All) etc
I tried adding "?q=" and while this doesn't make the page crash, it just directs me back to the front page

Currently, I am playing around with four files to try to figure out my problem: ".htaccess", "apache2.conf", "drupal.conf" and "settings.php"
I want to be able to access the Drupal tools to modify the website and run it locally, I simply want to test Drupal, I wanted to share this because it may simplify the solution.
Some of the code that I have added while trying to fix my situation:
drupal.conf:
            <Directory "/var/www/drupal">
                    Options FollowSymLinks
                    AllowOverride All
                    Require all granted
            </Directory>

apache2.conf:
<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

.htaccess:
RewriteBase /

# homepage redirect
RewriteRule ^$ /SUBDIRECTORY/index.php?q= [L]

# if directory or regular file...
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} =/favicon.ico
# stop here
RewriteRule ^ - [L]

# if a regular file in SUBDIRECTORY directory
RewriteCond %{DOCUMENT_ROOT}/SUBDIRECTORY/%{REQUEST_URI} -f
RewriteRule .* SUBDIRECTORY/$0 [L]

# Redirect everything to /SUBDIRECTORY
RewriteRule .* /SUBDIRECTORY/index.php?q=$0 [QSA]

settings.php:
$settings['trusted_host_patterns'] = array(
  '^127.0.0.1$',
  '^localhost$',
  '^www.example.com$'
  );

PS. I have tried both localhost and an example website url like www.example.com but it didn't help.
PS2. I am only using Firefox currently but I don't think the problem is with the browser.
I hope I was able to follow the question guidelines, I am really trying my best to make it a question "suitable" to the website, I am sorry if I made a mistake.
Edit1: I have rewrite already enabled.
Comment: Oh and you don't need to modify your `.htaccess`.
Comment: This is not a Drupal problem. Make sure that url `rewrite` is enabled. If not, you can enable it by running this command `sudo a2enmod rewrite` then restart or reload your Apache conf by running `sudo service apache2 restart`. After that make sure that your Drupal clean URL is enabled.
Comment: I have the rewrite already enabled.  How can I make sure that the Drupal clean URL is enabled?
Answer: I believe the problem was due to the location of my .htaccess file. (The main problem was the Clean URLs.)
My original location was /var/www/drupal/sites/default/files; after, I moved it to
/var/www/drupal. The .htaccess file started to being read. Previously, it was not being read.
I hope this helps someone else! This also may not be the solution because I am having a different issue now.
Comment: The .htaccess needs to be placed in the Drupal root directory, to be used. In other words, it needs to be placed where the index.php file used by Drupal is. That is how Apache works.

Only front page works


How do I set Content-Type when uploading to S3 with AWS CLI?

Question: I'm trying to set up S3 static website hosting, but it appears to return 403 on any of my objects that don't have the Content-Type metadata field set in the AWS console. I cannot figure out how to do this with the AWS CLI tool.
Using the --metadata option appears to work:
$ aws s3api put-object --bucket <bucket> --key foo.html --body foo.html --metadata Content-Type=text/html
{
    "ETag": "\"fd5ff7743e5ed1e1c304eb1c34e8e39f\""
}
$ aws s3api head-object --bucket <bucket> --key foo.html
{
    "AcceptRanges": "bytes",
    "ContentType": "binary/octet-stream",
    "LastModified": "Wed, 15 Apr 2015 06:39:48 GMT",
    "ContentLength": 189,
    "ETag": "\"fd5ff7743e5ed1e1c304eb1c34e8e39f\"",
    "Metadata": {
        "content-type": "text/html"
    }
}

But the Content-Type field on the object isn't visible in the "Metadata" section of the AWS console, and I get a 403 when trying to access the file in a browser.
Using the --content-type option also doesn't work:
$ aws s3api put-object --bucket <bucket> --key foo.html --body foo.html --content-type text/html
{
    "ETag": "\"fd5ff7743e5ed1e1c304eb1c34e8e39f\""
}
$ aws s3api head-object --bucket <bucket> --key foo.html
{
    "AcceptRanges": "bytes",
    "ContentType": "text/html",
    "LastModified": "Wed, 15 Apr 2015 06:46:49 GMT",
    "ContentLength": 189,
    "ETag": "\"fd5ff7743e5ed1e1c304eb1c34e8e39f\"",
    "Metadata": {}
}

While it appears to set some sort of special ContentType property, there still isn't a Content-Type metadata field in the AWS console, nor can I access the file in a browser.
I've also tried similar commands (aws s3 cp, aws s3 sync), with no luck. I have the bucket policy set to publicly-readable.
Answer: Your second example with --content-type is the way to set content type for an object.  The JSON response displayed is mapping the Content-Type header in the HTTP response to the ContentType key, but it corresponds to the actual Content-Type header of the object.  I confirmed that the content type value does show up in the metadata section in the console when using --content-type.
$ aws s3api put-object --bucket bucket --key foo.json --body foo.json --content-type application/json --acl public-read

$ aws s3api head-object --bucket jamesls-test-sync --key foo.json
{
    "AcceptRanges": "bytes",
    "ContentType": "application/json",
    "LastModified": "Wed, 15 Apr 2015 17:18:58 GMT",
    "ContentLength": 0,
    "ETag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
    "Metadata": {}
}

Also using curl, we can see the content type header is set:
$ curl -I https://bucket.s3.amazonaws.com/foo.json
HTTP/1.1 200 OK
x-amz-id-2: ZlSg1aDUBu7z+9gWUg24uRn2TioI0hk2AGBBZ1iVbpUkv8RTrHWovzbHxL/y21Qe
x-amz-request-id: 8568C73EB95EE5A6
Date: Wed, 15 Apr 2015 17:20:42 GMT
Last-Modified: Wed, 15 Apr 2015 17:18:58 GMT
ETag: "d41d8cd98f00b204e9800998ecf8427e"
Accept-Ranges: bytes
Content-Type: application/json
Content-Length: 0
Server: AmazonS3

Comment: This doesn't work if I omit the `--acl public-read` parameter. Is there a way to get this to work while locking down access to a certain IP range, as I've done in my bucket policy?
Comment: Never mind, it appears this setup already does exactly what I want: even though the object ACL is set to `public-read`, the bucket policy still applies as well.
Answer: This is not what the OP was looking for, but Google sends a lot of people here.
If you are wanting to set the content type of an object that is already on S3 without having to upload the --body again, see How to change content type of Amazon S3 Objects
Answer: In the AWS console, you can key in the content-type that you want even if the content-type is not listed in the drop-down.
Answer: This problem is old, but it's still really vexing.  I tried creating a lambda to look at the content type and fix it up and it caused some kind of recursion. I can't believe Amazon hasn't provided a way to fix this, at least the way Apache and others do it by letting you specify your own file extension to mime type mapping.  Or, even better, just do the right thing.  If I upload a file that's named xyzzy.js then it should be pretty obvious that it's mime type should not be "text/plain."  The fact that this screws up S3 backed CloudFront makes it even more boggling to me that it hasn't been mitigated.


Exception in thread "IDL" java.lang.UnsatisfiedLinkError: no idl_ips in java.library.path

Question: I'm trying to run IDL on linux, but the result is
<code>Exception in thread "IDL" java.lang.UnsatisfiedLinkError: no idl_ips in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at com.rsi.idldt.core.ips.IPS_Access.<init>(IPS_Access.java:44)
    at com.rsi.idldt.core.ips.IPS_Access.get(IPS_Access.java:51)
    at com.rsi.idldt.core.ips.IPS_Manager$3.run(IPS_Manager.java:482)
    at java.lang.Thread.run(Thread.java:748)
</code>
It seems like I have to install idl_ips but in the web I found only a version of idl_ips.dll for windows.
I'm sorry, maybe is simple but I am a beginner.
Can you solve this?
Answer: You might check this post, which describes a very similar-looking problem. In that post, it's libidl_ips from libXp which is missing, but it looks like different flavors of Linux have slightly different dependencies. The other poster linked to this IDL help page, which provides instructions for specific Linux installations.
Comment: ok, thanks.
It turns out that _idl_ doesn't need java, while _idldl_ does. So, using _idl_, I dont't need anymore to fix this problem.


Oracle SQL Developer script output not displaying readable format

Question: I have queries that provide the output, but the output is really weird looking.  It doesn't scroll over to look at the output, and the columns are really wide for things that are less than 20 characters.  How do I get it to look normal? This is using Oracle SQL Developer. I searched online, but this doesn't seem to be what I need to do: format output archive. Although, I don't see how to get to the preference screen they are referring to either.
This is a portion of the output:
<code>      RAK      SHEL SLT
---------- ---------- ------------------------------ PRT                                     BRDBND_
---------------------------------------- ---------- DSLAM
-------------------------------------------------- VEND
-------------------------------------------------------------------------------- MODE
-------------------------------------------------------------------------------- PORT_ADDR  CARRIER_ID
----------------- ----------------------------------------------------- CIRC_DE SERVICE SHELF_PT_NUM         CARD_PART_NUM
---------- ---------- ------------------------- ------------------------- CARD_PT_DESC
-----------------------------------
    3317 270812 1179G1                 1170F1
</code>
As you can see, hopefully, it has really wide columns for the output, and column headers aren't at the top of the output window, it's in the output window. None of the output is more than 20 characters wide. I'm not sure why it's displaying that way.
Update: Plus, it's printing the column headers in the output window over and over again.
Comment: Show us your sql
Comment: The problem wasn't the sql.  It was the settings in developer.  @ZynonPutneyII answered it already.
Comment: glad it's answered, but you made us guess. Next time show us you entire script + settings, then we can give you an educated answer
Answer: Try adding this line at the beginning of your script. It appears that your SQL Developer settings are what is making this output unreadable.
NOTE: I am using SQL Developer version 18.1.0.095
Edit: Added command to suppress reprinting of headers (pagesize) to 80 lines.
<code>set sqlformat ansiconsole;
set pagesize 80;
</code>
Comment: set pagesize 80 will make the output 80 lines before it reprints header.
Comment: It still seems to be printing the header every 10 output lines.  It's a little better though.


adjust drop down menu height to show more options (AngularJS Material)

Question: i'm new to Angularjs Material so maybe this is something obvious yet it seems i can't figure it out.
i have a multiple choice drop down menu which shows only 4 options when initially clicked on and the rest can be viewed/accessed by scrolling down. I'm trying to expand that view to another static number (e.g. to fit 8 options without scroll).
i found very similar question asked before:
Make multiple-select to adjust its height to fit options without scroll bar
however, it seems not to have any effect neither with "size" nor "ng-size"
here is my example:
<md-input-container>
    Providers
    <md-select ng-size="10" ng-model="vm.selectedProviders" ng-change="vm.prov()" multiple>
        <md-optgroup label="Providers">
            <md-option ng-value="provider.namep" ng-repeat="provider in vm.providers">{{provider.namep}}</md-option>
        </md-optgroup>
    </md-select>
</md-input-container>

Answer: Looking at the documentation of md-select, there doesn't seem to be an attribute that specifies the number of options to show.
So the other possible way is to change the maximum heights set by default in AngularJS Material. They're set like this:
md-select-menu, md-select-menu md-content {
    max-height: 256px;
}

For me, it displays 5 options by default (not 4). So, I added this to my CSS:
md-select-menu, md-select-menu md-content {
    max-height: 385px;
}

And it made all md-select tags fit 8 options instead of 5. The number doesn't have to be the same for you, so play with the height until you're satisfied.
Hope that helps.
Comment: @Ricky in your project CSS file.
Comment: Omar, this works great! You're right, it does return 5 values (including "title"). i looked into md-select directive and was hoping i somehow missed it out
Comment: @OmarEinea, where do these values go?


ANTLR match declaration only

Question: I'm trying to write a parser with ANTLR4 that should parse a very simple model file from hyperledger:
asset Car identified by id {
  o String id
  o String model
  --> Owner owner
}

participant Owner identified by id {
  o String id
  o String name
}

transaction Auction {
  --> Car asset
  o String newValue
}

I'm having a problem within the transaction: I can't give the variable of type Car the name 'asset', which is valid in the language specification. The ANTLR parser doesn't expect that. I get an exception similar like that: mismatched input 'o' expecting {'[', IDENTIFIER} I know the cause is the assetDeclaration in my grammar, which detects the asset keyword in the transaction as well.
Is there a way to ignore the asset within the transaction? Or can I make the declaration more specific, so that it is triggered when the asset is at the start and followed by letters?
This is my asset declaration:
assetDeclaration: ASSET IDENTIFIER
  (EXTENDS typeType)?
  IDENTIFIED
  IDENTIFIER
  classBody;

And my transaction declaration:
transactionDeclaration: TRANSACTION IDENTIFIER
  classBody
;

Asset, Transaction and so on defined as:
 ASSET: 'asset';
 TRANSACTION: 'transaction';
 IDENTIFIED: 'identified by';
 PARTICIPANT: 'participant';

The rest of the grammar is similar to the JavaGrammar which is available at GitHub
Comment: The name for this is "non-reserved keyword" - a word that has some special meaning to the language, but may also be used as an identifier.
Answer: If asset is allowed to appear anywhere where an identifier is allowed, you can just define identifier: IDENTIFIER | ASSET; and then use identifier everywhere instead of IDENTIFIER.
If asset is only allowed in certain places where identifiers are allowed, you should explicitly write (IDENTIFIER | ASSET) in those places.
The same applies to any other keywords that are also legal as identifiers.
Comment: Thanks, that works for me.

ANTLR match declaration only


let A be a $2\times 2$ matrix . Then the smallest number $n\in \mathbb N$ such that $A^n=I$ is

Question: let A be a $2\times 2$ matrix $\begin{pmatrix} \sin \frac \pi {18} & -\sin \frac {4\pi} {9}\\
\sin \frac {4\pi} {9}&\sin \frac \pi {18}\end{pmatrix}$. Then the smallest number $n\in \mathbb N$ such that $A^n=I$ is

(a). 3
(b). 9
(c). 18
(d). 27

My work
I checked for the order for 3. But, I could know that I am wrong in this way. And I tried to find that "Is it nth roots of some complex numbers" but in that way also I could not achieve. How can I proceed?
If I give this matrix what is the answer
$$\begin{pmatrix}1&0&0\\
0& \sin \frac \pi {18} & -\sin \frac {4\pi} {9}\\
0&\sin \frac {4\pi} {9}&\sin \frac \pi {18}\end{pmatrix}$$
Answer: Using the identity
$$\sin x=\cos\left(x-\frac\pi2\right)$$
we see that the given matrix is a matrix of rotation of angle $\frac{4\pi }{9}$ hence the answer is $9$.
Comment: It is rotation matrix .But can you please explain how you have got 9
Comment: The matrix $A^n$ is also a rotation matrix with angle $ \frac{4n\pi}{9}$ so what's the value of $n$ to get a multiple of $2\pi$.
Answer: Here's a hint (assuming you are indeed missing a minus sign): $\sin \frac{\pi}{18} = \cos \frac{4\pi}{9}$.


theme profile2 fields on registration form

Question: I have two profile types
teacher and student
so far I have used profile2 module and the profile 2 registration path module.
I have the core fields added
I am trying to add profile2 fields to my user-registration template
So far my template looks like this
<?php
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
?>

<?php print drupal_render($form['account']['name']); // prints the username field ?>
<?php print drupal_render($form['account']['mail']); // prints the mail field ?>
<?php print drupal_render($form['account']['pass']); // prints the password fields ?>

<?php print drupal_render($form['actions']['submit']); // print the submit button ?>
password is not being displayed

I am not sure how i can add profile2 fields to my registration form.
Answer: This link should help you in achieving it.
Comment: Welcome to Drupal Answers.  Normally, answers with just links aren't considered good ones.  Can you provide a short summary of how this will help with Profile 2 fields?
Answer: Given Andrew's link, I found the solution to get a profile form array.
First, check 'Show during user account registration' under your profile configuration.
Then call
drupal_get_form('user_register_form')

That's it !


How do I retrieve info of a job associated with a Google BigQuery execution on a public dataset?

Question: I ran a query against BigQuery from the Cloud Shell:
xenonxie@cloudshell:~ (welynx)$ bq query --dry_run "SELECT COUNT(1) as rowcount, COUNTIF(corpus = 'hamlet') as rowcount_hamlet FROM publicdata.samples.shakespeare order by rowcount_hamlet desc"
Query successfully validated. Assuming the tables are not modified, running this query will process 2464625 bytes of data.
xenonxie@cloudshell:~ (welynx)$ bq query "SELECT COUNT(1) as rowcount, COUNTIF(corpus = 'hamlet') as rowcount_hamlet FROM publicdata.samples.shakespeare order by rowcount_hamlet desc"
Waiting on bqjob_r152b89ff4ea17df1_0000016faa8d1546_1 ... (0s) Current status: DONE
+----------+-----------------+
| rowcount | rowcount_hamlet |
+----------+-----------------+
|   164656 |            5318 |
+----------+-----------------+

I can see that there is a job associated with it:
xenonxie@cloudshell:~ (welynx)$ bq ls -j -a
                    jobId                      Job Type    State      Start Time         Duration
 -------------------------------------------- ---------- --------- ----------------- ----------------
  bqjob_r152b89ff4ea17df1_0000016faa8d1546_1   query      SUCCESS   15 Jan 13:52:50   0:00:00.886000

Now, I want to retrieve the job's details as described in the BigQuery REST API documentation here:
https://bigquery.googleapis.com/bigquery/v2/projects/bqjob_r152b89ff4ea17df1_0000016faa8d1546_1/jobs

However, I received the error below:
xenonxie@cloudshell:~ (welynx)$ wget https://bigquery.googleapis.com/bigquery/v2/projects/bqjob_r152b89ff4ea17df1_0000016faa8d1546_1/jobs
--2020-01-15 15:10:23--  https://bigquery.googleapis.com/bigquery/v2/projects/bqjob_r152b89ff4ea17df1_0000016faa8d1546_1/jobs
Resolving bigquery.googleapis.com (bigquery.googleapis.com)... 188.8.131.52, 2607:f8b0:400c:c0d::5f
Connecting to bigquery.googleapis.com (bigquery.googleapis.com)|18.104.22.168|:443... connected.
HTTP request sent, awaiting response... 401 Unauthorized

Username/Password Authentication Failed.

Can anyone enlighten me as to what is going wrong here and how do I fix it? Thank you very much.
Answer: There are a couple things that don't look right here:

While you might be able to use wget to call the BigQuery REST API,
I do not recommend that method - the preferred, most commonly used
and easy way to go method is by using cURL instead.
The BigQuery REST API method you linked is for listing all BigQuery
jobs, not the details for a single one as you're asking. Moreover,
the requested URL must be in the form of
https://bigquery.googleapis.com/bigquery/v2/projects/{projectId}/jobs
as mentioned there - you've omitted {projectId} and placed the job
ID in its place instead.
Regardless, to view the details of single job ID, the BigQuery REST API method
jobs.get should be used instead, where the URL must be in the
form of
https://bigquery.googleapis.com/bigquery/v2/projects/{projectId}/jobs/{jobId},
replacing {projectId} with your project ID and {jobId} with the
BigQuery job ID.
To call the REST API using cURL you must provide some form of
authentication. One way is to use the access token, which can be obtained by running gcloud auth print-access-token from i.e
the Cloud Shell.

Given my previous points, and to summarize, the REST API call that should give you what you're looking for (using cURL) should like like this in the end:
curl -H "Authorization: Bearer "$(gcloud auth print-access-token) \
https://bigquery.googleapis.com/bigquery/v2/projects/{projectId}/jobs/bqjob_r152b89ff4ea17df1_0000016faa8d1546_1

Important: make sure you provide the project ID as a parameter, by replacing {projectId} (including the curly braces) accordingly, where the BigQuery job was created. Also, I copy-pasted the job ID from your question there, so depending on the job you want to check for, the last part should also be modified to your needs.
Comment: Thank you so much Maxim for the help, I got the needed result with the command you summarized.
Comment: While you can call APIs directly, Google recommend using one of the provided Client Libraries for various languages (e.g. python, go) instead. Generally these libraries simplify authenticating and interacting with the APIs. https://cloud.google.com/apis/docs/cloud-client-libraries


Integrate $\int \frac{1}{1+x+x^4}dx$

Question:
Find $$\int \frac{{\rm d}x}{1+x+x^4}.$$

WA gives a result, which introduces complex numbers. But according to the algebraic fundamental theorem, any rational fraction can be integrated over the real number field.
How to do this?
Comment: First factorize the denominator over $\mathbb R$ (gives two factors with degree $2$), then apply partial fraction decomposition.
Comment: Yes,but how to factorize it?
Comment: These are [some formulas for the roots](https://en.wikipedia.org/wiki/Quartic_function#General_formula_for_roots) of that denominator in terms of radicals.
Comment: By hand it is not easy. Do you know the roots ?
Comment: @flan Is the formula easy enough in this case ? Degree $4$ usually is quite complicated.
Comment: @Peter They are. Expressions in radicals are nothing compare to what it exists out there.
Comment: @flan In this case, you can give the factorization in an answer as a hint.
Answer: Yow-Zooey!  This is a horrendously difficult function to work with!  Are you sure there is not a typographical error somewhere?
The best way to identify a real quadratic factorization is to use a resolvent cubic.  Assume a factorization having the form
$x^4+x+1=(x^2-s^{1/2}x+t_1)(x^2+s^{1/2}x+t_2)$
where $s$ is to be real and nonnegative in a real factorization.  The fourth and third degree terms match trivially.  Now match the quadratic and linear terms:
$x^2\to t_1+t_2-s=0, t_1+t_2=s$  eq. 1
$x^1\to t_1-t_2=1/s^{1/2}$  eq. 2
We then have a linear system for $t_1,t_2$ in terms of $s$.  Solving by the usual methods for such a system leads to everything being rendered in terms of $s$:
$t_1=\dfrac{s^2+s^{1/2}}{2s}$
$t_2=\dfrac{s^2-s^{1/2}}{2s}$
So our quadratic factorization will be
$x^4+x+1=(x^2-s^{1/2}x+\dfrac{s^2+s^{1/2}}{2s})(x^2+s^{1/2}x+\dfrac{s^2-s^{1/2}}{2s})$  eq. 3
Now we have to find $s$.  To get that we have to match the constant terms:
$t_1t_2=(1/4)(t_1+t_2)^2-(1/4)(t_1-t_2)^2=1$
Substitute for $t_1\pm t_2$ from eqs. 1 and 2 and clear fractions leading to the cubic equation
$s^3-4s-1=0$
All the complexity in the roots given from another answer arise from solving this irreducible cubic equation, but we do guarantee one real, positive root from Descartes' Rule of Signs.  In practice you would probably have to approximate this root numerically; $s\approx 2.1149$.  An exact rendering for $s$ in terms of real functions requires using trigonometric functions:
$s=\sqrt{16/3}\cos(\frac13\cos^{-1}\sqrt{27/256})$
Plug this root into eq. 3 and integrate by methods appropriate when the denominator is a product of two distinct quadratic polynomials.
Answer: Factorize
$$x^4 +x+ 1= \left(x^2+ax+\frac{a^3-1}{2a}\right)\left(x^2-ax+\frac{a^3+1}{2a}\right)$$
where $a$ satisfies $a^6-4a^2-1=0$, or
$$a=\frac2{\sqrt[4]3}\sqrt{\cos\left(
\frac13\cos^{-1}\frac{3\sqrt3}{16} \right)}
$$
Then, decompose the integrand
$$\frac1{1+x+x^4}
= \frac a{2a^6+1} \bigg(\frac{2a^2x+2a^3+1}{x^2+ax+\frac{a^3-1}{2a}}
-\frac{2a^2x-2a^3+1}{x^2-ax+\frac{a^3+1}{2a}} \bigg)$$
and integrate
\begin{align}
&\int \frac{dx}{1+x+x^4}\\
=&\ \frac a{2a^6+1} \int \bigg(\frac{a^2(2x+a)+ a^3+1}{x^2+ax+\frac{a^3-1}{2a}}
-\frac{a^2(2x-a)-a^3+1}{x^2-ax+\frac{a^3+1}{2a}} \bigg)dx\\
=&\ \frac {a^{3/2}}{a^6+\frac12} \bigg(
\frac {a^3+1}{\sqrt{a^3-2}}\tan^{-1}\frac{\sqrt a(2x+a)}{\sqrt{a^3-2}}
+\frac {a^3-1}{\sqrt{a^3+2}}\tan^{-1}\frac{\sqrt a(2x-a)}{\sqrt{a^3+2}}\\
&\hspace{20mm} + \frac{a^{3/2}}2\ln \frac{x^2+ax+\frac{a^3-1}{2a}}{x^2-ax+\frac{a^3+1}{2a}}  \bigg)+C
\end{align}
Answer: One approach, although tedious, will lead to a fractional decomposition, from which the integral can be calculated easily without using complex variables. It is easy to check that the function $f(x)=1+x+x^4$ is not a perfect square and has no real roots ($f$ has a positive  global minimum at $x=-1/\sqrt[3]{4}$). This means that
$f(x)=(ax^2+bx+c)(ux^2+vx+w)$ with $b^2-4ac<0$ and $v^2-4uw<0$.
Expand this, equate coefficients to solve for $a,b,c,u,v,w$. Then, decompose as usual: there are real numbers $A,B,C,D$ such that
$\displaystyle\int \frac{1}{1+x+x^4}dx=\int \frac{Ax+B}{ax^2+bx+c}dx+\frac{Cx+D}{ux^2+vx+w}dx$
whose antiderivatives are logartithms and inverse tangents.
Answer: Why did you have to choose this rational function... ? Well there is a factorization like this:
$$1+x+x^4=\left(x^2-\sqrt{\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i \sqrt{687}\right)}}}
   x+\frac{1}{2} \left(\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i \sqrt{687}\right)}}-4
   \sqrt{\frac{\sqrt[3]{\frac{1}{2} \left(9+i \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2}
   \left(9+i \sqrt{687}\right)}}}+\left(\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i
   \sqrt{687}\right)}}\right)^{5/2}\right)\right) \left(x^2+\sqrt{\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i \sqrt{687}\right)}}}
   x+\frac{1}{2} \left(\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i \sqrt{687}\right)}}+4
   \sqrt{\frac{\sqrt[3]{\frac{1}{2} \left(9+i \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2}
   \left(9+i \sqrt{687}\right)}}}-\left(\frac{\sqrt[3]{\frac{1}{2} \left(9+i
   \sqrt{687}\right)}}{3^{2/3}}+\frac{4}{\sqrt[3]{\frac{3}{2} \left(9+i
   \sqrt{687}\right)}}\right)^{5/2}\right)\right)$$
(you can check that, even though $i$ is used in the construction of the coefficients, they are actually all real.)
Comment: More likely than not the OP is looking for factors with real functions.  When you get to the resolvent cubic, could you solve it [trigonometrically](https://en.wikipedia.org/wiki/Casus_irreducibilis)?
Comment: @OscarLanzi and Maximilian, suggest adding in integral of $\frac{1}{x^4 + x^2 + 1},$ in that WA also displays some complex numbers, but this one factors nicely
Comment: @will jagy That tends to diffuse the question and our answers.  Might want to make another question.
Answer: \begin{align}
\int \frac{{\rm d}x}{1+x+x^4}
\end{align}
It looks like the main problem is factorization
of the quartic, so here it is one more variant:
for
\begin{align}
a&=\sqrt{\frac1{\sqrt3}\,\cos\Big(\tfrac13\,\arctan(\tfrac19\,\sqrt{687})\Big)}
\\
&\approx 0.72713608449
,
\end{align}
\begin{align}
x^4+x+1&=
\Big(x^2-2\,a\,x+2\,a^2+\sqrt{4\,a^4-1}\Big)
\left(x^2+2\,a\,x+\frac1{2\,a^2+\sqrt{4\,a^4-1})}\right)
\\
&\approx
(x^2-1.45427216898\,x+1.40126836794)
(x^2+1.45427216898\,x+0.713639173537)
.
\end{align}

Integrate $\int \frac{1}{1+x+x^4}dx$


Como no ASP.NET 5 essa propriedade é definida?

Question: No ASP.NET 5 no método Configure da classe Startup podemos receber nos parametros uma referencia a um objeto cuja classe implemente IHostingEnvironment. Uma das propriedades dessa classe é EnvironmentName. Já vi em códigos de exemplo uma realização de uma verificação nessa propriedade para detalhar erros ou não. Se essa propriedade for Development então trata-se do ambiente de desenvolvimento e mostra-se os erros em detalhes. Caso contrário trata-se do ambiente de produção e mostra-se uma página amigavel avisando que ocorreu um erro.
Até aí tudo bem, o que eu não entendo é como essa propriedade é definida. Por que sempre que rodo ela tem valor "Development"? Como essa propriedade é realmente definida?
Answer: O que você está procurando está no código de ConfigureHostingEnvironment.cs:
using System;
using Microsoft.Framework.ConfigurationModel;

namespace Microsoft.AspNet.Hosting
{
    internal class ConfigureHostingEnvironment : IConfigureHostingEnvironment
    {
        private IConfiguration _config;
        private const string EnvironmentKey = "ASPNET_ENV"; //esta é a variável de ambiente

        public ConfigureHostingEnvironment(IConfiguration config)
        {
            _config = config;
        }

        public void Configure(IHostingEnvironment hostingEnv)
        {
            hostingEnv.EnvironmentName = _config.Get(EnvironmentKey) ?? hostingEnv.EnvironmentName;
        }
    }
}

Coloquei no GitHub para referência futura.
Então para mudar a propriedade é necessário alterar a variável de ambiente ASPNET_ENV no sistema operacional.
Há uma discussão sobre isto no GitHub.
Answer: O que o @Maniero disse em sua resposta está correto! E aquele é processo interno que é utilizado para obter o valor de EnvironmentName.
Mas para testar seu sistema em outro ambiente em tempo de desenvolvimento você não necessariamente deve ter que setar a variável de ambiente do OS, a ferramenta Visual Studio já disponibiliza uma forma de você configurar/alterar variáveis de ambiente para o seu projeto, que é a seguinte:
Clique com o botão direito sobre seu projeto e depois em Properties, irá surgir o painel de propriedades de seu projeto, acesse a sessão/tab Debug e em seguinda você vai observar uma tabela de propriedades chamada "Environment Variables", que seriam as variáveis de ambiente para o projeto, seria algum similar a isso:

Então para testar você pode alterar o valor da propriedade Hosting:Environment para Production, assim ao rodar o sistema novamente o valor da propriedade EnvironmentName do objeto IHostingEnvironment será "Production".


Keep searchfield-value after selection when using jquery autocomplete plugin

Question: I'm using Jörn Zaefferers autocomplete plugin for jQuery to enable a live search field, which is working great. The user input gets sent to a search service, that returns formatted results in Json format. When a result gets chosen, the values are entered into a separate table.
What I'm having trouble with is: After a user selects a search result from the drop-down, I don't want the search (parameters entered by the user) to be overwritten by the result. Which is the default behaviour.
I'm looking for an option that I can use to disable this, If it doen't exist though, I may have to look for a workaround / different plugin.
Here is my current usage of the autocomplete plugin with options:
<code>$('#searchInput').autocomplete('searchUrl',
    {
        dataType: 'json',
        parse: function(data) {
            //logic to parse search results that are returned from search
            return datarows;
        },
        formatItem: function(row, i, max) {
            return row.Description;
        },
        width: 500,
        highlight: false,
        multiple: false,
        minChars: 2,
        delay: 800,
        selectFirst: false,
        autoFill: false,
        cacheLength: 10
    })
    .result(function(event, item) {
        //logic to handle item chosen by the user
    });
</code>
Comment: if possible, give a demo site?
Comment: sorry, isn't possible. It's for internal use and I don't have any place to make / publish a demo app
Answer: What you want is not an autocomplete function, therefore an autocomplete plugin won't work. You have to modify the plugin so that it doesn't overwrite the result. I'm looking at it to see what changes you need to make and will add my proposed solution shortly.

Something came up at work, so I have to make this quick.
In the plugin, the input value is modified via the $input.val() function. When an argument is passed to it, like this:
<code>$input.val('test')
</code>
The input's contents change, in this case to "test". You have to get rid of those lines. Note that calling $input.val() only returns the value without changing it so you want to leave those lines alone.
A couple I found:
On line 233, comment
<code>$input.val(v);
</code>
On line 297, comment
<code>$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
</code>
There are more for sure. From what I have seen I would expect to find at least one in the function that hides the menu. Use the editor's search function.
This may or may not break the plugin, you'll have to start by commenting out those lines and then debug it.
I hope I was helpful enough, good luck :)
Comment: Ah, of course..for some reason the thought didn't occur to me that I could modify the plugin itself. I'll have a look into this in a bit and let you know how it works out
Comment: Works great! As you say I'm working against the way the autocomplete-plugin works out of the box, and seeing that there aren't any options that do this modifying the plugin is the way to go. Thx :)
Comment: Great, an additional tip: now that you know which lines can be safely removed, exploit JS's dynamic nature to make the plugin more generic. Add an initialization option called "pleaseDontChangeTheInputFieldValueThanks" and instead of  commenting out the offending lines wrap them in IFs that check for the truth value of the option. That way you can reuse the plugin if you need a traditional autocomplete function. Good luck with the rest of your project :)


Erro ao consultar dados no JTable com Hibernate

Question: O seguinte erro da ao consultar os dados:

 INFO: HHH000182: No default (no-argument) constructor for class:
 Classes.Funcionario (class must be instantiated by Interceptor)

 Hibernate: select funcionari0_.ID_Funcionario as ID_Funci1_0_,
 funcionari0_.`Data de Admissao` as Data2_0_, funcionari0_.`Data de
 Demissao` as Data3_0_, funcionari0_.Nome as Nome4_0_,
 funcionari0_.`Estado Civil` as Estado5_0_, funcionari0_.Sexo as
 Sexo6_0_, funcionari0_.CEP as CEP7_0_, funcionari0_.CPF as CPF8_0_,
 funcionari0_.RG as RG9_0_, funcionari0_.`Data de Nascimento` as
 Data10_0_, funcionari0_.Estado as Estado11_0_, funcionari0_.Cidade as
 Cidade12_0_, funcionari0_.Bairro as Bairro13_0_, funcionari0_.Endereco
 as Enderec14_0_, funcionari0_.TEL as TEL15_0_, funcionari0_.CEL as
 CEL16_0_, funcionari0_.Email as Email17_0_, funcionari0_.Cargo as
 Cargo18_0_, funcionari0_.`Nivel de Escolaridade` as Nivel19_0_ from
 funcionario funcionari0_

Exception in thread "AWT-EventQueue-0" org.hibernate.InstantiationException: No default constructor for entity:  : Classes.Funcionario

TELA DO JTABLE
package Telas;

import Classes.Funcionario;
import Hibernate.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

 */
public class Tela_ConsultarFuncionario extends javax.swing.JInternalFrame {

    List <Funcionario> funcionarios  = new ArrayList<>();

    String [] Colunas = new String [] {"nome,datadeAdmissao,estadoCivil,sexo,cep,cpf,rg,datadeNascimento,estado,cidade,bairro,endereco,tel,cel,email,cargo,niveldeEscolaridade"};
    String [] [] Dados = new String [10] [16];

    public Tela_ConsultarFuncionario() {

        initComponents();

        Tbl_Funcionarios.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

}

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        String [][] Dados = new String [funcionarios.size()] [17];

        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();

      Query query = session.createQuery("select c from Funcionario c");
       funcionarios = query.list();

         int i = 0;

          String [] Colunas = new String[]{"nome,datadeAdmissao,estadoCivil,sexo,cep,cpf,rg,datadeNascimento,estado,cidade,bairro,endereco,tel,cel,email,cargo,niveldeEscolaridade"};

         while( i<funcionarios.size() )
        {

            Dados [i][0] = funcionarios.get(i).getDatadeAdmissao();
            Dados [i][1] = funcionarios.get(i).getNome();
            Dados [i][2] = funcionarios.get(i).getDatadeNascimento();
            Dados [i][3] = funcionarios.get(i).getSexo();
            Dados [i][4] = funcionarios.get(i).getEstadoCivil();
            Dados [i][5] = funcionarios.get(i).getCep();
            Dados [i][6] = funcionarios.get(i).getCpf();
            Dados [i][7] = funcionarios.get(i).getRg();
            Dados [i][8] = funcionarios.get(i).getEstado();
            Dados [i][9] = funcionarios.get(i).getCidade();
            Dados [i][10] = funcionarios.get(i).getBairro();
            Dados [i][11] = funcionarios.get(i).getEndereco();
            Dados [i][12] = funcionarios.get(i).getTel();
            Dados [i][13] = funcionarios.get(i).getCel();
            Dados [i][14] = funcionarios.get(i).getEmail();
            Dados [i][15] = funcionarios.get(i).getNiveldeEscolaridade();
            Dados [i][16] = funcionarios.get(i).getCargo();

          i++;

        }

        session.beginTransaction();
        session.getTransaction().commit();
        session.close();

        DefaultTableModel modelo = new DefaultTableModel(Dados,Colunas);
       Tbl_Funcionarios.setModel( modelo );

    }

}

TELA FUNCIONARIO
package Classes;

import java.io.Serializable;

public class Funcionario implements Serializable {

    private Integer iDFuncionario;
    private String datadeAdmissao;
    private String datadeDemissao;
    private String nome;
    private String estadoCivil;
    private String sexo;
    private String cep;
    private String cpf;
    private String rg;
    private String datadeNascimento;
    private String estado;
    private String cidade;
    private String bairro;
    private String endereco;
    private String tel;
    private String cel;
    private String email;
    private String cargo;
    private String niveldeEscolaridade;

    public Funcionario(String nome,String datadeAdmissao,String datadeDemissao,String estadoCivil,String sexo,String cep,String cpf,String rg,String datadeNascimento,String estado
    ,String cidade,String bairro,String endereco,String tel,String cel,String email,String cargo,String niveldeEscolaridade) {
      this.nome=nome;
      this.datadeAdmissao=datadeAdmissao;
      this.datadeDemissao=datadeDemissao;
      this.estadoCivil=estadoCivil;
      this.sexo=sexo;
      this.cep=cep;
      this.cpf=cpf;
      this.rg=rg;
      this.datadeNascimento=datadeNascimento;
      this.estado=estado;
      this.cidade=cidade;
      this.bairro=bairro;
      this.endereco=endereco;
      this.tel=tel;
      this.cel=cel;
      this.email=email;
      this.cargo=cargo;
      this.niveldeEscolaridade=niveldeEscolaridade;
    }

    public Funcionario(Integer iDFuncionario) {
     this.iDFuncionario=iDFuncionario;
    }

    public Integer getiDFuncionario() {
        return iDFuncionario;
    }

    public void setiDFuncionario(Integer iDFuncionario) {
        this.iDFuncionario = iDFuncionario;
    }

    public String getDatadeAdmissao() {
        return datadeAdmissao;
    }

    public void setDatadeAdmissao(String datadeAdmissao) {
        this.datadeAdmissao = datadeAdmissao;
    }

    public String getDatadeDemissao() {
        return datadeDemissao;
    }

    public void setDatadeDemissao(String datadeDemissao) {
        this.datadeDemissao = datadeDemissao;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEstadoCivil() {
        return estadoCivil;
    }

    public void setEstadoCivil(String estadoCivil) {
        this.estadoCivil = estadoCivil;
    }

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getRg() {
        return rg;
    }

    public void setRg(String rg) {
        this.rg = rg;
    }

    public String getDatadeNascimento() {
        return datadeNascimento;
    }

    public void setDatadeNascimento(String datadeNascimento) {
        this.datadeNascimento = datadeNascimento;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getCel() {
        return cel;
    }

    public void setCel(String cel) {
        this.cel = cel;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    public String getNiveldeEscolaridade() {
        return niveldeEscolaridade;
    }

    public void setNiveldeEscolaridade(String niveldeEscolaridade) {
        this.niveldeEscolaridade = niveldeEscolaridade;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (iDFuncionario != null ? iDFuncionario.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Funcionario)) {
            return false;
        }
        Funcionario other = (Funcionario) object;
        if ((this.iDFuncionario == null && other.iDFuncionario != null) || (this.iDFuncionario != null && !this.iDFuncionario.equals(other.iDFuncionario))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Classes.Funcionario[ iDFuncionario=" + iDFuncionario + " ]";
    }

}

TELA MAPEAMENTO DO FUNCIONARIO
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="Classes.Funcionario" table="funcionario" >
  <id name="iDFuncionario" column="ID_Funcionario">
      <generator class="native"/>
  </id>
        <property name="datadeAdmissao" type="string" length ="50" column="`Data de Admissao`" />
        <property name="datadeDemissao" type="string" length ="50" column="`Data de Demissao`"/>
        <property name="nome" type="string" length="50" column="Nome"/>
        <property name="estadoCivil" type="string" length="50" column="`Estado Civil`"/>
        <property name="sexo" type="string" length ="50" column="Sexo"/>
        <property name="cep" type="string" length ="50" column="CEP"/>
        <property name="cpf" type="string" length ="50" column="CPF"/>
        <property name="rg" type="string" length ="50" column="RG"/>
        <property name="datadeNascimento" type="string" length ="50" column="`Data de Nascimento`"/>
        <property name="estado" type="string" length ="50" column="Estado"/>
        <property name="cidade" type="string" length ="50" column="Cidade"/>
        <property name="bairro" type="string" length ="50" column="Bairro" />
        <property name="endereco" type="string" length ="50" column="Endereco"/>
        <property name="tel" type="string" length ="50" column="TEL"/>
        <property name="cel" type="string" length ="50" column="CEL"/>
        <property name="email" type="string" length ="50" column="Email"/>
        <property name="cargo" type="string" length ="50" column="Cargo"/>
        <property name="niveldeEscolaridade" type="string" length ="50" column="`Nivel de Escolaridade`"/>
    </class>
</hibernate-mapping>

Comment: Não domino hibernate, mas o erro parece estar relacionado a falta de um construtor padrao, no caso, `public Funcionario(){...}`
Comment: Adicione sua classe funcionario.
Comment: de que maneira ?
Comment: Eu quis dizer adicionar a classe na pergunta, esta classe está envolvida no erro também.
Comment: Ah ta,não tinha entendido kkkkk
Comment: Dica, não use o snipet para códigos java, basta colar o código, seleciona-lo e clicar em `{}`
Comment: Blz,muda alguma,fica melhor assim ?
Comment: Pelo que li no SOEn, o hibernate exige que se tenha um construtor default, ou seja, aquele sem argumentos como exemplifiquei no comentário anterior, pois ele usa reflexão para criar o bean. Primeiro ele cria um objeto vazio e depois vai preenchendo com os getters e setters conforme for necessário. Quando você personaliza o construtor com argumentos, o construtor padrao precisa ser implementado de forma explicita na classe.
Comment: ah,ta vou ver mexer aqui para ver
Comment: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
Comment: agora mudou o erro
Comment: Ai já é outro problema, o que demandaria outra pergunta diferente. o erro da pergunta se resolveu com a dica passada. Converti como resposta para melhorar a visibilidade da dica para outras pessoas.
Comment: Não se esqueça de citar esta pergunta na nova, para facilitar a analise de quem responder :)
Comment: Só criar outra pergunta então ?
Comment: Sim, e adicionar a pilha completa do erro como fez nessa.
Answer: Conforme esta resposta do SOEn, o hibernate exige que se tenha um construtor default, ou seja, aquele sem argumentos como exemplifiquei nos comentários, pois ele usa Reflection para criar o bean. Primeiro ele cria um objeto vazio e depois vai preenchendo com os setters conforme for necessário. Quando você personaliza o construtor com argumentos, o construtor padrão precisa ser implementado de forma explicita na classe.
Creio que adicionando um construtor padrão da forma abaixo resolva o erro:
public Funcionario(){

}


Carly Comando - Everyday. Do I need to use right pedal?

Question: I am currently learning such a beautiful song like Everyday by Carly Comando. I have Kawai CN24 at home. The way it sounds is different from the original song that is why I have some concerns that probably I do not use pedal properly. Could you help me to figure out do I need to use right pedal? According to music sheet, I couldn't find this information however on YouTube I can clearly see that it is used but again, result sound is completely different even though I am playing correct notes.
Please, advise me. Thank you.
Answer: Yes, every bar/chord change needs to be pedaled using the right pedal. This, on an acoustic piano, will keep the notes sounding after you've lifted your fingers off. On a digital type piano, it'll have the same sort of effect, but produced differently. Some pedals are not that effective.
Watching a youtube version of this, you can see the dampers on a grand piano lifting as the pedal is pressed. The timing of proper effective pedaling is an acquired art, and it's far easier to have a teacher explain the process. Lots of self-taught piano players pedal badly, and the result is a mushy sound.
Comment: Hi Tim, thank you for you reply. Does it really matter whether I push pedal to the ground or a little bit? I can hear the difference in sound the way I push the pedal, but still it's not easy to reproduce again.
Comment: On all acoustic pianos, the amount the pedal is depressed makes a big difference. On some electrics, there will be a 'half pedal' arrangement. It's equivalent to JUST lifting the dampers, but only just. If the jack plug is TRS it'll be that sort. You'll have to experiment to find the spot. But for this song, full pedaling will be fine.


What's the efficient method to find the farthest vertex from centroid

Question: Say I have a arbitrary convex polygon, what I wonder is the longest length from its centroid to its vertex, and which vertex it is.
I've looked it up on Wikipedia finding that I have to calculate its area firstly, then there's a formula determine the coordinates of centroid. I can then calculate all the lengths. Is there any other way faster?
Comment: Is your polygon regular? How may sides does it have? Could you show us it's form?
Answer: Actually the area of a convex polygon is computationally quite easy: it is the sum of the (oriented) areas of all the triangles formed by the origin of the coordinate system and two adjacent vertices (in a fixed order around the circumference of the polygon).
The double of the oriented area of such an individual triangle is $A_i=v_{i,x}v_{i+1,y}-v_{i,y}v_{i+1,x}.$ You will also need the individual $A_i,$ not just their sum, in your formula for the centroid.
The idea is that you can apply the "subdivision" from Wikipedia using any point of the plane as the third vertex of your triangles, even if it lies outside the polygon (as the origin of the coordinate system might), as long as you use oriented areas. Remember that oriented areas may be negative.
The centroid of an individual triangle is also easily computed as (two thirds of) $v_i+v_{i+1}.$
This means that your computation has to loop through the vertices once to calculate the $x$ and $y$ coordinates of the centroid of the polygon, and one more time to find the vertex (or vertices) with minimal distance.


Changing default REST actions in rails

Question: I want to be able to change the default mapping of actions with RESTful url and type of request.
For example,
After adding map.resources :fruits in the routes, by default, sending a GET request to /fruits/:id calls show action in fruits controller. However, I would like to call a custom action, say display, in the fruits controller instead of show action. How do I do it? This has to be a route configuration.
Comment: This isn't directly related to your question, but please be aware that Rails' "RESTful routing" has nothing to do with REST. Pretty URIs are orthogonal to REST. There's no such thing as a "RESTful URL". If you're interested in REST, please read into it some more - Fielding's dissertation is the authoritative source, or you can browse some of the REST explanations on this site.
Answer: I would like to recommend you to read this page:
http://guides.rubyonrails.org/routing.html
It explains in detail all aspects related to routing.
Using :path_names you can customize the new and edit generated paths. If you want to change GET /fruits/:id from activating the show action to activating a display action, then the change is invisible to the user. And you would be deviating from the flow with no apparent reason.
Comment: There are actually decent reasons to do this if you're using nested resources, particularly deeply nested resources. At some point you end up with massive controller proliferation by accepting the defaults, and overriding them allows you to keep the nested structure while sending multiple resources to the same controller. I find this particularly useful when you would otherwise end up with a parent controller that has only an index action and nothing else but more complex child resources.

Changing default REST actions in rails


New piano flaking near hitch pin

Question: I recently purchased a new Yamaha C1X, and I noticed that the paint has started to flake off at various places after a few days, near the hitch pin (see picture).
This doesnt seem to affect the sound (yet), but just wanted to see if there are any piano technicians who might be able to advise if this is a common problem or not?

Thanks!
Comment: The piano came straight from Yamaha UK, and probably had an preliminary tuning.I had suspected that the flaking was probably due to someone "seating the strings" too aggressively (after shipping, some technicians usually place a screwdriver and tap on the strings with a mallet after shipping).

When I contacted Yamaha, they suggested that this was "not normal", and asked me to raise a ticket via the retailer (Yamaha does not deal direct with customers). Retailer has now schedule a replacement.
Comment: Just wondering what might cause that. Was the piano tuned in preparation for sale? Maybe the tuning wrench slipped and cracked the paint and it's only now coming off due to the vibration of being played?
Comment: I know this question is almost 2 years old. However, as both a mechanic and musician, I would be more annoyed than concerned about this defect. Japanese manufacturers have historically used inferior coatings (paint) on all of their products. The high resolution of this picture also suggests that the coating may have been applied too heavily and that the surface may not have been properly prepared prior to the application of the coating. THZP should post their resolution to this problem.
Answer: I noticed this question was posted 2 years ago, but for any others, I hope this helps.
It happens to some Yamahas. It will not affect your sound. If you do not like the looks of it, you can contact https://ca.yamaha.com/en/support/contacts/index.html.
I hope this helps.

New piano flaking near hitch pin