Trigonometry - Finding $\sin\theta$ when given only $\tan\theta$

Question: I need to find the $\sin\theta$ when I am only given $\tan\theta = 1.936$
Thank your for any help. I am just having a hard time when I don't have examples to refer to with step-by-step directions.  It's an online course. Some videos are helping but not for this particular example
thanks
More info :
Just asked to find the sin in decimal form which according to the answer sheet is 0.888
Comment: There are convoluted relations you can use to calculate it directly, but I advise you to find $\theta$, and then just take the sine of that.
Comment: Without a calculator or trig tables, find $\theta$ directly is not straightforward.  Whereas the "convoluted relations" ($sin \theta = \tan \theta*\cos \theta = \tan \theta *(\sqrt {1 - \sin^2 \theta}$) are absolutely straightforward.  I'd say do $\sin \theta = \sin (\arctan 1.936 [+ \pi])$ (which is just trivial definition) but I'd use the "convoluted relations" if an actual figure is required and we aren't allowed to access a calculator.
Comment: Hmmm... is there a reason all the answers are ignoring a potential negative value?
Comment: @fleablood You don't have access to a calculator or tables, and you still expect to be able to solve the quadratic equation $\sin \theta = \tan \theta \sqrt {1 - \sin^2 \theta}$?
Comment: Without a calculater to do trig tables.  Solving sin a = sin artan tan a is ... begging the question and one presumes avoids the purpose of the excercise or question.  $\sin a =\pm  \frac{1.936}{\sqrt{1 + 1.936^2}}$ is a perfectly acceptable answer.
Comment: $1.936=2-.064=2-8/125;1+1.936^2=1+4-32/125+insignificant\approx 4+93/125=4+18/25+3/125=4+4*4.5/25+15/725\approx(2+4.5/25)^2$. so $\frac{1.936^2}{\sqrt{1+1.936^2}}\approx\frac{2-8/125}{2+9/50}=\frac{500-16}{500+45}=484/545=97/109-1/545\approx\frac{10/11}{10/11}97/109\approx .88$
Answer: Draw a right triangle with one angle $\theta$ and the side adjacent to that having length !$1$.  By the definition of tangent, the side opposite $\theta$ will have length $\tan \theta$.
The length of the hypotenuse, by the Pythagorean theorem is
$$
\sqrt{1^2+\tan^2\theta}
$$
Now $\sin\theta$ is the ratio of the opposite side to the hypotenuse, therefore
$$
\sin\theta = \frac{\tan\theta}{\sqrt{1+\tan^2\theta}}
$$
When $\tan\theta=1.936$, this gives
$$\sin\theta = 0.888$$
Comment: $\pm 0.888$, yes?  Because sin and cos may be both positive or negative?
Answer: Try drawing a right triangle with legs of size $1$ and $1.936$. The hypotenuse will have length $h = \sqrt{1^2 + (1.936)^2}$. Now let $\theta$ be the angle of this triangle that is opposite to the leg of length $1.936$. It will follow that $\tan \theta = \frac{\mathrm{opposite}}{\mathrm{adjacent}} =\frac{1.936}{1} = 1.936$, and this is what it should be. Knowing all the side lengths of the triangle, and that your $\theta$ is one of the angles, you can now compute $\sin \theta = \frac{\mathrm{opposite}}{\mathrm{hypotenuse}} = \frac{1.936}{h}$.
Answer: $\tan^2 \theta =3.75$
$\dfrac{\sin^2 \theta}{\cos^2 \theta}=3.75$
$\sin^2 \theta=3.75 \cos^2 \theta$
$\sin^2 \theta=3.75(1-\sin^2 \theta)$
$4.75\sin^2 \theta=3.75$
$\sin^2 \theta=0.789$
$\sin \theta=\pm 0.888$
Comment: Kiran - why did you use tan2 ? Because yours looks straightforward so was just wondering the logic Thanks
Comment: And thank you to everyone answering !
Comment: What if $\theta$ is reflex, i.e. $\pi < \theta < 2\pi$ ?
Answer: Well the is the arctan function so that $\sin \theta = \sin (\arctan 1.936)$ or $\sin (\arctan 1.936 + \pi)$ but I'm assuming you are asked to find the calculated value without tables.
$\tan \theta = \frac {\sin \theta}{\cos \theta} = \frac{\sin \theta}{\pm\sqrt{1-\sin^2 \theta}} = k = 1.936$
$\sin^2 \theta = k^2(1 - \sin^2 \theta)$
$\sin^2 \theta(1+ k^2)= k^2$
$\sin \theta = \pm \frac {k}{\sqrt{1+k^2} }= \pm \frac {1.936}{\sqrt{1 + 1.936^2}} = \pm 0.888$
$\tan \theta > 0$ so $\sin \theta$ and $\cos \theta$ are both either positive or negative, i.e. $\theta$ is in the first or third quadrant.  But we have no way of telling which, so
$\sin \theta = \pm 0.888$ is as accurate as we can determine.
Comment: Is it reasonable to compute so many decimals when the input value is probably accurate to a thousandth ?
Comment: It was a cut and paste and the answer is absolutely not.  I was doing the lazy that it was electronic age thing where it's easier to simply list 12 digits and assume it's only accurate to 3 then to list the 3 digits only.  I'I'll fix.
Answer: Few posts mention the obvious
$$\theta=\arctan(1.936),\\\sin\theta=\sin(\arctan(1.936))\approx0.888.$$
Note that as the arctangent is undetermined to a multiple of $\pi$, the sign of the sine is undeterminate.
Comment: I mentioned it.
Answer: Arc tan supplies two angles separated bt $\pi.$(  They lie in first and third quadrants),  The sine of the first angle comes out as $+ 0.888,$ and the second one in third quadrant as $-0.888$


Is it really mandatory to practise sight reading at the piano?

Question: I have seen many questions & answers regarding practising sight reading the right way etc. But I couldn't find the answer to my question whether it is even that important to practise sight reading.
What I mean by practising sight reading is for example picking a random piece that you haven't played before which is below your level and practise sight reading everyday with random pieces like that. But is it even necessary? Don't you automatically develop your sight reading skills just by working on your pieces at your level, instead of  practising sight reading SEPARATELY  with random pieces?
Comment: Side remark to nuance the importance of sight reading. After years playing "classical" piano, I became a sight reading robot, just reading sheets and playing them back. I realized seeing my brother play jazz guitar (with either nothing or a basic key chart), that he was a musician (with deep understanding of harmonics), and I was not. So now 99% of what I do is play by ear and I can tell you that: I think I'm becoming a musician + my sight reading is better (since I now understand music better, reading it is also easier). My advice: focus on being a better musician, sight reading will follow.
Comment: After due consideration regarding all the answers to this thought-provoking question, please let us know what *your* final thoughts are!
Comment: What if all you did was play by ear with pieces at or below your level?
Comment: I am convinced that sight reading is indeed important and even fun when starting slowly.
Answer: Yes it is really important to practise sightreading. Being able to sightread well makes it much quicker to learn new pieces and eventually possible to play pieces reasonably well without having practised them at all.
Sightreading does improve simply by learning repertoire, but not that quickly. This is because you are only truly sightreading a piece the first time play through it. After that, you will have memorised at least some of the material, and are no longer sightreading in the strictest sense.
This is often a problem for pupils studying for instrumental music exams. Once they have memorised their pieces, and are "polishing" them, they are not really reading the sheet music while playing them, even if they are following the music to aid memory. For this reason I find it really important to ensure that pupils read and play a wide variety of new music alongside pieces they may be learning in detail for exams or performances.
Comment: You know, @aaaaaa, good teachers teach different pupils in a whole load of different ways, tailoring their approach to the interests and abilities of each pupil. But good teachers will also try to subtlety introduce ways to learn which their own experience tells them has great value, even if the pupil might find them more challenging and maybe less interesting. A good teacher will make something like sightreading fun, and encourage a pupil to stick with it, even if they can't immediately see the benefit.
Comment: I played cello growing up and I really wish teachers would motivate students to learn how the students themselves prefer to learn.  Most importantly teachers should make playing fun.  Nothing about sight reading is inherently important.  It all depends on what the student wants to get out of their experience, and personally I enjoyed playing a single piece for a long time and making it sound the way I wanted it to.  Sight reading was very uninteresting to me, especially the part where you play pieces at a lower level.
Comment: The easiest thing to do as a teacher, is to avoid doing any activities which a pupil finds difficult, and to only do things which they already enjoy. But this lets the pupil down in the long run. It's not the end of the world if you don't do lots of sightreading, but being able to do it will allow you to do things you aren't even aware of yet. I couldn't sightread well until my late 20s, and in fact it was teaching that VERY quickly improved my sightreading. I know that I would have had more opportunities available earlier if my reading had been better, and I don't want my pupils to miss out.
Comment: Ah, don't misunderstand me... Finding out what a pupil finds interesting, what kind of music they like, and yes, how they might like to learn, and what they want to achieve, is all part of good teaching. I'm just saying it's important not to cut off any possibilities too early by not encouraging the development of a broad range of musical skills. In fact, delivering this broad musical education in a way that coincides with a pupil's own interests is a side of teaching I find most rewarding, and ultimately effective.
Comment: Being able to quickly translate printed music into performance is helpful.  For some, sight reading is a useful part of that, but others might learn music better in other ways.  Learning a piece by sight reading requires three simultaneous processes: 1. Reading the score; 2. Playing the music; 3. Memorizing what one is doing.  Some people may be able to do #1 and #2 together, but after reaching the end of a piece of music remember nothing of what they just played.  Such people might learn music more effectively by studying it without trying to play it at the same time.
Comment: haha that does make sense.  I appreciate the explanation.
Comment: good points for sure - I just think exploring what motivates the student is a more valuable direction than presenting her with challenges meant to "help them in the long run".  If you're able to make these activities fun and motivating then that's incredible.  In the end, learning a skill should feel like gaining a hobby, not a job.
Comment: Church pianist here - I agree with @aaaaaa , I always hated sight reading. I was always much more interested in learning chords and music theory, which complemented my good aural ability. My teacher eventually got frustrated with my lack of practise on the sheet music she was giving me, and focused instead on making sure I learned every single scale, and optimizing the fingering for them. This is the reason I now can play any song put in front of me... _almost_ right away.
Answer: Mandatory, as in "commanded"? No, but if you see it that way, you'll resist it.
I'm a guitarist, and you probably know the joke, "How do you get a guitarist to stop playing? Put sheet music in front of him!" Accordingly, I neglected this skill until I was 50, to my detriment. My answer now is not that practicing sight-reading will make you better at...sight-reading. That's obviously true. My answer is that it will make you a better musician. There is almost no other way to compel yourself to work out fingerings for music you would never have imagined, or to connect these fingerings to music theory (i.e. to relate what is obviously an arpeggio in the written music to an arpeggio on the fretboard). You may be a native genius (IIRC Wes Montgomery didn't and George Benson doesn't sight-read); then again, you may not be. If you want some insight into how a Charlie Parker solo, or a Bach cello suite, is put together, get the sheet music and struggle with it.
As you get better at sight-reading, you'll begin to be able to play notes you've already scanned visually, while your eyes are already on the next measure. You will necessary internalize scales, arpeggios, etc. You will necessarily learn to shift positions, which you'd otherwise avoid.
I could have chosen to noodle on the blues scale from now into my golden years, but I realized I was getting bored. There's plenty of interesting music out there...in written form. Learn to read it.
Comment: I love that joke.  Like the one about clearing out a room by having the bassist solo.  Of course neither is true.
Answer: Reading in general, and sight reading specifically may never be used by some players. If you are playing in a band where you are writing all the parts and don't plan to play in another setting then maybe reading isn't going to be on the top of your list of things to practice.
But if you want to be good at sight reading the only way to practice is to read stuff you have never seen before, or haven't played to the point of memorization.
Think of this, when you were first learning how to read (books not music) you had to sound out each word. Once you learn a word well enough you can just look at it and know what it is. Now when you read for the most part you just know most words. However, sometimes you come across a word you have never seen and you will need to sound it out. If you do this enough times you no longer need to sound the word out, you can just see that it is the word. Sight reading is sounding out the words in real time. If you do it enough you learn that word. This is different that memorizing a speech or a poem. It is learning the ability to recognize that word at first glance.
If you ever want to be a studio musician, or sub for an orchestra player, or countless other settings, it will be very beneficial to learn how to sight read.
As far what you say when you say:

practicing sight reading is for example picking a random piece that you haven't played before which is below your level and practice sight reading everyday

This indicates to me that your sight reading level is below your playing level. I think each player may have different levels in different areas. Some players can't read but are great at improvising. Some can sight read very well, but can't improvise. Sounds to me that your sight reading level is below your playing level. If you want to improve your sight reading to catch up to your playing, then you need to practice sight reading. If you are weak in reading in general, sight reading will help with that BUT reading the same piece over and over might not necessarily help your sight reading beyond a very basic point because you have memorized the "works" only in that very setting. To sight read you need to test those words out come at you in a setting you have never seen before.
Hope this helps.
Comment: @b3ko I have a similar question: is it possible to have a sight reading level equal to you playing level?? Sounds counterintuitive, because I think one can always play very difficult and fast parts that he could never sight read. This would mean the playing level is always better than sight reading level, right?
Comment: There's a demand for high-level pianists who are red-hot sight-readers though.  They work in orchestras, recording studios, as staff accompanists etc.   John Ogden was amazing.  I met him a couple of times, heard him play a few more.  He was sometimes criticised for the music seeming to go straight from his eyes to his fingers, by-passing his brain and emotions.  Well, maybe.  But he certainly played all the notes!
Comment: If you are a working musician that pays the bills by playing gigs every tool in your tool box puts a dollar in your pocket. It would be bad to turn a gig down because your site reading wasn't up to par. That being said if you dedicate your practice time to something else you can maybe get gigs with that skill. You have to judge what your goals are and practice what makes the most sense to achieve those goals.
Comment: @stallmp think of the hardest thing you can play. If someone wrote a a piece that was just as hard could you site read it? If not start off easier. If you want to read two hands practice two hands. If that's too hard start with one and work your  way up.
Comment: That really helped, thanks. I have one question though: isn't it normal to practise sight reading with easier pieces since you haven't played them before? Or should you actually practise sight reading with pieces on your own level? And also, when sight reading pieces do you instantly try to play the left hand and the right hand?
Comment: See my comment to the answer above.  Yes, I think my sight reading level is pretty close to my playing level.  But then I don't spend my live playing highly technical music.  I don't think many concert pianists sight-read a difficult new work.  John Ogden might have.  He had a very special mind.  Read about him:  https://en.wikipedia.org/wiki/John_Ogdon
Comment: @LaurencePayne - when you think about it, concert pianists don't really have the need to sight read. It's not a skill that they'd use, particularly. Their skill is in being able to learn and interpret pieces, perfectly, and remember them for the concert. Being good sight readers may save them some time, but I don't think it's something they would consider paramountly important.
Answer: One thing that may not be obvious at first is that you will need to use sight reading skills at random times. You'll sometimes be the only musician in the room and there will be a call to play some hymn, or national anthem, or locally-important-piece-of-music, you will be chosen. I'm not even a professional musician but I've been call upon to do such things as sight read a Gilbert & Sullivan score so the singers could practice (takes to long to describe the circumstances.) Once, my mother had to fill in for a concert pianist who suddenly took ill on the day of a performance. She got to sight read a concerto without the benefit of rehearsal with the orchestra; the bragging rights still linger.
Sight reading only takes practice; it's no worse that learning a piece from memory; it's just a different skill. You will use it.
Answer: It is my opinion that sight reading is a byproduct of a knowledge of music theory, having a trained ear that knows where the music is going and a solid technique so you don't have to think about how to play what you are trying to play.
When sight reading, most of us are not seeing EVERY note.  Our brains can fill in the gaps when we combine theory and ear training.  For instance, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm.
So no, you don't need to practice sight reading.  It will happen when everything else falls into place.
Although, some people have a fear of making mistakes and are obsessed with reading every note.  Those who are a slave to notation never become good sight readers.
You can improve your sight reading by laying by the pool, transcribing music in your head.  But, if you are like me, you'll fall asleep in two minutezzzzzzz . . .
Answer: If you want to get good at sight reading, practice sight reading.  Preferably get yourself in a situation where you HAVE to sight read, like playing the song for morning assembly in a school, or the hymns at a church.
Maybe YOU have no need for sight reading skills.  But I doubt it!
Comment: Like I said, just do lots of it.  This can be hard to arrange artificially, I agree.  I'm good at sight reading (I joke that 'if I can't sight-read it, I probably won't ever be able to play it', but there's some truth there) because I continually HAVE to sight read.  Of course, one could ask how I got jobs where sight reading is required without being expert already :-)  That applies to lots of jobs where experience is paramount.  I guess you just bluff your way in and get expert pretty fast!
Comment: I've yet to find effective ways in which to 'practise sight reading'. Holy grail?
Comment: @LaurencePayne i gave you an upvote because i think your answer is spot on for the most part. I do disagree with the last sentence. There are plenty of musicians out there that don't read at all or are very poor at site reading. *I* happen to think it is a good skill to have no matter what, but i also played in bands for 10+ years and never had to read in that setting. it totally depends on what setting you are playing in.
Comment: Indeed.  And my last sentence referred to "jobs where sight reading is required".
Answer: Practising sight reading alone isn't that satisfactory in the progress department. Certainly read through stuff below your level of playing, both with just rhythm, l.h. and r.h. and together.
Problem with doing it alone is that you won't know if you're getting it right. With someone to guide you, it's a very different situation.
Mandatory? Who knows? To get full marks in the sight-reading section of exams, of course. To be able to hear something and play it back? No help. To be able, eventually, to play anything in any style, with the dots in front of you? Way too obvious an answer!.
It's up to you. Want to become a fully rounded player and musician? Better buckle down to it. You probably learned to read words so long ago, you can hardly remember doing it. Ask the simple question, do you regret learning how to?
Answer: While I can't answer for the piano, I can say that as a classically trained vocalist, the ability to sight-read music is invaluable.
If you talk to any of the members of any professional singing groups around, you'll find that they might not have the most beautiful voice of any of the people who auditioned for their parts, but the ability to sight-read through music got them the job.
Answer: Nothing in life is "necessary" except death and taxes.
There is a bit of opinion to this.  Sight reading has two purposes (both really the same, to be literate).

