Why $K(u)$ is a field?

Question: Let $F$ be an extension field of $K$ and $u\in F$.
How do we know that adjoining an element of F to K, makes $K(u)$ a field?
I know that $Q(\sqrt2)=\{a+b\sqrt2|a,b\in Q\}$ is a field, but in the general case are we guaranteed that $K(u)$ is a field?
How can this be proved
Thanks :D
Update: Following @GitGud
Let $S= \{\cap B_i|\forall i , K\cup\{u\}\subseteq B_i\}$ be the intersection of all subfields of F that contain $K∪\{u\}$.
Proof:
Since $0,1\in B_i \ \ \forall i\rightarrow 0,1\in S$
If $a \in S\rightarrow a\in B_i \ \ \forall i\rightarrow  a^{-1},-a\in B_i \ \ \forall i \rightarrow a^{-1},-a\in S$
If $a,b \in S$then $a*b^{-1}\in B_i \ \ \forall i$ and $a-b\in B_i \forall i \rightarrow$ S is closed under sums, and multiplication.
Thus $S$ is a subfield of $F$ and $S=K(u)$
Comment: @abe15 That's easy, just take the intersection of all subfields of $F$ that contain $K\cup \{u\}$. The interesting question is when you don't have a 'larger field' (as you have $F$ here).
Comment: Hint: How is $K(u)$ defined?
Comment: @JiK That beggs the question: why does there exist a field that has $K\cup \{u\}$ as subset.
Comment: @Jik The smallest subfield of $F$ that contains $K$ and $u$, but how are we sure such a subfield exist?
Comment: @GitGUD Is the quick proof ^^ good ?
Comment: I'm curious now! What exactly happens if there isn't a larger field?
Comment: I think $\mathbb{C}$ is an example
Comment: @abe15 Your proof seems fine, except for the fact that it should be $S= \bigcap\{B|K\cup\{u\}\preceq B\}$. As for the other question, I think the smallest field containing $K\cup \{u\}$ (with $u\not \in K$) is the set of expressions $\dfrac{f(u)}{g(u)}$ where $f(u),g(u)\in K[u]$.
Answer: Unfortunately I do not have enough reputation to comment, but I would say that $K(u)$ is typically defined as the smallest field containing $K \cup \{u\}$, so taking the intersection of all subfields of $F$ with this property is really the definition of "smallest" field with that property. Then all you have to do is show the intersection of subfields is a subfield, which is straightforward.
As for your question as to "What if there isn't a bigger field?" well, it depends on your context. For one, you can always consider the algebraic closure of a field to be a "bigger" field if yours isn't algebraically closed, which exists for any field by Zorn's lemma. If your field is algebraically closed, like $\mathbb{C}$, then $\mathbb{C}(u)$ can be thought of as a field extension where $u$ is some symbol defined to be transcendental over $\mathbb{C}$. Then this would be all rational functions in $u$ over $\mathbb{C}$. I would suggest reading about function fields if this interests you.

Why $K(u)$ is a field?


How broad arpeggiated chords are reasonable?

Question: I am one in a long line of presumptuous amateurs who makes music that they themselves cannot play, so I must ask around to know whether my music is what you might call "reasonable" to be performed. I am fine with it being hard to play, but it should not be physically impossible, impossible for anyone below the level of Volodos, or unusually awkward for the hands which the music does not justify.

To further specify "reasonable": imagine if you will a hypothetical pianist who is at the level where they, with practice, could perform average Frans Liszt pieces to a level of quality and musicality that's perhaps not good enough for a disc but good for a grainy YouTube video, and satisfies them. I hold no expectations that any such pianist will ever just show up and play what I made, but allowing this hypothetical figure to effectively perform it is what I wish to accomplish to be personally satisfied with my arrangement.

My specific query is about arpeggiated chords. How broad can I make them, and still allow a performer to make it sound as a single chord?
The piece in question is part of a piano arrangement of Shostakovich's 7th symphony. Here's the section of music as the computer plays it, so you can judge the tempo for yourself. And here's a plain image of the relevant passage. Tempo is ♩ = 120.

When making my arrangements I tend to use other pieces as reference for physical limitations. Here, arpeggiated chords of this width might be found in Liszt's Heroischer Marsch S.231.
An obvious difference is that those chords are used only at the starts of measures, so they may be stretched out for effect. That's less possible in my score, where they are repeated twice per measure. The overall tempo can be slowed down, as it's an expressive section where rubato is very welcome, but the broad chords - which evolve from much smaller and non-arpeggiated chords - should continue sounding like "one whole", rather than an ascending set of notes. That gradual widening of the chords is also why I haven't already removed or moved up the bottom notes by an octave - the downwards line over the course of these measures is one that I wish to preserve, if I can.
So the question is: does this music seem reasonable? And if not, what is about the width where I should start considering removing or replacing notes so that the overall chord is more manageable? What are some general guidelines here?
Comment: @user1079505 There's 568 questions with the word "playable" on this site - many ask for physical playability but a great deal are about reasonable playability, e.g. https://music.stackexchange.com/questions/89826/orchestration-how-to-know-a-comfortable-playable-speed-to-low-register-instrume Now I understand that there may be a wider range of skill for the piano and my indication of "below Volodos" may not be accurate enough - so could you perhaps suggest another way to define it?
Comment: Don't forget to take into account that Liszt had hands like shovels. He [& Rachmaninov] could reach a 13th.
Comment: Define "reasonable" in music.
Comment: I found out I have been looking at a wrong score without paying attention. So we were in fact not looking at the same score. I intend to delete my former comments. Anyway thanks for providing the correct link.
Comment: @Tetsujin Thanks, that's fair. Liszt is my go-to reference because most of his pieces are what I'd call "reasonable", they are technically challenging but still quite commonly played, unlike composers like Alkan or Méreaux. And his Beethoven symphony transcriptions are a good reference for my amateur Shostakovich symphony arrangements :)
Comment: I know you are asking about the LH chords but there are some large stretches in the RH as well.  Are you using the pedal at all?
Comment: @JimM I didn't notate any pedaling, but my understanding is that a performer will use the sustain or sostenuto pedal with their own judgement. Explicit pedaling markings only seem to be used when a composer really wants a specific texture and I haven't reached that level of sophistication yet. Do correct me if I have that wrong though!
Comment: Most pianos found to the right of the Atlantic are not blassed with a sostenuto pedal. So that's a factor to consider. Using the damper pedal will eliminate the rests marked for l.h.
Comment: Since they are marked staccato I would just play a fast arpeggio without holding down any of the notes (or using the pedal), meaning it would be doable even for small hands
Comment: I found the orchestra score for Shostakovich's 7th symphony ln IMSLP and I have been trying to find the part that you have made into a piano arrangement. I can find no place in the score that seems to fit with your arrangement. I have searched all 4 movements with no result.
Comment: @LarsPeterSchultz It's the third movement, near the start - shortly before where it picks up speed. I would give you a timestamp but I'm on mobile right now.
Comment: I can find nothing in the third movenent that comes even close. Most obvious difference: your version is 3/4 while the third movement is 4/4. Then I looked at melodic lines. Could find none that was similar. Then I thought whether there is a triplet section that you for some reason converted into 3/4 . Found nothing.
Comment: @LarsPeterSchultz Are we looking at the same symphony? xD A big part of that movement is in 3/4. Here's a link: https://youtu.be/DMcf8K_RJPU my segment starts at 45:44
Answer: Reasonable? Almost
What makes this particularly challenging is less the span and more the fact that the arpeggios are mimicking a pizzicato effect, so pedal can only help in the most sparing way. Thus, where a pianist would otherwise use the pedal for some of the long notes in the right hand, that's not an option here.
Even so, most of this would be difficult, but playable for the hypothetical pianist proposed in the OP. There is one section, however, which, at best, borders on the impossible.
To understand the unreasonable part, first some discussion of the reasonable parts.
Where and how it's reasonable
Right hand assistance
Mm. 48–54b2 and mm. 60ff. can be played, particularly if the player has a wide span. As long as the pianist can reach a tenth, then the arpeggios' topmost Gs can be taken by the right hand when desired.
For example, the arpeggios in m. 53 are a bit awkward for because of how the chord is laid out. In that case, I can use my right-hand thumb, and no one's the wiser.
Pedal assistance
M. 54, can also use the above approach, but with the additional requirement of some judicious pedaling to keep the melody legato. On beats 1 and 2, the arpeggio can be played pizz., but then the pedal must catch the melody G and B, respectively, to connect them to their respective following A and C.
Where and how it's unreasonable
Mm. 55–59
Here, the span in the right hand precludes using it to help the left hand.
Measure 55 requires an eleventh, which, arpeggios aside, is not a reasonable expectation, especially since pedal isn't an option here.
Overall, these measure both don't allow for a right-hand or pedal assist, so the left-hand gymnastics involved at the speed required because extremely difficult to play accurately.
The pianistic solution doesn't work
Faced with this situation, most pianists would play the lowest note as a grace note before the beat and then play the remaining notes separately, using the pedal to make the connection. However, both the grace note and pedal would defeat the sound being sought here, so the "pianistic solution" doesn't work.
Comment: Thank you for your detailed answer :) One thing regarding measure 55 and onwards, my own consideration was that as soon as the arpeggio in beat 2 is released (before beat 3 starts), one could press down the sustain pedal and then release the high E, and jump to the lower melody. Then not release the pedal again until the end of beat 1 in the next measure. This would result in the E not sounding for the whole 3 measures but only just over 1, but 3 measures at this tempo would turn pretty inaudible anyway - the reason I notated it the full length was to indicate the overall melody.
Comment: @KeizerHarm Agreed. It could be executed exactly as you say. (The left hand could also jump up to play m55b3.) Consider putting the "unnecessary" tied notes in parentheses. That would help clarify your intentions — especially if you included a footnote.
Comment: Good suggestions. I think what I will also do is parenthesis the bottom notes of the arpeggios when on beat 2. Skipping the lower note the second time allows one to take more time for the first and hopefully still preserve the melodic line.
Comment: One last question: what about the way the chords in ms. 53 look like makes you consider them awkward? My understanding here is a bit limited - the best I can figure is that you generally want a black note in the middle so you can pull your fingers to there over your thumb on a white key, but that's where my understanding ends.
Comment: @KeizerHarm In m53... 1) suppose I use fingers 5-4-2-1, then C-G is an uncomfortable span for 5-4; 2) with 5-3-2-1, G-Eb is an uncomfortable span fir 3-2; 3) using 5-2-1-X, it's uncomfortable to cross over from 1 on Eb to another finger on G.
Answer: You're sort of shifting back and forth between "reasonable" and "physical limit."
So much depends on the notion of "reasonable" and what anyone thinks "hard to play" means.
One way to think of it is how likely are you to ever get a pianist to play something you wrote? I think it's reasonable to say the harder to play the less likely it will get played.
If your point of reference is Liszt and Rachmaninoff, you set the bar at the highest level, and less likely to get played.
If the point of reference were Mozart or Satie, for example, it's a lot less difficult, and more likely to get played.
That's just my opinion. And I'm an amateur, so I set the difficulty bar low. But we're talking about a whole spectrum from easy to most difficult and there really isn't a way to say there is one right or "reasonable" level.
About your particular chords. In some places you have the span of a tenth. You see than in lots of piano music, but it's also pointed out as hard to play for average hands. Arpeggiating it makes it more do-able. When the span gets to nearly two octaves it will be harder to play even as an arpeggio. But, there are a lot of octave doublings in the chords so you could shrink down the span by omitting some of the octave doublings. If you kept the span to a tenth, the arpeggios will be easier while still providing the sound of open voiced chords.
If you do go with very wide chords, at least consider what the specific piano fingers will be rather than relying only on the interval size. In the Liszt march there are some specific fingerings given for the very bitg arpeggios...

