Sharpened 5th in otherwise regular diatonic scale

Question: Generally, I'm very pitch intolerant; out of tune vocals can send me running from the room. I'm particularly intolerant of 3rds & whether they push or pull depending on whether the feel is minor or major - I will accept flat, but I cannot listen to sharp [See my previous musing on the sharp 3rd in the Oasis Wonderwall chorus - there's another more disparaging, but I can't find it right now]
That being said, Green Day's Basket Case has always intrigued me.
The song is a pretty basic* I IV V vi in E♭ with a diatonic melody, yet the vocalist fairly frequently pushes the 5th, B♭, quite hard towards B natural. He doesn't do this every time there's a B♭ nor is the push always as noticeable, but he does it sufficiently frequently that it becomes a part of the 'feel' for the track. The vocal overall isn't one that really needs cent-precision, of course.
By all rights, this should drive me nuts, yet it doesn't. My brain accepts it as a natural component of the song.
So, rather than this being "Why does this not hurt?" I guess I'm asking "What is the name or reasoning behind this phenomenon?" Is it like a comma pump?
Link to official Youtube… for those who don't like punk, he does this right at the head of the song, before the 'punkness' gets going properly, in the last word of the first & third lines
"Do you have the time to listen to me whine?" then "… melodramatic fools"

After comments.
For those who are not hearing it, here are the first couple of vocal lines in Melodyne with "whine" & "fools" circled in red, "do" & "time" in green. [Look at the pitch line not the note 'blob'. You'll need to click through then zoom in to see it properly.] He's really squeezing towards halfway between B♭ & natural on both "whine" & "fools" but not on "do" & "time".
I've never put it through any hard analysis before, so I'm glad it proves it's not psycho-acoustic, it's really there. ;))
The analysis for 'time' isn't perfect, the pitch detection breaks in the middle of the note.

Click for full size
*Listening to this more carefully after posting & actually getting the guitar & Melodyne out to see what's going on, the sharpened 5th is always against a G Major, a III Maj, which makes the B♭ very ambiguous, as G contains a B natural. This seems to be what causes the "argument" in the track at those points.
So, though it's a 'regular' I IV V, it contains both vi and III - that's what threw me… now I just need to figure out why that III is 'acceptable'.
Comment: For me, 'do' 'time' and 'whine' all sound exactly the same pitch, bang on the ^5 of the key. Not having ap maybe helps/hinders?
Comment: @Tim - I ran it through Melodyne & added to the question.
Comment: Just curious, for comparison, what does the Melodyne graph look like for a string quartet passage like this? https://youtu.be/wpoYUNfB-BI?t=42 What I've getting at is the red line (pitch?) inside the blob (amplitude?) isn't straight _anywhere_. If I reading it correctly there is pitch variation everywhere... and that is natural.
Comment: @MichaelCurtis - I can show you a picture of it - https://i.stack.imgur.com/AfGfx.png - but it means little to me. The entire thing reads sharp, but within that, things seems pretty 'static' in comparison.
Comment: Well, if the red line is pitch, the quartet pitches _are_ much more stable. I wonder is singing text - and at a fairly fast tempo - might account for more pitch variation?
Comment: @MichaelCurtis - sure, there's a lot of hit & miss on the vocal, but those specific notes show a real tendency to follow the Maj 3rd, beyond the boundaries of 'tuning'.
Answer: Final edit: I did some experiments, and the general feeling is that any gradual pitch bend of a note or a series of notes of gradually changing pitch is OK, as long as it starts on the right pitch or at least keeps moving and doesn't play a steady bad pitch for too long. And when the bending stops and the pitch clearly settles somewhere, then it better be in tune. I can't tell if others feel the same. And then my original speculation on why this particular pitch bend makes musical sense:

This is probably subjective, but to me, bending the melody Bb towards B over the G power chord turns the total chord from a G minor to a G major chord. Particularly for dominant chords, I like to make the third ambiguous by bending it between minor and major, or play both at the same time. In this song, a G major would be something like a secondary dominant G -> Cm. With a little more bending it starts to remind something quite different.

I haven't really experimented with it to know where the limits are. Does the note have to start on either minor or major, or does the pitch matter at all, as long as it's somewhere between the limits of minor and major? Intuitively, I'm inclined to say that particularly in blues/jazz/rock contexts, it doesn't matter where exactly the third is.
EDIT. Here's the spectrum of the "listen to me whine" line in the Transcribe! transcription application by Seventh String Software:

Here's the spectrum for the G-based chord after "whine":

Anyway, if there's indeed some B natural in there, then the singer is just slightly bending towards that. But to me it sounds like an overdriven power chord without actually attempting to articulate a major third.
One more picture. G-D power chord played with a simple sawtooth waveform through an overdriven guitar amp simulation. Transcribe! suspects there's a bit of a B note, even though none was played. Even a single G note played with the saw wave has some B in its overtones, but with the overdrive it's louder.
Comment: I think this is it! Interesting question and interesting answer.  A sharp major third might be nails on a chalk board, but a sharp _minor_ third (especially sung over a major or open fifth chord as it is here) is quite agreeable.  The basketcase melody would even work if it was sharpened all the way to a B natural (as you well pointed out here with your yesterday example!)
Comment: Interesting idea. The odd[er] thing is that the G Maj 3rd is actually stated - I can kind of hear it myself & melodyne confirms it's there [top right of the first red box]. So we have an implicit minor 3rd [5th of the root key] & a stated major 3rd, yet he sings right in the cracks, in a kind of 'split the difference' manner.
Comment: [I've added some more info to the Q, without distorting the original point so it doesn't mess up your answer, just adding info I'd noticed after the initial Q]
Comment: @Tetsujin There appears to be a faint B and it's shown in the spectrum as well, but it sounds like an accident, maybe a B string sounding through a little bit. I compared the sound on the record to actual articulated major and minor barre chords played through an overdriven amp (sim really), and Green Day's chord sounds like just a power chord, not meant to be a major. I could use the G chord from Green Day as a guitar sample backing a G minor chord without problem.
Comment: It's *really* hard to tell from the video [which may not be the 'truth' anyway] but he seems to have the guitar tuned down to D not E, so there would be no open B… which doesn't help at all. The B still seems the most 'natural' pump, even if it's only the vocal doing it. [btw, there's no argument from me here, I just can't quite straighten it all out in my head. It's a punk song, it should be 'easy'. ;)
Comment: Bizarrely - & rarely do I get hung up on something like this;) - if I first split the track into component parts in Izotope RX, then drop across to Cubase/Melodyne, then there is *definitely* no Maj3rd [or any 3rd] in the guitar. I can hear it's no longer there & Melodyne doesn't hear one either. Even the vox doesn't 'feel' as sharp soloed, though it still registers the same on Melodyne. Perhaps is *is* psycho-acoustic; you hear it more when both guit & vox are playing together. Maybe I just *want* it to be Maj not min there??
Comment: @Tetsujin The B natural comes from overtones, and it's amplified by the overdrive. I added a picture where I'm playing a plain G power chord with a simple synthesized sawtooth sound, through a guitar amp simulator with a "crunchy" preset. The spectrum shows a B, and the Transcribe! application shows it as a potential note guess. Maybe Melodyne is fooled by the overtones. Figuring out what frequencies belong to what notes should be its area of expertise, but maybe it makes mistakes every now and then. But maybe Izotope RX does something that helps it get past the confusion.
Comment: I don't know why there are discontinuities in the note-guesses on the piano roll, in the middle of the sound's timeline. It's a continuous synthesized organ-like sound. Maybe GuitarRig's amp model adds some "motion" to it.
Answer: I'm the first to analyze any microtonal detail, but come on... it's a punk rock song. The intonation is a bit all over the place, and that's kind of for its own sake. Insanity, paranoia, self-suppression... there's a lot of inner conflict here, and the swaying, sort of over-boiling pitch expresses this better than anything.
What is special about the ⅲ is that the minor note isn't at all in the guitar part, and so the vocal part has more freedom do go astray without it being all to obvious. But to my ears it's still definitely too low to make it a Ⅲ chord. Though keep in mind that even a powerchord contains a just major third as an overtone, but not a minor third, in that sense the B-natural does indeed sound, and with the overdrive sound and absent anything else in the arrangement at that point, one may be tempted to hear it as more of an actual note than you otherwise would. Perhaps Melodyne is also falling fool to that, it's not that it can perfectly distinguish any sound components, just remarkably well.
Regarding comma pump, in principle there could indeed be one here: if you construct the Cm as a Pythagorean whole step over the B♭ (instead 5:3 sixth over the tonic), then the G in it is already sharper than 12-edo, and if you then build a just minor third over that, it'll be perhaps 20 cents sharp on paper. But again... in this genre, nah.
Comment: Thanks for pointing out the overtones in a power chord. But I didn't quite get what you're suggesting as the answer to the main point of the question - why doesn't the slightly sharp pitch feel irritating for this note? My intuitive hypothesis was that it's ok, because it's a third relative to the bass note and it's ok to bend the pitch anywhere between a minor and major third, as is regularly done in bluesy genres.
Comment: @piiperiReinstateMonica I wouldn't agree that it's "ok to bend the pitch anywhere between a minor and major third" as a general statement. It always has a certain effect that may or may not be appropriate. In this case I'd say it is appropriate mostly because the whole piece asks for angry and unconforming expression. But yeah, if the guitar played a full minor chord in a clean sound at that spot, the vocal would have probably adapted and sung the note a little flatter as well.


Switching between ASIO4ALL ON/OFF without having to shut down browser

Question: So we know that if you run ASIO4ALL while you have some other program running a sound output, ASIO4ALL shows audio output as unavailable, since it is locked for it, until you quit all the apps that are using the sound output, be it a browser, media player or windows sounds.
This is all fine, I can switch it off. However, is there no way to make a force block/shut the use of sound output, so that I can free it for ASIO4ALL without having to shut down my whole browsing session? I tend to have many windows opened with many tabs on different desktops. Killing the whole browser means I'll lose this complex hierarchy and it requires me to rebuild it, after I stop using Ableton (ASIO4ALL). Even hangout extension leaves chrome application open after closing of all windows, so I have to kill the browser manually.
This is a very tiresome process and I would like to know if someone solved this somehow already.
Comment: You can make ASIO work for multiple programs at the same time. See http://music.stackexchange.com/q/20484/7218
Comment: While not a direct solution, using a browser which remembers your session could help alleviate this problem.(Opera does this by default, but I am sure Mozilla and chrome can be configured for this too)
Comment: ASIO4ALL is an excellent resource, but this issue drives me nutty.  I'm dying to see a good solution.
Comment: You could set ASIO4All as your default sound engine and just use it always (depending on what other sound software you use.. this worked for me when using Ableton and Winamp). Not sure if your browser would support it though.
Answer: This is a very annoying problem. A google search has brought about a fix for FL Studio only. The same link (below) also mentions steps you can take to make ASIO your default sound driver by disabling the default in msconfig.
http://mtippach.proboards.com/thread/2732
Let's hope this works.
Comment: from what I know there are some disadvantages to using ASIO as general. It is not that ASIO would be better. ASIO is just better for this one purpose - making cheaper sound cards have shorter response time, so that you can play the instrument and have immediate feedback instead of one with latency. Performance of multiprocess environment might not be that good with ASIO
Answer: Killing the shockwave/flash without shutting down the browser may do the job. This works for some external sound cards and may work for ASIO4ALL as well.
Answer: I have spent years trying to find a solution for this problem, and I have written an article about this here:
Low latency audio on a Windows PC with the built-in soundcard
To summarize the idea, there are many programs that allow you to do this, and the best options nowadays are probably:

