Using continue Statement in JavaScript

Question: I'm learning JavaScript and I'm experimenting with the continue statement, and from my understanding, it's suppose to "skip" an iteration and than continue. I wrote a piece of code from a Udemy course I'm doing. The for loop is suppose to fill the percentages2 array, and it does work.
However, I'm trying to have the array not be filled up with values less than 2. If it works I should be getting back 2 elements in my percentages2 array instead of 4.
Anyone know why the continue statement isn't working?

const populations2 = [332, 144, 1441, 67];
const percentages2 = [];

const percentageOfWorld4 = function (population) {
  return (population / 7900) * 100;
};

for (let p = 0; p < populations2.length; p++) {
  if (percentages2[p] < 2) continue;

  percentages2.push(percentageOfWorld4(populations2[p]));
}

console.log(percentages2);
Comment: Your `percentages2` array is empty when you're checking it in the for loop, so `percentages2[p]` will always return `undefined`. And `undefined < 2` always evaluates to false and so you never reach the `continue` statement. What're you trying to achieve?
Comment: In the condition you need to check the value of what `percentageOfWorld4` returns instead of `percentages2[p]` before pushing the value to `percentages2` array.
Answer: Hyy,

Your are looping an array populations2 right
first mistake inside the loop your are not checking the return result from function percentageOfWorld4 it should be  (percentageOfWorld4(populations2[p]) < 2)

And you should pass the pth value of populations2 then use continue

later you can push the other element to a different array percentages2.push(populations2[p]);

const populations2 = [332, 144, 1441, 67];
const percentages2 = [];

const percentageOfWorld4 = function(population) {
    return (population / 7900 ) * 100;
};

for (let p = 0; p < populations2.length; p++) {

    if(percentageOfWorld4(populations2[p]) < 2) continue;

    percentages2.push(populations2[p]);

}; console.log(percentages2); // [4.2025316455696204, 18.240506329113924]

It is a good practice to store the return value in a variable rather then calling the function twice
const populations2 = [332, 144, 1441, 67];
const percentages2 = [];

const percentageOfWorld4 = function(population) {
    return (population / 7900 ) * 100;
};

for (let p = 0; p < populations2.length; p++) {
    let result = percentageOfWorld4(populations2[p]);

    if(result < 2) continue;

    percentages2.push(result);

}; console.log(percentages2); // [4.2025316455696204, 18.240506329113924]

Comment: Why to call the function twice when you can store the return value in a variable?
Comment: It looks like OP want's to store percents to `percents2` array, not populations.
Comment: Then just push `percentages2.push(percentageOfWorld4(populations2[p]));` right
Comment: `let result = percentageOfWorld4(populations2[p]);
if(result < 2) continue;
    percentages2.push(result);`
Comment: @ullaskunder Thank you, I realized my mistake now. Essentially, I was pushing the results into my percentages2 array, while at the same time, using it as a condition (I think my terminology is correct). What I have to do is check the values themselves first, and that will make the continue statement work. Thank you and everyone for the time. I'm a complete novice. From now on I will also store my results in a variable for good practice.
Comment: Also, you guys said that in my original code, I called the function twice? I don't see it. I only type down percentagesOfWorld4 once. Again I'm still a novice, can someone please explain as a side note how I called it twice? Oh wait, do you say twice because I'm calling it numerous times in the loop with the values stored in the p variable?
Comment: hyy @Handsome Dragon , No @teemu commented on my old answer before the edited one. I called the `percentageOfWorld4` function twice, once in `if` condition and in `push` statement then later I used variable to store the result, then pass that variable rather then calling it again and again. ^_^
Comment: @ullaskunder Copy that, thank you!

Using continue Statement in JavaScript


How to convert unix timestamp (long) to datetime in pyspark sql?

Question: In pyspark sql, I have unix timestamp column that is a long - I tried using the following but the output was not correct.
from_unixtime(col("firstAvailableDateTimeUnix"), "yyyy-MM-dd HH:mm:ss")

from_unixtime output
Comment: first you need /1000
Answer: All you need to do is casting and then use date_format to format your timestamp:
date_format(col("firstAvailableDateTimeUnix").cast('timestamp'), "yyyy-MM-dd HH:mm:ss"))

Answer: import org.apache.spark.sql.functions._
val df = Seq(1651484635297L).toDF("firstAvailableDateTimeUnix").withColumn("goodDate",
from_unixtime(col("firstAvailableDateTimeUnix")/1000, "yyyy-MM-dd HH:mm:ss")
)

df.show(false)
//    +--------------------------+-------------------+
//    |firstAvailableDateTimeUnix|goodDate           |
//    +--------------------------+-------------------+
//    |1651484635297             |2022-05-02 12:43:55|
//    +--------------------------+-------------------+


Internal working and connection of Kubernetes Ingress Object and Ingress Controller

Question: I was trying to understand the relation between Kubernetes Ingress Resource and Ingress Controller.
I read that Ingress resource is mainly the rules and controller Pods route the traffic actually for Ingress rules.
I'm confused, like other Objects why Ingress resource can not spin up PODs on its own by specifying the image.
Secondly, how Ingress Object connects to actual Ingress Controller Pods to get its work done ( or say other way round). I don't see specifying any selector in the Ingress Object.
Thirdly, if the Ingress Resource gets its own IP address ( internal or external) then why Ingress Controller needs external IP address.
thanks
PS: I do not have a great knowledge of Kubernetes, please pardon if the questions sound silly.
Answer: Details with diagram are posted in GKE tutorial
Ingress with NGINX controller on Google Kubernetes Engine


Domain controllers can't ping (or connect to) each other

Question: First, some background: We have two sites connected via a FortiGate IPSEC VPN. They are each set up on different subnets - our main site is 192.168.2.x, and our second site is 192.168.0.x. We have a server (S01) running Windows Server 2008 Standard FE that is set up as our primary domain controller, Exchange, and DNS server; as well as DHCP for that site.
At our second site, we have a server (S02) running Windows Server 2008 that was originally just a file server, as well as DHCP for that site. I wanted to convert S02 to a domain controller to act as a backup in case the main server went down or internet connection was lost. So I ran dcpromo, and successfully converted S02 to a domain controller.
Now, I am having a problem: A few days after initial setup, I can't ping or connect to S01 from S02 any more, and vice versa. Both IP address and name fail for pinging or browsing shared folders. I also can't ping devices on the 192.168.2.x subnet from S02 by name, but IP addresses work. However, I can ping devices on the 192.168.0.x subnet from S01 by either name or IP, except for S02 itself. Running repadmin /showrepl on S02 gives the last successful sync about 2 days after initial setup.
I don't have any problems pinging any IP addresses from different devices - e.g. I can ping S01 and S02 from computers at both of our sites. I just can't ping the servers from each other.
Windows firewall is disabled on both servers, and I tried disabling the antivirus (ESET File Security) with no effect.
Both domain controllers are showing up in Active Directory. Running nltest /dclist:domainname.local gives me my two server as domain controllers, with S01 as primary. I can log on to both servers with Active Directory Explorer. My dns settings are 192.168.2.5 (S01) & 192.168.0.5 (S02) on both servers. DHCP services are still separate, since each server is providing IP addresses within different subnets.
I initially thought that something was messed up on the DNS side, but that wouldn't explain why I can't ping via IP address. Does anyone have any ideas?
Comment: Connectivity issues will lead to replication issues which can lead to DNS resolution issues. I would focus on the connectivity issues before taking on the other issues. Is the VPN configured to pass ICMP traffic? Have you reviewed the logs to verify ICMP is not being dropped by the VPN?
Comment: Yes, ICMP traffic can go through the VPN. I can successfully ping both S01 & S02 from computers at either of our sites. At least, I assume if pings can go through, that means the rest of ICMP traffic can as well.
Answer: I assume Fortigate is blocking traffic from DC's. Check firewall configs on fortigate. Unblock all trafic between DC's and then do in backwards and block all the traffic that is not needed between DC's


How do you write a dominant ninth in fourth inversion?

Question: How do you write in music notation a dominant ninth chord in its fourth inversion?
I only know of the ways to write first, second and third inversion. Fourth I have never come across.
Comment: Do you mean writing it on the staff, or the figured bass?
Comment: For a famous repertoire example, check out m. 42 of Schoenberg's *Verklärte Nacht*.
Comment: If this isn't just a theoretical question, can you post a sample of what you are analyzing?
Comment: @Richard, I added the Schoenberg example in my post. Did I get the right measure? If got it right, it looks like an 11th chord with the 9th in the bass!
Comment: @MichaelCurtis It should be a ninth chord. Perhaps there's a hidden clef change somewhere?
Answer: Let's take C9 - C dominant 9th. C9/D. The notes are C, E, G, Bb, D rising. So the fourth inversion needs the D underneath. The order of the others doesn't have to be in that same rising order, though, so it could be, and often is, voiced in another order. It will also be voiced differently depending on which instrument it's written for.
Comment: This is good jazz notation, and it's what lead sheets would use.
Comment: In a jazz context, `C9/D` implies that the comping instrument should play a `C9` chord, & the bass should play a `D`. This effectively changes the harmony to `Dsus♭13` or `Gmin6/D`. This is different from what I see Jolene asking about--my take is she wants a `C` in the bass and a particular inverted voicing in the piano/guitar. In a solo piano context, this is the difference between (1) playing a `C9` chord in the middle register & a `D` in the lower register/bass & (2) playing an inverted `C9` voicing in the middle register with either nothing in the bass or a `C` in the bass.
Comment: @jdjazz - Gm6/D doesn't have a C in it, so how does that work?
Comment: @Tim, that's true--I was thinking more about the underlying harmony than the proper writing. `Gmin13` would probably be a better way to actually write it, because the `13` often implies lower extensions like the `11`. But this still isn't really a way to notate a specific desired voicing. It would just be a way to notate the harmony in a lead sheet. The larger point I wanted to suggest is that the slash notation makes implications about what the bass would be doing which I suspect Jolene doesn't intend.
Answer: A review of Ottman, Kostka, and Piston all agree 4th inversion ninth chord aren't normally used. Piston gives all thee inversion figures for 1st, 2nd, 3rd: 7/6/(5), 6/5/4, 4/3/2. He points out ninth chord inversions are only occasionally found, and specifically 4th is not used. His general rule is 9th above the root and leading tone below thw 9th. Lacking a standard practice it seems best to list the complete figure for 4th inversion: V7/6/4/2.
Of course the question will be about the surrounding harmony and whether a 4th inversion 9th is actually the clearest analysis. When I play that 4th inversion in isolation it seems like it could be a 3rd inversion half-diminished chord with a non-chord tone above.