...because of the placement of the black keys those fit the hand fairly comfortably.
By comparison, this...

...if using similar fingering is less comfortable when reach the top G4. Not impossible, but just less comfortable. The point being you can test out fingerings (if you aren't already doing this) and try to be sympathetic to how it would feel to actually play passages.
Comment: Keeping with the sort of modernist theme Bartok's Mikrokosmos seems like one good point of reference, especially because it's graded. Perhaps too easy for your taste, but volumes V and VI are the high level sections. Learning more toward Romanticism, I would look into Grieg's Lyrical Pieces. To me they epitomize all the beauty of the romantic style, but at a level for mere mortal pianists. :-) Just some idea to add you the Liszt standard you already have.
Comment: @KeizerHarm Your earlier comparison of Liszt and Alkan is misleading. Alkan is rarely performed not because his music is hard but because it's largely unknown. Liszt on a program brings a bigger audience than does Alkan.
Comment: I don't think I ever asked what was physically possible. Liszt is my reference point for a number of reasons, but the relevant one is that I think that most of his works are "hard but not unreasonable", unlike say Méreaux or Alkan who stretched piano music to their absolute physical limit (losing musicality along the way, in some views). Thousands of people perform Liszt, and maybe ten people perform Alkan on a regular basis - for me there's a difference.
Comment: I have little hope that any actual pianist is going to come across my works, let alone attempt to play them. So my primary audience is myself and I enjoy writing an 80 minute symphony if I have more freedom in the technical department. But my secondary audience is a hypothetical pianist. That also helps constrain my hobby, otherwise I might as well write for piano rolls instead. This hypothetical pianist is capable of performing average Liszt pieces, but if my works are even harder or awkward to play then they wouldn't perform it either. So my goal is to be reasonable to this imagined figure.
Comment: I understand that, but then we're just disagreeing about what "reasonable" means. I put Liszt at the extreme end of difficulty even if there is more difficult piano music to be found.  I don't equate the extreme end of difficulty with a reasonable level. Again that's just my perspective. I wouldn't take Liszt level playing for granted. Not if I ever hoped to hear something actually performed.
Comment: And there is a possibility someone could play what you write. Long ago I took an independent study in composition at college. I wrote stuff I couldn't play, but my professor could sight read all of it! It wasn't especially hard to play, but it was beyond my skill. You might say I learned to write with his playing level in mind. And that's probably my main point. You could aim at a level within the range of players you might have the opportunity to work with. Anyway, wait for some other answers, there are many properly trained pianists on the forum.
Comment: Ok, that's very fair :-) I don't always properly respect skill level - which is exactly why I ask questions like this. I am also of coursed biased because I personally like to listen to Liszt's music, virtuosic or not. But given that I am not acquainted with any pianists, I wonder if you could perhaps suggest a composer/pianist or two that I might do good to use as a point of reference for "difficult but reasonable" instead?
Comment: You say it's unlikely a real pianist will play your works, so the question itself is pretty well hypothetical, and answers won't really make any difference!
Comment: @Tim I disagree. The pianist may be hypothetical but his skill level is defined (or I'm trying to define it), and my goal of satisfying him is very real, so answers like Michael Curtis's are very helpful indeed!
Comment: @Aaron That's definitely a factor, but I think that it can be inarguably stated that technical difficulty does play a much greater role in Alkan's works. And that is in turn another reason why he is less performed, which makes him less known to the modern audience.


You'd Be So Nice to Come Home To chord function question

Question: I have been playing through You'd Be So Nice to Come Home To. I have a pretty good grasp of the song and the chord functions up to the final section. I am interested to know the function and substitutions for the final 8 bars.
My lead sheet has it as:
D#diminished7, C/E, G#diminished7, Am7
D9, Ab7, D7b9, G7, C6, Bm7b5, E7b9
Where are these chords coming from, particularly the diminished chords, what was the thinking behind these substitutions and how would you approach playing over them?
Thanks very much!
Answer: I don't want to speculate on how representative that lead sheet might be of the original song, but the question about the dim7 chords in the posted chord progression can be answered regardless.
Dim7 chords are symmetric and there are many plausible explanations for why they "work" or what they do. One way is to not think about it, just play the dim7 in different songs and different contexts, and you'll learn how it works naturally. Another way is to see them as dominant chords, and because of the dim7 chord's symmetric nature, each dim7 can be seen as four different dominants. See this answer about how it works: Why don't diminished 7 passing chords work going downhill?
For the G#dim7 -> Am7 step this is clear: G# is the third of E7 and G#dim7 works as dominant for A-based chords. Or you can think of the G# as a leading note to A.
Why does the D#dim7 -> C/E step work? The D#dim7 doesn't work as a G7, so it's not a dominant for C? No, but it could work as a B7, which is a dominant for E ... so, bass goes to E, but the rest of the harmony goes to C?
Like I said, you could just as well play the song from the lead sheet, maybe play it in different keys, and learn the D#dim7 -> C/E step as an atomic basic ingredient that doesn't need any further explanations. Just like you probably don't need a theoretical explanation for why subdominant IV chords sound like they do. You just use them and that's it. :)
For me personally, one such "atomic" progression is C - Cdim7 - Dm7 - G7.  Why does that work going to Dm? Maybe because there's the downwards motion of the minor third E-G -> D#-F# - > D-F ? But is that a reason? Can you generalize that and use it in other contexts?
Comment: Yes I am right now, I have been trying this out and it is very helpful and opens up a lot of cool possibilities:) I take your point that it is just a way of explaining it but to understand I need to try examples out and listen! By the way the point about the minor thirds has also opened my eyes to looking more closely at this type of motion within chords. I will also read the other link thanks
Comment: @Babaluma It's actually a so-called _answer_. ;) Did you already try the suggestions? For example the idea "dim7 works as a dominant", take any song with a dominant seventh chord, for example C7, and substitute the chord with a dim7 rooted at the chord's third or seventh, for example C7 becomes Edim7. Or keep the bass the same, C7 --> Edim7/C (which is actually the same as C7b9)
Comment: @Babaluma Awesome! It's great if people actually try out and apply the ideas instead of being content with logical-sounding bedtime story explanations (however correct they might be), because learning only happens in practice, when you taste the sounds and see the colors. For more dominant substitution wonders, check out half-whole diminished scales and how Barry Harris talks about it on Youtube ...  though it's dangerous to watch Youtube, because it steals your practicing time and gets you hooked on brainless entertainment and attention wh*ring disguised as "learning".
Comment: yes pipieri absolutely. It don't mean **** unless you actually sit down and play it ...
Answer: I didn't compare the chords with any recording, so let's just assume they are correct. I hear that part in C major, so C is the I. My analysis would be
| V7/III | I | V7/vi | vi | V7/V subV7/V | V7/V V7 | I |
 [iim7(b5) V] => vi |
V7/III (D#dim7 which is just a rootless B7(b9)) resolves to I, which works because you have the E in the bass of the C chord (and even if you didn't have the E in the bass it would work as a deceptive resolution). Ab7 is the tritone sub of D7, and the last two chords are a iim7(b5) V leading to vi (i.e., Am).
Answer: There are (at least) two classic uses of dim7 chords in this style of harmony:

As a substitute for the V7 resolving to a minor. Eg Bdim7 to C minor. This works because the Bdim has everything G7b9 has, except the root. And the dominant G7b9 sounds pretty going to minor (the Ab and B natural colour notes are also great in the C minor scale).
Going to a major 7 - eg Cdim7 to Cmaj7. This is because the voice leading is appealing, rather than being a substitute. Here you get Eb leading to E and F#b to G. You hear jazz guys like Getz and so on do this a lot.

In this end sequence, we have both of these (in the other order). With them also being relative major and minor, and C/E sets up an E bass note just before the G#dim7 meaning you get even more of a hint of E7b9 without actually going there.
The other bars are pretty much "round the houses"  cycle of 4ths - the Ab7 being a tritone sub for D7 (but that looks to me like a Real Book "addition" anyway more than anything else).
Comment: It's funny, I think the voice leading works particularly well the other way, from maj7 to dim7: Cmaj7 - Cdim7 - Dm7 - G9
Comment: yes that also - classic bluesy run down, right? (ok almost ... )
Answer: Whoever invented those chord names apparently didn't understand what was going on. Look at the original sheet music here: http://images.indianahistory.org/cdm/ref/collection/p16797coll1/id/1542
Ignoring the details of the bass notes, That gives
Cdim - - - | C - - - | F6 - - F | - - - Fm6 |
C - Ab7 - | - - G7 - | C - - - | - - F E7 | (Am)
Inventing a convoluted argument that "D#dim7 is just a rootless B7(b9)" is irrelevant, since Cdim7 is identical to D#dim7 - though the sheet music editor had enough musical sense to realize that the A in the voice part wouldn't be improved by doubling it, and a "less is more" Cdim chord will sound better than a Cdim7.
Sorting out the rest of the creative fiction in the OP's chord sequence is too tedious to spell out in detail.
Comment: If you're not going to sort out the other chord functions (particularly the other diminished chord), then all you have here is an argument that OP's chords are wrong. Maybe so, but OP asked for analysis, and you're just disputing over history. It hardly matters where those chords did or did not come from.


Exercise with localization and minimal primes

Question:
Let $A$ be a ring and $p\subset A$ be a prime ideal. Call $f$ the canonical map $A\to A_p$, and set $I:=\operatorname {ker }f$. Show that $I\subseteq p$ and that $\sqrt I=p$ if and only if $p$ is minimal among the prime ideals of $A$.

$I\subseteq p$ is easy: $x\in I $ iff exists $t\in A\setminus p$ such that $tx=0$; since $0\in p$ and $t\notin p$, be $p$ prime $x\in p$.
Now I try to show that, if $p$ is a minimal prime, $\sqrt I=p$. Since $I\subseteq \sqrt I\subseteq p$, we can look at what happens in $A_p$. Here we have that the radical of $IA_p=0$ is $pA_p$, being the only prime containing it. Am I finished?
Now suppose that $\sqrt I=p$. Again, passing to $A_p$, we are in the situation that there is only a prime ideal, namely $\sqrt 0=pA_p$. Since any prime contained in $p$ would survive in $A_p$, can I conclude that $p$ is minimal?
These arguments actually seem defective to me, but I have not clear why. It seems to me that sometimes I reasoned like if the prime ideals of $A_p$ were in bijection with the primes of $A$ contained in $p$, other times like if the bijection was with the prime ideals contained in $p$ and containing $I$ (for example in saying that $\sqrt I A_p$ is the nilradical of $A_p$). Could you clear my ideas? Thanks
Answer: Here is a better way to prove this. The containment $\sqrt{I} \subseteq p$ is trivial once you have $I \subseteq p$ (by taking radical on both sides). By definition, $\sqrt{I} \supseteq p$ if an only if for all $x \in p$ there is $n>0$ and $t \in A \setminus p$ such that $tx^n=0$ if and only if $x/1 \in \mathfrak{N}(A_p)$ (for all $x \in p$). Recall that $\mathfrak{N}(A_p)$ is the intersection of all prime ideals of $A_p$.
If $p$ is minimal, then $x/1 \in pA_p = \mathfrak{N}(A_p)$ (there is only one prime ideal of $A_p$). Conversely, suppose $p$ is not minimal. Then we can find a minimal prime $q \subset p$. Assume, in contrary, that $x/1 \in \mathfrak{N}(A_p)$. In particular, $x/1 \in qA_p$. Thus, there exists $y \in q$, $t \in A \setminus q$ such that $x/1 = y/t$. Hence, for some $u \in A \setminus p$, $utx = uy \in q$ and so $x \in q$ by primality (since $u,t \not\in q$). Since $x \in p$ is arbitrary, we have $p \subseteq q$, a contradiction.
Answer: Here is an equivalent statement and proof, which do not involve localisation.  Thus you get a different perspective, and can see what is happening in the ring $A$ more explicitly.

Let $A$ be a commutative unital ring and let $P$ be a prime ideal.  Let $I$ be the ideal of $i\in A$ such that $ix=0$ for some $x\notin P$.
Then $\sqrt I\subseteq P$ as $a^nx=0$ with $x\notin P$ implies $a\in P$.  Similarly, for any prime ideal $P'\subsetneq P$, we have $a^nx=0$ with $x\notin P$ implies $x\notin P'$, so $a\in P'$.  Thus $\sqrt I \subseteq P'\subsetneq P$ and $\sqrt I\neq P$.
Conversely, suppose $\sqrt I \neq P$.  Pick $a\in P \backslash \sqrt I$.  Then $a$ and $A\backslash P$ generate a multiplicatively closed set $M$, disjoint from $\sqrt I$ (if $a^nx\in \sqrt I$ with $x\notin P$, then $(a^nx)^ky=0$, with $y\notin P$, which implies $a\in \sqrt I$ - a contradiction).  By Zorn's lemma, one may find an ideal $J\supseteq \sqrt I$, maximal amongst ideals disjoint from $M$.  Then $J$ is a prime ideal and $J\subsetneq P$, as it is disjoint from $M$.

Note the following lemma is used explicitly at the end of the above argument, and implicitly in the corresponding argument by @Ray (as it is the key ingredient of the proof that only nilpotent elements lie in the intersection of all primes):
Lemma Let $A$ be a commutative unital ring, let $M\subseteq A$ be a multiplicatively closed subset, and let $J$ be maximal among ideals disjoint from $M$.  Then $J$ is prime.
Proof: If $u,v\notin J$ then by the maximality property we have: $$\lambda u=j_1+m_1, \qquad \mu v=j_2+m_2,$$
with $\lambda,\mu\in A$, and $j_1,j_2\in J$, and $m_1,m_2\in M$.  However in that case: $$\lambda\mu uv=(j_1j_2+j_1m_2+j_2m_1)+m_1m_2,$$
so $uv\notin J$ (otherwise $m_1m_2\in J \cap M$ - a contradiction). $\qquad\qquad\qquad\Box$


Creating a block with installation profile

Question: To create a block I am currently using this code:
<code>$default_theme = variable_get('theme_default', getDefaultTheme());
$blocks = array(
  array(
    'module' => 'user',
    'delta' => 'login',
    'theme' => $default_theme,
    'status' => 1,
    'weight' => 0,
    'region' => 'sidebar_first',
    'pages' => '',
    'cache' => -1,
    ),
);

// Save blocks
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($blocks as $block) {
  $query->values($block);
}
$query->execute();
</code>
My question is what do the 'module' and 'delta' field exactly do? What can I fill in there if I made a custom block? And how do I define on which pages this block should be visible, should I add a page name or id?
Answer:
I think that's not the correct way of creating the block as it won't fire the required api call for block creation and later on will cause issue.

Delta: This is a unique identifier for the block within the module. Delta values only need to be unique and is used in following purposes:

Passed into the other block hooks in your module as an argument to identify the block being configured or viewed.
Used to construct the default HTML ID of "block-MODULE-DELTA" applied to each block when it is rendered. This ID may then be used for CSS styling or JavaScript programming.
Used to define a theming template suggestion of block_MODULE_DELTA, for advanced theming possibilities.

Module: Name of module creating that block. E.g: If you are creating the block from custom module than it will take the value of that module name.

To programatically create the block, you need to use hook_block_info(), hook_block_view() in your custom module something like below:
<code>/**
 * Implements hook_block_info().
 */
function MyModule_block_info() {
  $blocks['test1'] = array(
    'info' => t('Block info 1'),
  );
  $blocks['test'] = array(
    'info' => t('Block info 2'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MyModule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'test1':
      $block['content'] = 'Required content 1';
      break;

    case 'test2':
      $block['content'] = 'Required content  2';
      break;
  }

  return $block;
}
</code>
Comment: Thanks and do you know how can I apply my block to a specific page in the array key `'pages'     => '',` ?
Comment: @mparryy you can pass the pages as `'pages' => 'node/8
node/9
node/10',`

You can check the `pages` column of `block` table, you will get the idea how the values are getting saved.


Drupal 7.27: 408 Request time out in Chrome browser

Question: We are getting 408 request time out errors in Chrome browser only since the beginning of May. We have not been able to replicate the problem with any other browser. With one website we had a SSL protocol and the error only occured in Chrom on http://
After implmenting a redirect from http:// to https:// via .htaccess the error seemed to have gone.
On a second site there is no SSL certificate and the error only occurs occasionally but it does. We have set the request_time_out to 10080 in the php.ini to no avail. Another thing we tried: We redirected that site to be accessed only with "www".
Has anyone experienced something similiar? Any suggestions would be very welcome.
Comment: What your server's logs says about it? Are requests made by Chrome in any way different than those by other browsers? Do you have any browser-detection code? As for *"Any suggestions would be very welcome"* - no. This site is **not a forum**, it is for **answers**, so please ask your question as something that can have definitive answer, like "what's the cause" or "how to prevent that", or something. It should be relatively easy in this case.
Comment: If my questions do not sematically fit your expectations than have my apologies. Of course I wanted to know the cause but was not sure whether it was a problem limited to my installation or a general problem so I phrased my question with best intentions. And it was not relatively easy to detect as the bug only occurs on Chrome browsers with an http:// protocol and HAProxy running on the server. The solution is easy, though: errorfile 408 /dev/null
Answer: This is a Chrome bug.
https://meta.stackexchange.com/questions/208790/408-request-time-outs-still-continues/232275#232275
One solution: http://blog.haproxy.com/2014/05/26/haproxy-and-http-errors-408-in-chrome/
Seems to be limited to Chrome, page requests through http:// and servers running HAProxy.


Parametrization variables $URL using JMeter

Question: I testing backend project in JMeter
i would like can testing both localhost and url development address.
i would like switch URL address in JMeter between localhost and url development address and can change $url variable between http://{$url} and ws://{$url}.
So I would like set variable $URL and can a change between websocket and http connection, such as I can have a choice if I would like send POST to a web socket or to a http connection.
and i would like also can a change between localhost and development URL.
What I can the best set this in JMeter ? ;)
please describe me step by step.
Answer: I believe you need to split your parameterization implementation in 2 parts:

Protocol (http or ws). As these 2 protocols are handled by different samplers you need to have a possibility to switch between implementations basing on some variable, the easiest way to do it is going for Switch Controller, define your Test Plan as follows:

Switch Controller - Switch Value -> ${protocol}

Simple Controller with name http

HTTP Samplers

Simple Controller with name ws

WebSocket Samplers

So if the ${protocol} variable value is http - you will have HTTP Request samplers executed and vice versa, check out Selection Statements in JMeter Made Easy article for detailed explanation if needed.

URL variable - hopefully you know how to parameterize it, once you define its value somehow just put it into Path field of the relevant sampler

With regards to parameterization itself, depending on where you want to have variable values there could be different approaches. Personally I stick to command-line arguments as this is the most CI-friendly way of providing external parameters.

Add User Defined Variables to your Test Plan and configure it like

Provide the values using -J command-line argument like:
jmeter -Jprotocol=http -JURL=example.com -n -t test.jmx -l result.jtl

Answer: It's a little inconvenient that JMeter doesn't take an origin argument directly, but instead requires you to provide each component as a separate argument.
If you have Bash and Python at your disposal, the following one-liner will automate this process:
function jmorigin { python3<<<"from urllib.parse import *; a=urlsplit(\"$1\"); print('-Jserver='+a.hostname+' -Jprotocol='+a.scheme+' -Jport='+str(a.port))" ; }

Using this, you can simplify the parameterization of JMeter:
ORIGIN=https://example.com:443
jmeter $(jmorigin $ORIGIN)

which expands to...
jmeter -Jserver=example.com -Jprotocol=https -Jport=443


unwanted margin with css

Question: I'm working on a fairly simple webpage and I'm a little bit dusty so I could've made a really obvious mistake but please stick with me. I'm getting a very thin (maybe 5-10px) margin on all sides of my document. I'm including an abbreviated version of my code. Can anyone tell me why I'm getting it and how to get rid of it.
html:

Hello, I'm ...

css:
#wrap { background: url(Andres/images/background-bg.png);  margin: 0 auto;
 }

#para p { padding: 20px; }

#footer { background:url(Andres/images/footer.png); height: 80px;}

#footer #social li { float: left; padding: 10px; list-style: none; }

Comment: Are you inheriting some library that has a padding?
Answer: Its likely the default margin on the  element - most browsers include 8px on all sides, just add:
body {
margin: 0;
}

Answer: While Adrift's answer does answer your specific question - you might want to look at something like
http://necolas.github.io/normalize.css/
It's provides a good baseline when starting a project in order to minimise css issues like the one you encountered
Answer: It's good practice to add a "reset" to your CSS to remove some of the cross browser quirks. I typically add at least this line to all of my projects:
* {
  margin: 0;
  padding: 0;
}

Here's an article to check out about CSS resets.

unwanted margin with css


webform submission details not getting displayed

Question: i have multiple nodes each per language and the default is English(node/1).
For french node(node/2) after submitting the details of the contact form, the details not getting displayed in Webform-Confirmation.tpl.php page, however when i do the same in default English node, it is getting displayed. any configuration should i do for this please help
Comment: Have you overridden template `webform-confirmation.tpl.php` for `node/2`?
Comment: yes made it as webform-confirmation.tpl.2.php still not worked
Comment: It should be `webform-confirmation-[nid].tpl.php` and you have to create template for other node.
Comment: how to create that template for new node.is there any work around, as am very new to drupal am struggling with this
Comment: Copy file from webform module and rename file as `webform-confirmation-[nid].tpl.php` and you should replace `[nid]` with your node id and clear cache.
Comment: i created a new webform-confirmation-2.tpl.php and cleared cache. still not getting the confirmation page
Comment: Edit your webform and check _Redirection location_ in your _form settings_ tab of the webform. It should be _Confirmation page_ checked.
Comment: I have added this as answer so it will help future user.
Answer: You should set Redirection location of webform in form settings.

Edit your webform node.
Click on webform tab in top of page and it will redirect you to webform configuration of the node.
Click on form settings link in webform
Checked Confirmation page radios in Redirection location field-set and save the form.


Beginner - XML to XML conversion using XSLT

Question: I'm new to XSLT and trying some sample applications, I found examples on XML to HTML and XML to XML conversion but I'm facing issue in XML to XML conversion using XSLT.
This is my source XML:
<?xml-stylesheet type="text/xsl" ref="articale.xsl"?>

  <title>the title</title>
  <para>a para para para para para</para>

This is my XSLT:
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org 1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="article">
    <foo><xsl:apply-templates/></foo>
  </xsl:template>

  <xsl:template match="title">
    <foo.title><xsl:apply-templates/></foo.title>
  </xsl:template>

  <xsl:template match="para">
    <foo.para><xsl:apply-templates/></foo.para>
  </xsl:template>
</xsl:stylesheet>

But this is generating plain text like:
the title a para para para para para

Can somebody please help on this.
Steps I followed:

Created XSL file.
Included the XSLT file in the source XML that is here first one.
Accessed this in browser.

Please correct me if I'm doing wrongly the execution of this XML.
Comment: "the title a para para para para para" this is the output in the browser. the view source feture is showing like

 the title
 a para para para para para
Comment: What tool/platform are you using to run the transform? How are you looking at the results?
Comment: "the title a para para para para para" is the output in your browser? Use the browser's View Source feature to see the raw XML and post that
Comment: I'm depending on mozilla only.
Comment: you can try [this](http://www.xmlper.com/) online editor
Comment: You did say what you see. You forgot to mention what you *want to see*. How should anybody know?
Answer: The XSLT transformation engines in the browsers assume that you want to generate HTML, and they then render the HTML. If your output is XML, and contains tags that mean nothing to the browser, then the rendering engine in the browser will typically ignore them.
If you're trying to become familiar with XSLT and play with its capabilities, then the browser isn't a very good playground. It "renders" the output, rather than showing you the output "as is", and most of the browsers are very bad at giving clear error messages when you get things wrong. Get yourself an IDE like oxygen, or if you want something cheap and cheerful, try KernowForSaxon. Or just use the command line if you're comfortable with it.
Comment: Thanks for your answer.I will try KernowForSaxon to get generated xml.


why I use ajax with Google GeoChart api failed

Question: I'm new to javascript. And I tried to use Google Geochart to create a nice report.
From the example, the code should like:
function drawRegionsMap() {
        var data = google.visualization.arrayToDataTable([
          ['Country', 'Popularity'],
          ['Germany', 200],
          ['United States', 300],
          ['Brazil', 400],
          ['Canada', 500],
          ['France', 600],
          ['RU', 700]
        ]);

        var options = {};

        var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    };

And in my case, the data is from a ajax request. So I change my code as:
function drawRegionsMap() {
var jsonData = $.ajax({
        url: "json/geo.pl",
        dataType: 'json',
        async: false
        }).responseText;

            var data = google.visualization.arrayToDataTable(jsonData);

            var options = {};

            var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        };

But it not works for me. The Error message in Firefox is "Error: Not an array".
Hope someone can help me. Thanks!
The output of json/geo.pl is:
-bash-4.1$ json/geo.pl
Content-Type: application/json; charset=ISO-8859-1

[
   [
      "Country",
      "Uploads"
   ],
   [
      "AL",
      1
   ],
   [
      "AP",
      1
   ],
   [
      "AR",
      47
   ],
   [
      "AT",
      25
   ],
   [
      "AU",
      75
   ],
   [
      "AZ",
      10
   ],
   [
      "BD",
      4
   ],
   [
      "BE",
      65
   ],
   [
      "BG",
      15
   ],
   [
      "BN",
      1
   ],
   [
      "BR",
      177
   ],
   [
      "CA",
      536
   ],
   [
      "CH",
      37
   ],
   [
      "CI",
      3
   ],
   [
      "CL",
      35
   ],
   [
      "CN",
      947
   ],
   [
      "CO",
      4
   ],
   [
      "CS",
      1
   ],
   [
      "CY",
      2
   ],
   [
      "CZ",
      20
   ],
   [
      "DE",
      135
   ],
   [
      "DK",
      51
   ],
   [
      "DO",
      1
   ],
   [
      "EE",
      26
   ],
   [
      "ES",
      53
   ],
   [
      "EU",
      2
   ],
   [
      "EU",
      9
   ],
   [
      "FI",
      19
   ],
   [
      "FR",
      183
   ],
   [
      "GB",
      341
   ],
   [
      "GE",
      14
   ],
   [
      "GR",
      11
   ],
   [
      "HK",
      94
   ],
   [
      "HR",
      2
   ],
   [
      "HU",
      7
   ],
   [
      "ID",
      37
   ],
   [
      "IE",
      36
   ],
   [
      "IL",
      122
   ],
   [
      "IN",
      543
   ],
   [
      "IS",
      5
   ],
   [
      "IT",
      129
   ],
   [
      "JP",
      200
   ],
   [
      "KG",
      4
   ],
   [
      "KR",
      451
   ],
   [
      "LB",
      3
   ],
   [
      "LK",
      1
   ],
   [
      "LT",
      5
   ],
   [
      "LU",
      4
   ],
   [
      "MA",
      2
   ],
   [
      "MD",
      3
   ],
   [
      "MO",
      3
   ],
   [
      "MU",
      2
   ],
   [
      "MX",
      77
   ],
   [
      "MY",
      43
   ],
   [
      "NG",
      1
   ],
   [
      "NI",
      1
   ],
   [
      "NL",
      33
   ],
   [
      "NO",
      27
   ],
   [
      "NZ",
      4
   ],
   [
      "OM",
      1
   ],
   [
      "PA",
      4
   ],
   [
      "PH",
      9
   ],
   [
      "PK",
      20
   ],
   [
      "PL",
      76
   ],
   [
      "PT",
      14
   ],
   [
      "PY",
      2
   ],
   [
      "QA",
      2
   ],
   [
      "RO",
      6
   ],
   [
      "RU",
      164
   ],
   [
      "SA",
      30
   ],
   [
      "SE",
      148
   ],
   [
      "SG",
      101
   ],
   [
      "SK",
      34
   ],
   [
      "TH",
      22
   ],
   [
      "TR",
      28
   ],
   [
      "TT",
      1
   ],
   [
      "TW",
      110
   ],
   [
      "UA",
      26
   ],
   [
      "US",
      9386
   ],
   [
      "VE",
      1
   ],
   [
      "VN",
      28
   ],
   [
      "ZA",
      89
   ],
   [
      "ZM",
      1
   ]
]

Answer: I have fixed the issue by convert json/array from ajax responseText in to javascript array.
function drawRegionsMap() {
var jsonData = $.ajax({
        url: "json/geo.pl",
        dataType: 'json',
        async: false
        }).responseText;

var output = new Array();
output = JSON.Parse(jsonData);
            var data = google.visualization.arrayToDataTable(output);

            var options = {};

            var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        };


Adding help text to drupal comment form

Question: using Drupal 7, I'd like to add some help text underneath each field for the user who is filling out the comment for a node.
For example, under 'your name' I'd like it to say, possibly in smaller font, "only give your name if you want it published with your comment".
Anyone know how to do this (maybe with hook_form_alter)?
Answer: Or just edit comment.tpl.php in your template files. Copy comment.tpl.php to your template folder and if not present in the code, add $author name and desired text.
Answer: I think in hook_form_alter, you need to check the $form_id first, so that you can target comment form. If it is a comment form, then you need to add description for the field you want. Just like this
function hook_form_alter(&$form, &$form_state, $form_id) {

$form['name']['#description'] = t('Me help text'),

}

Adding help text to drupal comment form


Sql query with optional fields for Search Web Application

Question: Not an SQL expert:
I am currently implementing a Searching Web Application. The user will send a GET request to a particular Endpoint.
The Endpoint will accept a set of URL Params and the request can come with optional fields. Such as 1, 2 or 3 fields.
My Database table for USER looks like this.
+--------------+---------+------+-----+---------+----------------+
| id        | firstName    | lastName | email | zip | phone      |
+--------------+---------+------+-----+---------+----------------+

Now the web application will get a GET Request with either Phone or Zip or Email.
I have two solutions for doing this but both look bad:
Solution 1:

Have multiple SQL Queries and Execute them according to the URL Params, I receive.
Select * from User where phone=1111111111  and zip=12345 and email@example.com;
Select * from User where phone=1111111111 and zip=12345;
...
...

And so on........I will end up having many queries and this will be a bad implementation. Also will be bad to maintain.
Solution 2:

Other solution that I am thinking of is to have a method, which will build an SQL query based on the URL Params I receive.
Example:
buildSQLQuery(phone,zip,email){

String sql = "Select * from User where "

if(phone!=null  && email!=null && zip!=null ){
sql = sql   + "phone = " + phone + " and zip = " + zip + " and email = " + email;
}else if (phone!=null  && email!=null && zip==null){
sql = sql + "phone = " + phone + " and email = " + email;
}
.......
......
And so on have all conditions and build that particular query.
}

I don't like both these solutions.
Is there a way to write a Single SQL query and that will handle all the above conditions.
Something like if the URL Param value is NULL then that should not affect the query and I will get my expected results.
As in my case the optional values, which don't come in are set to NULL.
Can I implement something like this?
Select * from User where (if notNull (phone))(phone = phone ) and (if notNull (email))(email = email ) and (if notNull (zip))(zip = zip )

If any of the above one value is null then don't use that part in  where Condition.
Also I will always have one field present, so there will be no case where all values are null.
I am implementing this web application in Java and Spring MVC. If anyone can guide me in the correct direction.
Thank you.
Comment: Yes you can do that with `if()` if you provide `fiddle` for your table here it will be easy to find solution.
Comment: You are using Spring MVC. I highly recommend you usage of Spring Data JPA and Hibernate framework. http://projects.spring.io/spring-data-jpa/ Then you will not have to write SQL boilerplate code like this.
Comment: Can you give me an example for using spring-data-jpa? in my case.
Comment: See [here](https://stackoverflow.com/questions/29990281/how-to-form-a-sql-query-dynamically-based-on-the-input-field-values) too.
Answer: I think one more possible solution like:
String sql = "Select * from User where 1=1 "

    if(phone!=null){
    sql +=  " and phone = " + phone ;}

    if(email!=null){
    sql +=  " and email = " + email ;}

    if(zip!=null){
    sql +=  " and zip = " + zip ;}

OR You can try following single query:
select * from User
where (@phone is null OR phone = @phone) AND (@email is null OR email = @email) AND (@zip is null OR zip = @zip)

Comment: Be careful, SQL injection is strongly possible here.
Comment: I would be curious to see if this answer could be updated in such a way that SQL injection is not possible.
Answer: You can do like this:
SELECT * FROM User where(
   IF($phone != 0, IF(phone = $phone,1,0), 0) AND
   IF($email != 0, IF(email = $email,1,0),0) AND
   IF($zip != 0, IF(zip = $zip,1,0),0)
)

assumed for PHP you can change the syntax, may be this query not do the job completely but if you provide fiddle i will modify this to give the proper result.


Why is there a message missing? How can is fix it?

Question: I am absolutely new to RIAK KV. I actually learn it in the university and have to write some Java Code to store 5000 datasets in an RIAK Cluster. So I started to code:
package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.Scanner;

import org.w3c.dom.NameList;

public class Product {
    String artikelnummer;
    String name;
    String color;
    Integer price;
    String picture;
    Integer max = 999;
    String filepath = "./assets/products.txt";
    ArrayList<String> productNames;

    public Product() throws FileNotFoundException{
        productNames = readFile(filepath);
        name = randomName();
        color = randomColor();
        price = randomPrice(max);
        picture = randomPic();
    }

    private String randomPic() {
        String[] picNames = {"ikea0.jpg","ikea1.jpg","ikea2.jpg","ikea3.jpg","ikea4.jpg","ikea5.jpg","ikea6.jpg","ikea7.jpg","ikea8.jpg","ikea9.jpg"};
        Random randPicIndex = new Random();
        int randomPicIndex = randPicIndex.nextInt(9);
        return picNames[randomPicIndex];
    }

    public Integer randomPrice(int max){
        Random rand = new Random();

        int randomNum = rand.nextInt(max);
        price = randomNum;
        return price;
    }

    public String randomColor(){
        String[] colorArray =  {"blue","red","yellow","magenta","green","black","white","cyan","purple","brown"};
        Random randIndex = new Random();
        int randomIndex = randIndex.nextInt(10);
        int i = randomIndex;
        color = colorArray[i];
        return color;
    }

    public String randomName(){
        Random randomName = new Random();
        name = productNames.get(randomName.nextInt(productNames.size()));
        return name;
    }

    public ArrayList<String> readFile(String filepath) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File(filepath));
        ArrayList<String> nameList = new ArrayList<String>();
        while (scanner.hasNextLine()){
            nameList.add(scanner.nextLine());
        }
        scanner.close();
        return nameList;
    }

    //Class for testing purposes
    public void printProduct(){
        System.out.println("Produktdatenblatt: Artikelnummer --> "+ artikelnummer + " " + name + " mit Farbe: " + color + " mit dem Preis: " + price + " ein Bild --> " + picture);
        System.out.println("Hat funktioniert!!!");
    }
}

Above you can see the code that contains the Product Class. To generate 500 products randomly and store this products in the KV Database of Rick i wrote following:
package main;
import io.netty.util.internal.shaded.org.jctools.queues.MessagePassingQueue.WaitStrategy;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.annotations.RiakKey;
import com.basho.riak.client.api.annotations.RiakLinks;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakNode;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import com.basho.riak.client.core.query.RiakObject;
import com.basho.riak.client.core.query.links.RiakLink;
import com.basho.riak.client.core.util.BinaryValue;

public class ProductRiakCluster {
    static String artikelnummer;

    public static void main(String args[]) throws FileNotFoundException, UnknownHostException, ExecutionException, InterruptedException {
        System.out.println("main-method started...");
        System.out.println("Starting create RiakCluster...");

        for (int i = 5000; i > 0; i--) {
            dataGenerator(i);

            RiakClient client = RiakClient.newClient(8087, "127.0.0.1");
            System.out.println("RiakClient " + client);

            RiakObject riakObj = new RiakObject();
            System.out.println("RiakObjekt " + riakObj);

            Namespace productsBucket = new Namespace("products");
            System.out.println("Bucket " + productsBucket);

            Location productObjectLocation = new Location(productsBucket, artikelnummer);
            System.out.println("Location " + productObjectLocation);

            StoreValue storeP = new StoreValue.Builder(riakObj).withLocation(productObjectLocation).build();
            StoreValue.Response response = client.execute(storeP);

            client.shutdown();
        }
        System.out.println("RiakCluster setup finished...");
    }

    public static class ProductPojo {
        @RiakKey
        public String artikelnummer;
        public String name;
        public String color;
        public Integer price;

        @RiakLinks
        public Collection < RiakLink > picture = new ArrayList < RiakLink > ();
    }

    private static void dataGenerator(int i) {
        System.out.println("Started DataGenerator...");

        try {
            artikelnummer = String.valueOf(i);
            generateRandomProduct(artikelnummer);

        } catch (FileNotFoundException e) {
            System.out.println("File not found...");
            e.printStackTrace();
        }
    }

    private static void generateRandomProduct(String artikelnummer) throws FileNotFoundException {
        System.out.println("Method <generateRandomProduct> is running..." + artikelnummer);

        Product product = new Product();
        ProductPojo propo = new ProductPojo();

        propo.artikelnummer = artikelnummer;
        propo.name = product.name;
        propo.color = product.color;
        propo.price = product.price;
        propo.picture.add(new RiakLink("pictures", product.picture, "Produktbild"));

        product.printProduct();
    }
}

After I started this program the following error occurs:
RiakClient com.basho.riak.client.api.RiakClient@2096442d
RiakObjekt RiakObject{contentType: application/octet-stream, value: null, riakIndexes: null, links: null, userMeta: null, vtag: null, isDeleted: false, isModified: false, vclock: null, lastModified: 0}
Bucket {type: default, bucket: products}
Location {namespace: {type: default, bucket: products}, key: 1}

Exception in thread "main" shaded.com.google.protobuf.UninitializedMessageException: Message missing required fields: value
at shaded.com.google.protobuf.AbstractMessage$Builder.newUninitializedMessageException(AbstractMessage.java:372)
at shaded.com.basho.riak.protobuf.RiakKvPB$RpbContent$Builder.build(RiakKvPB.java:18352)
at com.basho.riak.client.core.converters.RiakObjectConverter.convert(RiakObjectConverter.java:198)
at com.basho.riak.client.core.operations.StoreOperation$Builder.withContent(StoreOperation.java:158)
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:151)
at com.basho.riak.client.api.commands.kv.StoreValue.buildCoreOperation(StoreValue.java:72)
at com.basho.riak.client.api.GenericRiakCommand.executeAsync(GenericRiakCommand.java:41)
at com.basho.riak.client.api.commands.kv.StoreValue.executeAsync(StoreValue.java:112)
at com.basho.riak.client.api.RiakCommand.execute(RiakCommand.java:91)
at com.basho.riak.client.api.RiakClient.execute(RiakClient.java:355)
at main.ProductRiakCluster.main(ProductRiakCluster.java:49)