To learn pieces by reading the score for the piece.  For this type of work it is not necessary, expected, or even possible for some musicians to read through a piece first time without mistakes.  A concertmaster or soloist could spend a year or more (estimate) working up a set of pieces for performance.
To read on the spot if a job calls for it.  If you get called to sub in a pit or similar type of gig you may get a short time to read through the music score.  On occasion you may have read through a new piece on the spot (I've been there).

Reading random new pieces is great training for the second scenario.  It is absolutely NOT necessary and you are right in your statement that by reading anything you are getting a work out at reading.  Some musicians may develop good sight reading habits and skills w/o the type of training you are asking about, but for many this does help.  Especially on instruments where there are several options for playing the same voicing of a chord or melodic pattern (like the guitar).
On a completely different note, literally reading music out loud but reciting the letter names is a technique that improves sight reading overall.
Answer: If you want to be able to sight-read, it is important to practice it. It is not something that must be done every day, but periodically take out music that looks "readable" and play it. As a pianist, my ability to sight-read has served me extremely well. I work primarily as an accompanist, and my sight-reading ability cuts down on my total practice time a tremendous amount. When I can get 80-100% of the notes correct the first time, it does not take long to polish off a new piece.
I started practicing sight-reading at age 5 or 6 when my piano teacher started randomly pulling out new pieces for me to try which weren't part of my regular practicing for the week. Later on in my teens, I would pull out songs for fun that I just wanted to "try", whether it was some rock-song arrangement or some Mendelssohn. Being able to read new stuff quickly allows you to assess a piece and decide if you like it enough to polish it, even if you don't need the skill for a job like I do. It also means that you don't have to be dependent on others to play it for you (in person or via recording) to get a sense of how it goes.
As has been mentioned above, a knowledge of theory helps tremendously. I do not really read every single note. I see the patterns of chords and intervals and that helps me quickly process what's on the page.
I also would say that sight-reading doesn't do much of anything if you do not know your instrument well enough to find the notes quickly. Scales and chords (block and arpeggio, all inversions.)  Over and over and over. Your hands need to be able to feel the patterns automatically when you see them on the page.
Answer: Trying to learn to sight-read on the piano as a kid is one of the reasons I no longer enjoy playing the piano. I don't believe you should feel any pressure to learn to sight-read unless you want to. I know it's in exams but I don't care, enjoying what you do when you play piano is far more important.
In my opinion, it's far more fun, social, and useful to learn to improvise than to sight-read. Improvising is rewarding in-the-moment, and to make it sound better when you have no-one else to play with, you can just pick one of millions of backing tracks on YouTube and jam along. It might feel awkward at first if you've never done it before, but eventually it gets really relaxing to do this.
Improvising for long enough will eventually naturally lead to an interest in keyboard harmony. Keyboard harmony is being able to play chords to accompany a melody (either sight-read or improvised) in real time. It is incredibly useful, challenging, and more focused than a vague 'practise sight-reading' instruction.
Knowing keyboard harmony will ironically lead back to knowing how to sight-read in a much more effective way: you'll be able to eventually identify chord structures along a whole bar or even line at a time at a glance. This will mean you don't have to sight-read by going note-by-note (which is like reading language by reading letter-by-letter, you'll never be able to go quick enough). Chords are the words in music and chord sequences are the sentences. It was only after knowing a bit about chords that I ever became marginally less hopeless at sight-reading.
I found it far more rewarding to study harmony, both on paper and at the piano, than I ever did forcing myself to pick up a random piece a day and fail at playing it.
Comment: The word "fail" is important here. It's unfortunate that you felt like you were failing at sightreading. Sightreading is a hard skill to start with. So, it is not a failure to sightread less than perfectly; it is an *achievement* to sightread at all. I prefer to always talk about sightreading in really positive terms e.g. "wouldn't it be great to play something you like without hours and hours of practice?", "wouldn't it be great to play straight away with other musicians?"
Comment: Your penultimate para. gets close to it. By understanding and knowing harmony, sight reading gets easier. Look along the line of a new piece - just by hearing the melody, you'll get close to whatever harmony will be there, it's often just the voicing that won't be the same as your interpretation.  Your 2nd para.:in order to improvise, the melody needs to be known - learned, often. Once you can sight read, you can pick up anything - the world is your oyster. No need to have to hear something first. Makes sense?
Comment: BTW, should have said, I'm a harmony nut too, so completely share your enthusiasm! And I totally agree that having a knowledge of harmony helps one to read and play music. But, in fact, most of the varied aspects of music knowledge reinforce each other, so an open mind about all of these different ways of practising can lead to a greater level of skill, understanding and enjoyment across the board.
Answer: Yes
It is mandatory. There will be penalties.
:)


How to understand Bayesian statistics?

Question: How can one easily and quickly grasp the idea of Bayesian statistics and modelling? I can understand the Bayesian theorem on conditional probabilities, I understand how frequentist statistics works (test statistics, p-values, hypothesis testing...), I understand some ideas of Bayesian statistics, but how does Bayesian inference work (technically) - that's still a little mystery to me.
Comment: A lot of introductory lectures on [Bayesian inference](http://en.wikipedia.org/wiki/Bayesian_inference) can be found with Google. As it stands, your question is very broad and is likely to gather a collection of links to such tutorials. What are you interested in: How do the frequentist and bayesian approaches compare each other (e.g., when interpreting a p-value)? When to use one or the other? Please, add any details that might help to refine your question.
Comment: @chl, thanks. I updated the question. I already understand things like [this](http://stats.stackexchange.com/questions/2356/are-there-any-examples-where-bayesian-credible-intervals-are-obviously-inferior-t/6431#6431), but not how it actually works. Thanks, Tomas
Answer: One very famous statistician has a short PowerPoint presentation at
http://www.stat.ufl.edu/~casella/Talks/BayesRefresher.pdf
explaining the difference between the Bayesian and frequentist approaches.
If you need an application to understand what is going on with the Bayesian
techniques, an excellent article entitled "Basketball, Beta, and Bayes" written
by Matthew Richey and Paul Zorn in Mathematics Magazine, Vol. 78, No. 5 (Dec., 2005), pp. 354-367 can clear up any confusion.
Comment: Thanks for a good presentation, it was (partially) useful :-)

How to understand Bayesian statistics?


Add text label to d3 node in Force directed Graph and resize on hover

Question: I am trying to add text label to nodes in d3 Force Directed Graph, there seems to be an issue.
This is my Fiddle:

When I add the node name like this:
<code>node.append("text")
    .attr("class", "word")
    .attr("dy", ".35em")
    .text(function(d) {
        console.log(d.name);
        return d.name;
    });
</code>
There's no change but the names are getting logged.
When i tried using bounding box , the node labels appeared but the nodes are stacked up on the top-left corner of box while the node links are fine.This fiddle is the outcome of that effort i put in. Can anyone tell me what am i doing wrong?
Answer: You are adding a text element inside a circle, that won't work. You can add groups under the svg element and then append the circle and a text in each group:
<code>// Create the groups under svg
var gnodes = svg.selectAll('g.gnode')
  .data(graph.nodes)
  .enter()
  .append('g')
  .classed('gnode', true);

// Add one circle in each group
var node = gnodes.append("circle")
  .attr("class", "node")
  .attr("r", 5)
  .style("fill", function(d) { return color(d.group); })
  .call(force.drag);

// Append the labels to each group
var labels = gnodes.append("text")
  .text(function(d) { return d.name; });

force.on("tick", function() {
  // Update the links
  link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

  // Translate the groups
  gnodes.attr("transform", function(d) {
    return 'translate(' + [d.x, d.y] + ')';
  });

});
</code>
A fork of your fiddle with this strategy is here
Comment: Pretty much what i wanted, had to edit a bit for the re-size on hover .Thanks a lot.
Comment: Using `call(force.drag)` on `gnodes` would allow the user to drag the labels or the circles (everything under the groups), whereas using them in `node` only allow to drag the circles.
Comment: I know this post is old, but note that .call(force.drag) should be on gnodes, not node.
Comment: Where do I put the exit().remove() call? You need to have that in order to update the graph
Comment: Either before or after the `force.on('tick', callback)` call, probably inside teh `drawGraph` function on the original fiddle http://jsfiddle.net/draditya91/RRUzZ/


Support function of closed convex set and subset

Question: Let $B$ be a closed and convex subset of $\mathbb{R}^n$. Define the support function of $B$ as $S_B(y)=\sup\{y^T x \mid x \in B\}$. Can we say that $A\subseteq B$ if and only if $S_A(y)\leq S_B(y)$ for all $y\in \mathbb{R}^n$?
The forward direction is trivial. For the reverse, we can say that if $x\in A\setminus B$ then we can find some $a\in \mathbb{R}^n$ that strictly separates $x$ and $B$. Then $S_A(a) \geq a^T x > a^Tz$ for all $z \in B$. Now if $B$ is also bounded (that is $B$ is compact) then we have a contradiction since the supremum in the definition of the support function of $B$ becomes maximum and then we would have $S_A(a) > S_B(a)$. The same argument does not work when $B$ is not assumed bounded because the strict inequality becomes non-strict when taking supremums. So we can only conclude that $S_A(a) \geq S_B(a)$ and we somehow have to rule out the equality case.
Is the result even true when $B$ is just closed? If yes, how can one proceed with the proof? If not, is there a counterexample?
Answer: Since $B$ is closed, its complement is open. Take $x \in B^c$, then there is $\rho>0$ such that $\{ z: \ \|x-z\|\le \rho\} \subset B^c$. Then separate the ball and $B$: there is $a\ne0$ such that
$$
a^Tz \ge a^Ty
$$
for all $y\in B$ and $z$ with $\|x-z\|\le \rho$. Set $z:= x  - \frac\rho{\|a\|}a$. Then
$$
a^Tx - \rho \|a\| \ge a^Ty,
$$
which implies
$$
a^Tx \ge S_B(a) + \rho \|a\|,
$$
and if $x\in A\setminus B$ then $S_A(a) \ge a^Tx \ge S_B(a) + \rho \|a\|$.


Google Analytics: Page views but no sessions? No page visits but positive avgTimeOnPage?

Question: I am new to GA and need help interpreting the results.  I built a simple report that shows username, # of sessions, # of unique page views, and average time on page.  I am seeing some odd results that I can't explain.

I have users that have 0 sessions but positive unique page views.  How can this happen?  Doesn't visiting a page automatically initiate a session?
I have other users with 0 sessions, 0 page visits, but a positive avgTimeOnPage.  I am at a loss to explain this.  Any ideas?

Thanks!
Comment: Does this happen when you look at your AdWords campaigns in GA or from Analytics reports directly?
Comment: I voted to move this question to the respective forum, due this question is not related to programming
Comment: I'm pulling the GA data via the API.
Answer: This can be a tricky question, this can happen due to 2 reasons:
1 .- If you are mixing different scope you can have reported with an unexpected Behaviour. For example, if you're using the dimension as Pagepath (a hit Scope) with Sessions metrics (Session Scope), this can give you page with no sessions due to the query on the database only take the first element on the sessions. In that way, the totals of sessions matches with all the other reports, in other way this report becomes incomparable. Think that is an object behind. There is an easy post explaining what happens.
https://help.analyticsedge.com/googleanalytics/misunderstood-metrics-sessions-for-pages/
2.- There is a second issue that can cause this but is way less common, that is sent only a non-interaction hit with no pageview, this can cause creations of sessions will


How to change the plot.background in Donut ggplot graph?

Question: How to change the plot.background in a 'geom_rect()' + 'coord.polar()' in a Donut ggplot graph?
I dont know what I´m missing, but I´w working in html black background style and needing to set panel as well plot background to black, but the graph sides of my ggplot are white and I need to know which attribute or command I need to use to turn sides to black too.
Below my code:
my_df %>%
  ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
  geom_rect() +
  geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
  coord_polar(theta="y") +
  xlim(c(2, 4)) +
  theme_void() +
  theme(legend.position="none",
        plot.background=element_rect(fill = "black"),
        panel.background = element_rect(fill = "black"),
        panel.border = element_blank(),
        legend.key = element_blank(),
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        panel.grid  = element_blank())

Below the resulted graph (see the "white" sides at right and left I need to fill with black)
Comment: Hi, thanks for your comments. This is not the way. And if you click in the image you see what I mean with the stripes.
Comment: Sorry. My fault. Now I see what you mean.
Answer: The problem here is that ggplot by default calls grid::grid.newpage before drawing. This creates a blank (white) screen. It will then set up a square viewport to fit your plotting window because you are using coord_polar. Once it has done this, it considers the square area to be "the" plotting window. In a sense then, ggplot has no knowledge or control over these white areas. No theme element can touch it.
The solution is to explicitly call grid.newpage yourself, draw a black background manually, and then explicitly print your ggplot using the parameter newpage = FALSE. You could alternatively set the grid gpar parameters so that the background is black by default, but this is likely to have undesired side effects later on.
Here's a reprex with some made-up data:
my_df <- data.frame(max = c(160, 320), min = c(0, 161),
                    ResultCode = c("A","B"),
                    labelPosition = c(80, 240), label = c("A", "B"))

p <- my_df %>%
  ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
  geom_rect() +
  geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
  coord_polar(theta="y") +
  xlim(c(2, 4)) +
  theme(legend.position="none",
        plot.background =  element_rect(fill = "black", color = "black"),
        panel.background = element_rect(fill = "black", color = "black"),
        plot.margin = margin(0,0,0,0),
        panel.border = element_blank(),
        legend.key = element_blank(),
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        panel.grid  = element_blank())

grid::grid.newpage()
grid::grid.draw(grid::rectGrob(gp = grid::gpar(fill = "black")))
print(p, newpage = FALSE)

Comment: Thanks a lot @Allan Cameron!  Yes, I was expecting the problem would be something like that and would depend on grid to work around. Same time I was curious if ggplot would have some specific setting for that.


Petals for points near the origin

Question:
Let $P(z)=-z+z^{p+1}$ where $p$ is a positive integer.  How many petals does $P$ have at the origin?

From a few examples in my notes, I noticed the following:

$-z+z^{14}$ has 13 petals.
$-z+z^3$ has 4 petals.

I'm not able to find a proof of the result above, but I am able to deduce that there are:

an $2p$ petals if $p+1$ is odd
if $p+1$ is even then there are $p$ petals.

Could you provide some intuition, or a sketch of the result?
There is a theorem I'm leaning on to get some information:

Let $R$ be a rational map and suppose that $R(z)=z+az^{p+1}+...$ near the origin.  Let $\Pi_j$ be the petals of $R$ and for each $j$ let $F_j$ be the component of the Fatou set that contains $\Pi_j$.  Then $R^n(z) \to 0$ and $\arg R^n(z) \to 2\pi k/p$ on $F_k$ and $F_0,...,F_{p-1}$  are distinct components of the Fatou set.

But using this theorem, it only shows me that there should always be $p$ petals (ex, there is a petal in between every $\frac{2\pi k_i}{13}, \frac{2\pi k_{i+1}}{13}$).
Besides getting a sketch of the proof, I have one more questions:

In the even case, there is an overlap between attracting or repelling petals?
Comment: The theorem that you are leaning on, called the Leau-Fatou flower theorem, doesn't apply directly to your case because your coefficient of $z$ is -1, rather than 1. If $f(z)=-z+z^{p+1}$, you can apply the theorem to
$$F(z) = f(f(z)) = -(-z+z^{p+1}) + (-z+z^{p+1})^{p+1} = z-z^{p+1} + (-z+z^{p+1})^{p+1},$$
which has the same Julia set as $f$. Now, if you expand the $(-z+z^{p+1})^{p+1}$, term, the first term will be $(-1)^{p+1}z^{p+1}$, which will cancel with the $-z^{p+1}$ term precisely when $p$ is odd. Thus, you'll only have $p$ petals when $p$ is even.
Comment: https://en.wikibooks.org/wiki/Fractals/Multibrot_sets#z.5En_.2B_m.2Az
Answer:
Let $P(z)=z^{p+1} - z$ where $p$ is a positive integer.  How many petals does $P$ have at the origin?

In the parabolic case critical orbit looks like n-th arm star
Arms tend to attracting directions near fixed point. Number of attracting petals is equal to n.
So I have checked critical orbits using this Maxima CAS script. Here are examples for p=2 and p=13

My results are listed below:

p = 1  ( degree =  2) there are  2 petals
p = 2  ( degree =  3) there are  2 petals
p = 3  ( degree =  4) there are  6 petals
p = 4  ( degree =  5) there are  4 petals
p = 5  ( degree =  6) there are 10 petals
p = 6  ( degree =  7) there are  6 petals
p = 7  ( degree =  8) there are 14 petals
p = 8  ( degree =  9) there are  8 petals
p = 9  ( degree = 10) there are 18 petals
p = 10 ( degree = 11) there are 10 petals
p = 13 ( degree = 14) there are 26 petals

so:

for p odd there are 2*p petals
for p even there are p petals
Answer:
In the even case, there is an overlap between attracting or repelling petals?

It depends what definition of petal you use.  There is no unified definition of petals.
Petal of a flower can be :

attracting / repelling
small/alfa/big/

Small attracting petals do not ovelap with repelling petals, but big do.
One can choose overlapping ( red) or not ( yellow)  petals

Petals for points near the origin


Treinamento de imagens no tensorflow

Question: Boa noite!
Eu estou tentando construir uma rede neural em python utilizando tensorflow e suas demais bibliotecas, minha dúvida e, eu tenho 4 classes e preciso fazer um treinamento delas tenho muitas imagens para cada classe, preciso usar a rede neural CNN já entendo modestamente como ela funciona. Eu precisava programar montar ela em python usando tensorflow alguem algum exemplo? Simples em python pois eu precisava gerar o arquivo dataset ou pb (protoboof) para isso sei que pode levar dias o treinamento em fim minha maior dificuldade e iniciar a programação em python da rede CNN.
Alguem tem algum exemplo? Todos que existe na internet eu vi mas quase miguem tem tutorial ensinando como gerar um arquivo dataset todos os tutoriais ensinam com datasets baixados de websites como ImageNet, Incept, e Mnist. O que eu preciso e de um simples exemplo de como gerar dataset de minhas próprias imagens
Também da Li os videos do  Iris data (classificação de flores) mas ele também trabalha com informações já prontas.
Abraços!
Comment: No caso o problema seria colocar as imagens na array para treino?
Answer: Você pode usar esse modelo com tensorflow-hub (https://github.com/tensorflow/hub/tree/master/examples/image_retraining).
Com esse modelo você pode executar várias manipulações, inclusive incluir um novo dataset.
Basta executá-lo com as linhas de comando
python retrain.py --image_dir "caminho do diretório onde estão suas pastas com imagens"
O algoritmo já vai separar conforme a estrutura das suas pastas, após treinado basta usar um classificados de imagens para testar novas imagens.

Treinamento de imagens no tensorflow


Junit Test Method

Question: I have always a confusion about the Methods  in Junit.

If someone is asking whether can I make a test method Private/Protected in Junit, So is he talking about the Method which should start with test or any other method like setup() , teardown() in Junit.
What is the return type of Junit Method. So I have always seen the return type use to be Void so can we change the return type?
Now sometimes the question will come like can I test a Private method Using Junit. So as much I know Junit by default call the method which will start with test and it should be Public then only It will be able to call outside of the class using Junit. So if I declared a test Method as private how Junit will call it or test it outside of the class.
Answer: 1) Your test methods should be public.
2) return type is always void.
3) You don't test private methods you test the public methods in your class, which will in turn presumably call the logic within your private methods. You should try and cover all the branches of code within these private methods too.
Comment: Thanks for the Response. Specially for 3rd Point. Now No confusion. :)
Comment: You can [test private methods in Junit](http://stackoverflow.com/questions/34571/whats-the-proper-way-to-test-a-class-with-private-methods-using-junit), but it's a bad practice.
Comment: @gkiko Cheers for the link you provided I had not seen the question before, some great content there.
Answer: From org.junit.Test annotation docs
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case
Answer: For testing private methods, I recommend making them protected or package protected. Then you can create a subclass that overrides the method and test it.
I have seen many posts stating flatly that you MUST not test private methods. I cannot imagine less useful straitjacketing. If you are trying to refactor your code, you are obligated to yourself and everyone around you to create a set of tests that ensure that the functionality is preserved before you even start changing the code. With regression problems properly fenced in, you can then start refactoring/retesting/refactoring.
Similarly, internal methods often are the places where fault recognition or recovery are done. Testing of those methods requires that proper firewalling of data is performed and that "impossible" situations are recognized. Recovery operations should also be checked to see that they handle "impossible" situations as well.
Using reflection to test private methods is a last resort, but it may be necessary if you cannot change the class under test or if you have orders from management. The "bad practice" is that you are violating encapsulation. However, encapsulation is only of concern to blackbox testing; the process of whitebox testing involves finding out if ALL of your code works, not just the visible stuff.

Junit Test Method


How to solve $\lim _{x\to \infty }\left(\frac{\sqrt{3x+2}}{x\sqrt{x+6}-\sqrt{x^3+2x}}\right)$?

Question: I have a problem with this limit, i have no idea how to compute it.
Can you explain the method and the steps used?
$$\lim _{x\to \infty }\left(\frac{\sqrt{3x+2}}{x\sqrt{x+6}-\sqrt{x^3+2x}}\right)$$
Comment: Asymptotic expansion
Answer: $$
\sqrt{3x+2}\sim \sqrt{3}\sqrt{x}+\frac{\sqrt{1/x}}{\sqrt{3}}-...$$
$$
x\sqrt{x+6}\sim x^{3/2}+3 \sqrt{x}-(9/2)\sqrt{1/x}+...
$$
$$
\sqrt{x^3+2x}\sim x^{3/2}+\sqrt{1/x}+...
$$
Therefore, the $x^{3/2}$ in the denominator cancels out, and what remains is $\sqrt{3x}/(3\sqrt{x})=1/\sqrt{3}$, which is the correct result.
Comment: If you are unsure about these expansion, take for example the first term $\sqrt{3x+2}$. Factorize it as $\sqrt{3x}\sqrt{1+\frac{2}{3x}}$. Now, $2/(3x)$ is small, and you can use the Taylor series of $(1+\epsilon)^{1/2}\sim 1+\frac{\epsilon}{2}-\frac{\epsilon^2}{8}+\frac{\epsilon^3}{16}-...$ as $\epsilon\to 0$.
Answer: Hint: $\frac{1}{\sqrt{a}-\sqrt{b}} = \frac{\sqrt{a}+\sqrt{b}}{a-b}$
Answer: $$\frac{\sqrt{3x+2}}{x\sqrt{x+6}-\sqrt{x^3+2x}}=\frac{\sqrt{3x+2}\left(x\sqrt{x+6}+\sqrt{x^3+2x}\right)}{x^2(x+6)-(x^3+2x)}$$
$$=\frac{\sqrt{3+\frac{2}{x}}\left(\sqrt{1+\frac{6}{x}}+\sqrt{1+\frac{2}{x^2}}\right)}{6-\frac{2}{x}}\stackrel{x\to \infty}\to \frac{\sqrt{3}\left(\sqrt{1}+\sqrt{1}\right)}{6}=\frac{1}{\sqrt{3}}$$
Answer: $$\begin{align}\lim _{x\to \infty }\left(\frac{\sqrt{3x+2}}{x\sqrt{x+6}-\sqrt{x^3+2x}}\right) &= \lim_{x\to\infty}\left[\left(\frac{\sqrt{3x+2}}{x\sqrt{x+6}-\sqrt{x^3+2x}}\right)\left({x\sqrt{x+6}+\sqrt{x^3+2x} \over x\sqrt{x+6}+\sqrt{x^3+2x} }\right)\right]\\ &= \lim_{x\to\infty}\left({\sqrt{3x+2}\left(x\sqrt{x+6}+\sqrt{x^3+2x}\right) \over x^2(x+6) - (x^3 + 2x) }\right) \\ &=\lim_{x\to\infty} \left({x\sqrt{(x+6)(3x+2)} + \sqrt{(x^3+2x)(3x+2)}\over6x^2-2x}\right) \\(*)& = \lim_{x\to\infty}\left({x\sqrt{3x^2} + \sqrt{3x^4}\over6x^2}\right) \\ &= \lim_{x\to\infty}\left({\sqrt3x^2 + \sqrt3x^2\over6x^2}\right)\\&= \lim_{x\to\infty}\left({2\sqrt3x^2\over6x^2}\right) \\& = \lim_{x\to\infty}\left({\sqrt3 \over 3}\right) \\ &= {\sqrt3 \over 3}\end{align}$$
The step $(*)$ is valid because at infinity, the smaller terms don't matter so we may discard them. The step immediately following is also valid because we are only working with positive values of $x$ as $x\to\infty$.


How can I set \repeatTie to follow a note

Question: I need a small tie like the \repeatTie, but it has to be behind a note, not before:
\version "2.18.2"

\relative c' {
  \clef treble
  \key c \major
  \time 4/4

  r2 c4 d8 d~
  \repeat volta 2 {d8 e4. r2 r2 c4 d8 e~ e2 e4 f8 d8~
  d4 r4 e f8 f~ f g4. r2 r2 e4 f8 g~ g2 g4 a8 g~ g4
  r4 g a8 c~ c2. r8 c8~ c2. r4 c c c a8 g~ g4 r4 g a8 c~
  c2. r8 a~ a2. r4 g f f c8 d~ }
  \alternative {
    {d4 r4 c4 d8 d}
    {d4\repeatTie  r r2 }
  }
  }