FlexASIO
O-Deus AsioLinkPro 22.214.171.124 (see the article above about the distribution of this softwareà
Answer: Go to sound control panel and uncheck 'allow exclusive access'. Probably that can increase ASIO4ALL latency a bit.
Comment: Update: you have to do this per each sound output, i.e., headphones, speakers and so on.


Solution of recursive differential equation

Question: I have to integrate:
$$dX_{t} = \alpha X_{t-1}dt$$
But I don't know if this should be interpreted as
$$\frac{1}{X_{t-1}}dX_{t} = \alpha dt$$
How can this $X_{t-1}$ be integrated w.r.t $dX_t$? Or how can it be integrated as $\alpha X_{t-1}dt$?
Comment: As I explained in my previous comment, your question is not well written and I think it may have mistakes. If you want to solve $\frac{d}{dt}X_t = \alpha X_{t-1}$ then that's fine, but this is a very different type of equation to the first one you give. If you edit your question to address the points I've raised, I will try to help you with your problem
Comment: I think your question has got a little confused. Do you mean to start with $\frac{d}{dt} f_k(t) = \alpha f_{k-1}(t),$ and then solve this equation by $f_k(t) = \frac{1}{k!}(\alpha t)^k$? If this is the case, you should edit your question to make it more clear. Then the second equation you have,  $\frac{d}{dt} X_t = \alpha X_{t-1},$ this is currently a very different type of equation because it doesn't depend on $k$. I wonder if you copied this one down wrong?
Comment: How is the second equation $\frac{d}{dt}X_t = \alpha X_{t-1}$ calculated?
Comment: I have edited it. I'm very confused with this, hope you can help me...
Answer: It looks to me that what you have here is a delay differential equation. I would consider dividing by $dt$ to write it as $$\frac{d}{dt}X_t = \alpha X_{t-1},$$ which is similar to the example considered here, at the end of the section 'The Characteristic Equation'. I think you then want to consider $X_t$ as a function of $t$, and integrate in $t$ to solve.
As in that example, try an ansatz of the form $X_t=Ae^{\lambda t}$. Substituting this into the equation gives a characteristic equation of the form $$\lambda =\alpha e^{-\lambda},$$ which can be solved for $\lambda$ in terms of the Lambert W function. Rearranging gives $\lambda e^{\lambda} =\alpha,$ with solution $\lambda = W(\alpha)$.
Then your original equation has solution $$X_t=Ae^{W(\alpha) t}.$$
Comment: @Sinem if you're happy with my answer, can you press the tick next to the voting arrows to accept it?


Changing default domain in domain access causes 'access denied' for admin

Question: I'm using Drupal 7 with the Domain Access module version 7.x-311. I've successfully configured a bunch of subdomains running sites correctly, with one subdomain as default.
All worked well until I swapped out the default domain with a new one. Now, every login attempt for admin including  user 1 hits an 'access denied'.
I've updated the domain access settings to set the new domain as default. I've also ensured that the default domain is not set in the settings.php file, plus set the domain cookies settings reflects the top-level domain.
I've also cleared cache and cleared browser cache and cookies, still I get an access denied. I cannot work it out.
Has anyone got advice on where to look next?
N
Comment: Hey @travis-johnston - thanks for the reply. I've cleared the session table as you suggested, and still no luck. There's no heavy caching in affect in this instance.
Answer: Caching would be my first thought, make sure to clear cache (through drush since you can't log in). Also if you have any heavy caching like Varnish - clear that too. You may have an active session still in Drupal for the admin account, try removing that via - drush sql-query 'TRUNCATE TABLE sessions;'


Continuity of a function at $x^*$ implies that a property $P(f(x^*))$ holds for points near $x^*$?

Question: I'm working through Numerical Optimization by Nocedal and Wright, and I'm having trouble with some of its proofs that seem too handwavy to me. Take the first theorem for example:

Theorem: If $x^∗$ is a local minimizer and $f$ is continuously differentiable
  in an open neighborhood of $x^∗$, then $∇ f (x^∗) = 0$.
Proof (excerpt): Suppose for contradiction that $∇ f (x^∗) \neq 0$.
  Define the vector $p = −∇ f (x^∗)$ and note that $$p^T ∇ f (x^∗) = − \|
 f (x^∗)\|^2 < 0.$$ Because $∇ f$ is continuous near $x^∗$, there is a
  scalar $T > 0$ such that $$\forall t ∈ [0, T ], p^T ∇ f (x^∗ + tp) < 0 $$

Similarly, in another proof (second-order necessary condition), the author assumes $∇^2 f (x^∗)$ is not positive definite (so $\exists p\in\mathbb{R}^n, p^T ∇^2 f (x^∗)p < 0$), and uses the (assumed) continuity of  $∇^2 f$ near $x^*$ to conclude the existence of a scalar $T > 0$ such that $\forall t ∈ [0, T ], p^T ∇^2 f (x^∗+tp)p < 0$.
On the surface, the argument roughly seems to be:
if $f$ is continuous at $x^*$, and a certain property $P$ holds for $f(x^*)$, then $P$ holds for $f(x)$ when $x$ is near $x^*$. But of course this is not true in general  (for example, take $f$ to be $f(x)=x$, $x^*=0$, $P(f(x^*))$ to be $f(x^*)\geq0$).
I would appreciate some help justifying such statements as "Because $∇ f$ is continuous near $x^∗$, there is scalar $T > 0$ such that $\forall t ∈ [0, T ], p^T ∇ f (x^∗ + tp) < 0 $", specifically using the $\epsilon-\delta$ definition of a continuous function in a metric space (what's the appropriate $\epsilon$ here?).
Comment: Well, the property used in the proof isn't just some general property. Consider the function $g : x\mapsto p^{\mathrm{T}}\nabla f(x)$. Due to the continuity of $\nabla f$ in a neighborhood of $x^*$ (I don't have the full context, so this is assumed from the provided proof excerpt) *and* the continuity of matrix multiplication, $g$ will be continuous, which will give you the final statement in the proof excerpt. The second proof is also omitting the (important but obvious) continuity of matrix multiplication.
Comment: I see; the continuity of $\nabla f(x)$ alone is not sufficient... Thanks!
Answer: The essence of this step is, if $\phi : X \to \Bbb{R}$ is continuous at a point $x_0 \in X$ and $\phi(x_0) < 0$, then there exists some $\delta > 0$ such that $\phi(x) < 0$ for all $x \in B(x_0; \delta)$. I hope you can justfy why, for fixed $p$, and continuously differentiable $f$,
$$x \mapsto p^\top \nabla f(x)$$
is continuous.
To prove this lemma, take $\varepsilon = |f(x_0)| = -f(x_0) > 0$. By the $\varepsilon$-$\delta$ definition of continuity, we know that there must exist some $\delta > 0$ such that
\begin{align*}
d(x, x_0) < \delta &\implies |f(x) - f(x_0)| < \varepsilon = -f(x_0) \\
&\implies f(x_0) < f(x) - f(x_0) < -f(x_0) \\
&\implies 2f(x_0) < f(x) < 0.
\end{align*}
Hence, $f(x) < 0$ for all $x \in B(x_0; \delta)$.
Comment: For the continuity of $p^⊤ ∇f(x)$, a simple application of Cauchy-Schwartz inequality shall suffice, right?
Comment: C-S is what you'd use, yes. You're composing the map $x \mapsto p^\top x$ (continuous by C-S) and $x \mapsto \nabla f(x)$ (continuous by assumption).


Profile2 Registration Path loose registration field after translate URL alias

Question: I use Profile2 and Profile2 Registration Path module. This is the original Registration Path, set in the configuration.
I tried to translate the Registration Path at Administration » Configuration » Search and metadata » URL aliases.
But when i visit for example the Belgium dutch version, i loose my extra added Profile field at my Registration form (RIZIV number)?
Answer: Profile2 Registration Path module does not support multilingual URL aliases. Profile2 fields are added to reg form based on the alias that you set up on profile2 edit form. That is why your profile2 fields are not displayed on dutch version of reg form. Your best choice is to remove translated alias and set your original regpath alias to something that sounds good in both languages. Or you can improve the module by adding multilingual alias support (though it may require some reworking in module's logic).
Comment: thanks. And is there any other module same like Profile2 where you can translate the aliases?
Comment: as of today - no


Organic groups api?

Question: I have the Organic Groups module working in my site, but when I try to use a simple function like og_load() in my module, I get the following error:

Call to undefined function og_load().

What should I do to use these functions?
Answer: og_load() is defined on the module file, which means it should be available once the module is enabled. Be sure to call the function when Drupal completed its bootstrap, and loaded all the enabled modules. If you call it inside hook_boot(), or hook_exit(), the function could not be available, if Drupal didn't complete its bootstrap.
Sometimes it's enough to increase the weight of the module calling og_load() to avoid the error (if the function is not called in the hooks I previously described). Execute the following code in hook_install(). (Replace mymodule with the short name of your module.)
$weight = db_query("SELECT weight from {system} WHERE name = 'og' AND type = 'module'")->fetchField();
db_update('system')
  ->fields(array('weight' => $weight + 1))
  ->condition('type', 'module')
  ->condition('name', 'mymodule')
  ->execute();

Comment: Well, the module is enabled, and working, and I'm trying to call the function in a simple [hook_preprocess_node](http://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7). I don't quite get how the weight would affect the access to the functions, but i'll check it up thanks
Answer: The function is undefined within the scope of your module because your module doesn't know about the Organic Groups module. You have to invoke the Organic Groups module before you can call its functions. (This is the case when using any module's functions.)
Using module_exists() should do the trick. As a bonus, it'll also protect you from unforeseen errors if the Organic Groups module is ever missing or turned off on your site:
if (module_exists('og')) {
  // your og_load() code goes here
}

Answer: If you are looking for drupal 7, the api function no more exist, instead node_load($group_id) can be used.
Check this issue link.

Organic groups api?


GoodData charts components throwing error of TypeError: item.predicate is not a function on setting color from configuration

Question: On setting colors from configuration and using Gooddata UI Charts component it is throwing following error
TypeError: item.predicate is not a function

My config is as follows, On reseting default color it is working fine but as change color i get the colorMapping object in the api and after applying this config throwing the error.
How can i resolve it, Please help me out.
<code>         config={{
            colorMapping: [{
              color: { type: "guid", value: "17" },
              id:"0d447449c2844b228923c37de7b6aaf9"
            }]
          }}
</code>
Answer: usage of ColorMapping is described in documentation
https://sdk.gooddata.com/gooddata-ui/docs/chart_config.html#Color-mapping
You need to define predicate function which when returning true, will apply corresponding color (https://sdk.gooddata.com/gooddata-ui/docs/ht_create_predicates.html).
In your case localId predicate seems to be right for you
https://github.com/gooddata/gooddata-ui-sdk/blob/master/libs/sdk-ui/src/base/headerMatching/HeaderPredicateFactory.ts#L264
In case you are using older version of Gooddata UI.SDK than v8, you need to implement predicate by your own. Something like this (or equivalent for measures).
<code>predicate: headerItem =>
        headerItem.attributeHeaderItem &&
        headerItem.attributeHeaderItem.localIdentifier === "0d447449c2844b228923c37de7b6aaf9", // find attribute item by localIdentifier
</code>
You can switch the official documentation to whathever version of Gooddata UI.SDK lib you are using and read the same article about ColorMapping
https://sdk.gooddata.com/gooddata-ui/docs/7.9.0/chart_config.html#color-mapping


Mysql 4.0.30 Error 1046... but working on 5.5!

Question: On our dev-server we've got MySql version 5.5, but on production server (from aruba.it) we've Mysql 4.0.30.
The SQL query that cause problem is:

SELECT r.iduser,ra.desapp,
  r.cognom,f.desfig, r.fl_dip, (Select
  sum(o.numore)/8 From  OreConsuntive o,
  Prjtask pt, Prjprogetti pp, Prjordini
  po Where o.IDuser = '54'and   o.dt_cns >= '20110101' and
    o.dt_cns <= '20110131' and o.codcop='F00' and
  o.codtsk=pt.codtsk and
  pt.codprj=pp.codprj and
  pp.codord=po.codord and
  left(po.cliatt,3)<>'CSA' group by
  o.numore) as TOTGIORNIFATTMESE FROM
  Risorse r, Figure f, RisorsaArea ra
  WHERE r.codfig=f.codfig AND
  r.areapp=ra.codapp AND r.IDuser='54'
  ORDER BY r.areapp desc

I'll try to execute only this part

Select sum(o.numore)/8
  From  OreConsuntive o, Prjtask pt,
  Prjprogetti pp, Prjordini po Where
  o.IDuser = '54'and o.dt_cns >=
  '20110101' and    o.dt_cns <= '20110131'
  and o.codcop='F00' and
  o.codtsk=pt.codtsk and
  pt.codprj=pp.codprj and
  pp.codord=po.codord and
  left(po.cliatt,3)<>'CSA' group by
  o.numore

and it seems to work!
Can the problem be caused by the annidated select ?
How con I modify my query to get a working one on mysql 4.0.30 ?
Thanks a lot!
Davide
Answer: MySQL versions prior to 4.1 do not support subqueries. You will have to rewrite your query to avoid that.
Unfortunately, I can't easily tell how to do that in your case, but try reading http://dev.mysql.com/doc/refman/4.1/en/rewriting-subqueries.html - it may help you to rewrite it.
I don't know your particular host, but if they cannot upgrade you to a newer MySQL, you should try to downgrade your development server to run the same version as your production server - a lot of things have changed since 4.0, and catching them early might be a good idea.


Beta distribution central moment

Question: I am studying the note "On the sub-Gaussianity of the Beta and Dirichlet distributions" written by Olivier Marchal and Julyan Arbel(2017) which is available here.
In page 5, it says
$$ E\Bigg[\Big(X-\frac{1}{2}\Big)^{2j}\Bigg]=\frac{(2j)!}{2^{2j}j!}\frac{\Gamma(2\alpha)\Gamma(\alpha+j)}{\Gamma(\alpha)\Gamma(2(\alpha+j))}=\frac{(2j)!}{2^{2j}j!}\frac{(\alpha)_j}{(2\alpha)_{2j}}$$
where $X \sim Beta(\alpha, \alpha)$, and $(\alpha)_j=\alpha(\alpha+1)...(\alpha+j-1)=\frac{\Gamma(\alpha+j)}{\Gamma(\alpha)}$.
Can someone tell me what algebra can make the expectation as RHS.
Answer: The Beta$(\alpha,\alpha)$ density, defined on the interval $[0,1],$ is
$$f_\alpha(t) = \frac{1}{B(\alpha,\alpha)}\, t^{\alpha-1}(1-t)^{\alpha-1}$$
where the normalizing constant is the Beta function, known to equal
$$B(\alpha,\alpha) = \int_0^1 t^{\alpha-1}(1-t)^{\alpha-1}\,\mathrm{d}t = \frac{\Gamma(\alpha)\,\Gamma(\alpha)}{\Gamma(2\alpha)}.\tag{*}$$
The substitution $t = (1+\sin\theta)/2$ is a one-to-one mapping from $[-\pi/2,\pi/2]$ to $[0,1]$ that re-expresses the expectation as
$$\begin{aligned}
E_{f_\alpha}\left[\left(X-\frac{1}{2}\right)^{2j}\right] &= \int_0^1 \left(t-\frac{1}{2}\right)^{2j}\,f_\alpha(t)\,\mathrm{d}t\\
&=\frac{1}{2^{2j+2\alpha-1}B(\alpha,\alpha)}\int_{-\pi/2}^{\pi/2} \cos^{2\alpha-1}(\theta)\,\sin^{2j}(\theta)\,\mathrm{d}\theta\\
&= \frac{B\left(j+\frac{1}{2},\alpha\right)}{2^{2j+2\alpha-1}B(\alpha,\alpha)}.
\end{aligned}$$
(The trigonometric integral is well known; see, for instance, Whittaker & Watson 12.42.)
Use the formula $(*)$ and the Gamma recurrence
$$\Gamma(z+1) = z\Gamma(z)$$
to re-express this in the form given in the question.

Reference
E. T. Whittaker  & G. N. Watson, A Course of Modern Analysis. Fourth Edition (1927).
Comment: Thank you very much. I fully understand the transformation. Since I didn't know $\Gamma(\frac{1}{2}+n)=\frac{(2n)!}{4^nn!}$, it took a little bit more time to reach the end of the equation.
Answer: A bit more precise answer: the central moments of beta distribution can be expressed in terms of the hypergeometric function.
https://mathworld.wolfram.com/BetaDistribution.html
The setup $\alpha=\beta$ from the question follows then as in such a case formulas greatly simplify (well-known special cases).

Beta distribution central moment


Is it possible to show taxonomy terms in a views filter sorted alphabetically?

Question: I have some content that is classified using a two-level taxonomy:
Accommodation -> B&B
Accommodation -> Hotels
Accommodation -> Self Catering
Things to Do -> Arts & Crafts
Things to Do -> Family attractions
Eating out -> Cafes
Eating out -> Restaurants
In some situations, I need to display all these categories together in views as a taxonomy filter.
When I do that, they are displayed grouped by the parent term, so they look weirdly random.  Is it possible to break them out from their parent term and show them in the filter sorted alphabetically, or alternatively, show the parent term as well as the child term, so that it's clear why the terms are sorted like that?
I am on Drupal 7, Views 3.11.
Answer: Upgrade taxonomy and views to the latest version and select the following options.

And when the filters terms are being listed, they will be listed in alphabetic order.

You can confirm that there is hierarchy in terms and they are not alphabtic in order.
Comment: That looks like exactly what I need, but I can't find it - I'm on Drupal 7.38, Views 3.11, and when I edit the filter, the only options I can see are : Dropdown, Autocomplete and Show hierarchy in Dropdown.   Where would I find these extra settings?


Confused results in my OpenMP code using task clause

Question: I am new to using the task clause in OpenMP and I am not sure if I have understood the meaning of it correctly. Here is my test code:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void task(int p)
{
    printf("Thread ID: %d, task: %d\n", omp_get_thread_num(), p);
}

#define N       5
int main(int argc, char* argv[])
{
    int i;
#pragma omp parallel num_threads(3)
    {
#pragma omp single
        {
            for(i = 0;i < N; i++)
            {
            #pragma omp task
                task(i);
            }
        }
    }
return 0;
}

I use the Intel 16.0 compiler to compile my code and expect to get the output like this:
- Thread ID: 0, task: 0
- Thread ID: 2, task: 4
- Thread ID: 2, task: 3
- Thread ID: 0, task: 1
- Thread ID: 1, task: 2

However, the actually output of this code is:
- Thread ID: 0, task: 5
- Thread ID: 2, task: 5
- Thread ID: 2, task: 5
- Thread ID: 0, task: 5
- Thread ID: 1, task: 5

The output of 'task:' is fixed to be 5 instead of ranging from 0 to 4 which is not what I expected to be. Can anyone help me to understand this result?
Comment: I have also tried the gcc 4.4.7 compiler , the result is similar to the Intel compiler
Answer: The problem is related to the implicit data-sharing of i in the task construct.
If I recall correctly, i is determined to be shared in the task construct because this variable is implicitly determined to  be shared in the parallel, but perhaps i'm wrong. Assuming that I'm right, your code generates a race-condition since the task is capturing &i rather than the value of i. Note that i is passed by value once the task is executed (and potentially the value of i can be 5).
My advice: if you are not sure about the implicit data-sharing of a variable, make it always explicit. In your case, annotate the task with firstprivate(i)
Answer: The problem you're observing is due to the variable visibility. I have rerun your application while compiling it for gcc 4.8.4 and icc 16.0.3 and I got the following results (which vary across executions):
gcc
Thread ID: 2, task: 1
Thread ID: 2, task: 5
Thread ID: 2, task: 5
Thread ID: 1, task: 5
Thread ID: 0, task: 2

icc
Thread ID: 0, task: 5
Thread ID: 1, task: 3
Thread ID: 1, task: 5
Thread ID: 0, task: 5
Thread ID: 2, task: 5

Since visibility of variable i is not declared in the #pragma omp construct the compiler decides that i should be declared as shared, which means that modifications done by any thread are observed by the remaining threads.
In your case, since you expect messages being printed showing task 0 to 4, that means that each thread should have its private copy of i, as in the following code -- which derives from yours. Notice the modification in the #pragma omp parallel:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

void task(int p)
{
  printf("Thread ID: %d, task: %d\n", omp_get_thread_num(), p);
}

#define N       5
int main(int argc, char* argv[])
{
  int i;
  #pragma omp parallel num_threads(3) private(i)
  {
    #pragma omp single
    {
      for(i = 0;i < N; i++)
      {
        #pragma omp task
        task(i);
      }
    }
  }
  return 0;
}

The result of this version, no matter the compiler you use, is:
Thread ID: 2, task: 1
Thread ID: 2, task: 3
Thread ID: 2, task: 4
Thread ID: 1, task: 0
Thread ID: 0, task: 2

NOTE that the placement of private can either go into the #pragma omp parallel construct, or as user smateo suggests, it can go into the #pragma omp task (but in the latter case as firstprivate to keep the value of the variable when going into the task construct). The actual decision on where it goes depends on the semantics of your application.
Comment: May I suggest you then to accept / upvote any of our answers? http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow


Disable rewrite of html_tag?

Question: In my module
<code>    function hook_page_attachments(array &$page) {

      $og_image = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' => 'og:image',
          'content' =>   'http://example.com/pic.php?id=839813.jpg&size=300',
        ),
      );

      $page['#attached']['html_head'][] =  [$og_image, 'og:image'];
}
</code>
On the page the results look like this
<code><meta property="og:image" content="http://example.com/pic.php?id=839813.jpg&size=300" />
</code>
The & is replaced for html use. Can I avoid that or added meta tags in another way?
Answer: I build a workaround. I created a custom path in drupal that redirect to the external image url like /image/{img-id} . If anyone find an answer on the main question please post.

Disable rewrite of html_tag?


Prove Cauchy-Schwarz equality.

Question: My professor asked me to prove the equality in Cauchy-Schwarz inequality. The equality holds iff the vectors $v$ and $u$ are linearly dependent.
I am able to show the equality using the fact $v$ and $u$ are linearly dependent.
But I don't know how to show the converse (i.e Showing the linear dependence using the equality).
Comment: A good start would be to look at your proof of this inequality. Given that, we can show you where to tinker a little to obtain the linear dependence from the equality.
Answer: \begin{align}
\|\vec u+t\vec v\|^2 & = t^2 \|\vec v\|^2 + 2t\vec u\cdot\vec v + \|\vec u\|^2 \\[10pt]
& = at^2+bt+c.
\end{align}
This quadratic polynomial with $a>0$ is positive for every $t$ if the discriminant $b^2-4ac$ is negative, and is positive for all except one value of $t$ if the discriminant is $0$.  Express the discriminant in terms of $\|\vec u\|$, $\|\vec v\|$, and $\vec u\cdot\vec v$.
Comment: @Hendrra : The point is that it has _no_ zeros except in the case where there is some value of $t$ for which $\vec u + t\vec v$ is $\vec0,$ i.e. except where $\vec u$ is a scalar multiple of $\vec v. \qquad$
Comment: That's a nice solution. I wonder however why the discriminant has to be equal to zero? Why does the quadratic polynomial must have only one zero?
Answer: Hint: Let $z = pr_u (v) = \frac{\langle u,v\rangle}{\|u\|^2} u$  then we may write $v = z + w$, with $w \perp z$. By  Pythagoras Theorem $$\|v\|^2 = \|z\|^2 + \|w\|^2$$
Then $$\|v\| \geq \|z\|$$
And $\|v\| = \|z\| \implies\|w\| = 0$.
Comment: Notice my edit and the different appearance of the notation afterwards.  That is standard usage.
Comment: @MichaelHardy Thanks! I didn't know that!
Answer: The CS inequality is: $|u\cdot v|^2 \leq|u|^2 |v|^2$ .
Observe that : $\left(|u| - t|v|\right)^2 \geq 0, \forall t \in \mathbb{R}$ expanding this and treat it as a quadratic function in variable $t$. This is true for all $t$ implies $\triangle \leq 0 \to$ CS inequality follows, with equality when $|u| = t|v| \to u = \pm tv \to$ linear dependent.
Answer: Suppose that
$$
|u\cdot v|=\|u\|\,\|v\|\tag{1}
$$
This means that $u\cdot v=\pm\|u\|\,\|v\|$. Then
$$
\begin{align}
\|u-tv\|^2
&=(u-tv)\cdot(u-tv)\\
&=\|u\|^2\pm2t\|u\|\,\|v\|+t^2\|v\|\\
&=(\|u\|\pm t\|v\|)^2\tag{2}
\end{align}
$$
If $\|v\|=0$, then $u$ and $v$ are dependent (vacuously).
If $\|v\|\ne0$, then, by division, there is a $t$ so that $\|u\|\pm t\|v\|=0$. Using that $t$, $(2)$ says that $\|u-tv\|=0$, that is
$$
u=tv\tag{3}
$$
in which case $u$ and $v$ are dependent.

Prove Cauchy-Schwarz equality.


What is the equivalent of a call to drupal_http_request()?

Question: In Drupal 7 I am using the following code.
<code>$url = 'testdomain/url';
$response = drupal_http_request($url, array('method' => 'POST', 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8')));
if ($response->code == "200") {
  $result = $response->data;
}
</code>
What is the equivalent code I should use on Drupal 8?
Answer: Finally i find a code in https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8 (1375)
and its working for me :)
<code> try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }
  }
  catch (RequestException $e) {
    return FALSE;
  }
