Bitwise Complement

Question: I have a sample problem with w=1, y=7, z=0, x = ~(w && y) | y; and the solution is x = -1, but I can't figure out why?
Here is my thought process:
(w && y) = (1 && 7) = 1
~1
1 in bits is 0000 0001
~1 in bits is 1111 1110
Not sure what to do from here.
Comment: So far so good.  Now you have `(1111 1110) | y`.
Comment: What's `1111 1110` ored with `111`?
Answer: The last step is a bitwise OR so you get:
1111 1110 | 0000 0111 = 1111 1111

which is -1.
Answer: ~1 in bits is 1111 1110,
1111 1110 or 0000 0111 is 1111 1111,
and 1111 1111 is -1. The most significant bit is the negative flag, and negative numbers are subtractive, I guess you could say. That's why a signed byte can hold down to -128 but only up to 127.
Answer: You're right that ~(w && y) gives 1111...0. The last bit of 7 is 1, so |ing this with 7 gives 1111...1, or -1.
Answer: First, you should be using & instead of && for bitwise operations.  Second, after ~1 = 111...1110 is calculated, it is ORed with y (7) to get 1111..1111, the 2's-complement representation of -1.
Comment: I would not suggest that, as you do not know the intention of the code (at least I don't know what it really does) and the results of & and && are different.

Bitwise Complement


Easy way of memorizing or quickly deriving summation formulas

Question: My math professor recently told us that she wants us to be familiar with summation notation. She says we have to have it mastered because we are starting integration next week. She gave us a bunch of formulas to memorize. I know I can simply memorize the list, but I am wondering if there is a quick intuitive way of deriving them on the fly. It has to be a really quick derivation because all of her test are timed.
Otherwise is there an easy way, you guys remember these formulas.
$\begin{align}
\displaystyle
&\sum_{k=1}^n k=\frac{n(n+1)}{2} \\
&\sum_{k=1}^n k^2=\frac{n(n+1)(2n+1)}{6} \\
&\sum_{k=1}^n k^3=\frac{n^2(n+1)^2}{4} \\
&\sum_{k=1}^n k(k+1)=\frac{n(n+1)(n+2)}{3} \\
&\sum_{k=1}^n \frac{1}{k(k+1)}=\frac{n}{n+1} \\
&\sum_{k=1}^n k(k+1)(k+2)=\frac{n(n+1)(n+2)(n+3)}{4} \\
&\sum_{k=1}^n \frac{1}{k(k+1)(k+2)}=\frac{n(n+3)}{4(n+1)(n+2)} \\
&\sum_{k=1}^n (2k-1)=n^2
\end{align}$
Note: Sorry if there is an easy and obvious answer to this question. Most of the students in my class already know these formulas from high school, but I only went up to Algebra 2 and Trig when I was in high school. PS: This is for a calculus class in college.
Comment: @VarunIyer I am OK with a **quick way of deriving them**. I say quick because I can't spent 5 minutes deriving one equation on a test with **very little time per question** that is also no calculator. Her test are hard because she gives us very little time per question. **If you know any quick derivations, I am open to them.**
Answer: Perhaps reorganizing them this way :
Class 1 : clear pattern (without end in fact!)
\begin{align}
\sum_{k=1}^n k&=\frac{n(n+1)}2\\
\sum_{k=1}^n k(k+1)&=\frac{n(n+1)(n+2)}3\\
\sum_{k=1}^n k(k+1)(k+2)&=\frac{n(n+1)(n+2)(n+3)}4\\
&\cdots\\
\end{align}
$$\boxed{\displaystyle\sum_{k=1}^n k^{(p)}=\frac{n^{(p+1)}}{p+1}}$$
(the rising factorial $\;k^{(p)}:=k(k+1)(k+2)\cdots(k+p-1)\;$ and the analogy between sum and integration should help to remember all these and... make nice mathematics!)
Class 2 : using simple relations as $\,\sum k^2=\sum k(k+1)-\sum k\;$ and previous results...
\begin{align}
\sum_{k=1}^n k&=\frac{n(n+1)}2\\
\sum_{k=1}^n k^2&=\frac{n(n+\frac 12)(n+\frac 22)}3\\
\\
\sum_{k=1}^n k^3&=\left(\sum k\right)^2\\
\end{align}
Class 3 : reciprocal rising factorial :
\begin{align}
\sum_{k=1}^n \frac 1{k(k+1)}&=\frac 1{1}-\frac 1{n+1}\qquad \text{}\\
\sum_{k=1}^n \frac 2{k(k+1)(k+2)}&=\frac 1{1\cdot 2}-\frac 1{(n+1)(n+2)}\\
&\cdots\\
\end{align}
$$\boxed{\displaystyle\sum_{k=1}^n \frac p{k^{(p+1)}}=\frac 1{1^{(p)}}-\frac 1{(n+1)^{(p)}}}\qquad 1^{(p)}=p!$$
Now remember that $\quad \displaystyle\int_{k=1}^{n+1} \frac p{k^{p+1}}\,dk=\frac 1{1^p}-\frac 1{(n+1)^p}$
(our upper-bound had to be changed from $n\to n+1$ while for class $1$ the lower-bound $1\to 0$)
Concerning the last one (sum of odds) remember this picture :
 $\qquad\displaystyle\sum_{k=1}^n (2k-1) =n^2\quad $
Comment: Glad you liked my reorganization @JamesSmith! Excellent continuation,
Comment: Awesome!!!! THANKS, so much.
Answer: I would like to share the way I ended up remembering these formulas. Most of them are geometric ways of remembering these summation formulas. I still like Raymond Manzoni answer, so I will leave that as my accepted answer! He really helped me on my test.
$\sum \:_{n=a}^b\left(C\right)=C\cdot \:\left(b-a+1\right)$: This is one where it is quite easy to remember by just understanding what summation definition means. It is basically saying keep on adding C, so $C+C+C+C+C+...+C$. You adding c, $b-a+1$ times. So, $C\cdot \left(b-a+1\right)$.
$\sum _{n=1}^k\left(n\right)=\frac{\left(1+k\right)\cdot \:k}{2}$ You can make a dot plot in the form of a triangle. This first column will have 1 dot, the second 2, the third 3, the fourth 4, and you will keep on doing it k times. The total amount of dots in one triangle is what we want to find out. If we make to identical triangles of this format and flip one over and overlap it to make a rectangle. We get a rectangle with height k and with k+1. But this give us the total form two triangles. We only care about 1, so we divide it by two.

$\sum _{n=1}^k\left(2n-1\right)=k^2$: For this, I like the picture Raymond gave. Look at his answer for the explanation of this.

$\sum _{n=1}^k\left(n^2\right)=\frac{\left(\left(2k+1\right)\cdot \:\frac{k\left(k+1\right)}{2}\right)}{3}=\left(\frac{\left(2k+1\right)\cdot k\left(k+1\right)}{6}\right)$: Create rectangles. First 1x1,2x2,3x3,...until you get up to k rectangles.Now, take three copies of each of you rectangles and arrange them as the picture. Take two copies and arrange them in decreasing order upward. Now cut the third copy of each rectangle and arrange them in the middle. They are color coded so you can see that all these dots appear from one of these rectangles. Now you form with a new rectangle with base 2*k+1 and width of $\sum _{n=1}^k\left(n\right)$. You already know $\sum _{n=1}^k\left(n\right)$ is equal to $\:\frac{k\left(k+1\right)}{2}$ from the triangle picture above. So now multiply length and width to find area(total dots), and you get $\left(2k+1\right)\cdot \:\frac{k\left(k+1\right)}{2}$, but this is three copies of each. So we divide by 3. Leaving us with $\frac{\left(\left(2k+1\right)\cdot \:\frac{k\left(k+1\right)}{2}\right)}{3}$

$\sum \:_{n=1}^k\left(n^3\right)=\left(\sum \:\:\:_{n=1}^k\left(n\right)\right)^2=\left(\frac{\left(1+k\right)\cdot \:\:\:k}{2}\right)^2$:Draw a cube with $1^3$ dots,$2^3$ dots,$3^3$ dots,$4^3$ dots,...till you get to k cubes. Now rearrange them,to squares and rectangles as shown in the picture. Every other square is cut in half. while others are stacked by planes of the next layer. Odd Layers=Stack. Even Layers=Cut. You get a resulting square of width  $\sum _{n=1}^k\left(n\right)=\frac{\left(1+k\right)\cdot \:k}{2}$ and height $\sum _{n=1}^k\left(n\right)=\frac{\left(1+k\right)\cdot \:k}{2}$.


Content edit links?

Question: I'm new to Drupal 8 and can't figure out a way to show the edit contextual links for content displayed through the Views module. This was simple in Drupal 7, but in Drupal 8, a view only shows the links for editing; there are no edit or quickedit links for the content.
It does seem to work with nodes and taxonomy terms, but not custom blocks.
Comment: Try to add operations field in view. It will provide edit,delete operations links in drop down.
Comment: Does not work since I'm not using fields.
Comment: Added answer may be it will help you.
Answer: Add show content and teaser/full view like below.

Goto page and it will show links.
Comment: Is there any possibility to change with fields rather than showing full/default mode?
Comment: Yes, but it doesn't work with custom blocks. Nodes and taxonomy terms work.
Comment: No, I will have to change the content to nodes instead of blocks.

Content edit links?


Ler texto em um local especifico da imagem

Question: Preciso de ajuda para tentar ler um texto em uma parte especifica da imagem.
O intuito é identificar um produto especifico dentre vários iguais, porém a única coisa que muda é o texto presente nele.
Estou fazendo o reconhecimento de um objeto e pegando a posição dele na imagem:
Imagem de exemplo:

Posição:
[727 1378 2852 1957]
Tentei utilizar o OCR, mas não consegui passar como o vetor como parâmetro.
OBS:
Preciso identificar o texto apenas dentro desse quadrado(rosa), por isso a utilização desse vetor.
É possível, utilizando OCR?
Se sim, como eu faço isso?
Se Não, há outra opção?
Answer: Opa amigo blz ? fiz algo para te ajudar mas não ficou muito bom, mas mesmo assim irei postar aqui para te dar um norte para seguir
<code>from pytesseract import Output
import pytesseract
import cv2

pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract.exe'

image = cv2.imread(r'C:\Temp\uno.jpg')
image = cv2.detailEnhance(image[220:1400 , 610:940], sigma_s=10, sigma_r=0.15)

#convertendo imagem em imagem em escala de cinza
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# convertendo para imagem binária por Thresholding
# este passo é necessário se você tiver uma imagem colorida porque se você pular esta parte
# então o tesseract não conseguirá detectar o texto corretamente e isso dará um resultado incorreto
threshold_img = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# agora alimentando imagem para tesseract
details = pytesseract.image_to_data(threshold_img, output_type=Output.DICT)
for i in range(len(details['text'])):
    text = details['text'][i]
    print(text)

cv2.imshow(f"Original", image)
cv2.waitKey(0)
</code>


How should I learn to read music if I don't play an instrument?

Question: I have several related questions. I'll try to lay out the context because you maybe able to answer the questions I am not asking as well :-)
Context

I do not know how to read music.
I do not play any instruments - and in all likelihood, it is not something I am going to learn to do in the near future (next 1-2 years).
I have been taking several listening courses, and I've been trying to apply the theory by doing listening exercises.  I find that it has really helped me to enjoy music even more, by helping me recognize sections, themes, forms, etc.
Several people on this forum have responded (or commented) on my questions, suggesting that I should learn to read music.
I have very little time, so I want to see if it is worth it for me to learn to read music or if it is something that I should leave for later when I have more time.

Goal

I guess I wish I could read music so that I could more easily follow structures & patterns in the music and learn to appreciate music on  different dimension (more easily) such as: modulations, contrasting themes in different keys, changes in tempo,...

Questions

If I could read music without playing an instrument, would I be able to analyze music by reading (such as this answer: Is the Rondo in Mozart's Piano Concerto No. 15 ABABA?)
How can I go about learning to read without playing an instrument (does it make sense? is it possible? any references?)

Follow up
Thank you very much for the detailed and thought through suggestions & explanations.  I have read and found valuable takeaways from each of the answers. I have a lot to think about, in the meantime, I'll continue my listening exercises and try to enjoy the music the best I can.
I have selected @Andy Bonner response as the answer, but like I said, I found valuable points in each of the answers.  Thanks again!
Comment: You might want to edit to include a detail: most of your prior questions have been about classical-music pieces. There are plenty of other music cultures that routinely play and teach people to play without relying strongly on written music—you could probably find a community or even a private teacher to teach you Irish fiddle without reading music. But if you want to stick within the canon of "classical" music, you run into the problem that this body of music was mostly created within a culture that prioritized notation. It might also be nice to edit this question to focus a bit more...
Comment: ... Because the question "*Should* I bother learning to read music" comes before "if so, what's a good way."
Answer: Short answer: the best way to learn something big and complex is to make sure you start at the beginning, and learn in small steps that build on each other.
Here's what I would do if you came to me as a private student. I'd figure out what your goals are—it sounds to me like your primary goal is to appreciate and better understand major works of the canon of Western, tonal, so-called "classical" music. You've recognized that you can enjoy a piece better when you study it, and you're very interested in the form and structure of pieces.
So the main focus of the study I'd assign you would be music theory. But I would definitely start by teaching you to read music, and I'd use an instrument to help you learn. I would probably encourage you to use piano, just because it's the most useful as you continue studying music theory. If you wanted to explore other instruments that are "easy to learn," then even a recorder or ocarina could get you started. To one of your core questions: Yes, you could "learn to read music" without ever playing an instrument at all, but it would be a bit like learning to read a written language without ever speaking. It's possible, but it's much easier to put it into practice, just because it will engage experiential pathways in your brain rather than purely conceptual ones. You certainly don't have to learn to play well, or quickly, or at anything more than a beginner level. I can't play anything on piano up to tempo that's much harder than a scale, but I still find it helpful to do music theory analysis sitting in front of a keyboard.
The most important thing is to "scaffold" your learning. I would advise you to get the starting book of a beginning piano method; this will probably start with some tunes that use only two or three notes. As you play them, you'll get familiar with the placement on the staff for those pitches. The beginning tunes will probably use all notes of the same length, too; after expanding your range to 8 or so notes, they might start varying the rhythm with longer or shorter notes. You "learn to read music" the same way you learn the instrument: by introducing only a few concepts to yourself at a time.
In fact, music theory study is similar. I can't teach you about German sixth chords before you know what chords are in the first place, and the definition of a triad, and a sixth, and that means talking about intervals, and that means talking about pitches. Similarly, analyzing the form of a sonata-allegro movement often comes down, not to recognizing melodies, but to identifying changes of key (or "tonal areas,") so that means understanding key, tonality, tonicism, tonic and dominant chords, cadences, etc.
Now, to answer the "question you didn't ask": If your end goal here is not to play an instrument or know music theory, but to enjoy music more by understanding it better: there are other kinds of study you can explore as well. To appreciate a musical artifact, it certainly helps to understand the context that created it. I would recommend exploring a course on the history of Western music. As you start at the beginning with ancient and medieval practices, this will open your ears to systems of music-making that are as far removed from Mozart as Charles Ives is, but as you proceed through time, by the time you get back to Mozart you'll understand how he was informed by Haydn, who was informed by Bach, and so on. Meanwhile, I'd encourage you to study the musics of other cultures too. You might not enjoy all of them as much as "classical" music, but they help make you aware of conventions within Western music that you might have mistaken for universal aspects of music, but are in fact cultural (like "having melody and harmony," "being in a key," and dividing the octave into 12 half steps). Being made aware of the phenomena, you're better able to appreciate them in Western music rather than take them for granted.
Comment: You can learn to read music without learning to play any instrument at all and still have that learning be worthwhile. All you have to do is learn to read music that you *sing*.
Comment: I'd consider it's a lot easier to learn to sight sing *after* having some experience playing an instrument.
Answer: The simple answer is to start learning an instrument. Specifically, you should learn basic keyboard skills. Learning to read sheet music and learning basic keyboard skills are very similar bodies of knowledge.
If you have a computer, then getting a MIDI controller and learning the basics of it would immensely improve your understanding and appreciation of music.
A MIDI controller is a keyboard, that can be quite small and affordable, that plugs into your computer and sends note playback instructions to your computer. On your computer you would run software that listens for MIDI note playback messages and then plays the corresponding notes through your computer speakers or headphones.
Combined with some free online materials about playing keyboards or piano, reading sheet music, and music theory, such a keyboard would enable you to synthesize the theories, practices, and sounds of music in a way you cannot do easily without an instrument.
If you can afford a few lessons (it doesn't have to be a commitment of time and money every week), even better. There are people who can teach you online if you prefer.
A second alternative is to learn to sing. Singing is great because you always have your instrument with you. The main disadvantage is you cannot sing chords, so a keyboard would help much more in the understanding of harmony and counterpoint.
Many areas of knowledge in music overlap. Performance, theory, composition, analysis, aural skills, acoustics, and appreciation are all connected. A person cannot reasonably master or even merely excel in any one of those areas without at least basic understanding of most, if not all of them. While that may seem like a lot of time and effort to put into studying at least a little bit of each of those topics, the rewards are literally unmeasurable.
Comment: @user1937198 Keyboard is definitely not the only good option. Any instrument is better than no instrument. The reason why keyboard is my top recommendation is twofold: Primarily, the keyboard provides a visual map of how pitch classes are organized in western music theory. Second, keyboards are the most flexible and broadly useful instruments. They can easily play chords, melodies, and counterpoint. MIDI keyboards can be used with a computer to approximate any sustained or percussive sound. And there are products available at a wide range of price points.
Comment: @user1937198 I would also point out that keyboard skills and vocal skills are required for every music degree at accredited US universities, partly for the reasons I've outlined and also for other reasons of general musicianship and utility in almost every kind of career in music. For better or worse, in western music, the keyboard is the master instrument.
Comment: @RedSonja - yes, it was an available instrument when I taught, in UK. It's where most of the teachers didn't have a clue, and most of the pupils developed some sort of dislike for music...
Comment: I would challenge that a keyboard is necessarily the best option. It is entirely possible to become proficient at reading music, whilst being unable to play a keyboard beyond a very basic level (single notes at low tempo). The skills involved in the hand manipulation to play chords and/or seperate voices are completly seperate from the abstract skills involved in reading music. If you can read music it shouldn't take much work to learn which keys need to be pressed and when to perform a piece, but that doesn't mean you know how to play them.
Comment: They are the most flexible, but they also are complicated as a result in the motion control required. I may be biased as someone who always struggled with that side of music, never progressing beyond the hunt and peck stage of keyboard play.
Comment: Just about everyone I know  - musically active or not - started on the recorder. Every primary school teaches it (where I hang out, at least), it's cheap and easy to learn. Anyone can learn with a beginner's book and YouTube.
Comment: @RedSonja Yeah. Recorder made me hate music for about 20 years after.
Answer: What is possible and what is practical are not necessarily the same thing.
Yes, you can learn to read music without playing an instrument. But, is reading without playing a practical way to learn notation? You will probably have an easier time learning to read if you are also learning to play. You want at least an introductory skill level for both.
Some of what you want to be able to do, which to me sounds line music appreciation listening enriched with following along in the score, can be done without full reading ability, without understanding the complexities of reading pitches and analyzing harmony.

First and most importantly you would need to learn how to read rhythm and keep time
Next you need to recognize the "systems" of staves for ensembles, know how to find each instrument in the system, and be able to aurally recognize which instruments you hear when listening
If you can keep time, and follow the rhythm, and hear which instruments get the main line, you then need to jump between the instrument parts within the notation systems to follow the melody and have your listening follow along with the score
Certain markings in scores delineate sections, things like key signature changes, different bar line types, and tempo/performance indications, so watch for those

If you want to get into the harmonic/tonal aspect of reading scores, absolute essentials include...

Learn all the key signatures and basic cadences in each key, be especially aware of the tonic, mediant, leading tone, and subdominant scale degrees of each key,
Learn about cadences and the handling of the sixth and seventh scale degree in minor keys

Be practical and start with scores that are easy. https://imslp.org/ is a great source for scores. Start with sets of classical dances like minuets or German dances and focus primarily on the rhythm.
For the harmonic aspect just identify cadences by type and what key they end in. Those cadences will also be the primary delineators or sections and form in the classical style. Another thing that you can do to examine the basic tonal material is look for accidentals in the score and simply try to identify what key/mode changes they effect. You don't need to do a full Roman numeral harmonic analysis to get the really important aspects of tonal design in a score. Just identify keys and cadences.
Baroque era solo and trio sonatas could also be good starting points for following rhythm and parts. But be aware of the performers ornamenting the written music (you might hear a lot of motion that isn't explicitly written in the score.)
Classical divertimentos can be another good source, because the music tends to be more straight forward.
String quartets are a good way to increase the complexity level, because there tends to be a lot more shifting of the melodic focus between parts. You need to jump between the various parts frequently to follow the main thread of the music.
Those are my suggestions for a practical approach. Again, if you focus on following rhythm first, it is do-able and can make listen more rewarding.
But, I have to end by encouraging you to try to play at a basic level. Take a look at Czerny's Recreations or Beyer's Preparatory School, Op. 101 both are good, gradual introductions to piano.
Answer: You don't even need to learn to read music to become a great musician! This may sound controversial - it's not supposed to be - it's a fact. There are and have been many great players over time who are as such despite the fact they cannot read music. Just as, I guess, there have been many great orators who cannot read well.
Being a good listener is probably a better attribute, and being able to 'pigeon-hole' different parts of the music you listen to.
There will be many who say it's absolutely paramount that you do learn properly to read, and to those who deign to dv this, please also post your reasons.
Being able to play an instrument doesn't necessarily necessitate being able to read. But for some, it's a great help. How you could follow a score without that skill, I can't imagine. It will depend on what you're like, as in how far can you imagine things as opposed to actually do them. It could go either way, we don't know you or your strengths/weaknesses.
Not learning how to read music and not playing may well hinder your goal, rather like not learning how to read words, and expecting to become a great orator or actor, as previously hinted at, it depends on so many diverse factors, no-one here can tell you which works for you.
I imagine learning the theory of music may be more advantageous, although that in itself will inevitably encompass learning to read at least some music, to reach the levels you aspire to. So, you can try, without, and you may/not feel the need at some time in the future, that it's a necessity. Or - do like a lot of us , and dip your toes into actually playing an instrument - choose a favourite - which will probably involve reading those dots, bringing them to life. But bear in mind, reading them isn't even half the story of what you need (maybe) to achieve your stated goal.
Comment: @RedSonja - I base my answer on having played with quite a few musos over the last 70 yrs, both in reading and non reading situations. I guess you only play with those who are expected to read. I've played with those, in that situation, and you're generally speaking, right. But in other situations, there's been no need to read, and the music made is wonderful, rather than a regurgitation of what's been played to death from the dots.
Comment: Anecdotally there may be great musicians who can't read music. However, I know a few mediocre musicians who can't read music (can't sight-read, don't understand basic theory) and they are a damned nuisance when you have to play with them.
Comment: Is this even trying to answer the question?
Answer: While you really should learn to play an instrument, it may help to install some notation program. Those programs can nowadays play entered notation by a built-in synthesizer. I, for one, use MuseScore because it covers my and probably other beginners' needs. Note, though, that you can learn to arrange that way. To play music and to learn the theory behind the practice is a quite different cup of tea.
While you copy existing scores in public domain (other scores vs. copyright are explicitly not covered here, at least I do not dare to recommend copying them), you will undoubtedly make errors. Listen carefully to find them, train your ears.
Answer: You can start off by learning the Clef signs, great staff and how the notes are placed on it. Examine some sheet music and learn the values of different notes. Once you are familiar with them, try listening to some music while looking at the corresponding sheet music. Select simple ones at first. Any music student would be given theory knowledge before moving into practical. In your case because you do not want to learn any instrument, you can start learning from the basics mentioned above.
With time, you will be able to identify patterns in music such as musical forms by looking at the notations.
I'd like to recommend John Thompson's Piano book series for you to get an idea on sheet music. These books are practical books. But, they are graphical and will guide any beginner on how to read music.
Comment: Have to disagree that 'any music student would be given theory knowledge before moving into practical'. I'd have lost most of my students had I taken that stance. They come to *play*!
Answer: If you are a singer, start by learning the sound of the C major scale also where the notes come on the stave (the five lines). Between,(and over top/under bottom) are F A C E G B (bottom to top) and on the lines are G B D F A (bttm to top) so on which line or between which line the note is determines the note, I recommend you learn the sound of the C major scale, C D E F G A B C
Comment: Welcome, and thanks for adding an answer! You can see [some tips on answering here](https://music.stackexchange.com/help/how-to-answer). You can also edit this answer to make it clearer; there are many resources that explain which line of the staff is which, and you might note that you're giving bass clef pitches.
Comment: Not a lot of help studying an orchestral score, with so many transposing instruments' lines!
Comment: @Tim Why is using the voice (which everyone has and most people know how to use to a basic level) any less help than learning any other single instrument?
Comment: @gidds - not my dv. But on an instrument, one can see as well as feel what notes are being played. I can sight-sing, and really it doesn't matter what the notes are, i sing *relatively* Looking at a score, and sight singing gets me quite mixed up, wit the different clefs and 'keys'.


How do location and scale parameters affect likelihoods?

Question: Many statistical procedures rely on analyses of a likelihood function.  Frequently, some (or all) of the parameters in that function are "location" and "scale" parameters.  (See Finding location and scale parameters from PDF for definitions and examples.)
How does this knowledge help simplify the analysis?  In particular, if we are given a likelihood function that does not involve a location or scale parameter, how do we re-introduce these parameters into the likelihood?
Answer: It reduces the analysis to a (generally simpler) "standard" likelihood in which the location and scale parameters have been set to convenient values.  There is a pitfall for the unwary, though: to obtain the general likelihood from the standard likelihood, you must introduce a factor that depends on the scale parameter.

A family $\mathcal F$ of probability distributions is a "location" family if, whenever the cumulative distribution function $F$ is in the family, then so is the function $x \to F(x-\mu).$  It is a "scale" family when $F\in \mathcal F$ implies the function $x\to F(x/\sigma)$ is in the family for any positive number $\sigma.$  (It is a location-scale family when both properties hold.)
We may take $\mu$ and $\sigma$ to be parameters of the family.  Additional parameters, which I will just generically call $\theta,$ may be needed to specify members of the family uniquely.
In this setting, for each value of $\theta$ we may choose a "standard" distribution $F_\theta$ once and for all to represent it, making the general distribution in the family of the form
$$F_\theta(x;\mu,\sigma) = F_\theta\left(\frac{x-\mu}{\sigma}\right).$$
(This first shifts the location by $\mu$ and afterwards scales it by $\sigma.$  If we were to reverse the order--which is perfectly reasonable--the argument would instead be $x/\sigma - \mu.$)
Almost always, such families consist of absolutely continuous distributions.  Let $f_\theta$ be the density associated with $F_\theta.$  Consequently, when $F$ is the distribution with parameters $(\mu,\sigma,\theta)$ its associated probability element is
$$\mathrm{d}F_\theta(x;\mu,\sigma) = \mathrm{d}F_\theta\left(\frac{x-\mu}{\sigma}\right) = \frac{1}{\sigma}f_\theta\left(\frac{x-\mu}{\sigma}\right)\,\mathrm{d}x.$$
Notice the appearance of the factor $1/\sigma.$  This subtlety is the reason for going through this analysis!
When a sample of (independent) data $\mathbf x = (x_1, \ldots, x_n)$ is observed from this family, its likelihood $\mathcal L$ is, by definition, its probability density.  Since independence means probability densities multiply, we obtain
$$\mathcal{L}(\mu, \sigma, \theta; \mathbf x) = \prod_{i=1}^n \frac{1}{\sigma}f_\theta\left(\frac{x_i-\mu}{\sigma}\right)= \sigma^{-n}\prod_{i=1}^n f_\theta\left(\frac{x_i-\mu}{\sigma}\right) = \sigma^{-n} \mathcal{L}\left(0, 1, \theta; \frac{\mathbf x - \mu}{\sigma}\right) .$$
On the right, $\mathbf x - \mu$ is shorthand for $(x_1-\mu, \ldots, x_n-\mu).$
Here, then, is the result: suppose you have an expression for the likelihood for a standardized distribution where $\mu=0$ and $\sigma=1;$ say, some function $\Lambda(\theta;\mathbf x).$  (This plays the role of $\mathcal L$ on the right hand side just above.) Then the likelihood in full generality is

$$\mathcal{L}(\mu, \sigma, \theta; \mathbf x) =  \sigma^{-n} \Lambda\left(\theta;\frac{\mathbf x - \mu}{\sigma}\right) .$$

That is, to obtain the general likelihood from the standard likelihood, (1) replace all $x_i$ by $(x_i-\mu)/\sigma$ and (2) multiply it by $\sigma^{-n}.$  Don't forget the second step!
Of course, in location-only families you can ignore $\sigma$ (set it to $1$) and in scale-only families you can ignore $\mu$ (set it to $0$).
Example
The Normal distribution family is a scale-location family (with no additional parameters).  For the last century, most people have chosen the function
$$f(x) = \exp\left(-\frac{x^2}{2}\right)$$
(defined for all real numbers) for the standard density.  Accordingly, using the rules of exponentiation, the likelihood of a dataset from the standard Normal distribution would be
$$\Lambda(\mathbf x) = \exp\left(-\sum_{i=1}^n \frac{x_i^2}{2}\right).$$
Therefore, the likelihood generally must be
$$\mathcal L(\mu,\sigma;\mathbf x) = \sigma^{-n} \exp\left(-\sum_{i=1}^n \frac{(x_i-\mu)^2}{2\sigma^2}\right).$$


Rhythm notation syncopation over the third beat

Question: I found this copy of Sloop John B online...

I wanted different line breaks so re-notated it.
But I changed the rhythm notation to use ties to the third beat...

What is the right way to notate these syncopations?
Comment: The question is not right or wrong, but your solution  is **better!**
Comment: As others have said, both are "correct". But why did you stop there? The "on" in the first measure and the "sau" in "Nassau" could also usefully be split into two eighth-notes. I think I'd prefer an all-or-nothing approach.
Comment: @AlbrechtHügli I would say that it's more modern.  The first example would be unsurprising in the romantic period or earlier.
Comment: @AdamChalcraft, I was following the rule of thumb about beats 1 and 3, like in Aaron's answer.
Answer: Your notation is correct. When notating syncopation, the goal is to visually preserve the strong (part of the) beat. In 4/4 time, that means making clear where beats 1 and 3 lie, which your notation does and the "original" version does not.
A couple of references articulating this idea: here and here.
Answer: It is standard practice to write 4/4 measures as if there was an invisible barline in the middle, forcing syncopation to be broken down to two 2/4 half-measures. (Excluding whole notes.) So your modified version is "better". It makes syncopation more explicitly visible if you're used to having things spoon-fed like that. ;) I'm sure you could get used to reading rhythms without everything being split to such small pieces.
Comment: I've seen before that rule of thumb to imagine an invisible bar line dividing 4/4 to 2/4. It's very helpful.
Answer: Your version is correct.
In the example below A is fine (to the extent that B would be considered incorrect).  C is acceptable, and even preferred to D in some circumstances.  The mainstream musical world is not yet ready for E.
Comment: @LaurencePayne the C version is a very common exception in classical music. I have encountered it many times.
Comment: A and C are accepted too, surely because of the clear symmetric structure.
Comment: @AlbrechtHügli, the symmetry of C was my thought too. It's easy to see three equally syncopated notes, compared to D. IMO.
Comment: From various notation guides I gather A and C are sort of conventionally preferred over B and D despite the "show beat 3" rule. Is there more to it than just convention? PS. I really need to get _Gould, Behind Bars._
Comment: Gould won't help you much.  She states the rule, then lists some 'common exceptions' including A but not C.  But Gould is very 'classical' orientated.
Comment: The time signature 4/4 is used both for pieces whose pulse is "DUM dum dum dum DUM dum dum dum", and those whose rhyhtm is "DUM dum Dum dum DUM dum Dum dum".  There isn't any way of notating a distinction between the two kinds of pulse, but I'd be inclined to use notation C for pieces which would better fit the former kind and D for those that would better fit the latter.
Comment: Another way of looking at it would be to say that if a listener would either hear or expect to hear something on beat 3, then it makes sense for the music to contain a note (the second of the two tied eighth notes) there, but if beats 2, 3, and 4 all sound the same, then there's no reason to call out beat 3.
Comment: @ Michael: Well, this was just my personal opinion ;) Norms and standards are built by statistics and now we're already 2 ...
Answer: The arguments of the other answers respecting the beats are all correct.
But there are exceptions like the example A and C of Laurence Payne which show a clear symmetric structure and also the group 3-3-2 notated by two dotted fourth are common. The goal is the readability of the notation and if we have a repeated rhythmic pattern 3-3-2 this notation is ok.
I don't think that any one has the competence to give rules about right or wrong. Rules in music are conventions and not laws and if they are convicting they become common used.


N-Tier Data Layer implementation with Entity Framework 5 Code-First and POCOs?

Question: It seems as if using N-Tier architecture with EF implies that you're forced to instantiate a new DbContext object for your Data Tier's load methods, and then instantiate another one when trying to save.
The downstream implication of this is that the entity that was loaded in the beginning of the workflow is no longer in state when you go to save, and thus saving the calls to something like ObjectStateManager.TryGetObjectStateEntry() returns false, when in fact the entity being saved did originate in the database. The result is that saving our edits result in adds.
This seems like a fairly common workflow in a fairly common architecture. Is there something obvious I've missed?
Comment: They recommend WebAPI or WCF Data Services for N-Tier Data Access. I didn't like any of that so I managed to make `DbContext` work with `Self Tracking Entities`. Now I send my entities via regular WCF and they come back with Self-Tracking changes and I `ApplyChanges()` in my `((IObjectContextAdapter)dbContext).ObjectContext` and call `SaveChanges()`. Everyone's happy so far.
Comment: In our company current project we have the same setup as you. EF5/POCO/3-Tiers; The "Downside" is that you have to pass along your data through your tiers. But in the long run, your code will be cleaner and more maintainable. Oh, and you lose Lazy Loading!
Comment: @Tico When you say "pass along your data" do you mean the wiring the DbContext object into your workflows, so that you save on the same instance that loaded your entities?
Comment: @TIco Lazy loading can still be enabled for `server-only` operations such as report queries and heavy business-logic related data access.
Comment: Yeah, something like that. Let me try to explain. The project structure is similar to this pic (found at google):(http://i.imgur.com/IIhBeX9.jpg)  One Layer has the POCOs (VO Layer), the other one is the BLL (Business Logic Layer), the DAL(Data Access Layer) and UI (whatever you like). The UI and DAL are 'dumb', so to speak. The responsibility for the logic is within the BLL. So, you have to query the DB, pass to BLL and to UI (same way around)
Comment: @HighCore Sure, you're right, but to our purposes it became "worthless" for some internal rules.
Comment: @Tico what do you think about my approach in the first comment?
Comment: @Tico Rather than trying to understand IoC on our data later to facilitate keeping our DbContext in scope, or wiring our DbContext through all our workflows, we've taken advantage of the fact that all of our entities implement surrogate keys so that we can implement the AddOrUpdate pattern described on the EF site where we attached as Modified if Id != 0. Thoughts?
Comment: @HighCore I can only @-tag one user per comment, but the above is for you too.
Comment: @bwerks We did start like you're describing right now. The 'problems' are starting to show up now. When we first started, we didn't know about MVVM, IoC, and all. I do believe that you can start right away, this approach (Modified id Id != 0) looks ok to me. But, read about which frameworks you're about to use! Other than that I agree with your first comment.
Comment: Err, for the record, that earlier comment was supposed to read "trying to UNDERTAKE IoC," hah. My mistake. We considered implementing Visitor as a means of centralizing our workflow logic & data (including the DbContext) but we decided against it when comparing the cost of implementation against "Id != 0."
Answer: You might be interested in trying N-Tier Entity Framework which is open source available on CodePlex and perfectly addresses your needs.


Wiping out user and/or root password in embedded linux

Question: We have a security camera system running an embedded linux. It boots with Lilo as a bootloader and has no tty access once booted. I don't know any username either.
SSH/22 is open, but I don't think brute force is an option.
I have tried all the common tricks to reset a linux user password (boot from the bootloader in single user mode = doesn't happen, still prompts for user login, boot to a live cd = can't access the file system...it's all loop files and other binary, etc etc), but they are all not possible as it is an embedded linux setup the way it is.
Any help/suggestions would be appreciated. Thanks
Comment: @TryTryAgain The point is to find a way to "get into" the camera, or at least its disk (or whatever nonvolatile memory holds the OS). Evidently you have an Ethernet connection; if there are other ports (e.g. a serial connector) you may get access that way. If you can mount the disk in another machine, you can wipe out the password from there. Unrelated note: you can only @notify one person per comment; I only saw your comment because I wandered by.
Comment: Does the manufacturer have any documentation that might help out?
Comment: What I/O ports does the camera have? What kind(s) of nonvolatile memory?
Comment: @Ryan The Manufacturer documentation is here: https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B6sxRcBgaAb3MDlkNzRkOGEtYTUwNC00YWJmLWE1NDAtM2ZlZDMxN2IxYmRj&hl=en_US&authkey=CIepxa8P and is of no help.  I got contact info from the reseller we bought it from, 3 people in Taiwan who have not gotten back to me.   @Gilles...the cameras come in as an old BNC to RCA AFAIK..memory..no clue...what would I be able to accomplish with that?
Comment: @Gilles thanks for your help, and clarification on @replies. I do have access to mount the disk. How would I wipe the password? When I mount the disk there is no /etc/shadow or anything to access, as I stated before, only loop files and other binaries.
Comment: @TryTryAgain You can mount the disk? Then you've probably won. What's on the disk? I mean precisely. What are the file names? What does `file` say about them?
Answer: Ended up getting in to the running system command line with root access via a serial console cable. Found nowhere in documentation, but with a little Cisco, HP, etc. console cable experience, and @Gilles pointing it out, gave me enough motivation to work on it and get it done.
EDIT: Although I don't have access to the system anymore to test, I believe the method of editing the /etc/shadow would have worked out:
http://geekswing.com/geek/resetting-root-password-on-a-linux-system-using-clonezilla/
Answer: try that:
in boot prompt enter
init=/bin/sh


Codename one - Form.initLaf throws random "Illegal Access" errors

Question: in my app, I get "IllegalAccess" errors, at seemingly random places and times.
The only thing in common is the stack trace:
java.lang.IllegalAccessError: class sun.reflect.GeneratedConstructorAccessor3 cannot access its superclass sun.reflect.ConstructorAccessorImpl
at sun.misc.Unsafe.defineClass(Native Method)
at sun.reflect.ClassDefiner.defineClass(ClassDefiner.java:63)
at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:399)
at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394)
at java.security.AccessController.doPrivileged(Native Method)
at sun.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393)
at sun.reflect.MethodAccessorGenerator.generateConstructor(MethodAccessorGenerator.java:92)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:55)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
**at com.codename1.ui.Form.initLaf(Form.java:969)**
at com.codename1.ui.Dialog.initLaf(Dialog.java:499)
at com.codename1.ui.Component.<init>(Component.java:687)
at com.codename1.ui.Container.<init>(Container.java:187)
at com.codename1.ui.Container.<init>(Container.java:199)
at com.codename1.ui.Form.<init>(Form.java:181)
at com.codename1.ui.Form.<init>(Form.java:172)
at com.codename1.ui.Dialog.<init>(Dialog.java:288)
at com.codename1.ui.Dialog.<init>(Dialog.java:275)
at com.codename1.ui.Dialog.<init>(Dialog.java:248)
at com.codename1.ui.Dialog.show(Dialog.java:994)
at com.codename1.ui.Dialog.show(Dialog.java:793)
at com.codename1.ui.Dialog.show(Dialog.java:746)
at com.codename1.ui.Dialog.show(Dialog.java:711)
at com.codename1.ui.Dialog.show(Dialog.java:652)
at com.codename1.ui.Dialog.show(Dialog.java:807)
at com.codename1.ui.Display.mainEDTLoop(Display.java:983)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

The line marked with ** .. ** is my annotation as this is the method of the Form class that throws the error.
Either when I open a new form, a dialog (which inherits from Form) or just anything that involves creating a new Form, this issue occurs, at random.
I have no idea how to debug this, as it seems that it is not my code that is causing the issue.
Any tips for debugging or even solving the issue?
EDIT
the error is not only limited to the creation of forms, but can also occur when internalizing objects. See stacktrace:
<same as above stacktrace after Class.newinstance>
at java.lang.Class.newInstance(Class.java:442)
at com.codename1.io.Util.readObject(Util.java:690)
at com.codename1.io.Util.readObject(Util.java:668)
at com.lequi.ep.dtos.ChatDTO.internalize(ChatDTO.java:47)
at com.codename1.io.Util.readObject(Util.java:693)

EDIT 2
with a lot more testing this issue, I found a single pattern so far. no matter which form or dialog I create, it depends on the number of times I instantiate them. At exactly the 13th time I want to instantiate a form (no matter which screen), this error pops up. I dont have to do anything, just opening the screen and going back. Relevant code snipped with which the error can be reproduced:
// main form activity
<omitted for brevity>
chatButton.addActionListener(e -> {
    new ChatScreen(this).show();
});

public ChatScreen(Form origin) {
    super("Chat", new BorderLayout());
    setUIID("ChatHistory");

    getToolbar().setBackCommand("", e -> {
        origin.showBack();
    });
    <omitted for brevity>
 }

Comment: Can you provide a test case for this issue?
Comment: Did you use an API like `LookAndFeel.setMenuBarClass`? That API should have been deprecated and removed
Comment: Francesco, unfortunately, I cannot reproduce the issue and I have not yet found any pattern which is even causing this error.

Shai, I dont use any APIs or other specialties. I just use the CN1 Webservice, connecting to a Postgres via Hibernate, if that helps to narrow down the scope.
Comment: Further infos that I found out just now added in above post.
Comment: Any possible updates? As of now, i cannot deploy this CN1 app, as it crashes after switching screens 13 times. Thats possibly a minute or so max
Comment: I'll need the source code of `ChatDTO` to update this further as there are many pitfalls with externalization. Also make sure you register these objects early on and don't load them in static initiliazers etc.
Answer: After setting up a second dev environment, importing my git project one to one, without any issues and also noting that this error does not happen on the mobile device itself, the issue can be limited to my specific environment.
I still dont know why this occurs, but the impact is neglectable.
Answer: This can happen because you didn't invoke Util.register() early enough in the code. Notice that you shouldn't do that before the init(Object) callback.
However, if you read/write objects before that's invoked (e.g. as a result of a static initializer) will produce an exception like that.
Other potential problems include code that returns getClass().getName() instead of a hard coded string. This can fail badly due to obfuscation. The first step is looking at line 47 of ChatDTO. What's the object that's read at that line and why?
Also who invokes at com.codename1.io.Util.readObject(Util.java:693) and when is it invoked?
The object doesn't read itself.


How to declare a SQL INSERT Statement with a Unicode letter

Question: I have a sql statemwent, which contain a unicode specific sign. The unicode sign is ę in the polish word Przesunięcie. Please look at the following SQL INSERT Statement:
INSERT INTO res_bundle_props (res_bundle_id, value, name)
VALUES(2, 'Przesunięcie przystanku', 'category.test');

I work with the Postgres Database. In which way can i insert the polish word with the unicode letter?
Comment: What is the template you are using for this table? Does it support the character set?
Comment: should work just fine. Are you sure the statement parameters are *received* correctly (from wherever you get them)?
Comment: have a look at this http://stackoverflow.com/questions/11429655/can-not-insert-german-characters-in-postgres
Comment: See here: http://sqlfiddle.com/#!12/8091a/1
Answer: Find what are the server and client encodings:
show server_encoding;
 server_encoding
-----------------
 UTF8

show client_encoding;
 client_encoding
-----------------
 UTF8

Then set the client to the same encoding as the server:
set client_encoding = 'UTF8';
SET

Comment: That's overly simplistic and often incorrect. Consider the case where the server is using utf-8 but the client is `psql` in an `iso-8859-8` encoded terminal. `ש` is a perfectly legal character in that terminal, and is encoded as `0xf9`. If you lie to Pg and say you're sending UTF-8 when you're really sending iso-8859-8, Pg will try to decode the client's `\xf9` as utf-8 and fail with an error complaining about bad Unicode input. It's rare that you need to change `client_encoding` directly; more often you just have to make sure it matches your inputs.
Answer: No special syntax is required so long as:

Your server_encoding includes those characters (if it's utf-8 it does);
Your client_encoding includes those characters;
Your client_encoding correctly matches the encoding of the bytes you're actually sending

The latter is the one that often trips people up. They think they can just change client_encoding with a SET client_encoding statement and it'll do some kind of magical conversion. That is not the case. client_encoding tells PostgreSQL "this is the encoding of the data you will receive from the client, and the encoding that the client expects to receive from you".
Setting client_encoding to utf-8 doesn't make the client actually send UTF-8. That depends on the client. Nor do you have to send utf-8; that string can also be represented in iso-8859-2, iso-8859-4 and iso-8859-10 among other encodings.
What's crucial is that you tell the server the encoding of the data you're sending. As it happens that string is the same in all three of the encodings mentioned, with the ę encoded as 0xae... but in utf-8 that'd be the two bytes 0xc4 0x99. If you send utf-8 to the server and tell it that it's iso-8859-2 the server can't tell you're wrong and will interpret it as Ä in iso-8859-2.
So... really, it depends on things like the system's default encoding, the encoding of any files/streams you're reading data from, etc. You have two options:

Set client_encoding appropriately for the data you're working with and the default display locale of the system. This is easiest for simple cases, but harder when dealing with multiple different encodings in input or output.
Set client_encoding to utf-8 (or the same as server_encoding) and make sure that you always convert all input data into the encoding you set client_encoding to before sending it. You must also convert all data you receive from Pg back.


Filter time in a dataframe using python

Question: I have a column where there is only time. After reading that CSV file i have converted that column to datetime datatype as it was object when i read it in jupyter notebook. When i try to filter i am getting error like below
TypeError: Index must be DatetimeIndex

code
newdata = newdata['APPOINTMENT_TIME'].between_time('14:30:00', '20:00:00')

sample_data
APPOINTMENT_TIME Id
13:30:00    1
15:10:00    2
18:50:00    3
14:10:00    4
14:00:00    5

Here i am trying display the rows whose appointment_time is between 14:30:00 to 20:00:00
datatype info
Could anyone help. Thanks in advance
Answer: between_time is a special method that works with datetime objects as index, which is not your case. It would be useful if you had data like 2021-12-21 13:30:00
In your case, you can just use the between method on strings and the fact that times with your format HH:MM:SS will be naturally sorted:
filtered_data = newdata[newdata['APPOINTMENT_TIME'].between('14:30:00', '20:00:00')]

Output:
  APPOINTMENT_TIME  Id
1         15:10:00   2
2         18:50:00   3

NB. You can't use a range that starts before midnight and ends after.
Comment: I tried you code and getting the error```TypeError: '>=' not supported between instances of 'datetime.time' and 'str'``` . the dtype of that column is object. could you help?
Comment: Rather looks like you have a datetime (or mixed) type. Can you provide a reproducible dataframe with the correct types?
Comment: i have added in the main question about the datatype. could you please check
Comment: Check your column, you probably have mixed types of datetime and something else (None, string...). One (dirty) option is to use `newdata['APPOINTMENT_TIME'].astype(str).between(...)` but better figure out what's going on with the data.

Filter time in a dataframe using python


Interface analog in Swift for callbacks realization

Question: Please, help me to make interface in Swift to use it for callbacks purposes.
Example in Java:
public interface ErrorListener {
    void onError(String errorMsg);
}

class SomeUiClass implements ErrorListener {

    public SomeUiClass () {
        SomeWorkingClass s = new SomeWorkingClass();
        s.setErrorListener(this);
        s.doSomething(true);
    }

    @Override
    void onError(String errorMsg) {
        System.out.println("Error msg: " + errorMsg);
    }
}

class SomeWorkingClass {

    ErrorListener listener;

    void setErrorListener (ErrorListener listener) {
        this.listener = listener;
    }

    void doSomething (boolean withError) {
        if (withError) listener.onError("Test error");
    }

}

//....
SomeUiClass ui = new SomeUiClass(); // prints: Error msg: Test error

So, I tried to use protocol in Swift for this purpose, but I didn't understand, how to use it properly.
Answer: It would look like this in swift
protocol ErrorListener {
    func onError(errorMsg:String)
}
class SomeUiClass : UIViewController ,  ErrorListener {

    func onError(errorMsg:String)
        print("Error msg: ", errorMsg)
    }
}

class SomeWorkingClass : UIViewController{

    weak var listener:ErrorListener?

    func setErrorListener (listener:ErrorListener) {
        self.listener = listener
    }
}

let ui = SomeUiClass() // prints: Error msg: Test error


Latest Best Practise: Reusing content/functionality between Drupal 7 sites

Question: Many of the Drupal 7 websites I make have the same functionality (e.g. blogs, news section, special offers). At the moment, I have to re-create the content types, fields, blocks and Views each time.
I am looking for a better way of working.
There seems to be a lot of modules that can help me, but I'm not sure which is the latest best practice.
Features - The module seems great for exporting content types, fields, menus and views. However, it does not seem to be able to export blocks, block positions or content.
Features extra - This module is designed for exporting blocks. However, on the project page, it says that UUID Features Integration is the future.
UUID Features Integration - This module doesn't seem to work (although A patch is available to fix things). Apparently, it has been dropped in favor of Deploy.
Deploy - This doesn't seem to work with blocks and is designed more for exporting nodes. I'm not really sure how it is a replacement for UUID Features.
Default Content - Another module that seems similar to deploy. (i.e. exports  nodes)
Apps - This seems to be a completely new approach that is a replacement for features. There is very little documentation on how to use it.
StrongArm - A lot of articles state that this module is essential for getting the most out of Features. However, I'm not sure how it relates.
I have searched quite extensively, but there seems to be a lot of conflicting information,
What is the best practice for what I want to achieve?
I would also like something that would work with Drush or a GUI so I can just select if I want a new site to have a blog, news archive special offer etc when building the new site in the first place.
Comment: what if you setup a 'template' database. install all your stuff. create your standard views, content types etc and use some shell scripting and drush to simply deploy your template setup by copying files, turning on modules and then syncing your new project db with the template db.
Answer: There are two more options to consider:

User Drush make to create your own distribution:

Drush make is an extension to drush that can create a ready-to-use
  drupal site, pulling sources from various locations. It does this by
  parsing a flat text file (similar to a drupal .info file) and
  downloading the sources it describes. In practical terms, this means
  that it is possible to distribute a complicated Drupal distribution as
  a single text file.

Run your sites in a multi site environment. This way you can easily reuse all installed modules and themes.

If you are running more than one Drupal site, you can simplify
  management and upgrading of your sites by using the multi-site
  feature. Multi-site allows you to share a single Drupal installation
  (including core code, contributed modules, and themes) among several
  sites.
Comment: The best thing is to put them into custom modules using features.
Comment: Thanks for the replies. But what about Blocks and (the regions blocks should be in) - what's the best way of handling them?
Comment: what about content types and other fields and views?
Comment: ugh. forgot about that one. so clearly the best opinion seems to be a combo of several mods? maybe worth writing something that leverages all of these together and builds your base install.
Comment: Yes, use features to extract your types, views and fields and then go and use drush make or a multi site installation using this modules.
Comment: Mmmm good point I'd say this would be worth a new question.
Comment: After experimenting with this, I have found a combination of Drush Make File, Features and Strong Arm to be the best options.


Implementation of Dominated convergence theorem

Question: Define $g_{n}(x) = \frac{1-\cos(nx)}{n^{2}x^{2}}$. I want to show that $\lim_{n \rightarrow \infty} \int_{0}^{\infty} g_{n}(x) \mathrm{d}x = 0$. To do this, I define $f(x) = \begin{cases} \frac{1}{2} & x \in (0,1] \\ \frac{2}{x^{2}} & x \in (1, \infty) \end{cases}$. I then claim that $|g_{n}(x)| \leq f(x)$, $\forall x \in (0,\infty)$. To do this, when $x > 1$ this is true. My question is on the proving for $x \in (0,1]$. Namely, argument is as follows:
$
\begin{align}
\\
\sin(nt) \leq nt , \forall t \in (0,\infty) \\
\implies \int_{0}^{x} \sin(nt) dt \leq \int_{0}^{x} nt dt \\
\implies \frac{1}{n} \left( 1 - cos(nx) \right) \leq \frac{nx^{2}}{2} \\
\implies \frac{1 - \cos(nx)}{n^{2}x^{2}} \leq \frac{1}{2} = f(x)
\end{align}
$
Moreover, $\int_{0}^{\infty} f(x) \mathrm{d}x = \frac{5}{2} < \infty$. Hence, DCT tell us that $\lim_{n \rightarrow \infty} \int_{0}^{\infty} g_{n}(x) dx = \int_{0}^{\infty} \lim_{n \rightarrow \infty} g_{n}(x) \mathrm{d}x = \int_{0}^{\infty} 0 \mathrm{d}x = 0$. I would like to know if $f(x) \geq g_{n}(x) \forall x \in (0,1]$ by the way I have shown and if the argument I have given is complete.
Also, what does it mean for $f \in C_{0}([0,\infty))$?
Comment: Your argument is very clean. You probably know this, but you could have performed the same argument by splitting the intervals as $(0,\epsilon),$ and $[\epsilon,\infty)$ for any $\epsilon>0.$

By the way, $f\in C_0([0,\infty))$ means $f(\infty)=0$, which is obvious given that $f$ is integrable.
Comment: Is there a general definition for $C_{0}(X)$, where $X$ is some set?
Comment: $$C_0(X) = \{f:X\to X : f\text{ continuous}\} $$
Comment: I thought that was $C^{0}(X)$, right?
Answer: $$\int_{0}^{+\infty}\frac{2\sin^2(nx/2)}{(nx)^2}\,dx \stackrel{nx\mapsto z}{=}\frac{1}{n}\int_{0}^{+\infty}\frac{2\sin^2(z/2)}{z^2}\,dz = \frac{C}{n},$$
so you do not really need the dominated convergence theorem.
Answer: Consider $\cos t-1+\frac  {t^{2}} 2$ for  $t >0$. The derivative of this function is $-\sin t+t$ which is positive. Hence the function $\cos t-1+\frac  {t^{2}} 2$ is incerasing. Since its value is $0$ when $t=0$ we see that $\cos t-1+\frac  {t^{2}} 2 \geq 0$ for  all $t \geq 0$. Put $t=nx$ to get the desired bound for $t \in [0,1]$.
Your function $f$ is not even continuous at $x=1$ so it is not in $C_0([0,\infty))$. $f \in C_0([0,\infty))$ means that $f$ is constant and $f(x) \to 0$ as $x \to \infty$.
Comment: What is the significance of $\cos t - 1 + \frac{t^2}2$? Why are we comparing $\cos$ to its Taylor polynomial? Also, I do not believe the OP claimed that his dominating function $f$ was in $C_0([0,\infty))$, but was only asking what $f\in C_0([0,\infty))$ meant.
Answer: You could also use trigonometric identities to get
$$
\frac{1-\cos(nx)}{n^2x^2}
=2\frac{\sin^2\frac{nx}2}{(nx)^2}
\le 2\frac{\min(1,\frac{nx}2)^2}{(nx)^2}
=\min\left(\frac12,\frac2{n^2x^2}\right)
$$
which directly gives an integrable upper bound.


erro em comparação usando substring

Question: maquina += numeroale.nextInt(4);
        maquina += numeroale.nextInt(4);

        //vez da mqauina
    for (int i = 0; i < maquina.length(); i++) {

        System.out.println("valor atual"+maquina.substring(i,1));

        if((maquina.substring(i,1)).equals("0")){
            System.out.println("0 pressed");
            b1.setBackground(Color.white);

            play("b1");

        }
        else if((maquina.substring(i,1)).equals("1")){
            System.out.println("1 pressed");
            b2.setBackground(Color.white);

            play("b2");

        }
        else if((maquina.substring(i,1)).equals("2")){
            System.out.println("2 pressed");
            b3.setBackground(Color.white);

            play("b3");

        } else if((maquina.substring(i,1)).equals("3")){
            System.out.println("3 pressed");
            b4.setBackground(Color.white);

        play("b4");

        }
        else{

        }

    }

o código não consegue comparar a segunda posição, mas a primeira vai depois da erro
Comment: De onde vem essa variável `maquina` e o que ela guarda? Adicione um [mcve]. Como já lhe disse na outra pergunta, adicionar um pedaço solto e não reproduzivel, só dificulta que você receba uma resposta.
Comment: só queria saber se a comparação está correta nos if
Comment: a variavel numeroale gera numeros aleatorio random
Comment: Se maquina é integer, porque você está usando substring??
Comment: maquina é uma String
Answer: O problema é que o segundo parametro (endIndex) de substring é exclusivo.
Ele indica também a posição onde deve acabar, e não o número de caracteres como é feito noutras linguagens.
Isto quer dizer que o endIndex tem de ser obrigatoriamente maior (pelo menos mais 1) do que o beginIndex. Dai o seu código falhar na segunda iteração onde o valor de i é igual a 1.
Corrija para o seguinte, em todo o lado:
maquina.substring(i, i + 1)

Comment: não sabia disso
Comment: obrigado ! deu certo agora

erro em comparação usando substring


Retorno estranho ao chamar uma função

Question: Estou tentando fazer um exercício sobre funções, no Python, com o seguinte enunciado: "Faça um programa que converta da notação 24 horas para a notação 12 horas". Exemplo: Converter 14:25 para 2:25 PM. O programa deve conter duas funções, uma que converta a hora e outra que imprima a hora (com AM ou PM).
Eu cheguei até certo ponto, mas agora estou com dúvida do porquê o programa não esta rodando.
Meu programa:
hora = int(input("Digite a hora: "))

minuto = int(input("Digite os minutos: "))

def converter_hora(hora):

         return (hora -12)

def imprime_hora(hora,minuto):

        if(hora <= 12):
           print(hora,minuto,"AM")
        else:
           print(converter_hora,minuto,"PM")

print(imprime_hora)

O Python esta devolvendo a seguinte mensagem:

function imprime_hora at 0x02D8C0C0

Alguma sugestão?
Answer: Para fazer uma chamada de uma função, você deve colocar o nome da mesma, seguido de parenteses. Se a função possuir argumentos, os valores destes devem ser especificados entre os (). No seu caso, você quer invocar a função imprime_hora, que possui os argumentos hora e minuto, então a chamada da função deve ser algo como:
print( imprime_hora(14, 25) )

Como, neste caso, os valores de hora e minuto são lidos do usuário, você deve fazer:
print( imprime_hora(hora, minuto) )

O mesmo acontece quando você invoca a função converter_hora em:
print(converter_hora,minuto,"PM")

Você deve informar o valor do argumento hora desta forma:
print(converter_hora(hora), minuto, "PM")

Aliás, considerando que a própria função imprime_hora já imprime o resultado, não é necessário fazer print( imprime_hora(14, 25) ), basta apenas fazer imprime_hora(14, 25).
O código final, já corrigindo os erros de indentação, fica:
hora = int(input("Digite a hora: "))
minuto = int(input("Digite os minutos: "))

def converter_hora(hora):
    return (hora -12)

def imprime_hora(hora,minuto):
    if(hora <= 12):
        print(hora,minuto,"AM")
    else:
        print(converter_hora(hora), minuto, "PM")

imprime_hora(hora, minuto)

Retorno estranho ao chamar uma função


Dynamic styling of SVG text

Question: <svg>
    <text id="test" x="0" y="15"></text>
</svg>

,
d3.select("#test").text("aaa");

or
document.getElementById("test").textContent("aaa");

works fine. But I need to add style to the text. Now:
d3.select("#test").text('aaa <tspan style="font-weight:bold">bbb</tspan> ccc');

unfortunately doesn't work, because the argument is treated as a pure string. What is the best, cross-browser solution for this issue?
Comment: `d3.select("#test).html('Hi')` no? Well actually thats jQuery syntax but otherwise you'll need `("#test").innerHTML+=` or `("#test").element.innerHTML+=`. It depends on what `d3.select("#test")` returns
Comment: There is no '' tag in ''
Comment: I mean this..: `d3.select("#test").html('aaa bbb ccc');`
Comment: https://github.com/mbostock/d3/wiki/Selections#wiki-html
Comment: For example, I tried this `d3.select("#wiki-content").html("Abcd")` on this site https://github.com/mbostock/d3/wiki/Selections in the console, and it worked :) That means you could add inline style, too, or classes (=better)
Comment: From the link you put: "The html operator is based on the `innerHTML` property". There is no `innerHTML` property for `` elems.
Comment: SVG has appendChild & removeChild methods :)
Answer: Working Solution
The main problem is that there is no innerHTML attribute on SVG elements and you need to create all sub nodes yourself. But you can convert your HTML string to styled tspans (without) string parsing magic by creating a temporary DOM object using only this string. After that you can use d3 to create correct tspans elements.
var text  = d3.select("#test"), tmp = document.createElement("text");  //create tmp
tmp.innerHTML = 'aaa <tspan style="font-weight:bold">bbb</tspan> ccc'  //create HTML children (not yet an SVG!)
var nodes = Array.prototype.slice.call(tmp.childNodes)                 //create a real array from the childNodes variable
nodes.forEach( function(node) {
    text.append("tspan")
        .attr("style", node.getAttribute && node.getAttribute("style"))
        .text(node.textContent)
})

Remaining Issue: This solution does not support sub nodes in the tspans which would require to traverse the childNodes of the source elements, copy the style (and maybe other properties) from the sub nodes and append new sub tspan elements (and other maybe tags) to the corresponding parent tspans (or other tags). This will eventually result in a a sub tspan compatible parser to solve the case completely.
Edit: There is a more general innerSVG shim that can also handle the sub nodes.
Broken Solutions
There are some other solutions that should work but are currently broken. As others already pointed out, using .html() directly in jQuery or d3 does not work, because they rely on innerHTML.
//not working
$("#test").html(...); d3.select("#test").html(...)

Copy and append (similar to my working solution) via jQuery is also broken. It creates the correct DOM but the tspan is not shown (tried in Firefox and Chrome):
//creates correct DOM, but disables/hides the created tspan
var tmp = $("<text>")
tmp.html('aaa <tspan style="font-weight:bold">bbb</tspan> ccc')
$("#test").append( Array.prototype.slice.call(tmp[0].childNodes) )

According to the W3C spec, it should be possible to mix tspan's and TextNodes.
Comment: Nice. I'll accept it if there won't be anything better. But it's not perfect. Eg. it won't work if there is `` in ``: `aaa bbbddd ccc`. And how about non jQuery solution? `.html()` in d3 doesn't work, because it is based on innerHTML property and this property doesn't exist for SVG elements.
Comment: Hey come on ;-) SO answers should not provide full solutions. But give you a hint in the right direction (esp. for such complex problems, caused by compatibility problems/missing implementations in browsers). I was tempted to add a solution for tspans in tspans (or `throw "SubNodesNotSupportedError"`), but there can be even other tags inside. In the end you will need a tspan sub-node compatible parser that either parses the source string or works on the sliced DOM elements array.
Comment: Sure, I just pointed it out. But it would be nice to see non jQuery solution. How to create a temporary element in pure JS? Anyway, thanks for your help and I'll accept your answer in few days.
Comment: There you go non jq solution and I found an innerSVG shim that you might give a try
Answer: var t = d3.select("#test")
t.append("tspan").text("aaa ");
t.append("tspan").text("bbb").style("font-weight","bold");
t.append("tspan").text(" ccc");