Answer: \laissezVibrer should do the trick.  That's basically a half-tie to the right, like \repeatTie is a half-tie to the left.
Comment: This helped me, too. @MichaelSchmitz: Don't forget to mark this answer as accepted!


How to post data from form in express.js?

Question: I am trying to make a user registration router in express. The backend seemed to work fine since I verified it using it postman. However, when I tried to add the front end to it(adding form), I got an error saying
{"errors":[{"location":"body","param":"name","msg":"Name is required"},{"location":"body","param":"email","msg":"Please include a valid email"},{"location":"body","param":"password","msg":" Please enter a password with 6 or more characters"}]} Since I included name attribute in each input tag, I could not figure out where is the problem.
Here is some part of my codes.
server.js
app.use('/api/posts', require('./routes/api/posts'));

users.js
router.post(
  '/',
  [
    check('name', 'Name is required')
      .not()
      .isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check(
      'password',
      ' Please enter a password with 6 or more characters'
    ).isLength({ min: 6 })
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array()
      });
    }
.
.
.

register.handlebars
<form class="form" action="/api/users" method="post">

                    <input name="name" type="text" placeholder="Name" requried>

                    <input name="email" type="email" placeholder="E-mail">

                    <input name="password" type="text" placeholder="Password" minlength="6">

                <input type="submit" value="Create account" class="button green-button" />
            </form>ss