EDIT
@Richard commented about an example from Schoenberg, I'm adding it below for convenience...
Answer: I don't remember ever seeing a fourth-inversion dominant 9th chord in classical music (the 9th is usually the topmost note), but the "figured bass" version is V 7/6/4/2. Maybe V 7/6 is the most elegant compressed version?
Answer: For example, we have a G9 chord.  This is the V9 of C major.  It has the notes G-B-D-F-A.  In the context of four-part harmony, we will omit the fifth.  So we will get G-B-F-A.
Root position: (G-B-F-A)
If we count the intervals from the bass note:

G-B is 3 - G(1) A(2) B(3)

G-F is 7 - G(1) A(2) B(3) C(4) D(5) E(6) F(7)

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

So, we mark the root position ninth chord as C: V9. (Chord name is G9)
First inversion: (B-F-G-A)
If we count the intervals:

B-F is 5 - B(1) C(2) D(3) E(4) F(5)

B-G is 6 - B(1) C(2) D(3) E(4) F(5) G(6)

B-A is 7 - B(1) C(2) D(3) E(4) F(5) G(6) A(7)

So, we notate the first inversion as C: V7/6/5. (Chord name is G9/B)
Second inversion: (D-G-B-A or D-G-F-A)
In the second inversion ninth chord, we can't omit the fifth because the fifth should be the bass.  So we'll omit the seventh or the third instead.
If we omit the seventh:

D-G is 4 - D(1) E(2) F(3) G(4)

D-B is 6 - D(1) E(2) F(3) G(4) A(5) B(6)

D-A is 5 - D(1) E(2) F(3) G(4) A(5)

If we omit the third:

D-G is 4 - D(1) E(2) F(3) G(4)

D-F is 3 - D(1) E(2) F(3)

D-A is 5 - D(1) E(2) F(3) G(4) A(5)

So we mark the second inversion as either C: V6/5/4 or C: V5/4/3. (Chord name is G9/D)
Third inversion: (F-G-B-A)

F-G is 2 - F(1) G(2)

F-B is 4 - F(1) G(2) A(3) B(4)

F-A is 3 - F(1) G(2) A(3)

So the third inversion will be notated as C: V4/3/2. (Chord name is G9/F)
Fourth inversion: (A-B-F-G)

A-B is 2 - A(1) B(2)

A-F is 6 - A(1) B(2) C(3) D(4) E(5) F(6)

A-G is 7 - A(1) B(2) C(3) D(4) E(5) F(6) G(7)

So, we'll notate the fourth inversion as C: V7/6/2. (Chord name is G9/A)

Overall, we get:

V9, V7/6/5, V6/5/4 or V5/4/3, V4/3/2, and V7/6/2. (Chord names: G9, G9/B, G9/D, G9/F, and G9/A)


ANOVA non-normal distribution of residuals - variance estimates

Question: Let's assume that the normal distribution of residuals assumption is not met when we perform an ANOVA. I understand that it will probably lead to inaccurate inferential results regarding p-values and CI coverage.
But what about the within and between group variance estimates? Are they necessarily biased?
I am sorry if this topic was already discussed but I did not find my answer.
Comment: The F-statistic is the ratio  MSB/MSW. If data are not normal then $F# does not have an $F$ distribution because MSB and MSW do not have the appropriate chi-squared distributions. So non-normality affects all three.
Comment: @BruceET in what way does non-normality affect the variance estimates please ? Is it consistent with the answer posted by Gordon Smyth ?
Comment: I am talking about **distribution theory** (hence reliability of P-value of F-statistic), @GordonSmith is talking about **unbiasedness** of estimators. //Consider exponential data instead of normal. In R, code `v = replicate(10^6, var(rexp(10))); mean(v)` returned $1.0006,$ suggesting unbiasedness, but a histogram of `9*v` is nowhere near compatible with $\mathsf{Chisq}(\nu=9).$ Also, `9*v` fails Kolmogorov-Smirnov test for that dist'n with P-value near $0.$
Answer: Unbiasedness of the within and between group mean squares depends only on second-moment assumptions and does not require normality. If the form of the ANOVA linear model is correct (first-moment assumption) and if the responses are uncorrelated and have equal variances (second-moment assumption) then the within and between group variance estimates are unbiased.
Comment: Thanks! And yes, linearity and independent observations are assumed.


What EXACTLY is new doing?

Question: This is going to be a tricky question.
Having a constructor:
var Constructor = new function(){
this.a = 'a';
this.b = 'b';
}

we can create an object:
var obj = new Constructor();

this in Constructor refers to window but when calling new Constructor() some magic is being done: now this is finding out the scope of a function it is in (how exactly is it working?) and assigning only that scope to obj returns it.
So basically it is doing something like:
var Constructor = new function(){
var this = {some object having variables needed for every object (like __proto__)}
this.a = 'a';
this.b = 'b';
return this;
}