Comment: This of course will work, but this is not a handy solution if I have the whole string in some variable (as in my case). (`aaa bbb ccc`) I would have to write another JS function, which would use regular expressions to cut the string into parts and then implement your code. What's more, later I need to remove any contest from the `#test` and `t.text("");` wouldn't work anymore.
Answer: document.getElementById("test").style.fontWeight="bold"

That above changes everything.
But you can try the innerHTML method:
document.getElementById("test").innerHTML('aaa <tspan style=\"font-weight:bold\">bbb</tspan> ccc');

Comment: And how it is supposed to solve the problem? It styles the WHOLE thing.
Comment: No, it doesn't work. Why it has 2 upvotes already? There is no `innerHTML` property for `` elems. Besides, `innerHTML` is not a function.
Answer: Try this
d3.select("#test").html('aaa <tspan style="font-weight:bold">bbb</tspan> ccc');

Comment: K ill try on my pc tomorrow.

Dynamic styling of SVG text


Capybara Ruby On Rails Login

Question: I have been trying to get the user login to be able to work but have no luck.  Please help me understand capybara and rspec better, im fairly new to this.
spec/features/login_spec.rb
# User Behavior

describe User do
  it "Can login" do
    visit root_path
    click_on "Login"
    expect(page).to have_text("Login to your account")
    within ".simple_form" do
        fill_in "Email", with: "firstname.lastname@example.com"
        fill_in "Password", with: 'password'
        click_on "Log In"
        subject.save!
    end
  end