</code>
Hope this will help for some one
Comment: No surprise, but this works for Drupal 9 as well.
Answer: HTTP client library added to replace drupal_http_request()
<code>$client = \Drupal::httpClient();
$request = $client->createRequest('GET', $feed->url);
$request->addHeader('If-Modified-Since', gmdate(DATE_RFC1123, $last_fetched));

try {
  $response = $client->get($feed->uri, [
    'headers' => [
      'If-Modified-Since' => gmdate(DATE_RFC1123, $last_fetched),
    ],
  ]);
  // Expected result.
  // getBody() returns an instance of Psr\Http\Message\StreamInterface.
  // @see http://docs.guzzlephp.org/en/latest/psr7.html#body
  $data = $response->getBody();
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e);
}
</code>
Comment: Not Working :( "The website encountered an unexpected error. Please try again later.)

Watchdog error is :

Recoverable fatal error: Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, string given, called in /var/www/drupal8/vendor/guzzlehttp/guzzle/src/Client.php on line 87 and defined in GuzzleHttp\Client->request() (line 126 of /var/www/drupal8/vendor/guzzlehttp/guzzle/src/Client.php)
Comment: https://www.drupal.org/node/1862446#comment-10640294
Comment: They fixed it, but yeah, change records are the first place to check :)
Comment: The code above uses $last_fetched var which is not defined anywhere and also in one place uses $feed->url and in onther $feed->uri
Comment: The error comes up as the RequestException class is not defined. Add use GuzzleHttp\Exception\RequestException;
Answer: This is working for me, sending a XML file with \Drupal::httpClient() POST
<code>$endpoint  = 'http://example.com/something';
$xml = '<>'; // You're XML here.