Answer: use body-parser
middleware with express
https://expressjs.com/en/resources/middleware/body-parser.html
Comment: Since it works in Postman, I don't think body-parser is the cause of the error here.
Comment: then add enctype="application/x-www-form-urlencoded" to html form


10 minutes wind speed data to 1 second wind speed data

Question: I have a wind speed data series .txt file (1 year long), in which in each register I have the following info:
date; hour; 10 minute wind speed average; 10 minute max value; 10 minute sigma
An example of the data would be like this:
050206 0130 8.05 10.28 0.84
050206 0150 7.29 11.06 1.13 ....
For each 10 minutes, the available information is the wind speed average, the maximum value in such 10 minutes and the standard deviation in such 10 minutes. Such statistics for each 10 minutes are calculated with 1 s sampling data (600 values for each 10 minutes).
It can be assumed that the 1 s sampled values are Normally distributed. The problem is that such 1 s sampled values are not available and I need them for my study.
So, the questions are:
-Is there a mathematical/statistical solid well known method to generate the 1 s values for each 10 minute register assuming that they are Normally distributed??
-Is there a mathematical/statistical solid well known method to link each 1 s values with coherence??
I would like to implement a Python script in order to do so.
Answer: Consider the following problem in reverse. I had data for 600 people and I recorded the mean and SD of their height and I noted also that height is normally distributed. But I threw away the 600 individual height measurements. Can you tell me the heights of the 600 people?
You can not solve this problem. You could simulate from a distribution with those properties, but you cannot solve this problem. Data once discarded cannot be recovered.
Your problem is not identical in form, as you have a time series. But how could that help? If you were willing to make some physically dubious assumptions about wind speed changing according to some scheme you could perhaps make better guesses than just simulating, but you are asking for white magic where no magic exists.
You used the tags "monte carlo" and "markov chain", but it is not clear to me why.
Comment: What I really want is to simulate/generate the 1-sec data, nothing about solving. Sorry if I expressed myself uncorrectly.
Comment: What do you want the simulated values for? They will just be multiple blocks with differing means and standard deviations. Computationally that would just be a matter of calling up some routine for randomly sampling from a normal or Gaussian. Somebody should have done that within Python, but in any case how to do in any software it is off-topic here unless you have a novel statistical question about generating random normal deviates.