end

devise/sessions/new.html.erb

Login to your account

        <%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

          <%= f.input :email, autofocus: true, class: "form-control" %>

          <%= f.input :password, autocomplete: "off", class: 'password form-control' %>

            <% if devise_mapping.rememberable? -%>

                <%= f.check_box :remember_me %>
                <%= f.label :remember_me %>

            <% end %>

                <%= f.button :submit, "Log In", class: 'btn btn-u-lg btn-u' %>

        <% end %>
        <%= render "devise/shared/links" %>

rspec error
F..
Failures:
 1) User Can login
     Failure/Error: subject.save!
     ActiveRecord::RecordInvalid:
       Validation failed: Email can't be blank, Password can't be blank

gemfile
group :development, :test do
  gem 'byebug'
  gem 'rspec-rails'
end

group :test do
  gem 'capybara'
end

spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'

Answer: Figured it out.
Needed to have a user already created in the DB for capybara to refer to!

Capybara Ruby On Rails Login


Use cor instead of acf function?

Question: I would like to have the same results using acf() function and cor() on a very easy ts. Unfortunately I am not able to. I thought that scalling factor should be $ (n-1)/n $, but it does not look like that. It look like the proper scaling factor is $ n-l/n $ where $ l $ is a lag. Can somebody help me and explain why it is like that?
tsExample <- c(1,2,1,2)
acf(tsExample, plot = FALSE)
cor(tsExample[1:4], tsExample[1:4])
cor(tsExample[2:4], tsExample[1:3])
cor(tsExample[3:4], tsExample[1:2])
cor(tsExample[4:4], tsExample[1:1])