// Make the request.
$options = [
  'connect_timeout' => 30,
  'debug' => true,
  'headers' => array(
    'Content-Type' => 'text/xml',
  ),
  'body' => $xml,
  'verify'=>true,
];

try {
  $client = \Drupal::httpClient();
  $request = $client->request('POST',$endpoint,$options);

}
catch (RequestException $e){
  // Log the error.
  watchdog_exception('custom_modulename', $e);
}

$responseStatus = $request->getStatusCode();
$responseXml = $request->getBody()->getContents();
</code>
Hope this helps.
More info about Guzzle here: http://docs.guzzlephp.org/en/latest/index.html


How to Post Json array of objects in AngularJS (using $resource save or via $http service) and How to consume it in Resteasy

Question: At first step, I achieved successfully to save a single user via $resource save in angularjs passed to Resteasy service and eveything works well.
At second step, What I'm trying to do now here is, I want to Post the JSON of array of users (and save  in onego via angularjs $resource save this array of objects) to consumer Restful WebService (I use Resteasy).
my json looks like this, right now (an array of users):
 [
        {
            "userid": 1,
            "firstName": "kevin",
            "lastName": "buruk",
            "email": "firstname.lastname@example.com"
        },
        {
            "userid": 2,
            "firstName": "helm",
            "lastName": "krpuk",
            "email": "email@example.com"
        },
        {
            "userid": 3,
            "firstName": "batok",
            "lastName": "kelapa",
            "email": "firstname.lastname@example.com"
        }
    ]

Backend
To achieve my goal I operate few changes on my previous working backend specifically on UserClientServiceImpl like so :

1- By changing the signature of create method (see code below) from
final User user signature onto final User[] users signature, to
handle array of users instead of a single user.
2- and by adding a loop FOR. to request the already well confirmed
working create     userService
@Path("/users")
public class UserClientServiceImpl implements UserClientService {
  @POST
  @Consumes(RestCookieBuilder.JSON_UTF8)
  @Produces(RestCookieBuilder.JSON_UTF8)
  @Override
  public Response create(final User[] users) {<---------Is Signature here is ok?

    Response.ResponseBuilder responseBuilder = Response.ok();

    for(User user : users) {

      try {

        userService.create(user);

      }
      catch(Exception e) {
        responseBuilder = Response.status(Response.Status.EXPECTATION_FAILED).entity("{\"error\":\""
                                                                                + "canceled user :("
                                                                                + e.getMessage() + ")\"}");
      }

    }

    return responseBuilder.build();
  }

}

Frontend
and changed my UserService in angularjs  by adding to save: isArray: true
because we are now not working anymore with a single user but instead we are
working with an array of users.
In AngularJS, on this service I wrote the below code
 (function () {

        'use strict';

        angular.module('app').factory('UserService', function ($resource){

            return $resource('rest/users/', [],
                {
                    delete: {method: 'DELETE', url: 'rest/users/:id'},
                    save: {method: 'POST',url: 'rest/users',isArray: true},
                    findAll: {method: 'GET', url: 'rest/users'},
                });

        });

    })();

In AngularJS, I made also some changes to the below controller code to post via $ressource to the WebService.
in my controller this time, I created a list of users
and then tried 2 things:
1-My first attempt was to post via $ressource save to the WebService (The code part
 that is commented in below Listing).
2-My second attempt was to post via $http to the WebService (see below in Listing).
var list = [];

            for(i = 0; i < users.length; i++) {
                var user={};
                user=users[i]['value'];
                list.push(user);
            }

            /*UserService.save(JSON.stringify(list), function (success) {
              $element.modal('hide');
              close({type: 'success', msg: 'Users created successfully'}, 500);
            }, function (error) {
              alert(" Errorrs for users  !!!!!! "+i);
              createErrorAlert(error);
            });*/

            var liststringifyed=JSON.stringify(list);
            $http.post("rest/users",{users:liststringifyed})
            .success(function (data, status, headers) {
                $scope.ServerResponse = data;
                $element.modal('hide');
                  close({type: 'success', msg: 'Users created successfully'}, 500);
            })
            .error(function (data, status, header, config) {
                $scope.ServerResponse =  data ;

                alert(" Errorrs for users  !!!!!! "+i);

            });

};