Java 8 lambda and alpha equivalence

Question: I am wondering, is any nice way (if it is possible at all) to implement an alpha-equivalence comparison in Java-8?
Obviously these two lambda-s are alpha-equivalent. Let us suppose that for some circumstances we want to detect this fact. How it can be achieved?
Predicate<Integer> l1 = x -> x == 1;
Predicate<Integer> l2 = y -> y == 1;

Comment: You can use instrumentation to read the lambda class, then use something like the asm library to work out if they are equivalent, which will likely be enough for a trivial example like you provided, but it wont work for more complicated cases.
Comment: @holi-java that's not what the OP wants...
Comment: @Andremoniy serializeable could be an option, but Im thinking about the order or instructions in a bigger lambda expression, they could be equivalent, but in *different* order... Ill have to try that
Comment: If the case is as simple as in the given example, a comparison of JVM instructions would solve the problem, because you can ignore the variable name and even the generic type, and only compare the list of instructions. A framework like [ASM](https://stackoverflow.com/questions/tagged/java-bytecode-asm) could help interpreting and comparing bytecode instructions, but that's probably alot of work.
Comment: @Marco13 Perhaps :) As soon as somebody provides such kind of answer, I will consider to change my decision.
Comment: You would need to find a way to obtain a canonical representation of your `Predicate` or to test them over their whole domain, and I don't see any practical way to do either
Comment: This may be of some help, but I'm not sure how much - https://stackoverflow.com/questions/24095875/is-there-a-way-to-compare-lambdas
Comment: well you could Serialize the lambda expression and compare the bytes, I have not tried this though
Comment: @Eugene first of all your idea about some byte code comparison is really interesting and it is exactly what I have been thinking about. Secondly, my goal here is slightly more theoretical, because it is really difficult to describe my practical idea here in brief.
Comment: @Eugene hi, what about the OP meaning ? could you show me a formular ?
Comment: @SME_Dev I am sure that any workable solution given as an answer will be much appreciated not only by my self :) Your idea could work
Comment: @holi-java please, consider learning lambda-calculus theory, this will reveal you the idea of my question
Comment: @Andremoniy that is hard for me. my english is so bad, sir.
Comment: @holi-java in this case I have no idea how to help you understand my question :-)
Comment: hi, someone has already point it out. compare the instructions. so the question is how java implements the equivalent  lambdas. Am I right, sir?
Comment: I'd like to know what are your thought. +1
Comment: @Andremoniy I'm surprised that you accepted the answer. Maybe people are still experimenting for a solution based on serialization, bytecode reading or similar approaches ...?
Answer: I'm going out on a limb with this answer, but it may be worth mentioning this:
There is no way to do this. As Brian Goetz pointed out in an answer to a related question, there are no specified, reliable ways of obtaining the "contents" of a lambda, in that sense.
But (and now comes the vague, handwaving part) :
There is no way to do this yet.
It might be possible to do this in the future. Maybe not with Java 9, but later. The Project Panama has ambituous goals, among them, giving the developer a deeper access to lambdas, aiding in further (runtime) optimizations, translations and processing.
And recently, Radosław Smogura posted in the mailing list :

I try to capture lambda expression to get them as expression tree during runtime. I'm able to do it for simple lambdas like (o) -> (var == var) && ((varX == varX) && (someField + 1 == 1)), so later user can use (missing) API to examine tree.
Right now tree can be accessed with code like this:
Method m = BasicMatadataTest.class.getDeclaredMethod("lambda$meta0");
Expression e = (Expression) m.invoke(null);
BinaryExpression top = (BinaryExpression) e;
BinaryExpression vars = (BinaryExpression) top.getLefthandExpression(); // represents (var == var)
(VariableExpression) vars.getLefthandExpression() // represents first var, and it's reference equal to vars.getRighthandExpression() as it's same variable

...

The key point here may be the comment:

represents first var, and it's reference equal to vars.getRighthandExpression() as it's same variable

(e.b.m)
So if I understood your question and this mailing list post correctly, then it might be possible to determine the equivalence between such expressions: Comparing the tree structure would be fairly trivial (given the functionality sketched above). And then it might boil down to treating two VariableExpression as being "equal", regardless of the actual variable name.
The mailing list message points to the repositories:

https://bitbucket.org/radoslaw_smogura/java-lambda-metaexpression-jdk9-langtools/branch/metaexpr
https://bitbucket.org/radoslaw_smogura/java-lambda-metaexpresions-jdk/commits/branch/metaexpr