cor(tsExample[1:4], tsExample[1:4])*(3/4)
cor(tsExample[2:4], tsExample[1:3])*(2/3)
cor(tsExample[3:4], tsExample[1:2])*(1/2)

cor(tsExample[1:4], tsExample[1:4])*(4/4)
cor(tsExample[2:4], tsExample[1:3])*(3/4)
cor(tsExample[3:4], tsExample[1:2])*(2/4)

Comment: Closely related: https://stats.stackexchange.com/questions/81754 and (perhaps) https://stats.stackexchange.com/questions/31621.
Comment: Thank You, very useful links! :)
Answer: Because the autocorrelation in R is estimated using the wikipedia definition,  which is to rephrase:
$$\hat{R_k}=\frac{1}{N-k}\sum_{i=1}^{N-k}X'_tX'_{t+k}$$
where $X_t'$ refers to standardized form of $X_t$. This standardization is common, i.e. assumes a common mean and common deviation, $\mu,\sigma$.
Edit: @Nick_Cox 's comment is critical. Your array has the same mean/std for sub-arrays while using the cor method, e.g. Sample mean and std of X[1:3] and X[2:4] are the same. If it wasn't, this scaling wouldn't work.
Comment: I don't think the key is that there are $N - k$ terms as that is the number available regardless. The key is whether leading and lagging values are standardised with respect to mean and SD of each set (leading, lagging) -- which being an analogue of Pearson correlation would imply -- or with respect to the same set of values. Even under weak stationarity sample means will fluctuate so that the same mean and SD are not guaranteed for leading $X_{k + 1}$ to $X_N$ and lagging $X_{1}$ to $X_{N-k}$.  Often the autocorrelation recipe is chosen so that spectral density estimates are better behaved.
Comment: Usually $N$ instead of $N-k$ is used in the denominator, otherwise the estimated autocorrelation function may not be positive semidefinite, see https://stats.stackexchange.com/a/294410/77222.