as you can see my first attempt see the commented part on code i.e UserService.save(JSON.stringify(list), function (success) it's not working.
on the other hand, in my second attempt I tried also with $http service like you can see but no result either.
Question about Backend:
What's the correct syntax for RestEasy service to consume that json users array ?
I mean : on line public Response create(final User[] users) is (final User[] users) as signature would be accepted or should I use other
 workarounds e.g URI or String AnArray and parse that String like here:
public  create (String AnArray) {
           JSONArray o = new JSONArray(AnArray);

                System.out.println(o.toString());

                return responseBuilder.build();
}

on the other  hand on front-end:
-What's the correct syntax in the UserService angularjs to achieve to successfully use save from angularJS $resource  service on this case where an array of objects is passed?
is the line JSON.stringify my list is the right thing to do
For $ressource.save
UserService.save(JSON.stringify(list), function (success) {

OR
For $http service
var liststringifyed=JSON.stringify(list);
$http.post("rest/users",{users:liststringifyed}){

N.B: if we can not use save from $resource for that case
     how to achieve this using $http service ?
Many thanks for your help.
Answer: Watch out a late answer but may be helpful for others , verify and check that you Post something like this:
[
        {
            "userid": 1,
            "firstName": "kevin",
            "lastName": "buruk",
            "email": "firstname.lastname@example.com"
        },
        {
            "userid": 2,
            "firstName": "helm",
            "lastName": "krpuk",
            "email": "email@example.com"
        },
        {
            "userid": 3,
            "firstName": "batok",
            "lastName": "kelapa",
            "email": "email@example.com"
        }
]

and not like the following Because by sending or Posting this:
{"users":[
        {
            "userid": 1,
            "firstName": "kevin",
            "lastName": "buruk",
            "email": "firstname.lastname@example.com"
        },
        {
            "userid": 2,
            "firstName": "helm",
            "lastName": "krpuk",
            "email": "email@example.com"
        },
        {
            "userid": 3,
            "firstName": "batok",
            "lastName": "kelapa",
            "email": "firstname.lastname@example.com"
        }
    ]
"}

you are posting an object with a single 'users' named property. you are not posting an array
So my case I were sending an object with a single named property, and when you receive this on backend try to remove the laste two caracters and the substring matching {"users":
another thing on the backend your parameter string  is a jsonstring so you have to remove all backsalshes to get a valid json.
so to answer this you have to add
dependencies to maven
<dependency>
           <groupId>org.json</groupId>
           <artifactId>json</artifactId>
           <version>20180813</version>
</dependency>
<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
</dependency>

add to
======
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;

  @POST
  @Consumes(RestCookieBuilder.JSON_UTF8)
  @Produces(RestCookieBuilder.JSON_UTF8)
  @Override
  public Response create(String AnArray) {
    String string2 = "{\"users\":\"";
    int index = AnArray.indexOf("{\"users\":\"");
    if(index == -1) {
      // Not found. What do you want to do?
    }
    else {
      String result = AnArray.substring(0, index) + AnArray.substring(index + string2.length());
      result = result.substring(0, result.length() - 2);
      String jsonFormattedString = result.replaceAll("\\\\", "");
      AnArray = jsonFormattedString.trim();
    }

    Response.ResponseBuilder responseBuilder = Response.ok();
    try {
      String passedObj = AnArray.trim();

      JSONArray array = new JSONArray(passedObj);
      User[] users = new User[array.length()];

      for(int i = 0; i < array.length(); i++) {

        JSONObject jsonObject = (JSONObject) array.get(i);

        Gson gson = new Gson();
        Object object = gson.fromJson(jsonObject.toString(), User.class);

        users[i] = (User) object;

      }

      for(User user : users) {

        try {
            userService.create(user);

        }
        catch(UserException e) {
          responseBuilder = Response.status(Response.Status.PRECONDITION_FAILED).entity("{\"error\":\""
                                                                                + "Users not created: ("
                                                                                + e.getMessage() + ")\"}");
        }
      }
    }
    catch(Exception e) {
      e.getMessage();
    }

    return responseBuilder.build();
  }

on the frontend AngularJS
=========================
  $http.post("rest/users",{users:liststringifyed})
                    .success(function (data, status, headers) {
                        $scope.ServerResponse = data;
                        $element.modal('hide');
                          close({type: 'success', msg: 'users created in onego'}, 500);
                    })
                    .error(function (data, status, header, config) {
                        $scope.ServerResponse =  data ;

                        alert(" Errorrs !!!!!! "+i);
                         // createErrorAlert($scope.ServerResponse);

                    });


Sending and receiving custom objects using Tcpclient class in C#

Question: I have a client server application in which the server and the client need to send and receive objects of a custom class over the network. I am using TcpClient class for transmitting the data. I am serializing the object at the sender side and sending the resulting stream of bytes to the receiver. But at the receiver, when I try to de-serialize the bytes received, it throws Serialization Exception and the details are :

The input stream is not a valid
  binary format. The starting contents
  (in bytes) are:
  0D-0A-00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00
  ...

My server code that serializes the object is:
byte[] userDataBytes;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, new DataMessage());
userDataBytes = ms.ToArray();
netStream.Write(userDataBytes, 0, userDataBytes.Length);

The client code that de-serializes it is:
readNetStream.Read(readMsgBytes, 0, (int)tcpServer.ReceiveBufferSize);
MemoryStream ms = new MemoryStream(readMsgBytes);
BinaryFormatter bf1 = new BinaryFormatter();
ms.Position = 0;
object rawObj = bf1.Deserialize(ms);
DataMessage msgObj = (DataMessage)rawObj;

Please help me to solve this problem and possibly suggest any other method to transmit objects of custom classes across network using TcpClient in C#.
Thanks,
Rakesh.
Answer: Have a look at this code. It takes a slightly different approach.
Example given by the link above: - Note: there was another problem he was facing which he solved here (keep-alive). It's in the link after the initial sample code.
Object class to send (remember the [Serializable]):
[serializable]
public class Person {
   private string fn;
   private string ln;
   private int age;
   ...
   public string FirstName {
      get {
         return fn;
      }
      set {
         fn=value;
      }
   }
   ...
   ...
   public Person (string firstname, string lastname, int age) {
      this.fn=firstname;
      ...
   }
}

Class to send object:
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

class DataSender
{
  public static void Main()
  {
   Person p=new Person("Tyler","Durden",30); // create my serializable object
   string serverIp="192.168.0.1";

   TcpClient client = new TcpClient(serverIp, 9050); // have my connection established with a Tcp Server

   IFormatter formatter = new BinaryFormatter(); // the formatter that will serialize my object on my stream

   NetworkStream strm = client.GetStream(); // the stream
   formatter.Serialize(strm, p); // the serialization process

   strm.Close();
   client.Close();
  }
}

Class to receive object:
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

class DataRcvr
{
  public static void Main()
  {
   TcpListener server = new TcpListener(9050);
   server.Start();
   TcpClient client = server.AcceptTcpClient();
   NetworkStream strm = client.GetStream();
   IFormatter formatter = new BinaryFormatter();

   Person p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object

   Console.WriteLine("Hi, I'm "+p.FirstName+" "+p.LastName+" and I'm "+p.age+" years old!");

   strm.Close();
   client.Close();
   server.Stop();
  }
}

Answer: When receiving on client side you do not know how much data you want to read.
You are only relying on the ReceiveBufferSize, while your data can be larger
or smaller then that.
I think the best approach here is to send 4 bytes that tells your client about the length of incoming data:
byte[] userDataLen = BitConverter.GetBytes((Int32)userDataBytes.Length);
netStream.Write(userDataLen, 0, 4);
netStream.Write(userDataBytes, 0, userDataBytes.Length);

and on the recieving end you first read the data length and then read
exact amount of data.
byte[] readMsgLen = new byte[4];
readNetStream.Read(readMsgLen, 0, 4);

int dataLen = BitConverter.ToInt32(readMsgLen);
byte[] readMsgData = new byte[dataLen];
readNetStream.Read(readMsgData, 0, dataLen);

Infact, I just realized, that you might has to do a little more to assure you read all data (just an idea because I haven't tried it, but just incase you run into problem again you can try this).
The NetworkStream.Read() method returns a number indicating the amount of data it has read. It might be possible that the incoming data is larger then the RecieveBuffer. In that case you have to loop until you read all of the data. You have to do something like this:
SafeRead(byte[] userData, int len)
{
    int dataRead = 0;
    do
    {
        dataRead += readNetStream.Read(readMsgData, dataRead, len - dataRead);

    } while(dataRead < len);
}

Answer: TCP is stream-based protocol (as opposed to datagram protocol) so it's possible to receive only part of sended data via Read method call.
To solve this problem you may use DataLength field (as cornerback84 suggested) or you may use your own "application-level packet" structure.
For example, you may use something like this
|-------------------------------|
|Begin|DataLength|   Data   |End|
| 4b  |   4b     | 1..MaxLen|4b |
|-------------------------------|

where
Begin - start packet identifier (for example 0x0A, 0x0B, 0x0C, 0x0D)
DataLength - Data field length (for example, from 0 to MaxLength)
Data - actual data (serialized Person class or some other data)
End - end packet identifier (for example 0x01, 0x05, 0x07, 0x0F).
That is, on client side you would wait not only for incoming data, after receiving data you would search you Application level packets, and you may deserialized Data part only after receiving valid packet.


Consultar métodos, classes e atributos na linguagem C

Question: Eu queria saber se na linguagem C e possível consulta bibliotecas disponíveis suas classes módulos e atributos como na linguagem Python que existe os métodos dir() e help() eu estou começando a aprender C gora e estou meio perdido. Vou citar um exemplo.
Eu importo a biblioteca stdio.h para trabalhar com dados de entrada de entrada e saída mas mas eu não sei os módulos, variáveis, nem classes que a biblioteca possui. Existe algum macete para me ajudar na hora do desenvolvimento?
#include <stdio.h>

int main()
{
  printf("C da depressão :\(\n");
  return 0;
}

Answer: C só possuem funções, constantes, tipos definidos, macros (que até somem antes da linguagem em si ser processada) e variáveis globais (ainda que raro, porque é desaconselhável). Uma forma de achar as informações é olhar os arquivos header (.h) onde tem as declarações.
Não aconselho tentar aprender dessa forma em nenhuma linguagem. É melhor procurar uma forma mais estruturada, provavelmente um bom livro. É até possível uma pessoa criar seu próprio método de estudo se ela já tiver um bom domínio de programação e ser fortemente autodidata com uma estrutura de comprovada eficácia. Não tente adivinhar o que as coisas fazem, aprenda o que realmente fazem e como usar. Programar não pode ser baseado em achismo, voluntarismo e tentativa e erro. Procure a documentação. Esse é o macete.

GNU
Microsoft
Man pages
Cppreference.com
Cplusplus.com

Só para complementar, já que a pergunta não fala sobre isso, mas a outra resposta é misleading: C, como Python, possui tipos para todos os dados. C, ao contrário de Python, possui tipos para todas variáveis. Os tipos disponíveis por padrão em C são: char, signed char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long, float, double, long double, _Bool ou bool (disponível em praticamente todos compiladores), struct, union, array e ponteiro.
Existem ainda alguns tipos definidos puramente em biblioteca, entre eles (não todos) size_t, intN_t, int_leastN_t, int_fastN_t, intptr_t, intmax_t, inclusos em <inttypes.h> e <stdint.h>.
Ponteiros e arrays acabam, de certa forma, se confundindo.
Ponteiros, assim como arrays, sempre são usados em composição com outros tipos. Ele serve tanto como referência para um tipo, como para indicação de uma sequência de dados de seu tipo. O ponteiro pode ser composto inclusive com funções. O conceito de string só existe mesmo no literal entre aspas e algumas funções em <string.h>, no fundo é apenas um ponteiro para char.
É possível criar seus próprios tipos, normalmente através de uma struct e typedef.
Eu entendo o que quis dizer a outra resposta, mas é bom deixar claro que dict do Python tem semântica bem diferente de struct. Na verdade acho que uma comparação até melhor seria a classe do Python com a estrutura do C. Pelo menos na forma mais simples da classe, se assemelha mais a uma struct, ainda que não dê as mesmas garantias. De fato a forma de simular uma classe em C é com struct. Simular um dict exige algo ainda mais complexo feito por conta própria ou usando uma biblioteca pronta.
Coloquei no GitHub para referência futura.
Answer: A linguagem C não possui Classes e/ou módulos como Python, Java, ou C++. O mais próximo disso são as structs que se assemelham com as dict em python.
Em relação as variáveis, o C possui int (inteiro),char (caractere), char* (texto), float (ponto flutuante), long int, e outros.
Além desses tipos de variáveis, tem as structs que funcionam bem semelhante a objetos, tanto que em C++, uma struct pode representar uma classe com construtores de destruidores.
Os comandos dir() e help(), só existem em python, pelo menos todas as outras linguagens que trabalhei não possuem essas funções. Em C, tem de se olhar a documentação, ou ver o tipo de valor de entrada e saída dos métodos através das IDEs.
Comment: ficar lendo o arquivo header das bibliotecs e meio chato, e a IDE que eu uso nao e muito boa nesse sentido eu uso CodeBlocks


Validating the data entered in numeric input in RShiny

Question: I am developing the Shiny app in which if the user enters non-numeric characters, the value should be changed to the value mentioned in updateNumericInput().
Here is my Rcode
library(shiny)
ui <- fluidPage (
  numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)

server <- function(input, output, session) {
  observeEvent(input$current, {
    updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
                           if(!(is.null(input$current) || is.na(input$current))){
                           if(input$current < 40){
                             40
                           }else if(input$current > 80){
                             80
                           } else{
                             return (isolate(input$current))
                           }
                         }
      })
    )
  })

  }

shinyApp(ui=ui, server = server)

Can anyone help me with this code?
Answer: Something like this?
library(shiny)
ui <- fluidPage (
  numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)

server <- function(input, output, session) {
  observeEvent(input$current, {
    updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
      else if(!(is.null(input$current) || is.na(input$current))){
        if(input$current < 40){
          40
        }else if(input$current > 80){
          80
        } else{
          return (isolate(input$current))
        }
      }
      else{40}
    })
    )
  })

}