Can anyone tell me how it is this mechanism of creation of new object in JS is working in low level? What exactly is being done underneath when calling new?
Comment: and what's the point of `new function()`?
Comment: @MatíasFidemraizer: [It's a mistake](https://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key)
Comment: *"now `this` is finding out the scope of a function it is in"* You seem to be confusing scope and `this`. They actually don't have anything to do with each other (other than that in each environment (scope), there is a binding `this`).
Comment: Also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Answer: "new SomeFunction()" is creating a new object, and calling SomeFunction with that object as "this".
Consider this:
function SomeFunction() {
    this.hello = "Hello, world";
}
var myObj = new SomeFunction();
myObj.hello; // "Hello, world"

var myObj2 = {};
SomeFunction.call(myObj2);
myObj2.hello; // "Hello, world"

What EXACTLY is new doing?


Clarification on marginal, posterior and likelihood distributions?

Question: I would like to clarify a basic question about how to use the concepts of marginal, conditional, and likelihood distributions.
When we observe data from phenomena $x$. We are looking at realizations from the marginal distribution $f(x)$?
When we want to say something about a parameter $\theta$ governing that phenomena, we are usually interested in its posterior distribution $f(\theta| x)$?
And in order to investigate that conditional distribution we make use of prior information and the hypothesized relationship between $\theta$ and the data $x$. We call this later relationship the likelihood distribution $f(x|\theta)$?
Is this the write terminology? If not I would appreciate clarifications where needed.
Thanks
Answer: Let's start by talking about a marginal distribution.  Whenever we have a joint probability distribution $P(X, Y)$, if we draw samples from this distribution and only look at $X$ we have essentially samples from the marginal distribution $P(X)$.  The marginal distribution removes $Y$ from the picture by summing or integrating $P(X,Y)$ over all possible values that $Y$ can take.
$$
P(X=x) = \int P(X=x, Y=y) dy
$$
In your examples you were mainly dealing with Bayesian Perimetric Models.  Let's consider the following model:
$$
\mu \sim \mathcal{N}(0, 1),
$$
$$
X_i \sim \mathcal{N}(\mu, 1).
$$
Let's refer to $(X_1, \dots, X_n)$ as $X$.  In this problem we have observed $X$ and we want to understand $\mu$.  With our model, if we knew $\mu$ calculating the probability of each $X_i$ would be easy.  So we can easily evaluate the conditional probability $P(X_i | \mu)$.  Because of the importance of this distribution in maximum likelihood estimation this is referred to as the likelihood distribution.
As you said in your question we are ultimately interested in $P(\mu | X)$.  This is another conditional distribution that we refer to as the posterior distribution ("post" or after we've seen data).  Bayes' Theorem tells us how to relate the Likelihood distribution and the Posterior Distribution.  However, in this formulation two more factors appear including the (frequentists call it subjective and this is a marginal but don't think about it too hard) prior distribution $P(\mu)$ and the (often horrible to calculate) marginal distribution $P(X)$.


Why is the stretch preferred over the wind-up?

Question: I just recently started coaching a little kid (8 years old) and this youngster is part of a travel team.  The coaches for that travel team (according to the kid and his father) have instructed all their pitchers to pitch from the 'stretch'.
Now let me tell you I pitched in college for a division 1 team so I have a lot of experience in this field (no pun intended), but I can't seem to figure out a legitimate reason as to why this is preferred.
In my opinion the stretch is more advanced than a wind-up, ESPECIALLY AT THE AGES OF 8-12.  I mean, the stretch is used to keep runners close to the bag while they take a lead.  At the age of 8, base runners aren't even allowed to take a lead, or even steal until the ball crosses home plate!  The timing, the mind-set, and the form is advanced for such young and developing players. And of course when I started coaching this kid and witnessed his stretch, the form was decent, but if you are going to start coaching a kid with pitching from the stretch I think they should at least be taught the correct methods. Such as not allowing the shoulders to move, stopping your glove after you are set, etc.. not a non-stop motion after coming to the set position.
Now, I have played with great players who don't use the wind-up either but again, they are far more advanced than an 8 year old player.
Can i get some explanation as to why this is preferred?
Answer: I'm interested as to why you think the stretch is more advanced than the wind-up.  It seems to me like the wind-up includes much of the stretch mechanics (roughly speaking) but with a lot of extra movements involved.  The fact that these kids don't have to actually worry about base runners should actually simplify things in learning the stretch delivery.
From one article on Ballfrog advocating for teaching the stretch to young players,

Professional ballplayers have honed their posture, balance, tempo, and timing for decades in many cases.  Kids have not had the benefit of this experience ....Pitching is complicated.  The mechanics of throwing a ball need to be in sync, and with many components to this motion, it can take time to learn.  Starting with the stretch introduces these complicated movements more slowly than does jumping straight into the windup.

They also suggest that injuries are reduced (fewer moving parts) and the wind-up can basically be added on after mastery of the stretch.
Former MLB pitcher Steven Ellis says:

The only reason you lose velocity out of the stretch is because you have spent more time developing your wind-up mechanics. There must be a 50/50 split between practicing both pitching motions.
  There are tons of MLB pitchers who strictly throw out of the stretch, and many of these pitchers throw above average velocity. In fact, many pitchers prefer throwing out of the stretch because it eliminates any unnecessary movement that could alter the progression of their mechanics.

So he's also saying that it's simpler and, interestingly, that the stretch isn't practiced enough.  I think the case could definitely be made then that for the long run it would be best to become very good at the stretch delivery and then, once the kid learns his balance and throwing technique, add the components of the wind-up to be proficient at both.
Comment: @BviLLe_Kid  I've never had to coach kids this, but I could imagine it being easy for a youngster to get so caught up in the footwork "dance" of a wind-up that they can't focus on the actual throwing.  Or conversely, they are so worried about throwing that their footwork suffers.  They need to learn one step at a time (pun?).
Comment: I really like this answer.  I guess the point in my question is that if you practice the stretch, at least practice it correctly (i know that is difficult for young developing players).  I think I am expecting a little much out of an 8 year old haha
Comment: I totally disagree with this answer.  So on one hand wind-up causes more injuries and on the other hand you use MLB quotes to support it, yet the ultra-analytic coaches/staff/trainers have their pitchers almost always pitch out of the wind-up?   The pitchers that only pitch stretch are usually relievers only coming into the game with men on or guys who have a dysfunction and can only make it doing that.   The first quote has no semblence of understanding youth pitching - other than being "different".   The second quote is some MLB pitcher who advocates (3%) for that method.
Answer: I have an 8 year old right now that I am teaching to pitch.  Both of his older brothers pitched, I pitched, a family of pitchers (catchers when not pitching).
I will tell you why this has evolved from both a teaching standpoint and a "norm" standpoint.
Stretch only Pros:

Can be used in all situations.
If you are on a good team - select or travel - the systems/teams treat the kids as more commodities now.   We have 7 good arms, we should be able to turn 4 of them into pitchers.   Much easier to do this factory-like approach by making the assembly line the exact same for each kid.  Boom we can train this kid to throw strikes in 5 hours instead of 10 or whatever they think.
The stretch motion has less moving parts which correlates with #1 and #2.

Pros of using a full wind-up with a young pitcher:

They will be able to throw harder out of the gate.   I do see that another answer has a quote from a player that talks about throwing hard out of stretch.   That is just his opinion and is not backed up with any data.   Any data that you get for MLB players will show they throw harder out of the wind-up.   Also the variance for less practiced players will be much greater.   A MLB player should be able to throw close to same speed since they have the techniques down hopefully (more on this later).   Coaching kids for years from 6-20 I can tell you unequivocally there is no discussion here - for sure more speed.
By not focusing on how hard you are throwing you are putting less pressure on your arm, elbows, shoulders.
One of the main points of the wind-up is momentum.   Very few kids at age 10 have the big arm and the quickness to snap forward - the kids that are good at snapping forward are usually smaller.   I would argue that the momentum a kid gets in the wind-up is a learned behavior that will eventually be carried into a stretch given the right emphasis by coaches.
To further point 3 most or a lot of little league fields do not have mounds.   Pitching out of the wind-up should force the new (not pro) pitcher to come forward faster.   You will see young kids in the stretch and they are pitching off their back foot almost like a quarterback heaving a long pass.   This puts a ton of pressure on parts of a young arm that can get overused quickly when throwing wrong.
And to keep with the momentum thing - it is also hip rotation.   When you are in the stretch your hip rotation is a very muscular movement.  (people do not understand that the hardest throwing pitcher ever - Nolan Ryan - was a squats/leg press junkie)   You have to exert an amount of force by your right foot to get your left foot (RH pitcher example) over, out and straight or you leave yourself in a closed/awkward position to throw.   The wind-up takes this muscular movement and puts a high degree of elasticity to it right away.

If I am coaching my kid or kids that I care about I will teach the wind-up exclusively at first.  I mean that is the reason most leagues have rules of no stealing the first two years kids are pitching.   If a kid is using reasonable form and is using their body (momentum and push) instead of their arm they can throw 200 pitches a day without issues.   It is really about odd angles and a kid trying to overpitch or "arm" the ball that gets them hurt.
Again not trying to be cynical of the new coaching methods but they were introduced by academies to teach pitchers faster.   If your kid has an arm issue, move on to the next kid.   I do understand that they are being sold that this is easier for kids since it is less to remember.   But it seems crazy that you think a kid is going to learn the forward momentum and hip rotation on their own.
I guarantee 99% of all major league pitchers spent more time during practice growing up in the wind-up than stretch.   For the exact reasons I mentioned.   Safer initially, teaches forward momentum, helps with hip rotation, defocuses arm action in correlation to pitch speed.   What some MLB or college player does later on (stretch only) has really nothing to do with your son as they have already practiced and learned the executions steps of a successful pitch.

I do agree that once perfected you are going to get close to 95-99% of the same ability out of the stretch.   It does make sense for some relievers to do this so they can always be ready for a man on base.   It also makes sense for higher caliber players to do this when they are having mechanical flaws or flaws in doing the full wind-up.   I am not dissing the approach, I am dissing when coaches are implementing the approach at the youth level.  If I saw my kid releasing the ball early (back or high), not turned, or off their back foot I would simply not allow my kid to pitch.   We are taking something done at the MLB level for mainly psychological reasoning and implementing it at youth sports as a "same" alternative.   Trust me if MLB owners/coaches/scouts thought throwing from the stretch was the same or better or even close the analytical data would have caused them all to shift to this years ago.   In something as analytics and science driven as baseball why would they support a pitching method that is inferior predominantly?
Also not allowing wind-up would limit my teaching of the best pick-off play in youth baseball.   Runner on 3rd (RH pitcher example), come up high with glove and ball, don't bring them together, step back with right foot at same time, and fire to 3rd... watch player and coach cringe.  Then watch coach yell "balk" to ump.
Answer: The old saying, "Opinions are like..... everyone has one" rings true here. Just because a pro says it works for those he's come in contact with does not mean it's gospel truth. I bet I could find other pros who'd differ on the subject. It can be very subjective.
I've been in the game for 30 years and coaching for 20+. I've seen more young arms sore and in pain throwing from the stretch than I ever have with the wind up. People say there are too many "moving parts" to the wind-up, but I don't buy it. I count 5 steps. That's not a lot. Momentum is everything. The wind-up minimizes the use of the arm, therefore reduces the chances of a painful experience. Small, weak, kids have a hard time controlling from the stretch (you'd think that not true, but it is). At the very least, a modified wind-up alleviates that to a certain degree.
My thought is, the stretch can turn into using the arm more. But the wind-up uses (or should use) more of the legs, which, in turn, takes away the possibility of sore arms (which I will always try and avoid with all youth players I work with).
I've watched young kid after kid try and muscle the ball to the plate by using the stretch. They might throw a few good pitches, but, for the most part, it's not consistent, especially with weaker arms. And "Yes" BK, the stretch is more used by relievers when trying to hold runners on base. I have yet to see an MLB starter (in today's game), pitch from the stretch without runners on base. I'm sure they are out there, but they are the exception, not the rule, by any stretch (pun intended).
I was at practice yesterday and some guy (with no experience) was trying to reteach my 8 year old to pitch from the stretch. I guess he did ok, but when he saw a batter he threw (maybe) 2 strikes and the rest were all over the place. Which leads me to believe that just because it might look like an easier approach, does not necessarily mean it's going to work. Also, the raw talent of the child needs to come into play. The more talented, the easier it would be to teach that child virtually anything. For others, it's more of a chore.
When the child I'm speaking of went back to the wind-up, his velocity increased and he threw more strikes than during the stretch position.
Bottom line, for me is, the wind-up may have a few more moving parts, but in the end I think it's better to teach that than it is to (potentially) teach a pitching style that have the potential to put more stress on a young arm.
Just my opinion.
Comment: Unfortunately this isn't a discussion site, so opinions need to be backed up with citations. You've put a lot of effort into the answer, so could you find some links to back up what you say? It would be a pity for your hard work to be wasted.
Comment: @TrueDub Is expertise enough? "I've been in the game for 30 years and coaching for 20+." Including citations reinforces expertise, but requiring citations on an otherwise expert-based answer undermines said expertise. That said, the question is also based on opinion with no citations.
Comment: Expertise would be fine, but the anecdote is irrelevant and serves only to demonstrate a lack of mindful practise, not a depth in it.
Comment: @MASTERMIND_ED I understand your point - expertise is an excellent thing, but it's also tough to prove sometimes.
Comment: I disagree with the dissension toward this answer. As a former high school pitcher, I can attest to some of the experience expressed here and is highly relevant to the question being asked. To say the answer has an irrelevant anecdote, demonstrates a lack of practice, and requires citations is borderline disrespectful to said answer.


How to write the mathematical equation for this model?

Question: I have a nested mixed effects model as follows:
lmer(log(Weight) ~ Gender + (1 | SubjectID / MeasurementID))

I have subjects who have two separate measurements of their weight, therefore I have a nested model where measurementID is nested within SubjectID, but I am not sure how to represent it mathetmatically.
Answer: If you have only two measurements per subject, then it would be more logical to first start with only one random intercept, i.e.,
$$\log(\texttt{Weight}_{ij}) = \beta_0 + \beta_1 \texttt{Gender}_i + b_i + \epsilon_{ij},$$
where $b_i \sim \mathcal N(0, \sigma_b^2)$ denotes the random intercept for the $i$-th subject, and $\epsilon_{ij} \sim \mathcal N(0, \sigma^2)$ denote the error terms.
The corresponding syntax with lmer() is:
lmer(log(Weight) ~ Gender + (1 | SubjectID), data = <your_data>)

The model you're trying to fit should not be identifiable because the nested random effect for each measurement collides with the error terms.


I do not know what to do Insert Calendar in Google Calendar API via Delphi

Question: I'am using REST components for invite Request for Google Calendar API and insert the calendar.
But I do not know what to do now, because Request response = 401 Unauthorized. I think that using the Header for credentials but I do I do that?
Help me please I new programmer in Delphi...
This my code now
    procedure TOAuth2TesterFrm.incluir_btnClick(Sender: TObject);
var
json,token: String;
begin
token:=AccessTokenEdt.Text;
json:=(
'{"kind": "calendar#calendarListEntry", "etag": "0", "id": "email@example.com", ' +
'"summary": "Calendario Outro", "description": "Descrição do evento", '   +
'{"date": "2020 August 11", "dateTime": "2020-08-11T17:35:36+03:00"}'+
'"timeZone": "Brasília-DF", "colorId": "15", "backgroundColor": "#9fc6e7", "foregroundColor": "#000000", ' +
'"selected": true, "accessRole": "owner", "primary": true, '+
 '"defaultReminders": [{"method": "popup", "minutes": 30}, {"method": "email", "minutes": 10}], '  +
'"notificationSettings": {"notifications": [{"method": "email", "type": "eventCreation"}, ' +
'{"method": "email", "type": "eventChange"}, {"method": "email", "type": "eventCancellation"}, ' +
'{"method": "email", "type": "eventResponse"}]}}');
try
    client.ResetToDefaults;
    request.ResetToDefaults;
    response.ResetToDefaults;
    client.BaseURL:='https://www.googleapis.com/calendar/v3/';
    response.ContentType := 'application/json';
    request.Method := TRESTRequestMethod.rmPOST;
    request.Body.ClearBody;
    client.AcceptEncoding:='UTF-8';
    client.ContentType:='application/json';
    request.Resource := 'calendars';
    client.Params.AddHeader('Authorization','Bearer '+token);
    client.Params.ParameterByName('Authorization').Options := [poDoNotEncode];
    request.AddBody(json);
    request.Execute;
    ShowMessage(request.Response.StatusCode.ToString);
finally
      request.Free;
      response.Free;
      client.Free;

end;
  end;

If I add the commented line, I get an Access Violation error
Comment: See https://stackoverflow.com/a/62303114/2339326 (it's c# but explains how a access token should be created - basically a JWT)
Comment: If your token is already a JWT, you need to add the header like 'Authorization:Bearer '
Comment: I'm already doing this, only because IDHTTP is not the right component, I'm using REST
Comment: In you code you are adding the header as ':Token', but google states you need to use ':Bearer'. Second you do not add a space between the the headername/prefix and the token.
Comment: Sorry, I changed my code and no updated her
Comment: I  tried it that way but it doesn't work because the THTTP component is used and I'm using the REST components
Comment: I need learning how to add header in REST components.
Comment: Can you 'read' the calendar using the api and token? Of so, then the token does not have the correct rights/rolles specified.
Comment: please edit your question and show us how you are getting your access token.  https://stackoverflow.com/a/38274129/1841839
Comment: Which scopes are you using for your request? @MárioAyala
Comment: I do not using scopo because I do not know where use, but I have a scopo
Comment: Scopes are added to the token, when creating the token. When you do not have the correct ones added while creating the token, to will probably get 'authorization sation' errors. Btw have you tried to send this request using this header in postman or so? Just to make sure that part is ok (or not).
Answer: As far as I can see, you need to use the TRestClient.Params property to add the header:
RestClient.Params.AddHeader('Autorization', 'Bearer ' + token);

If you still have problems, you might need to specify the 'Options' property of the added parameter: add the option poDoNotEncode
Comment: Still cool Unauthorized but thank you very much it helped a lot
Comment: If you do know what the problem is, please post it here
Comment: I do not know what the problem, but I'am trying solve
Comment: @MárioAyala that error message means its not detecting an authorization header.  Your still not setting it right.
Comment: Okay, but I added a header, just like the other friend said
Comment: I trying with Refresh token in URI and with Access token. I  Updated my code for your see.
Comment: I think one thing is missing, the Scope of the API
Comment: Help me somebody!!
Comment: What error are you receiving now? How did you obtain the token? @MárioAyala


Mixed public/private file upload

Question: In Drupal 6, the Private Upload module allows you to specify that a node file attachment should be stored in the private file system, so that it is not directly accessible by URL. There is a checkbox that toggles public/private.
In Drupal 7, some of this functionality has been moved into core. When you create a File field, you specify whether it uploads into the public or private file system. However, you cannot toggle public/private on each upload.
So what would be the best way in Drupal 7 to be able to specify that some file attachments be be in the public file system, and some be private? I could create two kinds of file fields, public and private, and have each node type have both kinds of file fields. Or I could have separate (though probably otherwise identical) public and private node types, with corresponding file fields. Both ways are awkward.
Any modules that would help with this that I have missed? (I put in a core feature request for a public/private toggle in the field, but that won't help in the short term.)
Comment: How do you determine when a file should be public or private if you were able to achieve one field for both options?
Comment: @nmc: I'm not sure what you mean by "determine". Do you mean Drupal or the person doing the uploading? In our case, the person doing the uploading knows whether it should be public or private. And Drupal will remember because it stores an internal URL ("public://..." or "private://...") that determines whether the file is public or private. The URL is in the **file_managed** database table; take a look in your own table for some examples
Comment: I was wondering how Drupal would know initially whether the person doing the uploading wanted the file public or private if using the same file field for both options.  Missed the part in your question about the toggle which I guess is what you're looking for.
Comment: (I added a link to the core feature request in the original question.)
Comment: "but that won't help in the short term"... still going 9 years later. lol
Comment: Looks like it's finally being implemented: https://www.drupal.org/node/1202074
Answer: What you want is to build a custom widget for the file field type, that has a checkbox that says "this file should be private". Drupal 7 natively handles per-file public/private upload, so at this point it is nothing more then a UI issue.
It has been stated that Private Upload will not be ported to Drupal 7, but I think this is wrong. It should be ported and provide two features:

An upgrade path from the custom, hackish, storage of private files in Private Upload to proper private files (this is not going to happen by magic)
A custom widget that allows the user to choose between public and private during upload
Comment: I was hoping not to have to write a module (which I haven't done before), but have been looking into using hook_field_widget_info_alter to tweak the current widget to add a toggle. I do wish the functionality were part of core; it seems like an obvious use case.
Answer: With OG, I have created my own switch by using file_field_paths and entering [node:group_content_access]/[node:nid]
as the path to store files. In my case every node published should be in an OG. Depending on the visibility of the node published, the files are put into a public or private section.
Note however, that this heavily depends on the contents of the group_content_access or Group Visibility field.

Mixed public/private file upload


Action of $S^1$ as a Lie Group on $S^2$ by "rotation"

Question: I'm studying Lie Groups and their actions on manifolds and I was looking for a "concrete" example of an action. All the stuff about $GL(n;\mathbb{R})$ acting on $\mathbb{R}^n$ is ok but I can't visualise it well, so I thought of an action by the Lie group $S^1$ on $S^2$ by "rotation" in this sense: every element of $S^1$ can be identified by and angle $\alpha$ given by the anti-clockwise rotation around the center $(0,0)$; in the same way we can parametrize $S^2$ using latitude and colatitude. The action that I came up with is simply
$$
\begin{gather}
S^1 \times S^2 \longrightarrow S^2 \\
(\alpha,(\theta, \varphi))\longmapsto (\alpha + \theta, \varphi)
\end{gather}
$$
which "spins" $S^2$ around the vertical axis.
Is this actually an example of a Lie group acting on $S^2$? Are there any other more "concrete" examples I can look at?
Answer: Indeed, that is an example of an action. Notice that there is another way to write the action without coordinates: if you think of $\mathbb{S}^{1}$ as the set of complex numbers of modulus one, the action $\mathbb{S}^{1}\curvearrowright \mathbb{S}^{2}$ is given by $z\cdot (w,t)=(zw,t)$.
If you want to see some other examples of Lie group actions, here are some:

Take $\mathbb{RP}^{2}$ to be the quotient of the $2$-sphere by the relation $x\sim -x$. The action $\mathbb{S}^{1}\curvearrowright \mathbb{S}^{2}$ descends to an action $\mathbb{S}^{1}\curvearrowright \mathbb{RP}^{2}$. Try to think on what the orbits are in this case!

Consider the Lie group $G=SO(2)\times \mathbb{R}$. This group acts on $\mathbb{R}^{3}$ by letting $(A,t)\cdot (x,y,z)=(A(x,y),z+t)$. Again, which are the orbits for this action?

Hope this helps!


Como identificar um número específico em um valor numérico qualquer?

Question: Por exemplo, minha variável valor (tipo inteiro) tem o valor 1354, repare que o numero 13 aparece neste valor numérico. Como posso identificar um numero especifico em outro valor numérico qualquer?
Eu gostaria de um exemplo em C.
Segue o enunciado do problema:
A China está construindo um elevador espacial, que permitirá o lançamento de sondas e satélites a
um custo muito mais baixo, viabilizando não só projetos de pesquisa científica como o turismo espacial.
No entanto, os chineses são muito supersticiosos, e por isso têm um cuidado muito especial com
a numeração dos andares do elevador: eles não usam nenhum número que contenha o dígito "4" ou a
sequência de dígitos "13". Assim, eles não usam o andar 4, nem o andar 13, nem o andar 134, nem o
andar 113, mas usam o andar 103. Assim, os primeiros andares são numerados 1, 2, 3, 5, 6, 7, 8, 9, 10,
11, 12, 15, 16, . . .
Como o elevador espacial tem muitos andares, e eles precisam numerar todos os andares do elevador,
os chineses pediram que você escrevesse um programa que, dado o andar, indica o número que deve
ser atribuído a ele
Indentifiquei uma forma de verificar se o ultimo algarismo termina com 4, segue o exemplo:
int andar(int numero)
{
    int sobra = 0;
    int resultado;

    sobra = numero % 10;

    if (sobra == 4)
    {
        resultado = numero + 1;
    }
    else
    {
        resultado = numero;
    }

    return resultado;
}

Minha duvida e como identificar o 13 e o 4 em um numero qualquer.
Comment: Eu não faria matematicamente, eu converteria para *string* e procuraria nela. Então, mostrei como fez o outro , como está tentando fazer este.
Comment: Você quer saber se existe uma sequência de dígitos dentro dos dígitos de um número? Já fez alguma coisa? Está com alguma dúvida específica? Algum problema no que está fazendo? Mostre o que tentou.
Comment: O problema aqui é identificar se o ultimo algarismo termina com **4**, este eu solucionei, já este que citei é identificar o numero 13 em um determinado valor, por exemplo: 413 tem o numero 13 já 414 não tem, deve haver alguma função matemática para solucionar isto.
Comment: Só precisa ver se está no final? Ou pode estar em qualquer posição?
Comment: Em qualquer posição, por exemplo: 42134 tem o 13 neste valor. E meio que uma pesquisa dentro de um valor **inteiro**.
Comment: Foi editar a pergunta e colocar o enuciado.
Answer: Converte para string e procura a substring.
#include <stdio.h>
#include <string.h>

int ProcuraNumero (int NumeroProcurado, int NumeroAlvo) {
    char NumeroProcuradoString[16];
    char NumeroAlvoString[16];

    sprintf (NumeroProcuradoString, "%d", NumeroProcurado);
    sprintf (NumeroAlvoString, "%d", NumeroAlvo);

    return strstr (NumeroAlvoString, NumeroProcuradoString) != NULL ? 1 : 0;
}

int main(void) {
    printf("%d:", ProcuraNumero (13, 1354)); // 1 = Encontrou.
    printf("%d:", ProcuraNumero (13, 1054)); // 0 = Não encontrou.
    return 0;
}

Exemplo rodando aqui: http://ideone.com/K1WyIc
Comment: Obrigado pela resposta.
Comment: Vou testar aqui.
Comment: É interessante elucidar porque é necessária a conversão para string. "1354" para o computador não é o número, mas a representação de um número (internalizado como binário) em base 10. Dizer que "1354" contem "13" faz sentido para a representação do número, mas não para o valor em si.
Answer: A solução para o problema acima, é utilizar a função do @Alexandre Borela ProcuraNumero(int NumeroProcurado, int NumeroAlvo) em um loop for.
Solução:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int ProcuraNumero(int, int);

int main(void)
{
    int n_andar , i, treze, quatro;

    printf("\nNumero do andar: ");
    scanf("%i", &n_andar);

    for (i = 0; i < n_andar; i++)
    {
        treze = ProcuraNumero(13, n_andar);

        quatro = ProcuraNumero(4, n_andar);

        if ((quatro == 1) || (treze == 1))
        {
            n_andar += 1;
        }
    }

    printf("\nNovo numero do andar: %i\n\n", n_andar);
}

int ProcuraNumero(int NumeroProcurado, int NumeroAlvo)
{
    int resultado;

    char NumeroProcuradoString[16];
    char NumeroAlvoString[16];

    sprintf(NumeroProcuradoString, "%d", NumeroProcurado);
    sprintf(NumeroAlvoString, "%d", NumeroAlvo);

    resultado = strstr(NumeroAlvoString, NumeroProcuradoString) != NULL ? 1 : 0;

    return resultado;
}


Is it possible to create a table from Paragraph fields in Views?

Question: I'm trying to create a table in Views with the information from a node that is using Paragraphs. Somehow I can't find a way to display the values from the paragraph fields in a proper table, is this even possible?
All I can manage to do is the table as shown in the picture below:
If possible, how can I create a table where each field has its own column instead? And if that's not possible – what other approach should I use?
Answer: You need to enhance your view with Relationships.
Let's say you have a content type Client with a paragraphs field Mail, which allows embedding instances of the paragraphs bundle Client_Mail. When you create a view on all Client nodes, you should find a Relationship to the field (Mail) which contains your paragraph bundle (Client_Mail).
After adding this relationship, the fields making up the paragraphs bundle will show up in the field list. You can add and arrange them like regular node fields, but make sure that the paragraphs relation is chosen in the field settings.


Searching with regex in superboxselect extjs

Question: I need to configure superboxselect component of extjs4 and make it search with regular expression. Does anybody have any idea which function should i override or does extjs already have a function or attribute which supports this?
Thanks in advance.
Answer: I don't fully understand your question but ExtJS supports Regular Expressions.
You can search a string with RegExp like this:
<code>var regex = /in/g; //or new RegExp("in","g");
var result = regex.exec("this is the string to search in");
console.log(result[1]);
</code>
From the docs:

If the match succeeds, the exec method returns an array and updates
  properties of the regular expression object. The returned array has
  the matched text as the first item, and then one item for each
  capturing parenthesis that matched containing the text that was
  captured. If the match fails, the exec method returns null.


For a series, can you always find a subseries whose sum is smaller in magnitude?

Question: Let's say you got a series $a_n$, such that $\sum^\infty_{n=0}a_n=L>0$. For any $0 \lt K \le L$, can you always find a subsequence $b_n$ of $a_n$, such that $\sum^\infty_{n=0}b_n=K$? If not always, when can you?
(Inspired by this comment.)
Comment: If $\sum_nx_n$ converges but $\sum_n|x_n|$ does not, then for any $r$ there is an infinite subsequence summing to $r$.
Comment: I recall it is in the book Infinite Sequences And Series by Bromwich. Let $P=\{n :x_n>0\}=\{f(n):n\in N\}.\; M=\{n:x_n<0\}=\{g(n):n\in N\}$ where $f,g$ are strictly increasing. Neither of $\sum_{n\in P}x_n, \;\sum_{n\in M}x_n\}$ converges but $x_{f(n)}$ and $x_{g(n)}$ go to $0$ as $n\to \infty.$ Take a finite set $A_1$ of consecutive terms of $A=\{x_{f(n)}:n\in N\}$  until their sum  $S_1$ exceeds $r.$ Then take consecutive terms of  $B=\{x_{g(n)}:n\in N\}$  of higher subscript than those in $A_1$, until their sum  $S_2$ satisfies $S_1+S_2<r.$ Then select from $A$ until....
Comment: Are we assuming that $\sum a_n$ converges?
Comment: @user254665 Do you have a citation for that? That sounds cool!
Comment: That's the (Levy-)Steinitz (derangement) theorem. Actually the first known formulation was by Grassmann some 50-60 years earlier, in the context of vector valued series.
Comment: Now that I re-thought it, the statement in Bromwich was that we could re-arrange the whole series to get a sum of any value. But here we are asked for a subsequence. I'm not at all familiar with the history of it.
Answer: We cannot always do it. Look for example at the series $\sum_0^\infty \frac{1}{10^n}$.
Answer: For large $L$, take $a_0 = L - 1$ and $a_n = 2^{-n}$ for $n \geq 1$. Then for any subset $I\subset \mathbb{Z}^{\geq 0}$, the sum $s = \sum_{n\in I} a_n$ has $s \geq L -1$ if $0\in I$ and $s\leq 1$ otherwise.


What are some of the considerations for putting electric guitar strings on a bass?

Question: After watching the linked video it came clear that putting regular strings on a bass has some groovy effects, Im just curious as to how bass pickups are going to work with strings that operate on different frequencies?
Is there some other pitfalls to doing this or can you use it for some new sonic possibilities?
Answer:
I'm just curious as to how bass pickups are going to work with strings that operate on different frequencies.

There's no basic problem there. Simplistically-speaking, bass pickups will work on all the frequencies that guitar pickups do.
IMO the main difference you will get is a difference in the feel of the instrument, which you may find inspiring - or just awkward.
To get it working as well as possible, you'll probably need to re-do the instrument setup once it has the new string set on.

Is there some other pitfalls to doing this?

watch for...

overtightening guitar strings - if you tune a guitar string to the same pitch as usual on a longer instrument, you will have tightened it much more.
buying strings that are too short (this is mentioned at the end of the video).


Limpar opção selecionada de um select com jQuery

Question: Estou com um formulário com radio buttons, e quando vou selecionando os radio buttons ele vai aparecendo/escondendo os campos que quero.
Até aí ta beleza, mas, se eu seleciono uma opção no  e depois mudo de radio button, aquele campo  some, mas, não limpa o valor escolhido nele, então se mandar o formulário, o valor é passado, mesmo o campo estando escondido.
Alguém saberia como limpar a opção selecionada do ?
Ja tentei com .empty(), mas aí ele apaga todos os valores do .
formulario:

Vencimento da 1ª parcela (dia) *

    <select class="form-control col-md-7 col-xs-12 select2_single forma" tabindex="-1" id="select-custom-field3"  name="custom_field[account][3]">
        <option value="" id="vazio"></option>
            <?php
                $b = array(5,15); //  ######## DIAS PARA PAGAMENTO
                foreach($b as $key => $value){
            ?>
        <option value="<?php echo $value;?>" <?php if($value == $vvencimento){ echo ' selected="selected"'; } ?> ><?php echo $value;?></option>
            <?php } ?>
    </select>

E o jQuery:
if (this.checked && this.value == '3') {
$("#gr-004").show();
$("#gr-002").hide();
$("#gr-003").hide();
$("#select-custom-field3").empty().append("#gr-003");

Desde já agradeço!

#### EDIÇÃO

Segue o formulário completo:

  Forma de pagamento *

    <input type="radio" name="custom_field[account][1]" id="id-custom_field-account-1-1" value="1" <?php echo ($vformapagamento == '1')?'checked':'';?> > Boleto Conta Um

    <input type="radio" name="custom_field[account][1]" id="id-custom_field-account-1-2" value="2" <?php echo ($vformapagamento == '2')?'checked':'';?> > Cartão Conta Um

    <input type="radio" name="custom_field[account][1]" id="id-custom_field-account-1-3" value="3" <?php echo ($vformapagamento == '3')?'checked':'';?> > Espécie (R$)

    <input type="radio" name="custom_field[account][1]" id="id-custom_field-account-1-4" value="4" <?php echo ($vformapagamento == '4')?'checked':'';?> > Depósito/Transferência

    <input type="radio" name="custom_field[account][1]" id="id-custom_field-account-1-5" value="5" <?php echo ($vformapagamento == '5')?'checked':'';?> > Cheque

  Qtde. Parcelas *
Caso seja pagamento à vista, selecione 1

    <select class="form-control col-md-7 col-xs-12 select2_single forma" tabindex="-1" id="select-custom-field2"  name="custom_field[account][2]">
      <option></option>
      <?php
        for($a=1; $a<=12; $a++){
      ?>
      <option value="<?php echo $a;?>" <?php if($a == $vqtdeparcelas){ echo ' selected="selected"'; } ?> ><?php echo $a;?></option>
      <?php } ?>
    </select>

  Vencimento da 1ª parcela (dia) *

    <select class="form-control col-md-7 col-xs-12 select2_single forma" tabindex="-1" id="select-custom-field3"  name="custom_field[account][3]">
      <option value="" id="vazio"></option>
      <?php
        $b = array(5,15); //  ######## DIAS PARA PAGAMENTO
        foreach($b as $key => $value){
      ?>
      <option value="<?php echo $value;?>" <?php if($value == $vvencimento){ echo ' selected="selected"'; } ?> ><?php echo $value;?></option>
      <?php } ?>
    </select>

  Data do recebimento*

    <input type="text" class="form-control col-md-7 col-xs-12 forma" name="custom_field[account][4]" id="input-custom-field4" value="<?php echo $vdatarecebimento; ?>" data-inputmask="'mask' : '99/99/9999'">

E o jQuery completo:
$(document).ready(function() {
  $("#gr-002").hide();
  $("#gr-003").hide();
  $("#gr-004").hide();

  $('input:radio[name="custom_field[account][1]"]').on("change", function() {
    if (this.checked && this.value == '1') {
      $("#gr-002").show();
      $("#gr-003").show();
      $("#gr-004").hide();
    } if (this.checked && this.value == '2') {
      $("#gr-002").show();
      $("#gr-003").show();
      $("#gr-004").hide();
    } if (this.checked && this.value == '3') {
      $("#gr-004").show();
      $("#gr-002").hide();
      $("#gr-003").hide();
      $("#select-custom-field3").val('');
    } if (this.checked && this.value == '4') {
      $("#gr-004").show();
      $("#gr-002").hide();
      $("#gr-003").hide();
    } if (this.checked && this.value == '5') {
      $("#gr-002").show();
      $("#gr-003").show();
      $("#gr-004").hide();
    }
  });
});

Comment: Dei uma resposta à tua pergunta mas fiquei curioso qual a ideia de `.append("#gr-003");`?
Comment: Eu estava tentando somente com o empty(), mas vi em fórum um cara dizendo pra usar o append, entao tentei usar ^^
Comment: Podes mostrar o HTML renderizado e o JS. Assim posso dar uma ajuda a organizar/simplificar esse código.
Comment: Editei a pergunta e coloquei o formulario e o jquery completo
Comment: Então cada `custom_field[account][1]` tem um `form-group` que pode ter um select ou um input, é isso? e quando um `custom_field[account][1]` fôr escolhido somente 1 `form-group` deve ficar visivel certo?
Comment: Só vai ficar um visivel se o radio escolhido for de valor 3 ou 4. Até aí em esconder/aparecer os campos ta beleza, o problema é que se eu preencho um campo, e depois de preenchido, escondo ele, então depois se eu colocar pra aparecer esse campo novamente, ele ainda vai estar preenchido. E o que quero é que quando eu esconda o campo, ele apague o valor dele
Comment: Editei a resposta, dá uma olhada.
Answer: A maneira de apagar o valor do select é usar .val('').
Assim o teu código pode ser:
$(document).ready(function() {
  $("#gr-002").hide();
  $("#gr-003").hide();
  $("#gr-004").hide();

  $('input:radio[name="custom_field[account][1]"]').on("change", function() {

    if (this.value == '1' || this.value == '2' || this.value == '5') {
      $("#gr-002, #gr-003").show();
      $("#gr-004").hide();
    } else {
      $("#gr-004").show();
      $("#gr-002, #gr-003").hide();
      $("#select-custom-field3").val('');
    }

  });
});

Comment: Obrigado pela resposta, mas com val('') ja havia tentado e ele não apaga do valor selecionado, quando volto pro select, o valor ainda esta selecionado
Comment: Sou iniciante com jquery, então só pra constar que fiz certo. #gr-003 é a div a ser escondida, e #select-custom-field3 é o id do select.
Esta correto mesmo?
Comment: @Gabriel `#gr-002` e  `#gr-003` serão escondidos. Dá uma olhada aqui: https://jsfiddle.net/9yfn540j/
Comment: O que preciso é que limpe o valor quando o campo for escondido, e não quando é clicado algum botão.
Não estou entendendo o porque o .val('') não funciona :/
Comment: O problema deve estar fora do jquery, este exemplo também não funcionou -_-
Comment: @Gabriel copia esse HTML todo e faz um jsFiddle. Assim dá para ver o problema isolado e será fácil de resolver.
Answer: Se entendi bem sua pergunta você deseja resetar o seu <select> se for isso vou criar um exemplo abaixo.

jQuery(document).ready(function(){

  jQuery('#limpar').click(function(){
    jQuery('#select').prop('selectedIndex',0);
  })
});

<select id="select">
  <option>Selecione</option>
  <option>Laranja</option>
  <option>Uva</option>
  <option>Goiaba</option>
</select>
<input type="button" value="limpar select" id="limpar">


Stratified Sampling in R- sample size issues

Question: I am trying to do stratified sampling in R using the stratified function in the splitstackshape package. I have four strata (labeled 1:4). When setting the size = 1, it returns one row belonging to each strata (great!). However, I'm not able to increase my sample size by one.
I want it to select 5 rows: 4 of them belonging to strata 1:4, and the fifth one belonging to strata #1 (the strata that covers the most amount of area in my study site); and ideally this will be done without replacement so the second row that is sampled from strata #1 will not be the same as the first.
Setting the size = 1 - 1.99 always returns 1 row from each strata (4 total). Setting the size = 2 returns 8 rows (2 from each strata).
Dataframe
homer_join_strat<- structure(list(cluster = c(4L, 3L, 4L, 5L, 5L, 4L, 4L, 4L, 5L,
5L, 5L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 5L, 1L, 1L, 5L, 4L, 4L,
4L), waterbody = c("Homer", "Homer", "Homer", "Homer", "Homer",
"Homer", "Homer", "Homer", "Homer", "Homer", "Homer", "Homer",
"Homer", "Homer", "Homer", "Homer", "Homer", "Homer", "Homer",
"Homer", "Homer", "Homer", "Homer", "Homer", "Homer", "Homer"
), transect_number = 1:26, BLG = c(75, 38.4204909284952, 77.634011090573,
82.1917808219178, 119.341563786008, 22.5422667501565, 155.275381552754,
81.1332904056665, 37.037037037037, 73.2824427480916, 71.608040201005,
208.806818181818, 116.504854368932, 119.775421085465, 104.408352668213,
117.391304347826, 12.0603015075377, 93.5593220338983, 166.795366795367,
20, 91.566265060241, 70.8860759493671, 0, 44.8765893792072, 0,
3.96563119629874), GSF = c(0, 6.4034151547492, 11.090573012939,
16.4383561643836, 4.11522633744856, 0, 0, 0, 0, 4.58015267175573,
0, 21.3068181818182, 0, 0, 6.96055684454756, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0), LMB = c(51.3157894736842, 83.2443970117396, 73.9371534195933,
71.2328767123288, 28.8065843621399, 37.5704445835942, 59.721300597213,
38.6349001931745, 66.6666666666667, 77.8625954198473, 67.8391959798995,
63.9204545454545, 46.6019417475728, 22.4578914535246, 6.96055684454756,
13.0434782608696, 24.1206030150754, 40.6779661016949, 60.2316602316602,
56, 28.9156626506024, 55.6962025316456, 20.2360876897133, 31.413612565445,
0, 31.7250495703899), YLB = c(0, 0, 14.7874306839187, 0, 4.11522633744856,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.63320463320463, 0, 0,
0, 0, 0, 0, 0), BLC = c(7.89473684210526, 12.8068303094984, 7.39371534195933,
10.958904109589, 0, 0, 3.9814200398142, 0, 3.7037037037037, 13.7404580152672,
11.3065326633166, 12.7840909090909, 3.88349514563107, 3.74298190892077,
0, 0, 0, 4.06779661016949, 0, 16, 9.63855421686747, 5.06329113924051,
20.2360876897133, 22.4382946896036, 0, 7.93126239259749), WHC = c(0,
0, 0, 0, 0, 0, 3.9814200398142, 0, 7.40740740740741, 0, 0, 0,
0, 7.48596381784155, 0, 0, 0, 0, 0, 0, 0, 10.126582278481, 0,
4.48765893792072, 0, 0), RSF = c(0, 0, 0, 0, 0, 0, 11.9442601194426,
0, 0, 13.7404580152672, 0, 0, 0, 0, 0, 0, 0, 0, 27.7992277992278,
0, 4.81927710843374, 0, 0, 4.48765893792072, 0, 0), CCF = c(0,
0, 0, 0, 0, 0, 0, 0, 3.7037037037037, 0, 0, 0, 3.88349514563107,
0, 0, 0, 0, 8.13559322033898, 0, 0, 0, 0, 0, 0, 0, 0), BLB = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8.52272727272727, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c(NA,
-26L))

Code
stratified(homer_join_strat, "cluster",  size=.06)
stratified(homer_join_strat, "cluster",  size=.07)
stratified(homer_join_strat, "cluster",  size=.09)
stratified(homer_join_strat, "cluster",  size=2)

Does anyone have experience using this function to select a number of rows that does not equal or is not a multiple of the number of strata in the data?
I am able to have it select 1, 2, 3, rows (in order of square area) by setting the size = .06, .07, .09 respectively (why I thought a number between 1-1.99 would give me 5 rows selected
Thanks in advance!
Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.
Comment: Sorry about that, dataframe/code added
Answer: from the documentation on the function you are using "If size is a named vector, the function will check to see whether the length of the vector matches the number of groups and that the names match the group names" - it then goes on to provide an example of exactly what your question asks.
  DF <- data.frame(
  ID = 1:100,
  A = sample(c("AA", "BB", "CC", "DD", "EE"), 100, replace = TRUE),
  B = rnorm(100), C = abs(round(rnorm(100), digits=1)),
  D = sample(c("CA", "NY", "TX"), 100, replace = TRUE),
  E = sample(c("M", "F"), 100, replace = TRUE))

  stratified(DF, "D", c(CA = 5, NY = 3, TX = 2))

Comment: I did see/try that but was still getting errors. Switching my cluster categories to letters instead of numbers ended up working. Thanks for your help!


How to get the eth: IP address of Client in UDP in C language

Question: My eth1 : IP adrress is something like a:b:c:d
What i get in server that is router given address (public ip): e:f:g:h
is there any way to find the local ip address of the system in C and must be udp
Comment: UDP is a protocol *above* IP - it doesn't have it's own IP address.  Also what O/S are you talking about; I assume Linux given the interface name?
Comment: Put more effort into your question. It's hard to tell what you are asking.
Comment: possible duplicate of [Linux / C++: Get the IP Address of local computer](http://stackoverflow.com/questions/212528/linux-c-get-the-ip-address-of-local-computer)
Answer: If your client is behind a NAT:ing firewall or router, then no, there's no way for the server to directly see the client's LAN IP address. Often, such addresses are "LAN only" (non-routable) e.g. 192.168.x.y or 10.x.y.z.
If using your own custom protocol, then you can of course embed the information in a datagram and send it to the server, but beware that there's a large change the address information is completely useless to the server, for the above-mentioned reason.
Comment: Doesn't he want his own address (I think his computer is the client)?
Comment: trojanfoe@ yes, My one pc is client and another one is 8 core server.It is basically a udp client-server multithreading experiment, where i am checking how much the load it can take.When i use inet_ntoa i get the client address which is not my real address.
Comment: unwind@ i liked your thinking and trying to do something like that.


how to use the Permission helper intent from dialogflow in wehhook c#

Question: I'm new to dialogflow and trying to use permission handler to ask for location permission using .NET core webapi. I've created intent, entities and event(google.assistent.permission) in dialogflow console. Now I want to send a request from my webapi to send the request to access location.
Can somebody please provide a code sample how to send request to access location from my webhook?
Answer: You need to include the helper intent DialogFlow JSON as part of the payload:
WebhookResponse response;
Struct payload;
response.Payload = payload;

Alternatively, it can be added as a fulfillment message with the payload type1.
The payload struct can be parsed from JSON:
response.Payload = Struct.Parser.ParseJson(@"{
  ""google"": {
    ""expectUserResponse"": true,
    ""systemIntent"": {
      ""intent"": ""actions.intent.PLACE"",
      ""data"": {
        ""@type"": ""type.googleapis.com/google.actions.v2.PlaceValueSpec"",
        ""dialogSpec"": {
          ""extension"": {
            ""@type"": ""type.googleapis.com/google.actions.v2.PlaceValueSpec.PlaceDialogSpec"",
            ""permissionContext"": ""To find a location"",
            ""requestPrompt"": ""Where would you like to go?""
          }
        }
      }
    }
  }
}");

Or created using the Protobuf API (slightly faster due to skipping the parsing step and type safe, but incredibly ugly):
response.Payload = new Struct
{
  Fields =
  {
    ["google"] = Value.ForStruct(new Struct
    {
      Fields =
      {
        ["expectUserResponse"] = Value.ForBool(true),
        ["systemIntent"] = Value.ForStruct(new Struct
        {
          // ... and so on
        })
      }
    })
  }
};

Keep in mind that including any message in the payload (which is necessary to call the helper) will override any other messages you added previously and ignore anything added afterwards (they are still part of the returned object, but stripped out by DialogFlow). That means: If you want any other rich response, it currently also needs to be manually added to the payload. At that point, you might as well create the entire JSON response from scratch.


Map method with specific attributes only

Question: I have a Book model and an User model. User has many books.
From my schema:
create_table "users", force: :cascade do |t|
  t.string   "email",                  default: "",    null: false
  t.string   "full_name"
  t.string   "gender"
  t.integer  "age"
  t.string   "country"
  t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
  t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
end

My goal is to map the User model into an array of user objects:
[{...}, {...}, {...}]
with objects only with attributes:
{id: 15, full_name: "Tim Test"}

I can map the users from the books with
@user = @books.map { |u| u.user }.uniq

But how can I only map with the attributes id and full_name?
Answer: Use pluck, it is the cheapest way to do what you want:
User.pluck(:id, :fullname)
#=>[[1, "Tim Test1"]
#   [2, "Tim Test2"]]

Then you can simply iterate it.
In this case, you don't create a heavy ActiveRecord object, so it's faster and consumes less memory than select.
If you want result exactly like in your question, you can simply build it:
User.pluck(:id, :fullname)
    .map { |e| [:id, :fullname].zip(e).to_h }


How to add intent on menu event

Question: I want to call activity on menu event.I am new to android so i am trying to open new screen on delete option on menu, for this i write switch case but i didnt get how to call another activity in that please help me my code is
@Override
     public boolean onCreateOptionsMenu(Menu menu)
     {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu, menu);
         return true;
     }
     @Override
     public boolean onOptionsItemSelected(MenuItem item)
     {
        switch(item.getItemId())
          {
            case R.id.delete:   Intent i= new Intent(this,deleteAct.class);
                                 startActivity(i);break;
            case R.id.edit://calling another  intent; break;
            case R.id.showall://calling another intent; break;
          }
       return true;
     }

please help me ..
Comment: What is the behavior you see ?
Comment: Note you can [format lines as code](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) by indenting them four spaces. The "{}" button in the editor toolbar does this for you. Edit your question and try it out. Click the orange question mark in the editor toolbar for more information and tips on formatting.
Comment: what error did you noticed in the log file?
Comment: Can you elaborate the question more, as the code (delete case) looks quite ok to me.
Answer: Neha... Did you declare the activity in the AndroidManifest.xml file as in:
<activity android:name= "deleteAct"
    android:label="@string/delete_act_title">
</activity>

Also, consider adding:
default:
    return super.onOptionsItemSelected(item);

JAL
Some code here.

How to add intent on menu event


How to follow C++ grammar for a calculator by hand?

Question: I'm following PPP using C++ by Bjarne Stroustrup and I'm having difficulty following along with his introductory grammar for a calculator (pg 189-192) as follows:
// a simple expression grammar
Expression:
    Term
    Expression "+" Term // addition
    Expression "-" Term // subtraction

Term:
    Primary
    Term "*" Primary // multiplication
    Term "/" Primary // division
    Term "%" Primary // remainder (modulo)

Primary:
    Number
    "(" Expression ")"

Number:
    floating-point-literal

Firstly we parse 2, which is a floating-point-literal which is a Number which is a Primary which is a Term which is an Expression.
Then we go to parse 2 + 3 :
2 is a floating-point-literal which is a Number which is a Primary which is a Term which is an Expression

Jumps straight to Expression (this is where I start getting lost)

3 is a floating-point-literal which is a Number which is a Primary which is a Term. Why does the book stop parsing here, "3" currently fits all the criteria to be an Expression?
When I try to perform this action by hand, I can only come to a conclusion that matches the given diagram when I ignore the "+" and parse 3 to Term to match the requirement Expression "+" Term.
Furthermore, if I try and extrapolate further to parse  9 + 3 * 2, without looking ahead for a * I cannot finish working through the grammar, as 9+3 is (apparently) a valid expression which has no grammar to be multiplied...
Answer: I guess the main issue you are having has to do with the fact that you are reading it from bottom to top. The arrows in the book are meant to denote information flow, but not parsing order.
Here is the grammar we are interested in (for reference):
Expression:
    Term
    Expression "+" Term
    Expression "-" Term

Term:
    Primary
    Term "*" Primary
    Term "/" Primary
    Term "%" Primary

Primary:
    Number
    "(" Expression ")"

Number:
    floating-point-literal

The following paragraphs try to give an overview of the parsing process in the case of this grammar, as well as in a more general setting.
Parsing expressions: a simple example
The above grammar gives the rules needed to parse an Expression. Expression is said to be an axiom of the grammar. This means that in order to parse any given expression, we have to start with the Expression rule.
Let us consider the expression 2 + 3. The parsing process goes as follows:

We match 2 + 3 against the rules for Expression. It has to be either a Term, an expression of the form Expression "+" Term or an expression of the form Expression "-" Term. It turns out it is an Expression "+" Term.
We match the left-hand side of 2 + 3 with Expression.

The only possible rule for 2 is Term.
We then match 2 against the rules for Term. 2 does not contain "*", nor "/", nor "%". It therefore has to be a Primary.
We proceed with the rules for Primary. As it does not contain any parenthesis, 2 has to be a Number.
Finally, we have that 2 is a floating-point-literal.

We match the right-hand side of 2 + 3 with Term.

As for 2, 3 has to be a Primary.
Again, following the same path as above, 3 is deduced to be a Number and then a floating-point-literal.

Finally, 2 + 3 is an expression of the form floating-point-literal "+" floating-point-literal.
Parsing expressions: complex expressions
We now know how to parse a simple expression. But what about a more complicated one, like (2 - 1) + 9 * 3? The techniques described above also apply in this case. Here is an unrolled version of the parsing process:

(2 - 1) + 9 * 3 is of the form Expression "+" Term.
We match the left-hand side with the rules for Expression.

(2 - 1) is a Term (as it does not contain "+" nor "-").
Similarly, (2 - 1) is a Primary.
(2 - 1) is of the form "(" Expression ")". By using the exact same process as for 2 + 3, we end up with "(" floating-point-literal "-" floating-point-literal ")".

We match the right-hand side with the rules for Term.

9 * 3 is of the form Term "*" Primary.
We match 9 against the rules for Term and we go on until we get a floating-point-literal.
We match 3 against the rules of Primary and also get a floating-point-literal after some refinement.
Finally, 9 * 3 is of a Term of the form floating-point-literal "*" floating-point-literal.

In the end, (2 - 1) + 9 * 3 reduces to "(" fp - fp ")" "+" fp "*" fp.
Comment: In other words, a parser can't tell the future so it keeps trying to pattern match until it finds a single interpretation. If there are multiple then the result is ambiguous and this is usually considered (a) an invalid program, and (b) a poor language.
Comment: Thank you, the addition explanation of complex expressions makes this the better answer.
Comment: *"`(2 - 1) + 9 * 3` is of the form `Expression "+" Term`"* - how do you determine that?
Comment: @VittorioRomeo `(2 - 1) + 9 * 3` is an `Expression`, so it can only be of the form `Term`, `Expression "+" Term` or `Expression "-" Term`. It might be an `Expression "-" Term` in this case, but then `(2` would have to be an `Expression`.
Answer: You are right that 3 would be an expression, but then "expression + expression" wouldn't  make sense. Seeing the "+" token, we only have one option how to interpret what's on the left and on the right of it:

Expression "+" Term

So we keep promoting both 2 and 3 until the leftmost becomes an Expression and the rightmost a Term.
The diagram on the right is arguably somewhat confusing. You might be better off reading it from top to bottom, rather than the other way round. Then you could make the following sense of it:

We're trying to parse an Expression, that's the starting point.
We find a candidate formed as 'Expression "+" Term'.
What (out of the three options) is the Expression on the left? It's a Term. What's that Term? It's a Primary. (Again, not a 'Term "*" Primary' or any of the other options.) What's that Primary? It's a Number. What Number? A floating-point-literal 2.
The + symbol in the middle requires no further investigation, it fits the pattern as it is.
What's the Term on the right of the 'Expression "+" Term'? Continue as in 2.


Is $\sin\left(\frac{1}{x}\right)$ periodic?with what period time?

Question: Is $\sin\left(\frac{1}{x}\right)$
periodic? with what period time?
Comment: no it is not periodic
Answer: No, it's not. If it were periodic, the derivative would be periodic too (I'll let you prove this result). But here,
$$f'(x)=\frac{-\cos\left(\frac{1}{x}\right)}{x^2}\to 0 \ \text{ as } \ x \to\infty, $$
and so, it's impossible that $x\mapsto \sin\left(\frac{1}{x}\right)$ is periodic.


modifying float with jquery not working

Question: I have this code:
if(scrollTop  0)
                headers[i-1].element.css('z-index', 100);
        }
    }

    //stick headers
    for(i in headers) {
        var header = headers[i];
        //make sure any stuck headers are stuck in the right place(fast scrolling sometimes messes this up)
        if(isStuck(header))
            header.element.css('top','0')

        //skip this header if its bellow the top of the window
        if(scrollTop  header.orgOffset) {
                //stick the header
                document.getElementById('log').style.display = 'block';
                document.getElementById('lista').style.float = 'left';
                document.getElementById('lista').style.marginLeft = '20px';
                header.element.css("left", "0px").css("box-shadow", "0 0 5px #000").css('background-color', '#FFF').css('width', '100%').css('position', 'fixed').css('z-index','100').css('top','0').before('

');
                if(i > 0)
                    headers[i-1].element.css('z-index', -1);

This works for sticky headers in my page. But modifying the float attribute to left and then back to none doesn't work in firefox. Everything else works fine, and it works fine in chrome, rockmelt and safari.
Answer: You need to use cssFloat as the style property instead of float for Firefox. You can refer this and this.
Ex
document.getElementById('lista').style.cssFloat = 'left';

modifying float with jquery not working


Problem about limit of Lebesgue integral over a measurable set

Question: This is actually problem 4T of Bartle's book "The elements of integration and Lebesgue measure".
Let $f_n$, $f$ be nonnegative measurable functions on $\mathbb{R}$ such that $f_n\to\ f$ for every real number (pointwise convergence). Suppose that $lim_{n\to \infty}\int_\mathbb{R}f_n=\int_\mathbb{R}f$.
Show that if $\int_\mathbb{R}f<\infty$, then $lim_{n\to \infty}\int_Ef_n=\int_Ef$ for every measurable set $E\subset\mathbb{R}$
Important theorems that I'm allowed to use: Theorem of Monotone Convergence, Fatou's Lemma, and Theorem of Dominated Convergence. I've been attempting to use dominated convergence by trying to define a sequence of functions bounded by f on $E$, but I haven't been able to come up with such a sequence.
Any hints would be greatly appreciated.
Answer: For any measurable set $E \subset \mathbb{R},$ we have $\displaystyle \int_Ef \leqslant \int_{\mathbb{R}}f < \infty$ and $\displaystyle \int_{E}f_n \leqslant \int_{\mathbb{R}}f_n \to \int_{\mathbb{R}}f$.
Hence, for sufficiently large $n$, we have
$$\displaystyle \int_Ef_n < \infty.$$
Using Fatou's Lemma,
$$\int_E f = \int_E \lim f_n=\int_E \liminf f_n \leqslant \liminf \int_E f_n$$
and reverse Fatou's Lemma,
$$\liminf \int_E f_n \leqslant \limsup\int_E f_n \leqslant \int_E \limsup f_n = \int_E \lim f_n = \int_Ef.$$
Hence,
$$\tag{*}\int_Ef \leqslant \liminf \int_E f_n \leqslant \limsup\int_E f_n \leqslant\int_Ef,$$
and
$$\liminf \int_E f_n = \limsup\int_E f_n=\lim \int_E f_n = \int_Ef.$$
Update:
We can avoid the argument based on reverse Fatou as follows.
Note that since $f_n \to f$ and $\int_{\mathbb{R}} f_n \to \int_{\mathbb{R}} f$ we have
$$\begin{align}\limsup \int_E f_n &= -\liminf \left(-\int_E f_n \right) \\&= -\liminf \left(\int_{\mathbb{R}\setminus E} f_n-\int_{\mathbb{R}} f_n \right) \\ &= -\liminf \int _{\mathbb{R}\setminus E} f_n+\liminf \int_{\mathbb{R}} f_n \\ &\leqslant -\int_{\mathbb{R} \setminus E} \liminf f_n + \int_{\mathbb{R}} f \\ &= -\int_{\mathbb{R} \setminus E} f + \int_{\mathbb{R}} f \\ &= \int_E f\end{align} $$
The chain of inequalities (*) now follows.
Comment: Update added.  I still think I had found the necessary dominating function to apply the reverse Fatou lemma, but I have to work on that further.
Comment: @salvador: You're welcome.
Comment: I think this step $$\limsup\int_E f_n \leqslant \int_E \limsup f_n$$ is incorrect ..... or in case I am wrong just tell me why is this inequality correct?
Comment: @Idonotknow: The reverse Fatou lemma involving $\limsup$ holds if there is a dominating integrable function $g$ such that $f_n \leqslant g$ for all $n$.  I think this can be found given the other hypotheses. As this is over 4 years old I have to spend some time trying to reconstruct my thinking that led me to believe it to be true.
Comment: So, I am sorry for this question I know the question is long ago but I can not see anything about reverse Fatou 's Lemma in Royden 4th edition "Real Analysis"
Comment: We can also show $\limsup \int_E f_n \leqslant \int_E f$ directly with the forward Fatou lemma and get the required inequality chain appearing above after "Hence,...".  I can add it as a comment or edit the answer if you like.
Comment: yes, please add it as a comment.
Comment: Also, I am wondering if this question was asked differently on this site ?
Comment: Ohhh I am sorry could you edit your answer instead as I am unable to read the comment
Comment: thank you soo much!
Comment: why is $\lim f_{n} = \lim inf f$?
Comment: Why is $\limsup \int_E f_n = -\liminf \left(-\int_E f_n \right) $? here we are dealing with functions and not sets @CalvinKhor , so why there is an equality? is not it should be inequality?
Comment: @Smart:  We are dealing with sets.  Given the sequence $a_n = \int_E f_n$ we have $\limsup a_n = \inf_n \sup_{k \geqslant n} a_k = \inf \{\sup \{ a_k: k \geqslant n\}: \, n \in \mathbb{N} \} $.
Comment: Why is the third equality in your update correct? are not the integrals sets and addition between sets means what? does it mean componentwise addition ?
Comment: @Smart: Either use $\liminf(a_n + b_n) \geqslant \liminf a_n + \liminf b_n$ so the third equality (noting the -1 factor ) is replaced with $\leqslant$ and we can proceed as before.  Otherwise note that if $b_n$ converges we have $\liminf(a_n + b_n) = \liminf a_n + \liminf b_n$. Here we have $b_n = - \int_{\mathbb{R}} f_n$ and $\liminf b_n = \lim b_n = -\lim \int_{\mathbb{R}} f_n = - \liminf \int_{\mathbb{R}} f_n $.


Auditoria com Entity Framework

Question: Estou querendo fazer as tabelas de auditoria das minhas entidades. A princípio eu pensei em sobrescrever o método SaveChanges. Também pensei em escrever um método que vai estar fazendo a auditoria em meu repository base. Usando das duas formas, eu terei uma única tabela de auditoria para todo o meu sistema.
Mas por questões de performance eu preciso que cada entidade tenha sua tabela de log.
Qual seria a melhor forma para interceptar o tipo da minha entidade para que eu possa salvar na tabela de auditoria da mesma?
Meu código até então, está assim:
public override int SaveChanges()
{
     var entriesAdicionadas = ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();

     var entriesModificadas = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified).ToList();

     var entriesDeletadas = ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted).ToList();
     foreach (var entry in entriesAdicionadas)
     {

     }
     int result = base.SaveChanges();

     foreach (var entry in entriesModificadas)
     {
         var nome = entry.Entity.GetType().Name;
     }

     base.SaveChanges();

     foreach (var entry in entriesDeletadas)
     {
         var nome = entry.Entity.GetType().Name;
     }

     return result;
}

Answer: Implementação Caseira
Primeiro você precisa criar uma maneira de relacionar o Model de Log com o Model que será auditado. Isso pode ser feito declarando uma Model com genérico. Por exemplo:
public class ModelDeLogGenerico<T>
    where T: class
{

}

T não precisa ser class. T pode ser uma classe ancestral de todos os seus Models, ou então uma interface. Em alguns projetos que eu faço, todos os Models derivam de uma interface chamada IEntityBase, em que forço o Model a ter duas propriedades a mais: na primeira registro a data em que o registro foi criado e na segunda a data em que ele foi modificado pela última vez, que é mais ou menos assim:
namespace MyProject.Models.Interfaces
{
    interface IEntityBase
    {
        DateTime LastModified { get; set; }
        DateTime CreatedOn { get; set; }
    }
}

Isto garante que seu Model de Log não pode receber necessariamente qualquer classe. A classe pra ser válida precisa implementar IEntityBase. Minha classe de Log, portanto, ficaria assim:
public class ModelDeLogGenerico<T>
    where T: IEntityBase
{

}

Suponha agora um Model qualquer do seu sistema:
public class Fruta
{
    ...
}

O Log respectivo dele será:
public class LogFruta<Fruta>
{
    ...
}

Tendo isso, podemos identificar agora que LogFruta audita Fruta. O seguinte código baseado em Reflection busca no Assembly da sua aplicação qual classe possui como argumento genérico a classe Fruta:
var log = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.GetGenericArguments()[0] == entry.GetType());

Soluções Prontas
O EntityFramework.Extended possui capacidade nativa de fazer o log pra você. Tem uma explicação aqui.

Auditoria com Entity Framework


Como consumir um WebService SOAP com AngularJS?

Question: Bom, tenho um WebService SOAP que é consumido normalmente por um cliente PHP, funcionando perfeitamente... por ajax consumo esse php e populo meu template..
Minha aplicação atual faz o seguinte processo Angular <-> PHP <-> service.wsdl
descobri a possibilidade de excluir essa ponte PHP, consumindo diretamente o WebService SOAP, usando angular-soap.
Porém ao reproduzir o exemplo, não consigo retornar nenhuma informação.. nem erro.
index.html

        {{response}}

service wsdl

<definitions xmlns:typens="urn:Service" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" name="Service" targetNamespace="urn:Service">
    <message name="getEmpresas">
        <part name="getEmpresas" type="xsd:string"/>
    </message>
    <message name="getEmpresasResponse">
        <part name="getEmpresasReturn" type="xsd:string"/>
    </message>
    <portType name="HomePortType">
        <operation name="getEmpresas">
            <input message="typens:getEmpresas"/>
            <output message="typens:getEmpresasResponse"/>
        </operation>
    </portType>
    <binding name="HomeBinding" type="typens:HomePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getEmpresas">
            <soap:operation soapAction="urn:HomeAction"/>
            <input>
                <soap:body namespace="urn:Service" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>
            <output>
                <soap:body namespace="urn:Service" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>
    <service name="ServiceService">
        <port name="HomePort" binding="typens:HomeBinding">
            <soap:address location="http://localhost/app/homeCrtl.php"/>
        </port>
    </service>
</definitions>

Quando faz a requisição ele envia um envelope via Request Payload.
<?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
       <soap:Body>
          <getEmpresas xmlns="urn:Service"></getEmpresas>
       </soap:Body>
    </soap:Envelope>

nas ferramentas do navegador em network > Response ele retorna meu próprio wsdl descrito acima..
é necessário/preciso modificar algo no servidor?
obrigado
Comment: Nas ferramentas de desenvolvedor do browser, o que é exibido sobre a requisição SOAP na aba de redes? E no console?
Comment: @ViníciusGobboA.deOliveira na requisição ele retorna meu wdsl e envia um envelope ``
Comment: E qual a resposta recebida? Veja ela também nas ferramentes de desenvolvimento do browser. Por favor, coloque-a na pergunta, para facilitar a ligibilidade.
Answer: 'use strict';

angular.module('myApp').service('Soap', ['$q', '$http',
    function($q, $http) {
         this.execute = function(metodo, params) {
            var envelope = '';
            var deferred = $q.defer();
            if (params) {
                envelope = '<ns1:'+metodo+'>'+
                                '<arg0>'+ JSON.stringify(params) +'</arg0>'+
                            '</ns1:'+metodo+'>';
            } else {
                envelope = '<ns1:'+metodo+'></ns1:'+metodo+'>';
            }
            $http({
                'url': 'http://localhost/api/1/service.wsdl',
                'method': 'POST',
                'data': '<?xml version="1.0" encoding="UTF-8"?>'+
                    '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://connect.webservice.business.com.br/">'+
                        '<SOAP-ENV:Body>'+ envelope + '</SOAP-ENV:Body>'+
                    '</SOAP-ENV:Envelope>'
            })
            .then(function(response) {
                var result = response.data.substring(response.data.indexOf("<return>") + 8, response.data.indexOf("</return>"));
                // console.log(result);
                deferred.resolve(JSON.parse(result));
            }, function(response) {
                deferred.reject(response);
            }).catch(function(fallback) {
                console.log(fallback);
            });
            return deferred;
        };
    }
]).controller('MainCtrl', function($scope, Soap) {

    Soap.execute('getEmpresa').then(function(response){
        $scope.response = response;
    });
});

Seguinte, não utilizei o angular-soap, usei apenas $http e montei meu próprio envelope, para montar a string do envelope eu instalei o software https://www.soapui.org/ e quando a requisição estava correta eu copiei o envelope q ele montou e elaborei o meu, no meu caso o back-end era Java, eu tive q habilitar "CORS", se não a requisição neem chegava lá!
Obs: Seguinte tente utilizar o SOAP apenas para coisas pequenas porque isso ehh uma gambiarra, usar SOAP e Angularjs, tipo use apenas se vc nao tem outra opção, mais sempre q possivel abra uma router do lado do soap com um belo rest e tudo ficara melhor! experiência própria!
Comment: Obrigado, pois é, tive que mudar a estrutura do webservice.. mas valeu a dica d+