Use cor instead of acf function?


Selecionar e arrastar componente Swing

Question: Fiz um aplicativo que desenha retângulos, pontos, retas, etc. Eu queria que quando o usuário clicasse com o mouse em cima de um polígono desenhado, selecionasse o polígono e arrastasse para onde ele quiser na tela, Como alcançar esse objetivo?
Comment: Eu não conheço muita coisa sobre o Swing, e já faz um tempo que não trabalho com Java. Mas acredito que nem o Swing nem o JavaFX têm esse tipo de funcionalidade, você teria que procurar uma biblioteca existente pra isso ou um manipulador (e fazer isso na mão daria um bom trabalho).
Comment: Eu queria fazer na mão mesmo, para me treinar mais no uso da linguagem, Mas se eu não conseguir, vou seguir sua dica :D
Answer: Não sei exatamente como você está criando os polígonos.
Mas se for um java.awt.Component creio que isso resolva:
import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;

public class Mover extends MouseAdapter {

  private Dimension snapSize = new Dimension( 1, 1 );
  private Component source;
  private Point pressed;
  private boolean potentialDrag;
  private static Mover instance;
  private Point locationBeforeMove;

  private Mover() {
  }

  public void deregisterComponent( Component... components ) {
    for ( Component component : components ) {
      component.removeMouseListener( this );
    }
  }