shinyApp(ui=ui, server = server)

Comment: Similar to this. If I enter **!(is.numeric(input$current))** in **if else** in my existing code it is not working.. Any solution available for this? @Pork Chop
Comment: it has to be evaluate first
Comment: use my solution
Comment: With your solution, I cannot check if there is no value entered in numericInput. Can you elaborate please!!
Comment: I have updated my code as per your solution. But still I didn't get the expected output. The updated code is above. Can you help me out? @Pork Chop
Comment: It works.. Thanks.. I accept your solution. @Pork Chop
Comment: @NevedhaAyyanar please click accept the answer if this is what you are looking for.  Avoid saying `thanks` and `it works` as other member of the community will need to reference it too https://stackoverflow.com/help/someone-answers


program to find the largest number in arraylist

Question: Let us imagine that we are having a arraylist in java which contains both intergers and strings value. I would like to loop through the entire arraylist(only taking the integers,ignore string) to find the largest number on the list???i need a program for this task????help me please
Comment: Could you show us what you've tried?
Comment: possible duplicate http://stackoverflow.com/questions/1484347/java-max-min-value-in-an-array
Comment: Use a for-loop with an `instanceof` check.
Comment: Questions asking for code must demonstrate a minimal understanding of the problem being solved.
Answer: Asuming an Object ArrayList, something like this should work:
int biggest = Integer.MIN_VALUE;
for (Object item : list) {
    if(item instanceof Integer && (Integer) item > biggest)
        biggest = item;
}

Comment: @MarkoTopolnik True, fixed.
Answer:
Don't keep different data types in a list. Use generics extensively.
you can use instanceOf (ArrayList keeps Integers and Strings) to check type and put the int's seperately and get the largest value.
Answer: private int getLargestNumber(ArrayList<Objects> list){
    int max = Integer.MIN_VALUE;
    for(int i = 0; i < list.size(); i++){
        Object obj = list.get(i);
        if(obj instanceof Integer && max < (Integer) obj)
                max = (Integer)obj;
    }
    return max;
}

Answer: When you pass a ArayList object to the below function it will return the bigest Integer from the list ..
 public static Integer getLargerInteger(ArrayList list){
    ArrayList temp=new ArrayList<Integer>();
    for (Object object : list) {
        if(object instanceof Integer){
            temp.add(object);
        }
    }
    return Collections.max(temp);
}

Answer: You can try the below approach using Comparator Interface rather then looping through all the elements.
    List arr = new ArrayList();
    arr.add(2);
    arr.add(5);
    arr.add(10);
    arr.add(20);
    arr.add("s1");
    arr.add("s2");
    arr.add("s3");

    Collections.sort(arr, new Comparator<Object>() {

        @Override
        public int compare(Object o1, Object o2) {

            if(o1 instanceof Integer && o2 instanceof Integer){
                Integer ob1 = (Integer) o1;
                Integer ob2 = (Integer) o2;
                return ob2.compareTo(ob1);
            }else{
                return -1;
            }
        }

    });
    System.out.println(arr.get(0));


Rails app using sqlite3 for development won't deploy into heroku

Question: I am trying to deploy a rails app that I created using SQLite3. But  after running git push heroku master I keep getting the following error
Initializing repository, done.
Counting objects: 164, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (147/147), done.
Writing objects: 100% (164/164), 78.88 KiB | 0 bytes/s, done.
Total 164 (delta 33), reused 0 (delta 0)

-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using 1.6.3
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
       Fetching gem metadata from https://rubygems.org/.........
       Fetching additional metadata from https://rubygems.org/..
       Installing rake 10.3.2
       Installing i18n 0.6.9
       Installing minitest 5.3.5
       Installing thread_safe 0.3.4
       Installing builder 3.2.2
       Installing erubis 2.7.0
       Installing rack 1.5.2
       Installing mime-types 1.25.1
       Installing polyglot 0.3.5
       Installing json 1.8.1
       Installing arel 184.108.40.20640414130214
       Installing coffee-script-source 1.7.0
       Installing execjs 2.2.0
       Installing thor 0.19.1
       Using bundler 1.6.3
       Installing hike 1.2.3
       Installing multi_json 1.10.1
       Installing sass 3.2.19
       Installing tilt 1.4.1
       Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
       /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/ruby-2.0.0/bin/ruby extconf.rb
       checking for sqlite3.h... no
       sqlite3.h is missing. Try 'port install sqlite3 +universal',
       'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
       and check your shared library search path (the
       location where your sqlite3 shared library is located).
       *** extconf.rb failed ***
       Could not create Makefile due to some reason, probably lack of necessary
       libraries and/or headers.  Check the mkmf.log file for more details.  You may
       need configuration options.
       Provided configuration options:
       --with-opt-dir
       --without-opt-dir
       --with-opt-include
       --without-opt-include=${opt-dir}/include
       --with-opt-lib
       --without-opt-lib=${opt-dir}/lib
       --with-make-prog
       --without-make-prog
       --srcdir=.
       --curdir
       --ruby=/tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/ruby-2.0.0/bin/ruby
       --with-sqlite3-dir
       --without-sqlite3-dir
       --with-sqlite3-include
       --without-sqlite3-include=${sqlite3-dir}/include
       --with-sqlite3-lib
       --without-sqlite3-lib=${sqlite3-dir}/
       --enable-local
       --disable-local
       Gem files will remain installed in /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/bundle/ruby/2.0.0/gems/sqlite3-1.3.9 for inspection.
       Results logged to /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/bundle/ruby/2.0.0/gems/sqlite3-1.3.9/ext/sqlite3/gem_make.out
       Installing rack-test 0.6.2
       Installing tzinfo 1.2.1
       An error occurred while installing sqlite3 (1.3.9), and Bundler cannot continue.
       Make sure that `gem install sqlite3 -v '1.3.9'` succeeds before bundling.
       Bundler Output: Fetching gem metadata from https://rubygems.org/.........
       Fetching additional metadata from https://rubygems.org/..
       Installing rake 10.3.2
       Installing i18n 0.6.9
       Installing minitest 5.3.5
       Installing thread_safe 0.3.4
       Installing builder 3.2.2
       Installing erubis 2.7.0
       Installing rack 1.5.2
       Installing mime-types 1.25.1
       Installing polyglot 0.3.5
       Installing json 1.8.1
       Installing arel 18.104.22.16840414130214
       Installing coffee-script-source 1.7.0
       Installing execjs 2.2.0
       Installing thor 0.19.1
       Using bundler 1.6.3
       Installing hike 1.2.3
       Installing multi_json 1.10.1
       Installing sass 3.2.19
       Installing tilt 1.4.1

       Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

       /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/ruby-2.0.0/bin/ruby extconf.rb
       checking for sqlite3.h... no
       sqlite3.h is missing. Try 'port install sqlite3 +universal',
       'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
       and check your shared library search path (the
       location where your sqlite3 shared library is located).
       *** extconf.rb failed ***
       Could not create Makefile due to some reason, probably lack of necessary
       libraries and/or headers.  Check the mkmf.log file for more details.  You may
       need configuration options.

       Provided configuration options:
       --with-opt-dir
       --without-opt-dir
       --with-opt-include
       --without-opt-include=${opt-dir}/include
       --with-opt-lib
       --without-opt-lib=${opt-dir}/lib
       --with-make-prog
       --without-make-prog
       --srcdir=.
       --curdir
       --ruby=/tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/ruby-2.0.0/bin/ruby
       --with-sqlite3-dir
       --without-sqlite3-dir
       --with-sqlite3-include
       --without-sqlite3-include=${sqlite3-dir}/include
       --with-sqlite3-lib
       --without-sqlite3-lib=${sqlite3-dir}/
       --enable-local
       --disable-local

       Gem files will remain installed in /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/bundle/ruby/2.0.0/gems/sqlite3-1.3.9 for inspection.
       Results logged to /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/bundle/ruby/2.0.0/gems/sqlite3-1.3.9/ext/sqlite3/gem_make.out
       Installing rack-test 0.6.2
       Installing tzinfo 1.2.1
       An error occurred while installing sqlite3 (1.3.9), and Bundler cannot continue.
       Make sure that `gem install sqlite3 -v '1.3.9'` succeeds before bundling.
 !
 !     Failed to install gems via Bundler.
 !
 !     Detected sqlite3 gem which is not supported on Heroku.
 !     https://devcenter.heroku.com/articles/sqlite3
 !

 !     Push rejected, failed to compile Ruby app

To email@example.com:rocky-dusk-1857.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'firstname.lastname@example.com:rocky-dusk-1857.git'

This is my gemfile:
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.1'
# Use sqlite3 as the database for Active Record
group :development do
  gem 'sqlite3', '1.3.8'
  gem 'spring'
end
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

group :production do
  gem 'pg'
  gem 'rails_12factor'
end

I deployed all the applications that appeared on the "Rails tutorial" by Michael Hartl with no problem but now I am developing my own apps with slightly newer version of rails and ruby and I am having trouble with this. Any help  will be greatly appreciate it.
Answer: Data
Heroku doesn't support SQLite3 as it stores data on the hard drive (which will get overwritten on a new push).
A persistent data store (database) is required, and Heroku recommend Postgres.
--
Error
I think your error will have several potential causes:

You've not updated your Gemfile.lock file
You've not committed your Gemfile properly before committing to Heroku
One of your gems depends on sqlite3 (unlikely)

I would resolve the issue like this:
#Gemfile
group :development do
   #gem 'sqlite' -> comment out for now
end

group :production do
   gem 'pg'
end

Then I would make sure I've committed all the changes:
$ git add .
$ git commit -a -m "Heroku"
$ git push heroku master