(Disclaimer: I have not tested this, and don't know how to get this running (or whether it works at all) - but to my understanding, it is at least very close to what the question was actually about).
Comment: @holi-java Yes. The *formal* definition of the equivalence is explained on [Wikipedia: Lambda Calculus Alpha Equivalence](https://en.wikipedia.org/wiki/Lambda_calculus#Alpha_equivalence). To my understanding, one core aspect of the question was whether there is a way to programmatically obtain the "contents" of a lambda (so that one could implement the logic that is described on the Wikipedia site). (I think that the serialization approach would only work for *very* limited cases, if at all, but that's another issue).
Comment: basically the short version would be - no way; *might happen*, but not sooner then jdk-10. *Might* being the keyword.
Comment: @Andremoniy Sure, this answer is not profound enough to be *acceptable*. There might be options with serialization or ASM or other bytecode magic, and I'd also be curious to see them (even if - and this is likely - they would be somehow implementation dependent or relied on other unspecified details). But I think that eventually, the path sketched in the mailing list (@Eugene ;-)) **might** be one that leads towards a real, proper API for achieving the goal.
Comment: That's very interesting, thanks! +1 But will still wait for some time if somebody finds any result with serialization
Comment: I finally understand what the OP want to do. plus one. he want to compare the lambda body's logic are equivalent . Am I right, sir?  but there are many  combinations for the same logic.

Java 8 lambda and alpha equivalence


Como definir os chutes iniciais para função nls para modelo de regressão potencial?

Question: Gostaria de saber como definir os "chutes" iniciais para utilizar
o modelo de regressão não linear de potencia. Estou trabalhando com estimação
de dados, testando vários modelos de regressão, mesmo não havendo ajuste,
gostaria de citar esse modelo, porém tenho dificuldades em definir os valores
iniciais, abaixo segue apenas um fragmento de dados para teste, gostaria de saber um método que me permitisse aplicar em qualquer conjunto de dados, para a obtenção dos valores inicias de A e B para a função nls(y~B*x^A,start=list(A=1, B=1.7))
dados<-structure(list(y = c(44.42, 77.9, 95.72, 40.24, 63.7, 46.62,
84.6, 52.49, 88.53, 56.52, 71.21, 65.16, 72.24, 53.81, 67.02),
    x = c(11.26, 14.78, 17.56, 10.37, 13.27, 10.3, 14.07, 12.26,
    13.3, 12.84, 13.72, 12.8, 14.86, 11.47, 15.06)), .Names = c("y",
"x"), row.names = c(NA, -15L), class = "data.frame")

attach(dados)

nls(y~B*x^A,start=list(A=1, B=1.7))

Answer: Essa resposta do Cross-Validated parece uma boa solução.
A sugestão aqui é tirar o log dos dois lados e ajustar um modelo linear. Que ficaria algo assim:
y = b*(x^a)
log(y) = log(b) + a*log(x)

Portanto, fazendo o modelo linear você terá uma estimativa inicial para log(b) e para a.
Ajuste o modelo linear:
linear <- lm(log(y) ~ log(x), data = dados)
linear
# Call:
#   lm(formula = log(y) ~ log(x), data = dados)
#
# Coefficients:
#   (Intercept)       log(x)
#        0.1371       1.5611

Assim você terá 0.1371 a estimativa de log(b) e 1.5611 estimativa de a.
Uma estimativa direta de b pode ser exp(0.1371) = 1.146943.
Esses valores podem ser utilizados como chutes iniciais.
modelo <- nls(y~B*x^A,start=list(A=coef(linear)[2], B = exp(coef(linear)[1])), data = dados)
modelo

# Nonlinear regression model
# model: y ~ B * x^A
# data: dados
# A     B
# 1.436 1.598
# residual sum-of-squares: 1040
#
# Number of iterations to convergence: 5
# Achieved convergence tolerance: 3.365e-07

No link tem outras várias respostas que podem ajudar!
Comment: Excelente resposta. Aplicar log em ambos os lados era a minha ideia para linearizar o problema e respondê-lo. Entretanto, esta pergunta não foge do escopo do site? Eu procurei perguntas sobre o assunto no [meta](http://meta.pt.stackoverflow.com/questions/4266/como-lidar-com-uma-pergunta-que-depende-de-um-conhecimento-al%C3%A9m-da-programa%C3%A7%C3%A3o/) e me parece que não há consenso entre os usuários a respeito do que fazer em casos assim. Particularmente, acho que tu agiu certo em responder, mas não existe o risco de vir alguém aqui e fechar a pergunta?
Comment: @MarcusNunes Obrigado! Para mim essa pergunta está na fronteira do "dentro" e "fora" do escopo... Existe o risco de alguém fechar, mas como está na fronteira, vais er difícil obter os 5 votos necessários. A resposta do [Carlos](http://meta.pt.stackoverflow.com/a/4355/6036) reflete bem a minha opinião. Ou seja, só não respondo se a pergunta não tiver nada a ver com programação. Aqui o problema do AP é mais: quero rodar o nls e não consigo pq da problema de convergência, como corrigir?. Ao meu ver, ele não veio pedir ajuda em estatística.
Comment: Levarei isto em conta nas minhas próximas respostas. Eu preciso aprender a responder o que é perguntado e não ir muito além na teoria estatística neste site.


Identifying outliers in different groups

Question: I have a data set where participants were assigned to different groups and completed the same tests. I know I can use the aggregate function to identify the mean and sd but I cannot figure out how to find the outliers in these groups.
df<-read.table(header=T, text="id, group, test1, test2
1, 0, 57, 82
2, 0, 77, 80
3, 0, 67, 90
4, 0, 15, 70
5, 0, 58, 72
6, 1, 18, 44
7, 1, 44, 44
8, 1, 18, 46
9, 1, 20, 44
10, 1, 14, 38")

I like the format of this code but do not know how to change it in order to identify outliers for each group for each test.
ALSO, I want outliers to be considered anything greater than 2 standard deviations rather than 3. Can I format that too within this code?
##to get outliers on test1 if groups were combined
badexample <- boxplot(df$test1, plot=F)$out
which(df$test1 %in% badexample)

This would work if I wanted the outliers of both groups together on test1 but I want to separate by group.
Output should contain:
Outliers for group 0 on test1
outliers for group 0 on test2
outliers for group 1 on test1
outliers for group 1 on test2
Answer: You can write a function to compute the outliers and then call it with ave.
outlier <- function(x, SD = 2){
  mu <- mean(x)
  sigma <- sd(x)
  out <- x < mu - SD*sigma | x > mu + SD*sigma
  out
}

with(df, ave(test1, group, FUN = outlier))
# [1] 0 0 0 0 0 0 0 0 0 0

with(df, ave(test2, group, FUN = outlier))
# [1] 0 0 0 0 0 0 0 0 0 0

To have new columns in df with these results, assign in the usual way.
df$out1 <- with(df, ave(test1, group, FUN = outlier))
df$out2 <- with(df, ave(test2, group, FUN = outlier))

Answer: An option, using data.table:
library(data.table)

df <- read.table(header=T, sep=",", text="id, group, test1, test2
1, 0, 57, 82
               2, 0, 77, 80
               3, 0, 67, 90
               4, 0, 15, 70
               5, 0, 58, 72
               6, 1, 18, 44
               7, 1, 44, 44
               8, 1, 18, 46
               9, 1, 20, 44
               10, 1, 14, 38")

DT <- as.data.table(df)
DT[, `:=`(mean1 = mean(test1), sd1 = sd(test1), mean2 = mean(test2), sd2 = sd(test2)), by = "group"]
DT[, `:=`(outlier1 = abs(test1-mean1)>2*sd1, outlier2 = abs(test2-mean2)>2*sd2)]
DT
#     id group test1 test2 mean1      sd1 mean2      sd2 outlier1 outlier2
#  1:  1     0    57    82  54.8 23.66854  78.8 8.074652    FALSE    FALSE
#  2:  2     0    77    80  54.8 23.66854  78.8 8.074652    FALSE    FALSE
#  3:  3     0    67    90  54.8 23.66854  78.8 8.074652    FALSE    FALSE
#  4:  4     0    15    70  54.8 23.66854  78.8 8.074652    FALSE    FALSE
#  5:  5     0    58    72  54.8 23.66854  78.8 8.074652    FALSE    FALSE
#  6:  6     1    18    44  22.8 12.04990  43.2 3.033150    FALSE    FALSE
#  7:  7     1    44    44  22.8 12.04990  43.2 3.033150    FALSE    FALSE
#  8:  8     1    18    46  22.8 12.04990  43.2 3.033150    FALSE    FALSE
#  9:  9     1    20    44  22.8 12.04990  43.2 3.033150    FALSE    FALSE
# 10: 10     1    14    38  22.8 12.04990  43.2 3.033150    FALSE    FALSE

Answer: Here's a way with dplyr -
df %>%
  mutate_at(
    vars(starts_with("test")),
    list(outlier = ~(abs(. - mean(.)) > 2*sd(.)))
  )

   id group test1 test2 test1_outlier test2_outlier
1   1     0    57    82         FALSE         FALSE
2   2     0    77    80         FALSE         FALSE
3   3     0    67    90         FALSE         FALSE
4   4     0    15    70         FALSE         FALSE
5   5     0    58    72         FALSE         FALSE
6   6     1    18    44         FALSE         FALSE
7   7     1    44    44         FALSE         FALSE
8   8     1    18    46         FALSE         FALSE
9   9     1    20    44         FALSE         FALSE
10 10     1    14    38         FALSE         FALSE


Ler um arquivo txt e adicionar a uma lista duplamente encadeada em java

Question: Sou bem iniciante em programação e estou codificando esse programa para um trabalho de faculdade.
Preciso ler os dados de um arquivo txt com os seguintes campos (titulo, estilo, ator, produtora, sinopse, caminho) e inserir em uma lista duplamente encadeada com a chave por Titulo, já montei a lista
public class Filme {

    private String titulo;
    private String sinopse;
    private String produtora;
    private String atorPrincipal;
    private String estilo;
    private String caminhoDoArquivoDaCapa;

    private Filme antTitulo;
    private Filme antAtor;
    private Filme antEstilo;
    private Filme proxTitulo;
    private Filme proxAtor;
    private Filme proxEstilo;

    protected final String SEPARADOR = ";";

    public Filme (String titulo, String sinopse, String produtora, String atorPrincipal, String estilo,
            String caminhoDoArquivoDaCapa) {

        this.titulo = titulo;
        this.sinopse = sinopse;
        this.produtora = produtora;
        this.atorPrincipal = atorPrincipal;
        this.estilo = estilo;
        this.caminhoDoArquivoDaCapa = caminhoDoArquivoDaCapa;

        this.antTitulo = null;
        this.antAtor = null;
        this.antEstilo = null;
        this.proxTitulo = null;
        this.proxAtor = null;
        this.proxEstilo = null;
    }

    public Filme() {
        // TODO Auto-generated constructor stub
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getSinopse() {
        return sinopse;
    }

    public void setSinopse(String sinopse) {
        this.sinopse = sinopse;
    }

    public String getProdutora() {
        return produtora;
    }

    public void setProdutora(String produtora) {
        this.produtora = produtora;
    }

    public String getAtorPrincipal() {
        return atorPrincipal;
    }

    public void setAtorPrincipal(String atorPrincipal) {
        this.atorPrincipal = atorPrincipal;
    }

    public String getEstilo() {
        return estilo;
    }

    public void setEstilo(String estilo) {
        this.estilo = estilo;
    }

    public String getCaminhoDoArquivoDaCapa() {
        return caminhoDoArquivoDaCapa;
    }

    public void setCaminhoDoArquivoDaCapa(String caminhoDoArquivoDaCapa) {
        this.caminhoDoArquivoDaCapa = caminhoDoArquivoDaCapa;
    }

    public Filme getAntTitulo() {
        return antTitulo;
    }

    public void setAntTitulo(Filme antTitulo) {
        this.antTitulo = antTitulo;
    }

    public Filme getAntAtor() {
        return antAtor;
    }

    public void setAntAtor(Filme antAtor) {
        this.antAtor = antAtor;
    }

    public Filme getAntEstilo() {
        return antEstilo;
    }

    public void setAntEstilo(Filme antEstilo) {
        this.antEstilo = antEstilo;
    }

    public Filme getProxTitulo() {
        return proxTitulo;
    }

    public void setProxTitulo(Filme proxTitulo) {
        this.proxTitulo = proxTitulo;
    }

    public Filme getProxAtor() {
        return proxAtor;
    }

    public void setProxAtor(Filme proxAtor) {
        this.proxAtor = proxAtor;
    }

    public Filme getProxEstilo() {
        return proxEstilo;
    }

    public void setProxEstilo(Filme proxEstilo) {
        this.proxEstilo = proxEstilo;
    }
}

public class Filmoteca {

    private Filme primeiroTitulo;
    private Filme primeiroAtor;
    private Filme primeiroEstilo;
    private Filme ultimoTitulo;
    private Filme ultimoAtor;
    private Filme ultimoEstilo;
    private Filme atual;

    public Filmoteca() {
        this.primeiroTitulo = null;
        this.primeiroAtor = null;
        this.primeiroEstilo = null;
        this.ultimoTitulo = null;
        this.ultimoAtor = null;
        this.ultimoEstilo = null;
        this.atual = null;
    }

    public Boolean estaVazio() {
        return (this.primeiroTitulo == null);

    }

    public void insereOrdenadoPorTitulo(Filme filme) {

        Filme aux, anterior;

        if (this.estaVazio()) {
            this.primeiroTitulo = this.ultimoTitulo = filme;
            return;
        }

        if (filme.getTitulo().compareTo(this.primeiroTitulo.getTitulo()) < 0) {
            filme.setProxTitulo(this.primeiroTitulo);
            this.primeiroTitulo.setAntTitulo(filme);
            this.primeiroTitulo = filme;
            return;
        }

        anterior = this.primeiroTitulo;
        for (aux = this.primeiroTitulo.getProxTitulo(); aux != null
                && filme.getTitulo().compareTo(aux.getTitulo()) > 0; aux = aux.getProxTitulo()) {
            anterior = aux;
        }

        anterior.setProxTitulo(filme);
        filme.setAntTitulo(anterior);
        filme.setProxTitulo(aux);

        if (filme.getProxTitulo() == null) {
            this.ultimoTitulo = filme;
        } else {
            aux.setAntTitulo(filme);
        }
    }

}

Não sei como fazer a leitura do arquivo pra inserir na lista. Alguém pode me ajudar, por favor?
Comment: Qual é o formato do arquivo? Separado por virgulas ou por ponto-e-vírgulas? Possui cabeçalho? Onde está a declaração da classe `Filme`?
Comment: O formato do arquivo é txt, é separado por ponto-e-vírgulas
Comment: Atualizei a pergunta e coloquei a declaração da classe Filme
Comment: os dados são gravados dessa forma no arquivo titulo;sinopse;produtora;atorPrincipal;estilo;caminhoDoArquivoDaCapa
Comment: Agradeço pelas informações, publiquei uma resposta. Veja se resolve seu problema!
Comment: vlw cara, ajudou muito, Obrigado!
Answer: Primeiro, vamos simular um arquivo, chamado arquivo.txt. Seu conteúdo será o seguinte:
T0;S0;P0;A0;E0;/P0
T1;S1;P1;A1;E1;/P1
T2;S2;P2;A2;E2;/P2
T3;S3;P3;A3;E3;/P3
T4;S4;P4;A4;E4;/P4
T5;S5;P5;A5;E5;/P5

Você pode fazer a leitura do arquivo da seguinte maneira:
try (final BufferedReader reader = new BufferedReader(new FileReader("arquivo.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // Faça algo com a linha lida aqui
        System.out.println(line);
    }

} catch (IOException e) {}

Com a linha lida, você pode dividi-la pelo charactere ; e criar um objeto Filme com os campos criados:
try (final BufferedReader reader = new BufferedReader(new FileReader("arquivo.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        final String[] campos = line.split(Filme.SEPARADOR);
        final Filme filme = new Filme(campos[0], campos[1], campos[2], campos[3], campos[4], campos[5]);
    }

} catch (IOException e) {}

Por fim, crie uma lista encadeada vazia antes de ler o arquivo e, conforme a leitura vai sendo feita, atualize a lista:
final Filmoteca filmoteca = new Filmoteca();

try (final BufferedReader reader = new BufferedReader(new FileReader("arquivo.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        final String[] campos = line.split(Filme.SEPARADOR);
        final Filme filme = new Filme(campos[0], campos[1], campos[2], campos[3], campos[4], campos[5]);
        filmoteca.insereOrdenadoPorTitulo(filme);
    }

} catch (IOException e) {}

As importações necessárias no topo do arquivo serão:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;


How to Send On Premises Kubernetes Logs to Stackdriver

Question: Objective: Get some logging/monitoring on Googles
Stackdriver from a Kuberntes HA cluster
that is on premises, version 1.11.2.
I have been able to send logs to Elasticsearch using Fluentd Daemonset for
Kubernetes, but the
project is not supporting Stackdriver
(issue).
That said, there is a docker image created for Stackdriver
(source),
but it does not have the daemonset.  Looking at other daemonsets in this
repository, there are similarities between the different fluent.conf files
with the exception of the Stackdriver fluent.conf file that is missing any
environment variables.
As noted in the GitHub
issue
mentioned above there is a plugin located in the Kubernetes GitHub
here,
but it is legacy.
The docs can be found
here.
It states:

"Warning: The Stackdriver logging daemon has known issues on
  platforms other than Google Kubernetes Engine. Proceed at your own risk."

Installing in this manner fails, without indication of why.
Some other notes. There is Stackdriver Kubernetes
Monitoring that clearly
states:

"Easy to get started on any cloud or on-prem"

on the front page, but
doesn't seem to explain how. This Stack Overflow
question
has someone looking to add the monitoring to his AWS cluster. It seems that it is not yet supported.
Furthermore, on the actual Google
Stackdriver it is also stated that

"Works with multiple clouds and on-premises infrastructure".

Of note, I am new to Fluentd and the Google Cloud Platform, but am pretty
familiar with administering an on-premise Kubernetes cluster.
Has anyone been able to get monitoring or logging to work on GCP from another platform? If so, what method was used?
Comment: AFAIK this is the official solution: https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/fluentd-gcp.  I would focus on figuring out what errors you see when you install it on your cluster
Comment: I was afraid so. Thanks for the help on editing. Ill update if I am able to get this working.
Answer: Consider reviewing this documentation for using the BindPlane managed fluentd service from Google partner Blue Medora. It is available in Alpha to all Stackdriver users. It parses/forwards Kubernetes logs to Stackdriver, with additional payload markup.
Disclaimer: I am employed by Blue Medora.
Answer: Check out the new Stackdriver BindPlane integration which provides on-premise log capabilities.
It is fully supported by Google and is free (other than typical Stackdriver consumption fees)
https://cloud.google.com/solutions/logging-on-premises-resources-with-stackdriver-and-blue-medora


Webform : how to count and live display results

Question: Update
webform_get_submission_count isn't precise enough (we need to count into submissions)
but
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $sql = "SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE \"".$atelier_1."\" ;";
    $count_atel_1 = db_result(db_query($sql));
  }
}
echo $sql;
echo $count_atel_1;
?>

This webform has been submitted <?php print $count ?> times.

looks ok
end update-------------------
We'd like to use a webform so that our students should register on some workshops.
The webform works great. Now we'd like to display live the number of students that are already register in on of the workshops so that the other should know if there remains some possibilities of registration (each workshop can only accept 20 students at the same time)
I'm trying with that that doesn't work ($atelier_1 = "sources" ;) is the name of one workshop :
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  if ($node->type == 'webform') {
    $count = db_result(db_query('SELECT count(*) FROM {webform_submissions} WHERE nid = %d', $nid));
    $atelier_1 = "sources" ;
    $count_atel_1 = db_result(db_query('SELECT count(*) FROM {webform_submitted_data} WHERE data LIKE %d', $atelier_1');
  }
}

echo $count_atel_1;
?>

Any help or suggestion welcome
Answer: I looked through the Drupal document from drupalcontrib.org and i saw that there is webform_get_submission_count function to get a count of the total number of submissions for a node. I think you can use that function instead by create a new one.


Rails 4: association boolean in scope

Question: I've got a has_and_belongs_to_many relationship between two models and I want to write a scope to check if a boolean on the relationship is true:
class Component

  has_and_belongs_to_many :templates
  scope :editable, -> { where(template.showable) }

  ....
end

On the Template model :showable is a boolean. How can I write this in Rails 4?
Answer: scope :editable, -> { joins(:templates).where( templates: { showable: true } ) }

Comment: Well that was easy. Cheers!

Rails 4: association boolean in scope


How to aggregate a boolean column in Pandas Dataframe in a Pivot Table as percentage

Question: I have a Pandas Dataframe. Among its many columns are ID, which is Boolean, Quarter, which gives year and quarter (e.g. 2016Q1) and State (e.g. TX, CA), so it would look something like:
id    Quarter State
True  15Q1    AZ
False 17Q1    WY
True  14Q2    NH
False 15Q1    AZ

I'm trying to build a pivot table with ID as the value, State as the index, and quarter as the columns. I'd like to use np.mean as the agg_func but I get DataError: No numeric types to aggregate
It displays right when I use count as the aggregate function instead. And when I aggregate the total np.mean(df['id']), I get .64, which is exactly the type of output I'm looking for except more aggregated instead of granular. So why does np.sum work there, but not when I use it as the aggregating function in a pivot table? How do I get it to work.
I think I could convert the True's and False's to 1's and 0's, but I'd prefer not to, since I actually have a lot of 'id' columns I'm looking to aggregate this way.
EDIT: So it's an issue that only pops up with my full dataset, and not the toy dataset I used as an example. I played around some more and the ValueError: No objects to concatenate still pops up if I do a groupby with mean as the aggregating function on 'Year' or 'State'. It even pops up when I try df['id'].describe()
Has anyone ever encountered an issue like this before?
Answer: Your output is not very clear but this is what I think you need
pd.pivot_table(df, index='State', columns='Quarter', values = 'id', aggfunc='mean')

You get
Quarter 14Q2    15Q1    17Q1
State
AZ      NaN     0.5     NaN
NH      1.0     NaN     NaN
WY      NaN     NaN     0.0

You can pass the parameter fill_values = 0 in pivot_table to replace the NaNs by 0
Comment: Hmmm, that's what I tried and it didn't work. I think my actual dataset has something weird that the toy dataset doesn't. I'll dig into it further, but I doubt I can get everything into the question. Thanks for your help, though.


How to get media entity field value in twig?

Question: Sometimes it is necessary to get the actual value of a field (not the formatted/rendered one), e.g. to check a boolean for true or false.
If I want to get a field value of a node or paragraph inside twig templates (node.html.twig / paragraph.html.twig) I can use node.field_my_boolean.value respectively paragraph.field_my_boolean.value.
How do I accomplish this in a media twig template? I've already tried media.field_my_boolean.value but it does not work.
Comment: try `{{ content.field_my_boolean }}` and you want the raw value without the HTML markup `{{ content.field_my_boolean.0 }}`
Comment: Both output the rendered value and not the actuall true/false. I can not use this because it is translated (e.g. "wahr"/"falsch" in German).
Comment: When you do `{{ content.field_my_boolean.0 }}` is it showing `wahr/flasch` or `1/0` ?
Comment: It depends on the display format setting. If I set the formatter to `1/0` I get `1` or `0`. If I set it to ``wahr/falsch` I get `wahr` or `falsch`. That's what I mean by "rendered value".
Comment: I have adjusted my answer.
Answer: Right now, the Media module does not pass its object in the variables like Paragraphs and Node does. This is why media.field_my_boolean.value does nothing.
You can correct this in your theme by implementing theme_preprocess_media, which adds the media object to the variables:
/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  $variables['media'] = $variables['elements']['#media'];
}

You can then access media. in your twig template and any connected fields on it just like Paragraph or Node.
Comment: You seem to be right. Actually `function mytheme_preprocess_media(&$variables) {$variables['media'] = $variables['elements']['#media']}` should be enough because your themes preprocess function is just adding variables. No need to copy the whole function from media module.
Comment: Gotcha - for some reason I had to use the whole function, could be an earlier build.
Comment: OK, I'm referring to Drupal 8.3.0 and Media Entity 8.x-1.6. Just update your answer and I will accept it.
Answer: You can with {{ content.field_my_boolean }} and if you want the raw value without the HTML markup use content.field_my_boolean.0

Both output the rendered value and not the actuall true/false. I can
  not use this because it is translated (e.g. "wahr"/"falsch" in
  German).

Then use the |t function and do this
{% if content.field_my_boolean.0 == 'Wahr'|t %}
    // do something
{% elseif content.field_my_boolean.0 == 'Falsch'|t %}
    // do something
{% endif %}


How to test JavaScripts without to delete the `test` database data?

Question: I am using Ruby on Rails 3.2.2, cucumber-rails-1.3.0, rspec-rails-2.8.1 and capybara-1.1.2. I would like to use Selenium in order to test JavaScripts, but without to delete the test database data each time I run the cucumber command line in my Terminal window. That is, if I state a feature like the following:
Feature: ...

  @javascript
  Scenario: ...

JavaScript is tested as well as expected. However, after the test has run, the test database data is deleted and I must seed again that database in order to properly run new tests.
I read the Official Documentation and the text present in the ROOT_APP/features/support/env.rb file (it seems that I installed all required Ruby gems - see below for more information about the Gemfile that I am using) but I didn't understand how to avoid to delete the database data and how to configure Cucumber and Capybara gems so to properly work with Selenium.
What should I make?
Note I: I would like to make the above because  I would like to have the same test database data when I "test"/"run" Scenarios.
Note II: In order to seed data in the test database (my application needs that data to work), I add the following code in the RAILS_ROOT_PATH/lib/tasks/cucumber.rake file and I run the rake db:test:prepare command line from the Terminal window.
namespace :db do
  namespace :test do
    task :prepare => :environment do
      Rake::Task["db:seed"].invoke
    end
  end
end

In the ROOT_APP/features/support/env.rb file I tried to uncomment one and both of the following blocks of code (BTW: I never changed the original file auto-generated by the cucumber-rails gem, so it is the default one), but after running tests it still deletes the test database data.
#   Before('@no-txn,@selenium,@culerity,@celerity,@javascript') do
#     # { :except => [:widgets] } may not do what you expect here
#     # as tCucumber::Rails::Database.javascript_strategy overrides
#     # this setting.
#     DatabaseCleaner.strategy = :truncation
#   end
#
#   Before('~@no-txn', '~@selenium', '~@culerity', '~@celerity', '~@javascript') do
#     DatabaseCleaner.strategy = :transaction
#   end

Gemfile excerpt:
group :development, :test do
  gem "rspec-rails"
end

group :test do
  gem 'cucumber-rails'
  gem 'database_cleaner'
  gem 'capybara'
end

Answer: I ran into this same problem, and managed to fix it by changing the following line in ROOT_APP/features/support/env.rb
from
Cucumber::Rails::Database.javascript_strategy = :truncation

to
Cucumber::Rails::Database.javascript_strategy = :transaction

Hope this helps...


Como redirecionar dominio .com com .htaccess

Question: Tenho 2 dominios, example.com e example.com.br apontando para o mesmo site wordpress.
Gostaria de redirecionar toda vez que alguem entrar em example.com, seja redirecionado para example.com.br/en
Achei esse código, mas ele redireciona também o example.com.br para o /en
RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ http://www.example.com.br/en [L,R=301]

Alguem pode me ajudar?
P.S: De preferencia funcione tanto com 'www', como sem.
Comment: Boa tarde @AmadeuAntunes acho que não seja uma duplicata desta pergunta especifica.
Answer: Isso deve ajudar.
RewriteEngine on
RewriteRule ^(.*)$ http://www.example.com.br/en [R=301,L]

Ou tenta assim:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule (.*)$ http://www.example.com.br/en [R=301,L]
</IfModule>

Comment: Neste caso o .com.br também redireciona, e eu só quero que o .com redirecione.
Comment: Bom, é simples, coloque este .htaccess somente no root do .com ou simplesmente crie um index de redirecionamento em cada.
Se os 2 apontam para a mesma hospedagem fica fácil.
Comment: Os 2 DNS fazem parte da mesma hospedagem, apontados diretamente pelo apache para o mesmo directorio. Então os 2 vão ler a mesma regra do htaccess.
Comment: Sua hospedagem tem cPanel? Se tem, você pode criar redirecionamentos diretamente no cPanel.
Comment: vou postar outra maneira editando a pergunta, olha lá.
Comment: Infelizmente não funcionou, mas eu achei uma solição através de um plugin do próprio WP. Agradeço sua ajuda.
Comment: Tranquilo. Sempre é bom procurar soluções alternativas do provável.


Persist /etc/environment variables to non interactive user

Question: Testing OS: RHEL7
Required OSs: RHEL & Derivatives & AIX
I have a user that was created as follows:
sudo groupadd madt
sudo useradd -r -g madt -s /bin/false madt

That user is being used in a systemd service as follows:
[Unit]
Description=MicroStrategy Mobile Access Distribution Tool
After=syslog.target

[Service]
User=madt
ExecStart=/usr/bin/java -jar /opt/pandera/mobile-registration/mobile-access-distribution-tool-1.0.0.jar --spring.config.location=/opt/pandera/mobile-registration/
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

The java app requires that an environment variable be present. I've set the variable in /etc/environment and confirmed that it works for root and all other interactive users.
How can I get the madt user to recognize my environment variable?
Comment: why you don't use Environment system directive?
Answer: You can use EnvironmentFile line in your systemd unit.
For example
EnvironmentFile=/etc/environment

Systemd will then read your file and inject variables from file to your program's environment.
If you need to set only single environment variable only for this system unit, just use
Environment=VERBOSITY_LEVEL=1


Is there a better way to write a swing than I'm doing right now?

Question: I'm currently trying to write out a song I made in another program. I used a swing like at the bottom of the picture, but I can't seem to find a way to write it down consisely. This is the best way I can think of, but is there a better way?
Comment: normally on notator programs you can set the notation and give in the humanizer, random or setting the .swing in %. Are you asking for playback or for reading  a sheet?
Answer: Write it out normally, and at the top say 'swing' and/or crotchet=2 tied triplet quavers and a single quaver. But in dots!
Comment: @AlbrechtHügli - 12/8 works far better than 6/8.
Comment: 12/8 is OK for slower tempos where swing more nearly fits a triplet timebase, i.e. the first note of each pair is close to twice the duration of the second. But at faster tempos the durations become (much) closer. At very fast tempos the durations are almost the same and the swing feel relies on the articulation. To me that's a powerful argument for this answer. Another argument is that is much easier to read.
Comment: Most swing music is notated like Tim explains. An other way is to write in 12/8 or 6/8 time.
Comment: Just to make sure I completely understand, do you mean like this? https://i.imgur.com/6lbwrbL.png
Comment: That's the way to do it!
Comment: More commonly seen like this: https://images.app.goo.gl/utXVarjgLJNgxAw46
Comment: I suppose we have to accept that the '8ths=triplets' indication is in the language, though I deplore it.  Swing isn't triplets.  It certainly isn't 12/8 - keep that for when you want a shuffle.   If you don't know the difference, listen to 'Satin Doll' then 'Blueberry Hill'.
Comment: @LaurencePayne - whilst I appreciate that swing isn't *always* triplets - a lot is, in my opinion - there just isn't another straightforward way to write it out. We're stuck with that way, and generally it's understood by players. I asked a question a long time ago about swing/shuffle, and still struggle with the concepts. That doesn't mean I can't play them - have done for 50 odd yrs.
Comment: The straightforward way to write out swing is straight 8s plus the word 'Swing'.  It's not the first time in musical history that the required performance wasn't strictly mathematically represented by the notation.


How to handle duplicate .module files that live in 2 places?

Question: I have not used Drupal before and have been thrown a project to fix up some things.
But I noticed the file I need to edit lives in two places:

one in includes/jobs.module.
another one in sites/all/modules/jobs/jobs.module.

Is one meant to be a sym link of the other or something? As this is not the case in the project I have been given. What file should I be editing?
I'm sure this is basic stuff for and Drupal dev. An suggetions?
Answer: There shouldn't be a job.module in the includes directory at all, your module files for your job module should all be in sites/all/modules/jobs.
You generally shouldn't put anything in (or modify anything in) the includes directory or you will make it harder for yourself to upgrade drupal core in future.
I would say you should:

check for any differences between the two files.
If they are different determine whether or not anything in includes/jobs.module should be in sites/all/modules/jobs/jobs.module. If so add it.
Delete includes/jobs.module
Answer: To further completed the answer from Rooby, you may want to consider using the Hacked module, which will identify various similar issues that may exist in your Drupal sites. Here is an excerpt from its project page:

... scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.


Cauchy residue formula

Question: Calculate the integral of $1/z$ around $C$, where $C$ is any contour going from $-\sqrt{3}+i$ to $-\sqrt{3}-i$ and is contained in the set of complex numbers whose real part is negative.
My answer: Let $f=1/z$ Then $f$ has a simple pole at $z=0$ with residue 1. But 0 is not enclosed in the contour, so in fact the integral is zero. Is this correct?
Thanks
Comment: I don't get it. Why don't you simply choose a contour and compute it? You will see it is nonzero..
Answer: No, it is not a closed curve.  Calculate the logarithm at both points, but remember the angle $\theta$ remains between $-\pi$ and $0$ for the whole path.
Comment: Doing the integral I get $ln(-\sqrt{3}-i)-ln(-\sqrt{3}+i)$. Is that right and can this be simplified further by using log laws?
Comment: Convert to polar coordinates $re^{i\theta}$
Answer: What you did isn't correct. You seem to be using the residue theorem which requires the path to be closed, but since the endpoints are different, there is no such path.
Even if such path existed somehow, you'd still need to justify that $0$ lies outside the region enclosed by the path, but of course such a region isn't well defined.
To find the integral note that $z\mapsto \dfrac 1 z$ has an antiderivative in the set of complex numbers with negative real part and use this chain of equalities (which justifies that the value of the integral is path indepedent):
$$\int _\gamma f=\int \limits _a^b f\left(\gamma (t)\right)\gamma '(t)\,\mathrm dt=\int \limits_a^b (F\circ \gamma)'(t)\,\mathrm dt=F\left(\gamma (b)\right)-F(\gamma(a)),$$
where $F$ is an antiderivative of $f$.
Comment: Thanks. What can an I use for gamma?
Comment: @user137090 why not a straight line between your two endpoints?
Comment: @user137090 You don't even need a path, you just need an antiderivative.

Cauchy residue formula