  public void registerComponent( Component... components ) {
    for ( Component component : components ) {
      component.addMouseListener( this );
    }
  }

  public Dimension getSnapSize() {
    return snapSize;
  }

  public void setSnapSize( Dimension snapSize ) {
    if ( snapSize.width < 1
        || snapSize.height < 1 ) {
      throw new IllegalArgumentException( "snapSize deve ser maior que 0" );
    }

    this.snapSize = snapSize;
  }

  @Override
  public void mousePressed( MouseEvent e ) {
    if ( !SwingUtilities.isLeftMouseButton( e ) ) {
      return;
    }
    if ( e.isConsumed() ) {
      return;
    }

    setupForDragging( e );
  }

  private void setupForDragging( MouseEvent e ) {
    source = e.getComponent();
    source.addMouseMotionListener( this );
    potentialDrag = true;

    pressed = e.getLocationOnScreen();

    locationBeforeMove = source.getLocation();
  }

  /**
   * Move the component to its new location. The dragged Point must be in the destination coordinates.
   */
  @Override
  public void mouseDragged( MouseEvent e ) {
    if ( !SwingUtilities.isLeftMouseButton( e ) ) {
      return;
    }
    if ( e.isConsumed() ) {
      return;
    }
    Point dragged = e.getLocationOnScreen();
    int dragX = getDragDistance( dragged.x, pressed.x, snapSize.width );
    int dragY = getDragDistance( dragged.y, pressed.y, snapSize.height );

    Component source = e.getComponent();

    Point location = locationBeforeMove;
    if ( location == null ) {
      return;
    }

    int locationX = location.x + dragX;
    int locationY = location.y + dragY;

    while ( locationX < 0 ) {
      locationX += snapSize.width;
    }

    while ( locationY < 0 ) {
      locationY += snapSize.height;
    }

    Dimension d = getBoundingSize( source );

    while ( locationX + source.getSize().width > d.width ) {
      locationX -= snapSize.width;
    }

    while ( locationY + source.getSize().height > d.height ) {
      locationY -= snapSize.height;
    }

    source.setLocation( locationX, locationY );
  }