My thoughts about this: I generate an "artikelnummer" but it doesn't occurs in the Pojo class and so the Pojo has a null value. But I have no solution how to fix this problem.
Comment: _I hope the code isn't to difficult to understand_ - It isn't. However, it is difficult to read. Please take some time and read about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve).
Comment: Thank you Hille for help to improve a little bit :)
Comment: @ElmoAll no problem, but please read the article, becouse i think most of the `imports` arent necessary for understanding the code. Btw. I just putted it in a Java Beautifier ;)
Comment: _`System.out.println("Hat funktioniert!!!");`_ How can you know?
Comment: That is just the message that the "object creator" works... it was for testing the class Product.
Answer: The problem is that you don't pass anything to RiakObject.
Return a generated instance of ProductPojo and save it in a variable, say productToSave.
Then, either call new StoreValue.Builder(productToSave), or use RiakObject as follows:
RiakObject riakObj = new RiakObject();
riakObj.setValue(BinaryValue.create(productToSave));

As a side note, your code suffers from a few programming issues, unfortunately. For examples, exchanging data between methods via a static member is not good. You also don't have to create and shutdown a client every time you need it  - reuse one instance for all of your queries.
Comment: You solution helped a lot. As you mentioned there are many programming issues. I fixed it a little bit and I create just one instance and shutdown after the complete program is done.