This will allow you to push a bona-fide version of your Gemfile to Heroku, consequently allowing you to test the deployment properly
If you need any further assistance, please comment & I'll help!
Comment: Silly me!! I was trying to push the master branch while making changes to a branch... I already merged the branch to master and pushed it again and everything went smoothly. Thanks for you help. Anyways it was a good  exercise to learn how to switch from one database to another.
Comment: Thank you for your help! I tried it but I still keep getting the same error. I also ran bundle after commenting out the sqlite gem and checked the resulting gemfile.lock to make sure that there were no gems that depended on it.
Comment: And still the same problem?
Comment: Yes. I decided to set pg also for development (entirely getting rid of sqlite3) as suggested on the link you posted. My project works fine locally using postgres now, but I still keep having the same error when trying to deploy.  I wonder if this has something to do with it "Gem files will remain installed in /tmp/build_c9d45d78-4c2b-4825-9bd8-b3961ccc175f/vendor/bundle/ruby/2.0.0/gems/sqlite3-1.3.9 for inspection." I do not understand how come it keeps saying Detected sqlite3 gem
Answer: In order to deploy on Heroku while using the SQL lite gem for development you must:
 bundle install --without production
Comment: [Heroku doesn't support SQLite](https://devcenter.heroku.com/articles/sqlite3) as it relies on storing the data on disk, rather than in a DB
Comment: @RichPeck You're certainly right about SQLite support on Heroku, but the words here make my head hurt. All modern databases I'm aware of store data in files.  (In the dark ages some avoided the OS file system for performance reasons.)  SQLite is not supported by Heroku because it's _serverless_.  It doesn't run a separate process.  Heroku Dynos don't have their own persistent store, so they need to communicate with a separate database process that does.
Comment: lol yes that's true - I meant storing it on a server as opposed to storing locally


Alerta ao clicar em botões

Question: Existe possibilidade de simplificar este código? Algo me diz que sim. Quero que apareça um alerta diferente após clicar em cada botão.
<input id="b1" type="button" onclick="clicar1()" value="Botão 1">
<input id="b2" type="button" onclick="clicar2()" value="Botão 2">
<input id="b3" type="button" onclick="clicar3()" value="Botão 3">

Tentei usar somente uma function, mas não está funcionando, assim:
<input id="b1" type="button" onclick="clicar()" value="Botão 1">
<input id="b2" type="button" onclick="clicar()" value="Botão 2">
<input id="b3" type="button" onclick="clicar()" value="Botão 3">

Me parece que o JS não aceita essa sintaxe "a.alert('xyz')". É isso mesmo?
Comment: sim tem, e o seu segundo código está bem próximo disso.. primeiro, passe para a função "clicar" o botão que disparou o evento (pode pegar isso de outra forma, mas assim é mais comum): `onclick="clicar(this)"` na função, pode pegar o valor do botão facilmente `function clicar(botao) {  alert("Voce clicou no botão " + botao.value); }`
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Quando você associa um evento ao elemento, como fez com o onclick=, você está passando uma expressão Javascript no corpo do atributo, ou seja, qualquer coisa que você por lá vai ser interpretado como um script.
Aqui nós temos um exemplo prático de como funcionaria:

<input id="b1" type="button" onclick="alert('Você clicou no botão ' + this.value)" value="Botão 1">
<input id="b2" type="button" onclick="alert('Você clicou no botão ' + this.value)" value="Botão 2">
<input id="b3" type="button" onclick="alert('Você clicou no botão ' + this.value)" value="Botão 3">

Claro que isso não é o ideal para fazer, pois está repetindo o código, e não está nem um pouco legível. Podemos reduzir o código acima para:

function alertarBotao(e) {
    alert(e.value);
}
<input id="b1" type="button" onclick="alertarBotao(this)" value="Botão 1">
<input id="b2" type="button" onclick="alertarBotao(this)" value="Botão 2">
<input id="b3" type="button" onclick="alertarBotao(this)" value="Botão 3">

Ainda não tá legal. E se reduzirmos mais ainda?

const elements = document.querySelectorAll("input[type='button']")
elements.
  forEach(e => {
    e.onclick = function() { alert(e.value) }
  })
<input id="b1" type="button" value="Botão 1">
<input id="b2" type="button" value="Botão 2">
<input id="b3" type="button" value="Botão 3">

De qualquer forma, no seu código, você não associa o evento onclick no seu Javascript em lugar nenhum (com excessão nos próprios elementos). Dos exemplos citados, somente o primeiro é o "desagradável", sendo que o segundo ainda também não é muito ideal.
No terceiro caso você tem que dar uma trabalhada com os seletores no querySelectorAll. Você pode associar uma classe para os elementos e procurar eles no seu código JS, sem interferir no funcionamento dos outros inputs:

const elements = document.querySelectorAll(".meu-botao")
elements.
  forEach(e => {
    e.onclick = function() { alert(e.value) }
  })
<input class="meu-botao" id="b1" type="button" value="Botão 1">
<input class="meu-botao" id="b2" type="button" value="Botão 2">
<input class="meu-botao" id="b3" type="button" value="Botão 3">

Todos os exemplos geram o mesmo resultado, no entanto, somente alguns são "ideais" em termos de manutenção e legibilidade.
Não utilize IDs como seletores quando está trabalhando com um grupo de elementos. Neste caso, é melhor utilizar classes mesmo, porque você pode usar a mesma classe em vários elementos. Você não pode usar o mesmo ID em dois ou mais elementos.
Este último exemplo vai tornar seu código mais organizado do que o precessor. Dá uma lida de como funciona eventos no Javascript aqui.

Alerta ao clicar em botões


Compound time and tempo indication in quarter note

Question: I am studying a piece, the time signature is 12/8.
The tempo indication is "Allegretto, (quarter_note) = 76". I am a bit baffled, as I expected a dotted quarter note.
Is this a typo? Or is this accepted notation? And if the latter: should I set my metronome to 76 or, uhhh, a third slower (50)?
Comment: Welcome to Stack Exchange! If you haven't already, please [take the tour](https://music.stackexchange.com/tour) and [visit the help centre](https://music.stackexchange.com/help).
Answer: Yes, you would expect a dotted quarter beat.  If it's a printed copy from an established publisher, I'd say it's a misprint.  If a computer-printed score from an amateur, I'd suspect ignorance!
But 50bpm is too slow for alegretto.  It's a misprint.
Comment: Why questioners accept answers but don't upvote is something i never understood, good answer btw.
Comment: I see "quarter note = " notation for compound meters (e.g. 12/8, 9/8) all the time in Musescore, mainly because that's the default tempo indication you can put on a score.
Comment: Yup.  Musescore is great for the price, but lacks many refinements.  And its users are often inexperienced.


How to add metadata to message in Akka

Question: I want to log events of sending and receiving message and use them to make some sort of visualization of whole messaging process. However, I have problem implementing reliable way of pairing those two events:

at both dispatch and arrival I only dispose current actor and message, the later being the only thing available during both events,
for now I use message type and hashcode but it's unreliable - overriding hashcode, sending message from remote actor or reusing the same message would make it impossible to pair events correctly,
I was suggested to use timestamp but duration of the transmission is nonzero and that would be merely heuristic.

The only reliable way would be to attach some unique information to each message, and use it to connect the events, but manually wrapping and unwrapping each message would be inelegant and error prone.
Is there some way to add metadata to the message? Or any other mean to reliably pair up events of sending and receiving message?
Answer: What about this?
object foo {

    // ID has a public getter and private setter
    trait Msg {
      private var _id = 0
      def id = _id
      private[foo] def id_=(value: Int): Unit = _id = value
    }

    // Companion object for the creation of Foo with an ID
    object Foo {
      def apply(id: Int, s: String): Foo = {
        val msg = Foo(s)
        msg.id = id
        msg
      }
    }

    // Private constructor => must be created from companion object
    case class Foo private (s: String) extends Msg

}

val msg = foo.Foo(42, "hello")
println(msg)
println(msg.id)

Output:
Foo(hello)
42

Make all your messages extend the Msg trait.
This way the ID can be set only during the creation of the message, then it's read-only.
Comment: Well, that's sufficient approach when we are developing new project and you can establish some sort of convention. However, when it comes to existing one, adding a trait to every single message might be a bit inconvenient. At the moment I already have to add a trait to each Actor and I'm looking for way to get rid of that as well.
Comment: I'm pretty sure that right now there is no 'out-of-the-box' way to add metadata to messages/case classes. Your only option are: 1) my solution 2) wrap in another case class.

How to add metadata to message in Akka


Equivalence of two countable-definitions

Question: This is an equivalence proof by myself. I need someone to tell me if the proof is alright or to point out its flaws.
Definition 1: A set M is countable iff $|M| = |\Bbb N|$ or |n $\in \Bbb N $| = |m $\in M$| (here I mean that if M is finite then you can just pair the element m $\in$ M to a natural number n $\in \Bbb N$ and it will become a finite bijection between all the elements of M and the same amount of numbers of $\Bbb N$).
Definition 2: A set M is countable iff $|M| \le |\Bbb N|$, i.e. there is some injective $g: M \to \Bbb N$.
So now I want to prove equivalence of the two definitions:
1 $\to$ 2: This is easy because if $|M| = |\Bbb N|$ or |n $\in \Bbb N $| = |m $\in M$|then also always $|M| \le |\Bbb N|$.
2 $\to$ 1: I split in two cases.
Case 1: $|M| \le |\Bbb N|$, i.e. there is some injective $g: M \to \Bbb N$, and rng(g) is finite. Then this leads naturally to the second variant of definition 1 because we can just take the n elements of rng(g) and map it into M which must be bijective.
Case 2: $|M| \le |\Bbb N|$, i.e. there is some injective $g: M \to \Bbb N$, and rng(g) is infinite. So it must be |rng(g)| = |$\Bbb N$| = |M| which lets us arrive at variant 1 of definition 1.
But why is |rng(g)| = |$\Bbb N$|? Because rng(g) $\subseteq \Bbb N$ which means that rng(g) is well-ordered as well and so every non-empty subset of rng(g) has a minimum element. So you can construct the following chain:
a_minimum $\in$ rng(g)
b_minimum $ \in$ rng(g)\a_minimum
c_minimum $ \in$ rng(g)\a_minimum, b_minimum
...
Since rng(g) is infinite this goes on endless and you can cleary see the structure of the natural numbers rising, so that there's a bijection possible between rng(g) $\to \Bbb N$, so that |rng(g)|=|$\Bbb N$|.
But why |rng(g)| = |M|? Because of the definition of rng(g) we get that the inverse function rng(g) $\to$ M must be surjective but the function rng(g) $\to$ M is injective by assumption of definition 2: $|M| \le |\Bbb N|$. That's why |rng(g)| = |M|.
Comment: You need to add $M$ not being finite to your hypothesis. Otherwise you can take $g: \emptyset \to \mathbb N$ or $g:\{ 15 \} \to \mathbb N$, both are injective, yet the domains are finite.
Comment: Now your first definition is wrong. $\{ 1 \}$ is countable, but there is no bijection $\{ 1 \} \to \mathbb N$.
Comment: I fixed it by including finite-countability.
Comment: No, because look at the last part where countable-finite is defined. I think its ok now, don't u think?
Comment: Now it's all good! :)
Answer: Let $g(M)=H_0$ be an infinite subset of $\mathbb N$. You may define $H_i$ for $i=1,2,\dots$ recursively:

$H_{i-1}$ is infinite non-empty by hypothesis, so by the well-ordering property of $\mathbb N$ it must have a minimal element, say $h_{i-1}$.
Let $H_i = H_{i-1} \setminus\{h_{i-1}\}$.
If $H_i$ was finite, then $H_{i} \in H_i \cup \{ h_{i-1} \}$ would be a union of two finite sets so a finite set, a contradiction. Thus $H_i$ is infinite.
Observe $h_{i-1} \notin H_i$ and $H_i\subset H_{i-1}$.

Observe $H_0 \supset H_1 \supset H_2 \supset \cdots$. We will show in a moment that $\{h_i\}$ are all distinct.
Let $h: \mathbb N\to g(M)$ be defined by $h(n) = h_n$. Observe it is an injective map, otherwise $\exists i>j$ such $h(i) = h(j)$ i.e. $h_i = h_j$. Then
$$h_j=h_{i} \in H_i \subset H_{i-1} \subset \cdots  \subset H_{j+1}$$
but $h_{j} \in H_{j+1}$ which contradicts our observations. Thus $h$ must be injective and we have $|\mathbb N|\leq |g(M)|$. Clearly if we restrict $g$ to be $g:M\to g(M)$ it is a bijection so $|M| = |g(M)| \leq |\mathbb N|$ Is is clear from here?
Edit: added working with the image of $M$.
Edit: some typos.
Edit: format.
Comment: Way over my head. Can u check my proof and point out things that are false? That would help me probably more in a first step because that is how i would think to prove the equivalence.
Comment: You claim that if a set $M$ is infinite then $|M|\geq  |\mathbb N|$. If said claim is somewhere in you book or you have a way to prove it, then your proof is all good.
Comment: That was intuitive thinking due to laziness because it would make everything easier. No idea, I hope someone can help, but of course why would my textbook present a rather complicated proof if it was so easy possible. That makes it probable that it is no theorem.
Comment: Well, this is the very thing I have shown above. I don't know if there is a significantly simpler way. Note it only holds if you assume axiom of choice. Which I suppose you do.
Comment: So do you think that the following is a theorem: M is an infinite set iff $|\Bbb N| \le |M|$? Because if it is my proof works and my proof is much simpler than yours.
Comment: I changed my proof further. Are u more/completely convinced now?
Comment: You edited your first definition again, and now it is incorrect, again. There is a bijection $f': \mathbb N \to \set{2,3,4,5,\cdots}$ but it is not countably finite. And no, I am far from convinced. You can't just willy-nilly say "yeah I think this works" and pass it as a proof. If you claim something holds "naturally", you should be able to write it out, you know, naturally.
Comment: The second part of the first definition means: some M is countable iff you have a bijection between some n elements of IN and the elements of M which can be called countable finite in opposition to the first case where countable infinite is defined.
Comment: I think the latest version of my proof should be pretty close. If you answer my last question with YES then the proof actually is legit.


Help with an analysis problem involving isomorphisms and volumes.

Question: I would like some help solving the following problem:
Let $f: U \subseteq \mathbb{R}^{m} \rightarrow \mathbb{R}^{m}$ be a class $C^{1}$ function. Suppose that for some $a \in U$ the derivative of $f$ in $a$ is an isomorphism. Prove that $$ \lim_{r \rightarrow 0} \frac{Vol \left( f \left( B\left[ a; r\right] \right) \right)}{Vol \left( B\left[ a; r\right] \right)} = \left| \det f^{\prime} \left( a \right) \right|,$$ where $Vol$ means volume and $B\left[ a; r\right] = \{ u \in \mathbb{R}^{m}: \| u-a \| \leq r \}$ is the closed ball.
So far, I only know that the right side of the equation is never zero, and was thinking that the hypothesis in this problem are the same as the Inverse Function Theorem. However I don't know if it is really of use here since it gives a result about $f \left(U\right)$ and the problem involves $f \left( B\left[ a; r\right] \right).$
I need some hints to get moving; I do not want the full solution of the problem,  since this is an exam-type exercise and I need to learn how to solve it by myself.
Answer:
Prove $|\det(f'(x))|$ is a continuous function.
Prove that for any continuous function $g(x)$ you have that $$g(x_0) = \frac{1}{\operatorname{Vol}(B[x_0;r])} \int_{B[x_0;r]} g(x) \, dx.$$
Use (1) in (2) and change of variables.

If you need more help just say.


Ao rolar a pagina e chegar em uma determinada DIV a cor de fundo da mesma mudasse

Question: Gostaria de quando alguém rolar a pagina e chegar em uma determinada DIV a cor de fundo da mesma mudasse tentei fazer assim:
JsFiddle
mas não deu certo. Qual seria a forma correta de se fazer?
Obs: O site sera responsivo logo scrollTop: 50px não iria funcionar!
Answer: Já havia respondido questão semelhante aqui.
Para fazer isso, tem que calcular a distância do elemento até o topo do documento menos o scroll, e subtrair pela altura visível da janela.
Adicionei uma variável aparecer que é a porcentagem em que o elemento estiver visível na janela para alterar a cor de fundo:

$(window).on("scroll",function(){
 var aparecer = 50; // porcentagem (neste caso, é a metade, 50%)
 var eleHeight = $('#div').outerHeight(); // altura da div
 var eleTopo = $('#div').offset().top; // distancia da div ao topo do documento
 var scrlTopo = $(window).scrollTop(); // quanto foi rolada a janela
 var distance = eleTopo-scrlTopo; // distancia da div ao topo da janela
 var altJanela = window.innerHeight; // altura da janela

 if(distance <= altJanela-(eleHeight*(aparecer/100))) {
  $("#div").css("background","blue");
 }
});

Role para baixo

 Texto texto texto texto

Comment: pq aparacer e dividido por cem?
Comment: se eu quiser alterar a cor novamente quando a pessoa subir a pagina e so eu por um else correto?
Comment: @LucasSimao Isso mesmo
Comment: tanks agora e guardar isso na minha cabeça


What is the proper way to show a visitor an error?

Question: I'm using a custom submit handler for a Webform, which POSTs important form data to another API. That part works, but on occasion there may be random network errors that prevent a successful submission, such as if the REST endpoint happened to be down at that particular moment (or whatever).
In those cases, I don't want the user to think their form successfully submitted when it didn't. How can I override the confirmation page with a custom error page? I tried drupal_set_message(), but it doesn't show up anywhere on the confirmation page that I could see.
Ideally, I would also be able to get back the event ID generated by watchdog logging so that the user, if they contact us by phone or email upon seeing the error, would be able to provide more information that can help us debug it.
So in summary, in a perfect world, a failed submission would result in:

The form submission ($form_state) being logged into watchdog or another log
Watchdog returns the associated event ID
The user sees a custom error page describing the error, with the event ID as an error code to help in debugging.

I can hack something together with die() and a hash of the form data as an error code, but is there a better, proper Drupal way?
Relevant code so far:
 try {
    $apiResponse = drupal_http_request($apiEndPoint, [
      'headers' => ['Content-Type' => 'application/json'],
      'method' => 'POST',
      'data' => drupal_json_encode($formData),
      'timeout' => 5 // Timeout in seconds.
    ]);

    // I'm not okay :(
    if ($apiResponse->code != "200") {
      throw new Exception ($apiResponse->data, $apiResponse->code);
    }
  } catch (Throwable $e) {
    watchdog('tfm_custom_form_handlers', "A custom form handler failed: (@code) @message.", [
      '@code' => $e->getCode(),
      '@message' => $e->getMessage(),
    ], WATCHDOG_ERROR);
  }

Thanks for the help!
Answer: Have your POST code inside a validate function, that runs last, after all other validation has passed.
Ex: $form['submit']['#validate'][] = 'mymodule_post_to_api';
and use form_set_error('form', 'Failed to connect to API, try again later'); inside your catch.
For POST's errors, don't wait for someone to report. Programmatically make Drupal send yourself or whomever maintains the code, an e-mail with the form fields & error details.
See How to programmatically send an email?
Comment: I rewrote the submit code to be a verification handler instead, and the code seems to work, but form_set_error doesn't seem to display the error anywhere. Is there a separate display_form_errors function or similar?

Also, great idea to send the email programatically. I'll have it do that, thank you!
Comment: For testing purposes, change to the default "bartik" theme. Perhaps your current theme is not displaying messages.
Comment: That's exactly what it was. Thank you so much for the help! I'll get it working with our custom theme, and the rest should be good. Appreciate it :)


Find the expected value of choosing 3 balls among 8 (each balls has different value)

Question: Let's say you have 8 balls in front of you, each of them contains a bank note (for example 1\$, 5\$, 10\$ etc...).
And let's say you can choose randomly 3 balls among the 8 (you don't know what's inside).
How to compute the expected gain, in function of the value of each notes?
As an example, let's say I have the following available notes: 0\$, 0\$, 0\$, 100\$, 100\$, 100\$, 200\$ and 500\$. The expected value should be 375$ (I did all the combinations by hand, but I want the formulae).
Thanks!
Comment: Use linearity of expectation: by simply averaging the values of the notes you find the expectation of a single random draw is \$125, whence the expectation of three draws is three times that.
Answer: Let's call gains as $x_1,...,x_8$. From a brute force perspective as yours, choosing $x_i,x_j,x_k$ in that specific order has probability $\frac{1}{8\cdot7\cdot6}$. If we think of all the combinations, the expected value can be formulated as
$$E[X]=\sum_{i\neq j\neq k}\frac{1}{8\cdot7\cdot6}(x_i+x_j+x_k)$$
Here, if you fix $i$, you'll actually have $x_i$ a total of $7\times6=42$ times in this sum. This is for a specific $x_i$, e.g. $i=1$. Same situation arises three times when we consider $x_j$ and $x_k$. So, The total sum becomes the following (let $S$ be the sum of your banknotes):
$$E[X]=\frac{1}{8}\times 3\times\sum_{i=0}^8 x_i=\frac{3S}{8}$$
It can be generalized to $\frac{kS}{n}$ I suppose (when we select $k$ balls out of $n$).
Another Solution
From a more probabilistic perspective, let $X_1,X_2,X_3$ be the three numbers we get. $E[X_1]$ is clearly $S/8$. Using Law of Iterated Expectations, we can calculate the others:
$$E[X_2]=E[E[X_2|X_1]]=E\left[\frac{S-X_1}{7}\right]=\frac{S}{7}-\frac{E[X_1]}{7}=\frac{S}{7}-\frac{S}{7\cdot8}=\frac{S}{8}$$
$$\begin{align}E[X_3]&=E[E[X_3|X_1,X_2]]=E\left[\frac{S-X_1-X_2}{6}\right]=\frac{S}{6}-\frac{E[X_1]}{6}-\frac{E[X_2]}{6}\\ &= \frac{S}{6}-\frac{S}{8\cdot6}-\frac{S}{8\cdot6}=\frac{S}{8}\end{align}$$
which means $E[X_1+X_2+X_3]=\frac{3S}{8}$.
Comment: While I like the directness of using the law of iterated expectations, what I did intuitively for myself was using symmetry (the order labels do not matter) to argue $E[X_1] = E[X_2] = E[X_3]$.
Comment: I agree with you actually, I just felt obliged to show in other ways that the expectations of consecutive draws are still $S/8$ whether we do it with or without replacement.