  private int getDragDistance( int larger, int smaller, int snapSize ) {
    int halfway = snapSize / 2;
    int drag = larger - smaller;
    drag += (drag < 0) ? -halfway : halfway;
    drag = (drag / snapSize) * snapSize;

    return drag;
  }

  private Dimension getBoundingSize( Component source ) {
    if ( source instanceof Window ) {
      GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
      Rectangle bounds = env.getMaximumWindowBounds();
      return new Dimension( bounds.width, bounds.height );
    }
    else {
      return source.getParent().getSize();
    }
  }

  @Override
  public void mouseReleased( MouseEvent e ) {
    if ( !SwingUtilities.isLeftMouseButton( e ) ) {
      return;
    }
    if ( !potentialDrag ) {
      return;
    }

    source.removeMouseMotionListener( this );
    potentialDrag = false;
  }

  public static Mover getInstance() {
    if ( instance == null ) {
      instance = new Mover();
    }
    return instance;
  }
}

Para utilizar a classe:
Poligono poligono = new Poligono();
Mover.getInstance().registerComponent( poligono );

Answer: Primeiramente acho que tem que rever o uso do Swing pois e não vai ser continuada, sugiro o uso do Java FX que e muito bacana, fácil de usar e tem componentes bem legais.
Sobre o problema você teria que utilizar algum recurso de drag & drop, que irá trabalhar com as posições da imagem. Algo nesse gênero.
Comment: Vou dar uma pesquisa em como funciona o java FX, valeu pela dica!
Answer: Dependendo do objetivo disso, teria que fazer "no braço": Detectando aonde o cara clicou, identificando qual o polígono é, e repintar o polígono na tela movendo ele e por aí vai... Isso depende de como vc ta desenhando o polígono
Comment: Estou desenhando com as primitivas da API gráfica do java, a dificuldade é identifica se o cara clicou em cima do polígono, tem como me da uma dica de como fazer isso...
Comment: na faculdade eu tive que fazer um problema como esse e a solução encontrada foi identificar qual o ponto mais perto do local clicado. A partir disso via de qual polígono pertencia aquele ponto e selecionava.
Comment: hum, vou tentar utilizar essa ideia aqui :D
Answer: Se você quer fazer na mão... já faz um tempo que não trabalho com Java, mas vou tentar dar umas dicas.
Sempre que o usuário desenhar um polígono, mantenha na memória as coordenadas desse polígono. É bom manter também uma espécie de "Z-index" pra poder ter polígonos um sobre o outro (caso você queira permitir isso)
private Vector<Poligono> poligonos;
public Vector<Poligono> getPoligonos() { return this.poligonos; }
public void setPoligonos(Vector<Poligono> poligonos) { this.poligonos = poligonos; }

public void desenharPoligono(int startX, int startY, int endX, int endY) {
    this.getPoligonos().push(new Poligono(startX, startY, endX, endY));
}

Quando o usuário fizer um clique rápido (não clicar e arrastar), faça uma varredura na sua lista de polígonos pra ver se ele clicou numa coordenada que pertence a um polígono... Se sim, bang, selecione seu polígono!
public void verificarCoordenadas(int x, int y) {
    for (Poligono poligono : this.getPoligonos()) {
        if (poligono.contemCoordenada(x, y)) {
            poligono.selecionar();
            return;
        }
    }
}

Se eu der mais dicas eu tiro o seu desafio de aprender sozinho. Seus próximos passos seriam criar a classe Poligono e implementar seus métodos (contemCoordenada, selecionar, mover  afins)...
Me deu um pouco de saudades de Java agora.
Comment: hum muito bom, já é um ótimo começo para me, valeu pela dica :D

Selecionar e arrastar componente Swing


BigQuery, load dataframe containing repeated fields using python client

Question: I am loading a pandas dataframe from a python program into a bigquery table.
The code:
table_id = 'project.dataset.table'
job = client.load_table_from_dataframe(df, table_id)
job.result()

My dataframe contains a couple of columns which store large arrays of floats.
There seems to be an issue loading repeated fields using the load_table_from_dataframe method in the python library due to some issues with the underlying pyarrow library, as can be seen here.
What would be the best way to work around this?
Answer: Answering my own question with a workaround.

I first tried using pandas_gbq.to_gbq() however this has poor type support so does not work.
The working solution involved converting the dataframe into a dict and streaming this into bigquery

df_dict = df.to_dict(orient='records')

def insert_bq_row(rows):
    global client
    res = client.insert_rows(table, rows)
    assert res == []

insert_bq_row(df_dict)


i want to parse date in my format but is give me exception in android?

Question: i am trying to convert original datetime in to my format but is  give me exception
my date :2014-01-22 13:24:03 in this format now i want to convert

Date.java

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd k:mm:ss");
Date date = format.parse("2014-01-22 13:24:03");

String strdate = android.text.format.DateFormat.format("dd.MM kk:mm", date).toString();

i want output like this
22.1 13.24

Logcat Error

01-22 13:24:24.421: W/System.err(27821): java.text.ParseException: Unparseable date: "2014-01-22 13:24:03" (at offset 10)
    01-22 13:24:24.431: W/System.err(27821): at java.text.DateFormat.parse(DateFormat.java:626)

Comment: Are you *sure* you want `kk` rather than `HH`? Will you really get an hour of `24` after midnight?
Answer: Use this code
  try
    {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date = format.parse("2014-01-22 13:24:03");
      String newdate = "" + date.getDate() + "." + date.getMonth() + " " + date.getHours() + "." + date.getMinutes();
    }
  catch( Exception e) {}