style doesn't reflect what's in css

Question: On my page http://www.athleticedgefitness.com/, I added a drop down menu under Contact. The hover color is yellow but for some reason, I cannot find that color style in my colors.css. What I found is that the devtools show that the background color change is caused
by a rule starting at line 44 in
http://www.athleticedgefitness.com/sites/default/files/color/corporateclean-659c1a2d/colors.css?mp37st
The rule is:
<code>#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation
.block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish
ul.sf-menu li li a:active  { background-color:#fbff24; }
</code>
But If I check in my colors.css, my rule actually looks like this:
<code>#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation .block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish ul.sf-menu li li a:active  { background-color:#1b1b1b; }
</code>
I have tried to clear the caches and everything but that didn't help either, any recommendations? This is in Drupal 7.x with the Corporateclean theme.
Thank you!
Comment: Well, there is webserver's cache, proxy cache, browser cache, sometimes Boost cache, ngnx or varnish cache... it's hard to be sure you cleared them all.
Comment: @Molot, yes, I also used different browsers to confirm
Answer: Have you checked the css file route (Chrome will show that in the dev tool) that the website is reading? I use superfish as well, there are some css files for the menu bar in '.../sites/all/superfish/css/', but I also have my overriding style in my custom theme folder. Are you sure the browser is linking to the css file that you think it is linking to?
And, that happened to me once, probably is not your case, but I once forgot to save my css after editing it :P
Good luck.
Comment: I don't exactly understand what you mean with the file route, canyou be more descriptive please? I'm not using superfish thus, there's no /sites/all/superfish/ - should I be using superfish? directory for my site... I did save my css file! :)
Comment: If you're not using Superfish it seems strange that you have CSS rules like `#navigation .block-superfish`...
Comment: @Clive I do not have a module superfish installed nor have I ever heard of that module at all before this thread...
Comment: @the_summer_bee I now installed and enabled superfish just to see what's happening but I still don't have a /sites/all/superfish/ directory, in my /sites/all/ dir, there's only libraries, modules & themes... any other idea? Thank you!
Comment: Hi, where did you get the css file from then? did you write it, or is it come with any other themes or modules? It is not important whether or not you have used superfish. The key thing is, the css file you think you are using probably is not the one the website is actually linking to.
Comment: It is worth checking all the css files you have there and make sure you are editing the right one.
Answer: Added and configured Nice Menus - can configure the style sheets properly with that, unsure why that yellow wouldn't disappear...

style doesn't reflect what's in css


Is there a ranking metric based on percentages that favors larger magnitudes?

Question: I have two groups, "in" and "out," and item categories that can be split up among the groups. For example, I can have item category A that is 99% "in" and 1% "out," and item B that is 98% "in" and 2% "out."
For each of these items, I actually have the counts that are in/out. For example, A could have 99 items in and 1 item out, and B could have 196 items that are in and 4 that are out.
I would like to rank these items based on the percentage that are "in," but I would also like to give some priority to items that have larger overall populations. This is because I would like to focus on items that are very relevant to the "in" group, but still have a large number of items in the "out" group that I could pursue.
Is there some kind of score that could do this?
edit: I should add that I also know the total number of items that are in and out across all categories. I have a pretty complete picture of how many items I have, what categories they are in, and whether or not they are in/out.
Answer: You can simply calculate proportion of 'in',
$$
P = {n_{in} \over n},
$$
but - as per your question - it's better to add a correction for total number of 'votes'.
One way to correct is to add some dummy 'outs' (e.g. $10$), so
$$
P' = {n_{in}  \over n + 10 }.
$$
items with a large number of votes see their modified percentage alters very little from their real percentage, but items with relatively few answers will see their modified percentage move considerably toward low values.
This is known as "Bayesian averaging".
In effect, the items with many votes will rank higher than items with the same percentage but fewer votes.
In your example $P'_A=0.9$ and $P'_B=0.93$.
Comment: Wow, this is so simple. I was trying all sorts of crazy calculations with logarithms and entropy-like formulas, but this makes much more sense and works much better. Thank you!
Answer: I don't know if there is a "standard" way to do this, but one approach is to scale the percent of each category by the number of "in" or the size of the category. For example, you could multiply the percent in by:

size of category (equivalent to counting the number of "in")
sqrt(size of category)
ln(size of cateogry)

You would need to select a function (one of the above or some other) that is most appropriate for your application.


Invoke and include a separate .php from within a callback for a drupal 6 page

Question: I'm new to Drupal (v6) and PHP, and I'm trying to implement some content through a custom module.  I've followed a tutorial, and figured out how to make Drupal aware of my module and even registered a URL for my custom page.  It's appearing in the navigation as I intended -- so far so good.
This is great for my toy example... but less good for the page(s) I actually intend to write.  Right now I have this:
function twtevents_menu() {

  $items = array();

  $items['gingerbread'] = array(
    'title' => 'Gingerbread Gallery',
    'page callback' => 'twtevents_gallery_gingerbread',
    'access arguments' => array('access twtevents content'),
    'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

function twtevents_gallery_gingerbread() {
  // content variable that will be returned for display
  $page_content = '';

  $page_content = '
'.  t("Some super-cool content") .'
';

  return $page_content;
}

But I don't want to write a large, complex page in the style of $page_content = '
'.  t("Some super-cool content") .'
'; -- and on and on.
I want to write the actual page in a style closer to this:
<div class="comment<?php print ($comment->new) ? ' comment-new' : ''; print ' '. $status ?> clear-block">
  <?php print $picture ?>

  <?php if ($comment->new): ?>
    <?php print $new ?>
  <?php endif; ?>

<?php print $title ?>

Where php code is sprinkled into HTML markup, rather than the reverse.
From within my function, I can call include($path) successfully, but (of course) this approach just places the output of my page in the top-left cornet of the broser... I need to send the output of the separate page as the return of my callback function.
Is there a PHP function for this?  A Drupal function?  Best practices?
Answer: To use your custom template file in a module, you should provide your hook_theme implementation. Below there is an example from advanced forum module.
function advanced_forum_theme() {
  // ...
  $items['advanced_forum_topic_header'] = array(
      'template' => 'advanced_forum-topic-header',
      'arguments' => array(
        'node' => NULL,
        'comment_count' => NULL,
        )
  );
  // ...
  return $items;
}

This is how the hook is invoked:
  // Build the topic header
  $variables['topic_header'] = theme('advanced_forum_topic_header',
                                      $variables['node'],
                                      $variables['comment_count']);

The template file that contains the layout is advanced_forum-topic-header.tpl.php.
Some links for more details: "Using hook_theme to style module output", hook_theme description for Drupal 6.
Answer: As Kniganapolke says, you want a hook theme implementation to call a template;
Something like;
function twtevents_theme(){
    return array(
        'template' => 'twtevents_gallery_gingerbread',
        'arguments' => array()
    ); }

Then place your template code into a file called twtevents_gallery_gingerbread.tpl.php in your module folder.
Then update your page callback to call the theme function like this;
function twtevents_gallery_gingerbread(){
    return theme('twtevents_gallery_gingerbread');
}

Now here is the important bit - once you've added the theme hook to your module you must clear your Drupal cache, otherwise it won't find your new template.
Comment: Thanks!  Both answers were very helpful... wish I could "accept" both.  As a PHP/Drupal newb, it makes a big difference that your code examples are more tailored to my situation and more complete (showing the full twtevents_gallery_gingerbread() function).


fgets() feeds \n to the subsequent string, not taking input

Question: I'm trying to input names for an array of structures. Though this is working fine for the 1st iteration, in the 2nd iteration, the name string of the structure  object receives \n and I don't know why that is.
I've tried the fflush(stdin) as well but it doesn't seem to work out :/
struct employee
{
    char ac_no[20], name[30];
    float balance;
};

void getdata (struct employee *);
void getdata(struct employee *ptr)
{
    printf("Enter Name: ");
    fgets(ptr->name, 29, stdin);
    ptr->name[strcspn((ptr->name), "\r\n")] = 0;
    printf("Enter Account Number: ");
    fgets(ptr->ac_no, 19, stdin);
    printf("Enter Balance: ");
    scanf_s("%f", &(ptr->balance));
    fflush(stdin);
}

//In Main()
struct employee emp[5];
register int i;
for (i = 0;i < 5;i++)
{
    printf("\nEmployee %d: \n", (i+1));
        getdata(&emp[i]);
}

Comment: `fflush(stdin)` is UB, and you don't need to pass `sizeof(x) - 1` in `fgets`, just pass `fgets(arr, sizeof arr, ...);`: `fgets` reads characters from stream and stores them as a C string into str __until (num-1)__ characters have been read or either a newline or the end-of-file is reached, whichever happens first.
Comment: Doesn't work with gets() too, the subsequent structure entities are getting **\n** as the **name** string.
Comment: Don't use fflush(stdin). This won't work for the intended purpose.
Comment: @AlterMann yeah okay, I'll do that. But that doesn't solve the problem of "\n" being fed into the name of the structure objects that follow.
Comment: @GineetMehta, as I said `fflush(stdin);` is UB, try to consume/flush the trailing new line using `int c; while ((c = fgetc(stdin)) != '\n' && c != EOF);`
Answer: scanf doesn't consume \n, so \n is still in stdin and read by fgets in next iteration. fflush(stdin) is not in standard C, so the behavior is undefined.
You can consume the newline after scanf_s using getc:
...
fgets(ptr->ac_no, 19, stdin);
printf("Enter Balance: ");
scanf_s("%f", &(ptr->balance));
getc(stdin);


Search for keyword matches in one Dataframe contained in another Dataframe

Question: I have a dataframe A with values that were entered by humans, so they have a degree of variance even though they refer to the same keyword: foo001, foo1, 0foo1 all mean foo1.
I have this other dataframe B with keywords as an index and properties associated to them in different columns.
My goal is to go through every row of dataframe A, and if a match for a keyword is found, it adds to this row the properties found in the dataframe B corresponding to the said keyword.
Dataframe A :

index
col1
col2

1
bar
baz

2
foo01
boo

Dataframe B :

index
col1
col2

foo
fooprop1
fooprop2

bim
bimprop1
bimprop2

A match is found in Dataframe A, so it becomes :
Dataframe A :

index
col1
col2
prop1
prop2

1
bar
baz

2
foo01
boo
fooprop1
fooprop2

I can figure out how to find matches for those keywords using regex. But i can't find a nifty way to do the other part, that is without using loops and all.
Thanks in advance if you have suggestions !
Answer: This is my approach but you may change the part for similarity checking between strings of col1. I use fuzzywuzzy for similarity checking between strings and filter those who have score higher than 50:
import pandas as pd
import numpy as np
from fuzzywuzzy import process

df1 = pd.DataFrame({'col1': ['bar', 'foo01'],
                    'col2': ['baz', 'boo']})
df2 = pd.DataFrame({'col1': ['fooprop1', 'bimprop1'],
                    'col2': ['fooprop2', 'bimprop2']})
df2.columns = ['close_word', 'prop2']

# create a choice list
choices = df2['close_word'].values.tolist()

def find_closest(word):
    close_word = process.extractOne(word, choices)
    if close_word[1] > 50:
        return close_word[0]
    return np.nan

# apply fuzzywuzzy to each row using lambda expression
df1['close_word'] = df1['col1'].apply(lambda x: find_closest(x))

# merge
result = pd.merge(df1, df2, on="close_word", how="left")
print(result)

Output:
     col1 col2     close_word     prop2
0    bar  baz       NaN       NaN
1  foo01  boo   fooprop1  fooprop2

Comment: Thanks for your quick reply. Your approach is deceptively simple, i love it ! I didn't know fuzzywuzzy, this looks like it's doing quite the job here and it's less of a hassle than using regex. But what i struggled the most with was merging the dataframes. I did read how df.merge worked but i cleary missed some key information and thought it couldn't do what i wanted. I know the lambda function but tbh i never really know when to use it so it didn't occur to me in this case. Thanks again, i learned a lot again !
Comment: @pinbeu Woow ! That's a lot of positive energy! Well I'm glad that it was helpful :D


How do you make an errorbar plot in matplotlib using linestyle=None in rcParams?

Question: When plotting errorbar plots, matplotlib is not following the rcParams of no linestyle.  Instead, it's plotting all of the points connected with a line.  Here's a minimum working example:
import matplotlib.pyplot as plt

lines = {'linestyle': 'None'}
plt.rc('lines', **lines)

plt.errorbar((0, 1), (1, 0), yerr=(0.1, 0.1), marker='o')

plt.savefig('test.pdf')
plt.delaxes()

Is the only solution to explicitly set linestyle='None' when calling pyplot.errorbar()?
Comment: An annoying default matplotlib. Errorbar implies that data want to be plotted; and data are usually discrete and should not be connected with a line.
Answer: This is a "bug" in older versions of matplotlib (and has been fixed for the 1.4 series).  The issue is that in Axes.errorbar there is a default value of '-' for fmt, which is then passed to the call to plot which is used to draw the markers and line.  Because a format string is passed into plot in never looks at the default value in rcparams.
You can also pass in fmt = ''
eb = plt.errorbar(x, y, yerr=.1, fmt='', color='b')

which will cause the rcParam['lines.linestlye'] value to be respected.  I have submitted a PRto implement this.
Another work around for this is to make the errorbar in two steps:
l0, = plt.plot(x,y, marker='o', color='b')
eb = plt.errorbar(x, y, yerr=.1, fmt=None, color='b')

This is an annoying design decision, but changing it would be a major api break.  Please open an issue on github about this.
errorbar doc.
As a side note, it looks like the call signature was last changed in 2007, and that was to make errorbars not default to blue.
Comment: The argument `fmt=''` still plots the connecting line so it does not solve the problem.
Comment: @strpeter I have the same problem, I had to specify some marker at least, e.g. `fmt='.'`, then the line was finally gone, and I needed a marker anyway.
Comment: `MatplotlibDeprecationWarning`: Use of `None` object as fmt keyword argument to suppress plotting of data values is deprecated since 1.4; use the string `"none"` instead.
Comment: Thanks, I've opened an issue: https://github.com/matplotlib/matplotlib/issues/2366
Comment: Yes, indeed I know but it's supposed to work without any further argument as well if I understood it correctly. Sometimes having an additional marker is just confusing.
Comment: This did not work, so I also had to use a marker. I used `fmt=','` because `fmt='.'` is still visible behind the error bars.
Answer: Using: fmt='' indeed doesn't work. One needs to put something that is not an empty string.
As mentioned by @strpeter, a dot or any other marker would work.
Examples:
fmt='.'
fmt=' '
fmt='o'
Answer: Or use an empty linestyle:
plt.errorbar(x, y, yerr=.1, fmt=None, color='b', linestyle='')

This works for me in matplotlib version 3.3.3


Solving for probability with negative logits

Question: I have a multinomial logistic regression tutorial question asking to manually solve the logits and probability. When I calculate logit for both comparisons I get negative values. How do I continue and solve for P? The question part b asks, "What is the model's prediction regarding the classification of the movie?"
If my calculations give me model 1 P = 0.05599435837 and model 2 P = 0.01193858104 do I do P(Low) = 1 - (0.05599435837) - (0.01193858104) = 0.93206706059 to get the missing probability? So does 93% means the model's prediction is 93% that the movie will be classified as low revenue? 93% seems pretty skewed does it not?

I am writing my formulas as:
model 1 - Low vs Medium
Movie Success = constant + 5.316*LOpening - 0.003*Theatres + 0*Rating
Movie Success = -7.007 + 5.316*2.4893 - 0.003*3017 + 0*1
Movie Success = -7.007 + 13.2331188 - 9.051 + 0
P = -2.8248812
model 2 - Low vs High
Movie Success = constant + 8.128*LOpening - 0.002*Theatres + 0*Rating
Movie Success = -18.615 + 8.128*2.4893 - 0.002*3017 + 0*1
Movie Success = -18.615 + 20.2330304 - 6.034 + 0
P = -4.4159696
p.s. I noticed that SPSS says

b. This parameter is set to zero because it is redundant.

I was told I could therefore discard that value. That's why I have it as 0.
Answer: Logit is defined as
$$
\operatorname{logit}(p) = \log\left( \frac{p}{1-p} \right)
$$
where $p$ is a probability, logit itself is not a probability, but log-odds. It can be negative, since it potentially ranges from $-\infty$ to $\infty$. To transform logit into probability you need to use logistic function for binary classification, or softmax for multiclass classification.
Comment: So I calculated both probabilities. `P = e^-2.8248812 / (1+e^-2.8248812) = 0.05599435837` and `P = e^-4.4159696 / (1+e^-4.4159696) = 0.01193858104`. Do I just add those two together? `0.05599435837 + 0.01193858104 = 0.06793293941`? If the final `P = 67%` how do I report/express that? The probability that the move will have a low chance of success is 67%?
Comment: @TokyoToo that's not what I said. Obviously probability cannot be equal to 8.24, since probability needs to be something between 0 and 1. The values you are referring to are logits, to make probabilities of them, you need to transform them first.
Comment: I know they are logits. That's why I transformed them to probabilities. See my comment :)
Comment: You lost me in the calculations. Maybe this helps: https://en.wikipedia.org/wiki/Multinomial_logistic_regression ?
Comment: I took the two logits `-2.8248812` and `-4.4159696` and used `E ^ Ln[P/(1-P)]` to transform them to two probabilities `0.05599435837` and `0.01193858104`. Then I did `P(Low) = 1 - P(Medium) - P(High)` -->> `P(Low) = 1 - (0.05599435837) - (0.01193858104) = 0.93206706059` -->> `P(Low) = 93%`. Is this correct?
Comment: @TokyoToo check https://stats.stackexchange.com/questions/233658/softmax-vs-sigmoid-function-in-logistic-classifier/254071#254071
Comment: Yes, Multinomial logistic regression is known as polytomous LR, multiclass LR, softmax regression, multinomial logit etc. That's not the problem. I want to know if in my situation I am using correct calculation method. Thanks for the info Tim. I appreciate it. I will post a new question and ask a more explicit question specifically related to my calculations.
Answer: A logit isn't the same as probability, see the definition here.
There's no problem with a logit being negative, that just means the probability is lower than half.
In addition, I don't think you can calculate the logit of Low w.r.t. Medium and High together, because you'd need to know the joint probabilities. And in any case, your question doesn't ask for that.
here's a link to a bunch of videos about logits and logistical regression btw, if you want a bigger refresher and background.
Good luck with your assignment!


I2C_SLAVE ioctl() failing with ENOTTY when used in JNI shared library

Question: I am having a problem trying to use an I2C device in Android (Gingerbread) via JNI.
The problem is with the I2C_SLAVE ioctl call.  The following code works when compiled into a standalone program:
    int main(int argc, char *argv[])
{
    int fd = -1;
    long rc;
    int addr = 0x22;

  if ( fd  < 0 ) {
      fd = open(radio_device, O_RDWR);
  }

#define I2C_SLAVE 0x0703

  if ( (rc = ioctl(fd, I2C_SLAVE, addr)) < 0 ) {
      printf("RadioService: I2C slave addr failed! rc=%d errno= %d [%s]\n", rc, errno, strerror(errno));
  }
  else {
      printf("RadioService: I2C slave addr 0x%x set\n", addr);
  }

  return 0;

}

Output when run (via adb shell ):
~ # testi2c
RadioService: I2C slave addr 0x22 set

However, the same code does not work as part of a JNI library:
void Java_biz_lectronix_android_radio_RadioService_nativeInit(JNIEnv* env, jclass clazz)
{
    long rc;
    int addr1 = 0x22;
    int addr2 = 0x18;

    if ( fd = open(radio_device, O_RDWR) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C open failed! %s", strerror(errno));
    }
    else {
        __android_log_write(ANDROID_LOG_WARN, "RadioService", "Opened fd");
    }

    __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C_SLAVE [0x%x], addr = %d (0x%x)", I2C_SLAVE, addr1, addr1 );

    if ( (rc = ioctl(fd, I2C_SLAVE, addr1)) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C slave addr1 failed! rc=%d errno= %d [%s]", rc, errno, strerror(errno));
    }
    else {
        __android_log_print(ANDROID_LOG_WARN, "RadioService", "I2C slave addr1 %d set", addr1);
    }

    if ( (rc = ioctl(fd, I2C_SLAVE, addr2)) < 0 ) {
        __android_log_print(ANDROID_LOG_ERROR, "RadioService", "I2C slave addr2 failed! rc=%d errno= %d [%s]", rc, errno, strerror(errno));
    }
    else {
        __android_log_print(ANDROID_LOG_WARN, "RadioService", "I2C slave addr2 %d set", addr2);
    }

    return;
}

Logcat output:
01-02 03:03:10.904: E/RadioService(1602): I2C_SLAVE [0x703], addr = 34 (0x22)
01-02 03:03:10.904: E/RadioService(1602): I2C slave addr1 failed! rc=-1 errno= 25 [Not a typewriter]
01-02 03:03:10.904: E/RadioService(1602): I2C slave addr2 failed! rc=-1 errno= 25 [Not a typewriter]

Does anyone have any idea what could be wrong here?
Answer: Not actually a problem with the I2C interface at all.  The issue is this line:
if ( fd = open(radio_device, O_RDWR) < 0 ) {
It should be this (note parentheses):
if ( ( fd = open(radio_device, O_RDWR) ) < 0 ) {
So, the I2C device is opened, but the comparison has higher priority than the assignment in C. The comparison fails, assigning 0 to fd - which is stdin.
The ioctl() call then fails because I2C_SLAVE is an inappropriate ioctl command for the device.


Traversing directed graph breadth first with vertexes having longest paths first

Question: Given a directed graph of dependencies, I want to traverse this graph from the root node level by level (that is breadth first) however taking the nodes on each level in a certain order. In my case, the order of nodes on each level must be sorted after their depth taking deepest nodes first.
Simple example:
<code>A -> B
B -> C
A -> C
</code>
Starting at node A, I want the travseral to give me order A, B, C (and not A, C, B because B has C under it). No cycles.
Any hints much appreciated. I'm new to the excellent JGraphT library so may have overlooked some simple solution.
One way to solve this problem would be to:

Find all paths from root (A)
Sort the paths according to length  (tallest first)
For each path travers the nodes and put node in right place in a list.
The right place is determined by a linear search of list at first position where new node is not found in the list

But maybe there is already some built in algorithm, so I don't have to encode the above? :-)
Comment: Tricky question. Can you make this more precise? For instance, if there would also be the arcs A -> D and D -> C what order would you then expect? It would help if you would formalize what you want a little more precise in mathematical terms. Also, is it possible that your graph contains cycles?
Comment: Sure. If you add arcs A -> D and D->C, then the order expected is {A, B, C, D} or {A, D, B, C}. As long as a node is not listed before a node which has a dependency to it, the order is correct.

There can be no cycles.

This should be a fairly common dependency resolution problem. I want to serialize a bunch of objects (generating code) in an order that guarantees that an object being serialized does not depend on any other object that has not yet  been serialized.
Comment: Sorry, mistake: The correct orders with added node D are:
{A, B, D, C} or
{A, D, B, C}.
In other words order of B and D is irrelevant, either sequence is fine because they do not depend on each other.
Answer: It sounds like you can simply use a topological sort of your graph. In jgrapht you can accomplish this with the TopologicalOrderIterator
Comment: Great, exactly what I was after! TopologicalOrderIterator does the job.


Does this integral have a closed form?

Question: I was working with this problem in an exam:
Given $\lambda\in(-1,1)\subset\Bbb R$, find
$$f
   (\lambda)=\int_{0}^{\pi}\ln\left(1+\lambda \cos x\right)\mathrm{d}x
$$
My try: put $\delta\in (0,1)$ such that $\lambda\in(-\delta,\delta)$. Using the power series of $\ln(1+x)$ and uniform convergence to take $\sum_{n=0}^\infty$ outside $\int_{0}^{\pi}$, finally, I got this:
$$f(\lambda)=-\sum_{k=1}^\infty{(2k-1)!!\over (2k)!!}{\lambda^{2k-1}\over 2k}$$
But I still wonder if there is a closed form for $f(\lambda)?$ And is my solution above right or wrong?
Comment: @CWeid After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/).
Comment: Regarding my edit: You have given an "explicit" formula because it is not, for example, written as a recursion, or given by a functional equation. In fact, I would say that even the original integral is an explicit formula. The technical word for what you are looking for is "closed form".
Comment: @EricStucky Thank you!I learned from this
Comment: (Please, if you don't have some technical restriction that prevents you from doing so, *put a space after punctuation symbols*. It's very disorienting to see two sentences smashed together like that.)
Comment: The antiderivative of your integrand has a closed form (not very nice at all !); its value at x=0 can be computed but, at x=Pi, the value is indeterminate and I have not been able to find its limit.
Comment: For n > 1, the integral of Cos[x]^n is given by ((1 + (-1)^n) Sqrt[Pi] Gamma[(1 + n)/2])/(n Gamma[n/2]).
Answer: The answer to your integral is
$$
    f(\lambda) = \pi \ln\left(\frac{1+\sqrt{1-\lambda^2}}{2}\right)
$$
Now to derivation. Given that
$$
  \int_0^\pi \cos^n(x) \mathrm{d}x = \frac{1+(-1)^n}{2} \frac{\pi}{2^n} \binom{n}{n/2}
$$
Doing the series expansion of the integrand in $\lambda$ and interchanging the order of summation and integration yields:
$$
   f(\lambda) = -\pi \sum_{m=1}^\infty \left(\frac{\lambda}{2}\right)^{2m} \frac{1}{2 m} \binom{2m}{m} = - \pi \int_0^{\lambda} \sum_{m=1}^\infty \frac{x^{2m-1}}{2^m} \binom{2m}{m} \mathrm{d}x
$$
The sum equals
$$
   \sum_{m=1}^\infty \frac{x^{2m-1}}{2^m} \binom{2m}{m} = \frac{1}{x} \left(\sum_{m=0}^\infty \frac{x^{2m}}{2^m} \binom{2m}{m} -1 \right) = \frac{1}{x} \left(\frac{1}{\sqrt{1-2x^2}} -1 \right)
$$
Integrating this gives the answer.
Comment: I wonder if there is not a typo in your elegant formula. I checked numerically and I got the same numbers with opposite sign. Cheers.
Comment: I repeated your calculations and effectively arrived to $$
    f(\lambda) =  \pi \ln\left(\frac{1+\sqrt{1-\lambda^2}}{2}\right)
$$
Comment: @ClaudeLeibovici The derivation is confuse. It's not clear.
Comment: @FelixMarin. I must confess that I have been partly lost in Sasha's derivation. So what I did was to expand as an infinite Taylor series Log[1+X], then replace X by lambda Cos[x], integrate inside the summation and sum again. I so arrived to the same formula as Sasha's but with the opposite sign. I then confirmed my result numerically.
Comment: @ClaudeLeibovici Mathematica yields your result as the correct one. It's easy to check the sign when $\lambda \approx 0$: The result is $-\pi\lambda^{2}/4$. $\tt @Sasha$ result yields $\pi\lambda^{2}/4$.
Comment: I have fixed the incorrect overall sign. Thanks for pointing out the error.
Answer: Here is the outline of a solution using complex analysis.
For $a > 1$, the integral $J_a = \int_0^{\pi} \ln(1 + 2a\cos t + a^2) \, dt$ has the value $2\pi \ln a$, and this integral essentially reduces to yours for an appropriate choice of $a$, but with an extra constant term.
To calculate the value of $J_a$, you can show that it is really $\int_\gamma \ln(a + z)/iz \, dz$ where $\gamma$ is the unit circle, described counterclockwise. To do this, break the integral into the top and bottom semicircle, parametrizing both from $0$ to $\pi$, going from right to left on each semicircle. Then subtract the bottom integral from the top one to obtain $J_a$.
By the residue theorem, the integral is $2\pi i$ times the residue at $0$, which is $(\ln a)/i$.
An alternative way to compute $J_a$ is to calculate the exact value, using trigonometry, of a Riemann sum with $n$ equally spaced points. This turns out to be: $$2\pi \ln a + \frac{\pi}{n} \ln \left[ \frac{1 + a}{1 - a}(a^{-2n} - 1) \right]$$ which tends to $2 \pi \ln a$. This last calculation is carried out in full in Cours de mathématiques spéciales (1991) by Ramis, Volume 3, p. 207.
Here is an idea for a third solution, though I haven't carried out the details. Integrating under the integral sign gives
$$f'(\lambda) = \int_0^{\pi} \frac{\cos x}{1 + \lambda \cos x} \, dx.$$
Now compute the integral on the right (easier said than done), integrate the resulting function of $\lambda$, and use $f(0) = 0$ to find $f(\lambda)$.
Comment: I like your answer, with its various solution methods clearly outlined. I took on the task of carrying out the third idea :) See my answer below.
Answer: Cool question, with some nice answers.
Let's look at using the method suggested at the end of user117487's post, the Feynman trick of differentiating under the integral sign, which happens to be my favourite technique for integration. Note that
$$f'(\lambda) = \int_0^{\pi} \frac{\cos x}{1 + \lambda \cos x} \, \mathrm{d}x,$$
upon which adding and subtracting a certain integral becomes
$$
\lambda \, f'(\lambda) = \pi - \int_0^{\pi} \frac{1}{1 + \lambda \cos x} \, \mathrm{d}x.
$$
Let's evaluate the remaining integral, using the Weierstrass substitution
\begin{align}
t & = \tan \frac{x}{2}, \\
\cos x & = \frac{1 - t^2}{1 + t^2}, \\
\mathrm{d}x & = \frac{2 \,\mathrm{d}t}{1 + t^2}.
\end{align}
Then the integral is
$$
\int_0^{\infty} \! \frac{2 \ \mathrm{d}t}{1+\lambda+(1-\lambda)t^2}
$$
Let $$t=\sqrt{\frac{1+\lambda}{1-\lambda}}\ u,$$
then we have
$$
2\sqrt{\frac{1}{1-\lambda^2}} \int_0^{\infty} \! \frac{ \mathrm{d}u}{1+u^2} = \frac{\pi}{\sqrt{1-\lambda^2}}.
$$
From previously,
$$
f(\lambda) = \pi \log \lambda - \pi \int \frac{\mathrm{d} \lambda}{\lambda\sqrt{1-\lambda^2}}.
$$
The remaining integral is fairly standard, so we obtain
$$
f(\lambda) = \pi \log \left( 1 + \sqrt{1-\lambda^2} \right) + c.
$$
Using the fact that $f(0) = 0$ gives $c=-\pi\log 2$, and we arrive at the same result given by the other posters.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{\fermi\pars{\lambda}
=
\int_{0}^{\pi}\ln\pars{1 + \lambda\cos\pars{x}}\,\dd x:
\ {\large ? }.\qquad\lambda, \delta \in {\mathbb R}\,,
\quad\verts{\lambda} < \delta < 1.\quad}$ It's clear that $\ds{\fermi\pars{\lambda}}$ is an even function of $\ds{\lambda}$ and $\ds{\fermi\pars{0} = 0}$ such that
we calculate

\begin{align}
\fermi\pars{\lambda \not= 0}&=
\int_{0}^{\pi}\ln\pars{1 + \verts{\lambda}\cos\pars{x}}\,\dd x
=\half\int_{-\pi}^{\pi}\ln\pars{1 + \verts{\lambda}\cos\pars{x}}\,\dd x
\\[3mm]&=
\half\int_{\verts{z} = 1 \atop {\vphantom{\Huge A}\verts{{\rm Arg}\pars{z}} < \pi}}
\ln\pars{1 + \verts{\lambda}\,{z^{2} + 1 \over 2z}}\,{\dd z \over \ic z}
\\[3mm]&=-\,\half\,\ic
\int_{\verts{z} = 1 \atop {\vphantom{\Huge A}\verts{{\rm Arg}\pars{z}} < \pi}}
\ln\pars{\verts{\lambda}z^{2} + 2z + \verts{\lambda} \over 2z}\,{\dd z \over z}
\end{align}
  The zeros $\ds{z_{\pm}}$ of $\ds{\verts{\lambda}z^{2} + 2z + \verts{\lambda}}$ are
  given by:
  $$
z_{\pm} \equiv {-1 \pm \root{1 - \lambda^{2}} \over \verts{\lambda}}\,,\qquad
z_{-} < -1\,,\quad -1 < z_{+} < 0
$$

Then,
$$
\fermi\pars{\lambda \not=0}=
-\,\half\,\ic
\int_{\verts{z} = 1 \atop {\vphantom{\Huge A}\verts{{\rm Arg}\pars{z}} < \pi}}
\ln\pars{\bracks{z - z_{-}}\bracks{z - z_{+}}}\,{\dd z \over z}
+\
\overbrace{\half\,\ic
\int_{\verts{z} = 1 \atop {\vphantom{\Huge A}\verts{{\rm Arg}\pars{z}} < \pi}}
\ln\pars{2z \over \verts{\lambda}}\,{\dd z \over z}}
^{\ds{\pi\ln\pars{\verts{\lambda} \over 2}}}
$$

\begin{align}
&\color{#c00000}{\fermi\pars{\lambda\not=0} - \pi\ln\pars{\verts{\lambda} \over 2}}
\\[3mm]&=\half\,\ic\int_{-1}^{z_{+}}{\ln\pars{\verts{x - z_{-}}\verts{x - z_{+}}} + \ic\pi
\over x + \ic 0^{+}}\,\dd x
+
\half\,\ic\int_{z_{+}}^{-1}{\ln\pars{\verts{x - z_{-}}\verts{x - z_{+}}} - \ic\pi
\over x - \ic 0^{+}}\,\dd x
\\[3mm]&=\half\,\ic\int_{-1}^{z_{+}}2\pi\ic\,{\dd x \over x}
=-\pi\ln\pars{\verts{z_{+}}}
=-\pi\ln\pars{1 - \root{1 - \lambda^{2}} \over \verts{\lambda}}
=\color{#c00000}{-\pi\ln\pars{\verts{\lambda} \over 1 + \root{1 - \lambda^{2}}}}
\end{align}

$$\color{#00f}{\large%
\fermi\pars{\lambda}
=
\int_{0}^{\pi}\ln\pars{1 + \lambda\cos\pars{x}}\,\dd x
=-\pi\ln\pars{2 \over 1 + \root{1 - \lambda^{2}}}}\,,\qquad
\lambda \in \pars{-1,1}
$$
Answer: I have not been able to find the error but, numerically, your formula does not lead to the results provided by Sasha. Using your formula, it seems that the result of the infinite summation is
$$
    f(\lambda) =  \ln\left(\frac{1+\sqrt{1-\lambda^2}}{2}\right) / \lambda
$$
which is not correct.

Does this integral have a closed form?


Are these two sorting format exactly the same for dict sort in Python?

Question: x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
    print(x.keys())
    s1 = [item[0] for item in sorted(x.items(), key=lambda item: (item[1], item[0]), reverse=True)]
    s2 = [item[0] for item in sorted(x.items(), key=lambda item: item[1], reverse=True)]
    print(s1)
    print(s2)

The prints are:
dict_keys([1, 3, 4, 2, 0])
[3, 4, 1, 2, 0]
[3, 4, 1, 2, 0]

I usually use the 2nd way to sort a dict by value, but today I saw someone's else code to sort a dict using the first way.
Are they exactly the same thing? They look the same based on print outs.
Comment: Try `x = {1: 0, 2: 0}`. With this input, the results are _guaranteed_ to be different for python 3.7+.
Comment: So what's the difference?
Comment: The first one sorts the dict also by the key (in descending order), when there is a tie based on the value.
Answer: In this particular case, the results are identical because there is a bijection between the set of keys and the set of values. If several keys share the same value (example: keys 3 and 4 share the value 3) the results diverge, as here:
x = {1: 2, 3: 3, 4: 3, 2: 1, 0: 0}

Your code print:
dict_keys([1, 3, 4, 2, 0])
[4, 3, 1, 2, 0]
[3, 4, 1, 2, 0]

In s1 case, the dict is sorted on both values and keys so when 2 keys share a common value they are sorted too.

In s2 case only values are sorted. As sort algorithm is stable, when 2 keys  share the same value their relative order is kept in the result.