Answer: You have a T in your pattern, but not in the date you're trying to parse. Get rid of the T in your pattern and the problem should go away.
From SimpleDateFormat documentation
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" --> 2001-07-04T12:08:56.235-0700

Note the T in the pattern matches the corresponding T in the date string being parsed.
It's also a little odd that your pattern includes Kk, as upper and lowercase k have different meanings:

k Hour in day (1-24)
K Hour in am/pm (0-11)
Answer: The correct pattern for that date format is: yyyy-MM-dd' 'HH:mm:ss.
Then, in order to format the date the way you need, you can use this pattern: dd.M' 'HH.mm.
Answer: Try do it in that way and review your formatting string.:)
String ISO_8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
SimpleDateFormat formatter = new SimpleDateFormat();
formatter.format(date);


Trying to understand Volume of a cone without the unit sphere

Question: I have been working on the double integral proof for the volume of a cone. I found that I can use a unit-sphere Where the base of the cone is the equator and the height is the distance ${\rho}$  to the pole. Using area of a ${\Delta}$=${1/2bh}$ I define the Area of the ${\Delta}$ with base ${\rho}$ and height ${\rho}$
as ${1/2\rho^2}$.
It follows $$V_{cone}={\int_0^R \int_0^{2\pi}1/2\rho^2d\rho d\theta}$$ $$V_{cone}={{1/6}R^3 \int_0^{2\pi}d\theta}$$ $$V_{cone}={{1/3}\pi R^3={1/3}\pi R^2 R}$$ Since the H=R I get $${1/3\pi R^2H}$$
I'd like to be able to prove this without the unit-sphere but I am having trouble understanding the logic in the triple integral proof in cylindrical coordinates. Can anyone help me see the parallels to my approach So I can finally understand the cylindrical method? Thanks in advance.
${edit}$
(Moved self answer into OP to condense the thread.)
I now understand.
Start with the observation that axes are arbitrary. Next we need to find the equation of the line in a cylinder with the height on the Z axis. $${Z=mX +H}$$ Where H is the Z intercept (the apex of the cone)
Change the X axis to ${\rho}$ then the slope of the line is $${(H/R)}$$ Where H is the apex of the cone and R is the radius of the base. (the limit of the base on ${\rho}$)
THen the equation of the slant is $${Z=(H/R)\rho + H}$$ IF we assume the slope is negative then the equation becomes $${Z=H-(H\rho/R)}$$
Now we can integrate $${\int_0^R\int_0^{2\pi}\int^H_{(H/R)p}(\rho )d\rho d\theta dz}$$
Integrating over z will give you the equation of the line but the ${\rho}$ keeps you from dragging it out of the integral with respect to ${\rho}$ So now we have $${\int_0^R \int_0^{2\pi} \rho[H-(H\rho/R)]d\rho d\theta}$$ ... $${\int_0^R\int_0^{2\pi}H\rho-(H\rho^2)/R}$$.. $${\int_0^{2\pi} (HR^2)/2-(HR^2
)/3}$$... $${\int_0^{2\pi}[(3HR^2)/6-(2HR^2)/6 = \int_0^{2\pi} HR^2/6}$$... finally $${(2\pi HR^2)/6 = (R^2\pi H)/3}$$
Thanks to @AlexJordan for the link.
Answer: You don't need calculus for the volume of something like this if you take Cavalieri's principle and dimensional rescaling as givens. (If you do not, see below for my comments on that.)
Start be decomposing a $1\times1\times1$ cube into six equal square-based pyramids, using a vertex at the center of the cube.
So the volume of these pyramids are each $\frac{1}{6}$. The height of each pyramid is $\frac{1}{2}$. Now, scaling a solid by $h$ in any one dimension scales the volume by $h$. (Again, see below if you feel calculus should justify this.) So to wind up with a pyramid of height $h$, scale in the vertical direction by $2h$, giving a volume of $\frac13h$.
Now Cavalieri's principle allows you change a horizontal cross-section to any shape of the same area and the volume of the shape will not change. If its a cone that you are looking for, you can change all the cross-sectional squares to circles of area $1$ and the volume is still $\frac13h$.
Lastly you can change the dimensions on the cross-sectional shape (in this case a circle) to whatever you want, as long as you scale all of the cross sections uniformly. If the area of the base cross section becomes $B$ (say after scaling or contracting the radii by $\sqrt{B}$) then you have scaled the volume by $B$, and have $V=\frac13Bh$.
Some say that this kind of argument really relies on calculus. But ancient civilizations had these principles long before calculus was formally developed. And to say that this kind of argument is not as valid, to me, is a bit like saying you need field axioms to prove $1+1=2$.
Comment: thanks for the input ( and don't get me wrong it was enlightening) but call me stubborn I still want to understand the trip int approach.
Comment: Take a look at [this](http://www.math24.net/calculation-of-volumes-using-triple-integrals.html).
Comment: I thought about that approach, but polar, cylindrical, and spherical coordinate lend themselves to much cleaner integrals. Once I understand the equation of the line in cylindrical coordinates it should just be a simple matter of $${\int_0^R \int_0^{2\pi}\int_0^H f(\rho)d\rho d\theta dz}$$
Comment: Thanks for the link looks like what I am after. Will study tomorrow though...bed time.
Comment: Thanks again for the link it really helped me understand the full process. I was able to explain it to someone else in detail.


Django redrect to a POST / form validate

Question: I would like to upload a file with data to Django, and use django's forms to validate the data.
My idea was to have two views:

A form where the user selecte the upload file The file is uploaded to thy server
When the file successfully we are redirected to a from processing view, where the data in the file is used to populate the form and process it.

According to this anser, you can't POST data with a redirect:
Django: How do I redirect a post and pass on the post data
Is there a common pattern to achieve this sort of behaviour?
I could easily use the initail kwarg to the form / view to populate it but the user needs to submit the from from the second page. I would like to process the form from the get request without the user needing to manually submit the initial form (a redirect with POST essentially).
(If this can be cleanly achived with generic class based views, all the better).
Answer: The simple way to do this would be to extract the data in the first view and store it in the session. The second view would then simply retrieve the data from the session and use it to populate the form.
Comment: Thats a decent option, it just seems a bit wrong from a separation of concerns point of view. I would prefer the excel parsing to be done by the second view. I'll go with that unless someone suggests something better.


How to add two registration form on single page?

Question: How can i add two registration form on single page
I had created two registration page using the Profile 2 module and given a custom path,eg:
http://localhost/dupal/member/register
http://localhost/dupal/non_member/register
How can I display that two form on single page
eg:http://localhost/dupal/user/register
Comment: check this http://drupal.stackexchange.com/questions/82040/how-can-i-create-two-register-forms-for-different-users
Comment: http://drupal.stackexchange.com/questions/7252/multiple-registration-forms
Comment: @Bala i had already created that two form just need to add on single page..
Comment: How do you create that forms?
Comment: using Profile2 Module
Comment: You can use drupal_get_form() function.
Answer: Give a try to Profile2 Registration Path module:
Problem with Profile2 module: By default, the Profile2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.
Solution:

Profile2 Registration Path enables you to set a unique registration path for each Profile2 profile type. Users who register via that unique path will be presented with fields from the chosen profile type(s).

Alternatively another method to include multiple forms (e.g: FORM1 and FORM2) on same page is somewhat like below(however I am not sure where it will work with the profile2 forms):
$output = array();
$output['FORM1_DISPLAY'] = drupal_get_form('FORM_1_FORM_ID');
$output['FORM2_DISPLAY'] = drupal_get_form('FORM_2_FORM_ID');
return $output;

Answer: You can implement hook_menu_alter in your custom module and adds custom page callback for user/register menu item.
In your custom 'page callback' function, you can use drupal_get_form function to render the both form.
You can check the code snippets and may be it will help you.
<?php

/**
 * Implements hook_menu_item_alter()
 *
 */
function custom_feature_menu_alter(&$items) {

  //Configuring user login and register menu item
  $items['user/login']['type'] = MENU_CALLBACK;
  $items['user/login']['page callback'] = 'custom_feature_user_register';
  $items['user/login']['title'] = 'Login / Register';

  $items['user/register']['page callback'] = 'custom_feature_user_register';

  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/register']['title'] = 'Login / Register';

}

/**
 * Callback to display user login and register form
 */
function custom_feature_user_register() {

  //Addding user login form
  $output = '
';
  $output .= '
Member Login
';

  $output .= drupal_render(drupal_get_form('form_id_1'));
  $output .= '
';

  $output .= '
';
  $output .= '
Register
';

  $output .= drupal_render(drupal_get_form('form_id_1'));
  $output .= '
';

  return $output;
}


How To Display YouTube Channel On Page

Question: I'm attempting my first Drupal site and would like to show a simple listing of the 5 most recent YouTube videos submitted (http://gdata.youtube.com/feeds/api/standardfeeds/most_recent?max-results=5).  I've been struggling with this for almost a week now and cannot get what I want.
I've tried Feeds and the YouTube parser and I've tried the Media Module as described here.  I can get the 5 most recent videos imported as separate nodes, but I want to just be able to list them, embedded, on the single page.
Any help would be greatly appreciated.  I'm new to Drupal and really looking for a walk-through at this point.  I'm using Drupal 7.19.
Thanks!
Answer: Did you try Aggregator? It's the first one listed on the modules page then on the configuration page it's call Feed Aggregator.
I then use Views to style my results.
Hope this helps!
Comment: I have played with that as well, but guess I just don't know enough to get it to work like I want.  Do you know of a tutorial that can walk me through it?
Comment: What kind of styling are try to do? For instance I display tweets and what I do is create a Block View. Format: unformatted list. Show: fields. Then for my Fields I have Aggregator Body. When you select that field you will get a pop up to configure that field. Here I select Rewrite Results then check rewrite the output of this field. You then select your replacement pattern to use and style the output of each feed.
Comment: Make sure when you create the view you select Show Aggregator Item
Comment: Come to think of it, if you can get the videos to show as nodes you should be able to create a view of those nodes so they are all on one page.
Comment: Can you point me to a tutorial that explains how to use a view for the nodes?
Answer: Come to think of it, if you can get the videos to show as nodes you should be able to create a view of those nodes so they are all on one page.
Comment: Can you point me to a tutorial that explains how to use a view for the nodes?
Comment: OK, I'm back to having the individual nodes but I can't get the video, just the title which is a link that takes me back to youtube.
Comment: Were you ever able to view the youtube video?
Comment: I was able to get a listing on a single page using the Feed Importer module a view, but I cannot get the videos to display like I wanted - embedded.  They're just links off to youtube.
Answer: Did you import the URL to embed? If so, you just need to theme the imported entities outputting that URL in the right format. If using the Field UI to customize the view modes of these entities, modules such as Link iframe formatter may help.
Answer: From your Dashboard, navigate to Appearance » Widgets. Then, under Available Widgets, click on the YouTube Feed widget. Choose which area you'd like to display it on, and click on Add Widget to save your choice. After doing this, check out your website and see your channel feed nicely displayed on your sidebar.

How To Display YouTube Channel On Page