Piano tuning just under the absolute pitch

Question: The other day, the piano tuner came to the semi-annual tuning of my piano (a Blüthner baby grand). I was not at the house when he did the tuning. When I got home, the piano was tuned in respect to itself but not according to the absolute pitch (about 15 cent down). I used the "Cleartune" Iphone app to determine that. This piano tuner has been tuning my piano for three years and is very professional.
Is this considered a tuning mistake?
Is an absolute difference of 15 cent is even distinguishable by a human ear?
Comment: Which keys did you measure?  Did you take stretched tuning into account?
Comment: You have used the same piano tuner for three years, kept the piano regularly tuned, and this is the first time it has been tuned lower?  Or is this the first time you have checked it against an external source?
Comment: @200_success  I checked the two visit before the last visit , and this is the first time it was tuned lower.
Comment: I can understand tuning it low if it was already flat, so as not to put too much stress on the frame all at once.  However, if it was already close to standard pitch, that's just bizarre.  I would ask your tuner to stop by to check it whenever he happens to be in the neighborhood.
Answer: It's pretty common place to tune a piano lower as it gets older since that puts less mechanical force on the frame. However that should better be done by consulting the owner and then bite the bullet and tune it down a full half step (so you can still play with others by transposing).
15 cent close to the "just noticeable difference" or jnd but it can certainly be audible. This website has some audible example of a middle C at different rates of detune.
It's also possible that your iPhone's internal crystal is slightly out of whack. In order to build a good tuner you need a reasonably good reference clock and the IPhone hardware has no particular reason to have one with a tightly controlled center frequency.
Comment: Good thinking about the crystal precision, but 15 cents off is too large for that. 15 cents at the 440 Hz A is an offset of around 4 Hz, that is 0.1 %. A crystal in the iPhone should be at worst +/- 20 parts per million (ppm), 0.1 % would be outrageous. That said, I wouldn't trust the writers of the app to give that level of precision, even if the hardware should.
Comment: Playing with others isn't really an issue unless their tuning holds well, and it takes more than a few minutes to re-tune.  Other than melodic percussion and recordings, there wouldn't be many instruments inside a house that would pose a problem.  Guitar, string, and wind instruments all have to be tuned each time they're played (or in the case of wind instruments, when they're played with others) anyway, so having the piano 15 cent out isn't that big a deal.  Still, bring it up with your piano tuner.
Comment: @Gauthier: I wasn't implying that the clock drift itself is out of spec, but that at some point Apple switched vendors or parts with a slightly different nominal frequency (say for the CPU clock). They have no reason not to.
Answer: From the perspective of a piano tuner, 15cts is a huge descrepency. It must have been tuned that way on purpose. Probably because a piano that low would require a pitch raise (and thus an additional charge) to bring up to concert pitch. Since you weren't there, he/she probably decided to leave it where it was. I would always talk to the owner before leaving a piano anywhere but right at concert pitch.
Answer: I highly recommend you do the following.
1) get a calibrated tuning fork and test one more time that your A 440 is off. So you are absolutely sure.
2) have a friendly chat with your tuner to discuss why this is off.
No one here can read minds. You really need to talk to your tuner about why he/she did not tune it the way you expected.
I also recommend that you are around the next time the tuner comes as this is a good time to discuss the condition and care of your piano. Have him check the action and check the hammers up close. My tuner removed the action last time and showed me what is breaking down. Although my studio grand is reaching 100 years old, it can still be tuned to concert pitch. I suppose because this was a quality build that it is aging well (Steinway).
Comment: Mind reading refers to the piano tuner as no one here knows what he was thinking, what he perceived and why he made his choices.
Comment: "*Is this considered a tuning mistake? Is an absolute difference of 15 cent is even distinguishable by a human ear?*" <--- **That** is the question.  What does reading the OPs mind have to do with this?
Answer: Did you measure at A above middle-C? (A4) The Cleartune app may not take the inharmonicity of your piano into account. Depending on how far away from that reference it is measured, you may see confusing results.
When I installed the professional tuning software called Tunelab on my iPhone and iPod Touch, it did not need calibration at all on either device when compared to the NIST analog standard. Spot-on, to the accuracy allowed by the calibration function of the software. I do not know if this is typical, but I suspect there is not that much variation between devices, at least not enough to be off by 15-cents at A4 (about 4 Hz).
Was there direct sunlight on the piano when you measured it? A tuner should call out environmental conditions that may affect your tuning stability. Temperature change is one way to get very rapid instability on your tuning.
A possible reason for "floating" pitch, since you say it is tuned twice a year, is if your piano has a relatively wide natural variation in pitch from low to high humidity seasons. Depending on the particular time of year, a tuner may not watch to "chase" the pitch up and down with the seasons. In this situation, I would try to recommend the best time of year to tune such that a piano would be close to pitch for as long as possible.
There are many variables, I would definitely ask your tuner what his intent was, describe how you took the measurements, and see what his response is.
Answer: jbm had some great points. As did a few others. I see that this post is an old one, but the question does come up frequently. So here's my 2 cents (no pun intended).
First, nice piano.  Second, always talk to your tuner immediately upon discovering any topic of concern.  The sooner, the better.  Then my recommendation is to get a temperature and humidity gauge that records minimum and maximum levels for both.  Then place it on the piano and observe the results over the following days, weeks, months and seasons.  The more stable the temperature and humidity in and around the piano, the more stable the tuning will be and the better for the piano over all.

A quick qualifier about myself.  I am the 5th generation in a 6 generation piano business.  I have personally rebuilt, restored, repaired, or tuned hundreds of pianos and have been responsible for thousands more.  I have been using a computer controlled tuning instrument for over 25 years.  It creates a custom stretch tuning for each piano, taking into consideration that pianos unique inharmonicity.  So I feel that I know something about computer aided piano tuning.

Back to your question.  One (1) Hertz (aka cycles per second) equals 4 cents.  Concert pitch of A-440 is simply means three strings at A4 vibrating in unison at 440 cycles per second - period.  Doesn't matter if it's summer or winter; an aural (by ear) tuning or a computer aided tuning ... A-440 is A-440.

One hundred (100) cents constitutes a semitone, also known as a half-tone or half-step.  Therefore, A4 to A#4 is a semitone or 100 cents (¢).  In your example of 15¢ flat (15/4= 3.75 Hertz flat) your piano was at A-436.25 (when you measured it) or 0.852273% flat. If you live in the northeast, seasonal changes will produce greater changes in pitch than that.  You would be doing a pitch raising in the winter and pitch lowering in the summer; changing the pressure within the piano by thousands of pounds each time.  To put it into perspective, a concert piano is tuned before every concert. We include 4 tunings and an action regulation check during the first year.  We install a humidifying/dehumidfing system with a humidistatic control when we are commissioned to do a restoration or rebuild - that is how important humidity control and maintenance is to us and the piano.  If your piano is near a window, door, fireplace, air conditioner, etc. you will have frequent pitch changes making getting a solid, long-lasting, right on pitch tuning next to impossible.

Regarding informing the customer of the pianos condition.  Before we even book a tuning for a new customer, we ask several questions.  Such as: is the piano played with other instruments (or voice)?  What is your piano playing skill level?  Does any one else ever play it?  When was it last tuned?  How old is the piano?  Plus many others.  The point is, we try to gauge.their needs and expectations and discuss them BEFORE we even book the tuning.  Discussing a pianos condition too much while at the house usually doesn't turn-out very well.  Just telling someone that a piano should be tuned 4 times the first year (if new), twice a year thereafter and the action regulated every 5 years can be a big turn-off.  When was the last time someone checked your plate screws for tightness, set the strings on the bridges, spaced the strings, filed & voiced the hammers?  How often have you heard that you should tune a piano at least once-a-year?  Especially if it's not being used!  Once-a-year tuning is an insurance policy to protect your investment and minimize long-term damage to the piano.  If three piano is not worth tuning one a year, sell it.  I can not remember how many pianos have be ruined by lack of service.  I can remember the few that were destroyed by abuse.  I hope that this is helpful to future readers of your post.
Answer: Not sure if this was mentioned, but some piano tuners like to "float" the pitch.
Floating the pitch means tuning A4 slightly flat in the winter and slightly sharp in the summer.
The rational is that if you tune a piano in the summer, it will eventual go flat in the winer, so if you tune it sharp, then it will settle close to A440 as the humidity drops. Similar reasoning for tuning flat in the winter.
Also, there is less pitch change to make if you come to a sharp piano in the summer and don't bring it all the way down to A440.
I never do this because I use a technique that creates extremely high accuracy octaves that are also precise, meaning I can repeat their size all the way up the piano.
Floating the pitch for me means I have to retune the treble and bass every time. When I tune A4 at A440, I will often get to the extremes and they will not need to be changed. The extra work to move A4 to 440 is saved in the extremes.
If your piano was tuned in the winter, it very well may have been floated. Ask your technician.
Comment: Roughly how many cents would the variation per season be?

I got a (relatively cheap) piano new that only had one tuning in 3 years, and only now bothered to measure where it's at.  A few unison strings obviously out, but the whole thing is uniformly about 7c flat (measured by 2 tuners).  Given that I live near WashingtonDC and it is winter, maybe that's where it should be?  This was a starter upright when I wasn't sure of my child's commitment.  I may actually get a good one and use the existing one to learn self-tuning on.
Answer: The Bluthner base strings are a bit prone to snapping if over-pulled, and it might be the case your tuner was afraid to put any more strain on them and so perhaps he decided impromptu to leave the whole piano flat.    Just a thought.
Answer: Good answers. Just some clarifications. 1hz at 440 is about 4 cents. Someone mentioned 15 cents. A tuning fork can vary up to 3 cents easily just from moderate temperature differences. Swings due to season changes, in my professional experience (tuning for 16 years) can be up to about 4hz. That's 16 cents at A4. Calibration of tuning software accounts for the variation in clock speed of different computers but in no way comes close to 15 cents. I've used NIST to calibrate Tunelab as part of teaching my tuning courses and it is a very small fine adjustment if any, far less than 1 cent. Call your tuner.


Bartok Mikrokosmos Book 3, no. 70

Question: I have recently been trying to master this piece from Bartok's Mikrokosmos, and at first sight, it appeared daunting due to the fact that the right-hand part is in B major and the left-hand part is in C major. Before playing it, it looked likely to be incredibly dissonant, with 5 sharps for one hand and none for the other, but it is actually much more consonant than I expected.
My question is this:
How do you set about composing a piece such as this with different key signatures for the two hands?
As well as learning the piano, I am currently trying to learn the (very) basics of composition, and find this particular piece a real puzzle (but I really like it!).
Comment: I suggest making the title something `Bitonal Composition - Mikrokosmos Book 3, no. 70`
Comment: I would definitely specify that your question is not directly about the piece,  but more a general question about composition.
Comment: Thanks, but I think I will leave it for now. Don't want to scare readers away with words like "bitonal" :)
Comment: The concept is called dual modaliy and this question should help you out: http://music.stackexchange.com/questions/25123/composing-a-piece-using-the-idea-of-dual-modality. I'll try and add a more direct answer  later as I've actually written a few short peices using this concept.
Answer: Look what the score is doing: you have an oscillation rising from F♯ in the initial RH part, moving up to C♯, but artfully dodging A♯. At the same time, you have an accompaniment that consists largely of the fifth D-A alternating with the auxiliary notes E-G. The entire section is acting like an elaboration of a D major chord in a kind of quasi-Lydian setting. The RH is working with F♯, G♯, B and C♯; the LH, with D, E, G and A.
From there, the RH holds a G♯ slightly overlapping the A which commences the melody in the LH. (Leading tone, anyone?) The LH melody oscillates around A using the same set of tones as the initial accompaniment while RH rocks between F♯-C♯ fifth and its auxiliaries, G♯-B, so you have an elaboration of F♯ minor, but with a stressed A. However, as the melody progresses, it starts to stress E and, later, D against the auxiliary chord (i.e., E7).
At m.17, both voices start a two-part counterpoint. These two bars are slightly ambiguous. There is a suggestion of F minor to E diminished to G major, but the real point seems to be oblique movement out from F to B, with a wedge motion in the LH through E to G - not so much a progression as a contrapuntal movement towards a goal. This is the first time that F♮ and A♯ make an appearance, and they are both acting as stressed upper and lower leading tones.
G leads to the D-A dyad, which leads to A held under an F♯-C♯ broken figuration, with the A "resolving" to the initial E-G third under C♯. (The A is held slightly under the C# before dropping into the third, i.e., there is a strong suggestion of A7.) From here, both sets of accompanying dyads - E-G and D-A in the LH, G♯-B and F♯-C♯ in the RH - settling into an alternation of D M7 and E split-third, finally touching on F♮-A♯ which leads into a wedge back through the E split-third to the final D M7 chord. This piece is very definitely in D.
The thing to note here is that the wedge to the final D M7 is possible due to the fact that the segments in each hand are related by inversion. F and A♯ give the missing semitone in each segment, which is why they get special handling.
So...

You have strong contrapuntal movement in a wedge to D M7 due to the inversional relationship between each hand's scale segments.
With F and A♯ being omitted until the crux of the piece, and the limitation of each hand to a range of a fifth, you have scale segments that essentially define a quasi-Lydian D.
The harmonies that are stressed tend to play up a quasi-Lydian D: D, F# minor, with E7, G, and A7 strongly suggested.
Comment: Wow, that is going to take a bit of understanding! I had noticed some of the things you say (like the first appearance of one new note in each hand in m.17), but some tings (like "wedge"?) might take me a bit longer. +1 for now ... will accept when I fully understand!
Comment: Wedge melodically at ms.17-18 in the LH, because the melody opens out F-E-G. I said the passage is a bit ambiguous because there is some suggestion of E minor as well as G. At the end of the piece, you can see the harmonic wedge movement quite clearly (from D M7 to the fourth on F and back) - it's a direct result of the mirroring between the hands. The music closes to the bare fourth and opens back up linearly to the final chord.
Answer: I have no idea what Bartok was thinking when he wrote this, but one way to create something similar would be:
1. Start with a "big idea". In this case, "hey, what happens if the left hand plays the white keys and the right hand the black keys". (OK, that's not quite accurate because the right hand plays the white key B, but you get the idea).
2. Figure out how to make some reasonable-sounding chords using that idea. In Bartok's case, D major and E minor.
3. Add some more notes around those basic chords (and don't get hung up about "rules" or "major and minor scales", just do whatever sounds interesting to you).
Then once you have a few bars (about 8, in Bartok's case) try using some general principles for writing counterpoint. The middle section is just a mirror image, top to bottom, of the first section. (J S Bach played that sort of game all the time - Bartok didn't invent that idea!)
The final section is (approximately) the first two sections superimposed on each other (Bach also did that at least once, in the "Well-Tempered Clavier"). That will make sense to the listener by reference to what has gone before it, even if he/she can't analyse exactly what is going on just by listening.
Of course if you try to make your own piece using those sorts of ideas, it probably won't sound as "good" as Bartok, the first (or even the hundred-and-first) time you try - but don't let that stop you from trying!

Bartok Mikrokosmos Book 3, no. 70


Proving that the sequence $f_n(x)= (1+x^n)^{1/n}$ converges uniformly

Question: Let's consider the sequence of functions $f_n : [0,2] \to \mathbb{R} $ defined by $f_n(x)= (1+x^n)^{1/n}$. I proved that this sequence converges pointwise to the function:
$ f(x) = 1$  if $0\le x \le 1$ and $ f(x)=x$ otherwise.  My problem is how can I prove that this sequence converges uniformly. (maybe I can prove that $f_n$ is a Cauchy sequence but it look complicated) Please help me )=
Comment: what did you try? did you try proving it straight out of the definition? those functions on [0,2] are bounded, try to use that. Also, did you prove the series is monotone decreasing for a given X? Try to prove the general case (uniform convergence occurs in all such cases of monotone decreasing sequences of functions)
Answer:
If $0\leqslant x\leqslant1$, then $1\leqslant f_n(x)\leqslant2^{1/n}\leqslant1+1/n$.
If $x\geqslant1$, then $x\lt f(x)=x\cdot(1+x^{-n})^{1/n}\leqslant x\cdot(1+x^{-n}/n)\leqslant x+1/n$  since $n\geqslant1$.

This proves that $f(x)\leqslant f_n\leqslant f(x)+1/n$, hence $\|f_n-f\|_\infty\leqslant1/n\to0$. (The exact value being $\|f_n-f\|_\infty=2^{1/n}-1\sim\log2/n$, the order of this upper bound is the correct one.)
Comment: I have a question! Why the second inequalities are useful?
Comment: @Daniel Without them nothing guarantees the convergence to $1$, respectively to $x$.
Comment: @Benjamin Gruenbaum, there is an easy way to prove that is monotone decreasing?
Comment: @Daniel yes, try using the binomial theorem and expanding the epxression. You can get a hint by first proving the easy case of (1+1/n)^n


Pass List to method expecting List in C#

Question: I'm creating an app that returns a list of metals to use in various conditions. I have a Metal class then classes for each type of Metal like Steel, Aluminum, etc. If I have a list of different Steels, I want to first select the best ones based on a set of properties common to all Metals then do a second pass based on the unique properties of Steel. (This isn't my exact problem but my problem is analogous.)
I can't figure out how to pass a List<Steel> to the GetBest() method of the Metal class as shown below that takes its first argument of type List<Metal>. The code won't compile due to error at the line highlighted below with **: "Argument 1: cannot convert from 'System.Collections.Generic.List<Steel>' to 'System.Collections.Generic.List<Metal>'.
public class Metal {

    public int PropA { get; set; }

    public List<Metal> GetBest( List<Metal> list, int condition1 )
    {
        var best = new List<Metal>();

      //Analysis code here...

        return best;
    }
}

public class Steel : Metal
{
    public int PropB { get; set; }

    public List<Steel> GetBest(List<Steel> list, int condition1, int condition2 ) {

        var bestSteel = new List<Steel>();

      //Do first pass selection based on properties of all metals.
        **bestSteel = Metal.GetBest(list, condition1);**

      //Do some additional analysis based to Steel's unique properties.
      //Analysis code here...

        return bestSteel;

    }

Comment: Change `Metal.GetBest` to accept `IEnumerable` rather than `List`, as `T` is covariant in `IEnumerable`.
Comment: Aside from the covariance problem solved by Johnathan's comment above I think you're probably approaching this problem incorrectly. The logic for picking the best "something" shouldnt be part of the "something" itself but a separate bit of logic.
Comment: a `List` cannot be treated as a `List` since someone could easily add `Tin` to the latter.
Comment: What's not clear to me in your example is why, given you have a method which looks like it is there to select a list of the best metals, would you pass in a list of metals in the first place? You never seem to use it.
Comment: @Jamiec - your comment stating that the logic for selecting the best something shouldn't be in that something's class is intriguing and has me thinking. I'm not sure I'll take the GetBest() methods out of the Metal and Steel classes but I'm definitely thinking about it. As for the list of metals passed to the method not being used, the list would be used in the analysis code.
Comment: I just now realized, in my original sample code, I didn't declare the GetBest() methods as static. I intended to and did in my actual code. Nonetheless, the answer provided by @Mureinik seems to solve my problem! Thanks to all for the input.
Answer: You could use a constrained generic method:
public static List<T> GetBest<T>(List<T> list, int condition1) where T : Metal
{
    var best = new List<T>();

    // Analysis code here...

    return best;
}

Answer: I'm going to answer a different question! A look at how I might approach this problem without confounding my objects (Metal, Steel) with my logic for picking the best metal based on some conditions:
public class Metal{}
public class Steel:Metal{}

public class MetalPickerContext
{
    public int Condition1{ get;set;}
}

public class MetalPicker<TMetal, TContext>
    where TMetal: Metal
    where TContext: MetalPickerContext
{
    public virtual IEnumerable<TMetal> GetBest(IEnumerable<TMetal> list, TContext context)
    {
        var result = new List<TMetal>();
        // logic for picking the best metal based on Condition1

        return result;
    }
}

public class SteelPickerContext: MetalPickerContext
{
    public int Condition2{get;set;}
}

public class SteelPicker : MetalPicker<Steel,SteelPickerContext>
{
    public override IEnumerable<Steel> GetBest(IEnumerable<Steel> list, SteelPickerContext context)
    {
        var initialResult = base.GetBest(list,context);
        // Having called the base logic apply more with reference to Condition2
        return initialResult;
    }
}

This compiles (as you can see here) and I could expand the example a bit given some more details to make it a working one. Let me know if that would help you.


A sequence defined by $x(1) = 11, x(2) = 23$ and $x(n) = x(n-1) +12x(n-2)$ for all $n ≥ 3$. Prove for all $n∈ℕ, x(n) = 2\times 4^n - (-3)^n$

Question: Brackets indicate it goes along with the variable, not multiplied except for (-3)
A sequence $\{x(i)\}$ is defined by $x(1) = 11, x(2) = 23$ and $x(n) = x(n-1) +12x(n-2)$ for all $n \geq 3$.
Prove for all $n∈ℕ, x(n) = 2\times4^n - (-3)^n$.
Comment: Hint: use induction. BUT you have to use LaTeX code to format your question. You have to explain what you have done yourself too. ALSO it is NOT linear algebra.
Comment: What tag am I supposed to put it in?
Comment: I changed the tag. Please try to use LaTex in formatting your question. Use dollar sign for instance. I did it this time for you. :-)
Comment: So try to use induction and write the proof yourself.
Comment: @Arash Actually this type of recursion has a beautiful linear algebra representation with a 2x2 matrix: [x(n+2) x(n+1)] = [23 11] * [[1 1] [12 0]]^n.  One approach to proving the invariant would be to look at eigenvector decomposition of the [[1 1] [12 0]] matrix.  Depending on his coursework, the tag might not be an accident.
Answer: Note that the condition holds for $x_1$ and $x_2$.
Then we proceed to using the induction hypothesis. We will assume the condition holds for $x_{n-1}$ and for $x_{n-2}$ and then prove that it holds for $x_n$.
\begin{align}
& 2*4^{n-1} - (-3)^{n-1} + 12 (2*4^{n-2}-(-3)^{n-2}) \\
& = \frac14 *2*4^n - \frac 1{-3} (-3)^n + 12(\frac1{16}2*4^n -\frac19(-3)^n) \\
& = \frac14 *2*4^n + \frac 13 (-3)^n + \frac342*4^n -1\frac13(-3)^n) \\
& = 2*4^n - (-3)^n \\
\end{align}
This is called proof by induction.
Answer: Assume $x(n)= A r^n$.  Then the recurrence becomes
$$r^2=r+12$$
Solve for $r$, get two solutions $r_1$ and $r_2$.  The general solution is then
$$A r_1^n+B r_2^n$$
Use the initial conditions you stated to find $A$ and $B$.


Bundle install - GEMFILE NOT FOUND

Question: I am having issues with running "bundle install" on macos. I get the following message after bundle install
bundle install
Ignoring ffi-1.9.23 because its extensions are not built. Try: gem pristine ffi --version 1.9.23
Ignoring gem-wrappers-1.4.0 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.4.0
Ignoring gem-wrappers-1.3.2 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.3.2
Ignoring openssl-2.1.1 because its extensions are not built. Try: gem pristine openssl --version 2.1.1
Could not locate Gemfile

Could you please help me?
Comment: are you sure you are doing `bundle install` from root of the project ?
Comment: you are not doing bundle from the app directory, navigate to correct directly where you can locate Gemfile
Answer: it seems like you are not on the root folder of the project.
go in your terminal to the root folder of the project and then run bundle install there.
Answer: Bundler uses the gem system, and the problems being displayed to you on the screen relate to that gem system. Try running the gem pristine commands it tells you to.
Comment: It's possible that your Ruby directory in rvm is corrupted -- you could try rvm installing a more recent version of Ruby or rvm removing 2.4.1 and rvm reinstalling it. Also, did you brew install openssl, or are you using the system openssl? There are known problems with that as well.
Comment: Also, when you post command output, it's important to also post the command that generated it.
Comment: Ignoring ffi-1.9.25 because its extensions are not built. Try: gem pristine ffi --version 1.9.25
Ignoring ffi-1.9.23 because its extensions are not built. Try: gem pristine ffi --version 1.9.23
Ignoring gem-wrappers-1.4.0 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.4.0
Ignoring gem-wrappers-1.3.2 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.3.2
Ignoring nio4r-2.3.1 because its extensions are not built. Try: gem pristine nio4r --version 2.3.1
Comment: Ignoring nio4r-2.3.1 because its extensions are not built. Try: gem pristine nio4r --version 2.3.1
Ignoring nokogiri-1.8.2 because its extensions are not built. Try: gem pristine nokogiri --version 1.8.2
Ignoring openssl-2.1.1 because its extensions are not built. Try: gem pristine openssl --version 2.1.1
Ignoring websocket-driver-0.7.0 because its extensions are not built. Try: gem pristine websocket-driver --version 0.7.0
Error loading RubyGems plugin "/Users/ramsan/.rvm/gems/ruby-2.4.1/gems/gem-wrappers-1.4.0/lib/rubygems_plugin.rb": cannot load such file -- gem-wrappers (LoadError)
Comment: ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass
Comment: This is what I get when I run gem pristine
Comment: Which error? The Gemfile not found error, or the gem pristine errors?

Bundle install - GEMFILE NOT FOUND


Can we add different class to first row and last row of view?

Question: Can we add different classes to first row and last row of view only ?
I have created a view of products listing in which i need to add unique class only in  first row and last row of view.
I need to implement it for creating different designs layout of each row.
In drupal 7 i did it by using below code :
 end($rows);
$last = key($rows);
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
<?php if ($id == $last): ?>
<?php $classes_array[$id] .= ' last-element'; ?>
<?php endif; ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
<?php print $row; ?>

How we can do the same in drupal 8?
Comment: Dont downvote the question without having proper reason as its not a off topic?
Comment: You can use css to target first and last items you know? See pseudo selectors `:first-child` and `:last-child`
Comment: we are creating dynamic section not static it might have 10 or 15 rows
Comment: CSS doesn't care about that.
Comment: @Vikramfz16 how is `div:last-child` and `div:first-child` different than `div.first-item` and `div.last-item`?
Comment: and whats about rest part apart from first and last child?
Comment: What about them?
Answer: You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.
You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}

               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}

        {% endif %}
        {% if loop.last %}

                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}

        {% else %}

                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}

        {% endif %}

    {% endfor %}


Printing numbers after another without adding them together Python

Question: I just started learning Python and I want to convert one of my codes to this language.
I have a little problem what I can't solve. My script have to make random numbers and printing them after another without adding them together.
time = random.randint(1000000000,9999999999)
no_hash = time+random.randint(1,100)+random.randint(1,10000)+random.randint(1,10000000)

Example output
4245200583 but I need just like this: 423694030332415251234.
As you see the code adding the numbers together (because of + between them) but I don't want to add the numbers together just print them.
Comment: cast to string, append to string?
Comment: In what languages would you expect this to work?
Comment: In Python I want to make it.
Answer: Each of your values is an int, so + will implement integer addition. You need to convert each int to a str first.
You can do that implicitly with various string-formatting operations, such as
time = random.randint(1000000000,9999999999)
no_hash = f'{time}{random.randint(1,100)}{random.randint(1,10000)}{random.randint(1,10000000)}'

or explicitly to be joined using ''.join:
time = random.randint(1000000000,9999999999)
no_hash = ''.join([str(x) for x in [time, random.randint(1, 100), random.randint(1,10000), random.randint(1,1000000)]])

Answer: use str() to concatenate the numbers
time = random.randint(1000000000,9999999999)
no_hash = str(time)+str(random.randint(1,100))+str(random.randint(1,10000))+str(random.randint(1,10000000))

Comment: Repeated concatenation with `+` is probably the worst way to join multiple values into a single string.
Comment: @TheMineSlash this method can also be used:  https://stackoverflow.com/a/42149618/14719340
Answer: You are adding a type of integer, when you need to add a type of string.
use the str() declaration to make sure Python sees it as string.
For example:
time = random.randint(1000000000,9999999999)
no_hash = str(time)+str(random.randint(1,100))+str(random.randint(1,10000))+str(random.randint(1,10000000))


Unable to create AVD with android sdk on Mac OS

Question: I have installed Android Studio and JDK1.8 on Mac OS. I followed the instructions and created a new application with API 15 as minimum sdk.
I tried to create an AVD from AVD manager to test my application by selecting create new virtual device->nexus 6->lollipop 22 armeabi_v7a android 5.1.1 as target. When I click finish, it takes me back to the first AVD manager screen without giving any errors and AVD is not created.
Where could be the problem?
Comment: http://developer.android.com/tools/devices/managing-avds.html
Here is the link from where you can find how to manage avd
Comment: I tried various combinations like nexus 4/5/6 with lollipop 21/22 etc but none of them is created and no error is shown anywhere. It just takes me back to AVD manager screen showing create a virtual device again.
Comment: Did you download your 1.5 sdks ? Take note, the virtual machine takes very long to boot, if you didn't install the intel x86 emulator accelerator haxm.
Comment: How do i check this?
Comment: I downloaded android-studio-ide-141.1980579-mac.dmg from https://developer.android.com/sdk/index.html and jdk-8u51-macosx-x64.dmg from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Comment: http://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2012/03/figure2.jpg  From the Android Studio Tools menu: Tools > Android > SDK Manager.
Comment: http://postimg.org/image/v77kyd5dl/
Comment: http://postimg.org/image/jqwkml1tl/
Comment: http://postimg.org/image/uga9eudmh/
Answer: First you need to download the SDKs you are interested in from Android Studio Tools menu -> Tools -> Android -> SDK Manager or  from the menu bar.
Don't forget to install the intel x86 emulator accelerator haxm from the SDK Manager - this will speed up significantly your android virtual device.
Then proceed as you mentioned in your question.
You can find more information here.
EDIT : From the comments your OS X version is 10.7.5 and Android Studio runs on 10.8.5 so you either :

Update your OS X installation
Install Eclipse and use the ADT plugin from google on your current configuration.
Comment: I have installed intel x86 emulator…  http://postimg.org/image/uga9eudmh/... along with sdks. I also restarted my system after all installations but unable to create AVD.
Comment: AVD manager is not showing any AVDs to delete. It shows the "create a virtual device screen" whenever i click and comes back to the same screen after creating AVD.
Comment: Thank you so much, I will try to run on a real device instead for emulator and if that too doesn't woek, will try to update my OS X. Have a great weekend!
Comment: try to delete your already created virtual devices and then recreate one and test, don't forget to set the correct SDK.
Comment: you could try downloading the latest sdk version then trying to create a new AVD with nexus for instance. this should eliminate the possibility that the device + configuration you want to use are incompatible.
Comment: if this doesn't work, there might be some problems with your installation, and instead of debugging and spending time on this, you should just delete it, and install again, fresh. let me know how this works for you.
Comment: I have uninstalled android studio and installed a fresh copy from http://developer.android.com/intl/zh-TW/sdk/index.html?utm_campaign=android-studio-1-3&utm_source=dac&utm_medium=blog. It is the latest version. I got this error after installing:
Comment: I have uninstalled android studio and downloaded and installed a fresh. It is the latest version. I got this error after installing: Downloading android-sdk_r22.6.2-macosx.zip from https://dl.google.com/android/android-sdk_r22.6.2-macosx.zip
Unpacking android-sdk_r22.6.2-macosx.zip
….  Done. 10 packages installed.
Android SDK is up to date.
Running Intel® HAXM installer
Silent installation Pass!
Creating Android virtual device
Unable to create a virtual device: Unable to create Android virtual device
Comment: Now when I create a new project and try to run by creating AVD from manager, it shows this screen http://postimg.org/image/e4kze26lf/ and then this one http://postimg.org/image/703650zc3/. What do I do?
Comment: These are the snapshots of installed tools from sdk manager: http://postimg.org/image/vgrdyixft/ , http://postimg.org/image/banvzn1s9/
Comment: What version of OS X are you using ? There might be some inconsistencies if it's not the latest. Also check your java version.
Comment: Mac OS x 10.7.5, java 1.8.0_51
Comment: Delete all your AVDs if any, open SDK Manager and use the "Tools" in the menu to manually enter the data to create an AVD. Seems like there are problems with the Android Studio, your OS is too old.
Comment: If you can't update your OS, you might consider installing [Eclipse](https://eclipse.org/) and the [plugin from google](http://developer.android.com/sdk/installing/installing-adt.html) to develop Android apps. Let me know if you encounter any problems.
Comment: https://developer.android.com/sdk/index.html#Requirements

Mac® OS X® 10.8.5 or higher, up to 10.9 (Mavericks), hence you need either to update your Mac OS or to use the previously mentioned method.
Comment: OK… it needs 10.8 or 10.9!
Comment: Consider selecting this answer to your question, updated the answer above. A great weekend to you too !
Comment: http://stackoverflow.com/questions/31800711/version-or-android-studio-for-mac-osx-10-7-5 … Please answer.


Can't Review Order, button loops back to checkout form '/cart/checkout'

Question: I'm having a problem which is prevent me from reviewing my order after completing the checkout form. Once I click on "Review Order" the page essentially refreshes itself because of the loop. Others with the same issue have varying solutions, I've tried a handful so far without any luck.
It seems the issue may be with the session being lost somehow, but I'm not sure what could be causing this. I haven't changed anything related to ubercart in months, yet the problem appeared days ago. Any suggestions or work arounds would be greatly appreciated.
I'm using PayPal Website Payments Standard, Drupal 6.2, Ubercart 6.29.
Thanks.
Comment: Are you on shared hosting, and if you are, have you contacted them to see if they changed anything in your server environment lately?
Comment: Hi David, actually I'm on a private server, I can't pin-point any significant changes on my server recently, except for the update from UberCart 2.8. I'm trying to determine if anything related to the update could be the issue. For now, I'm starting with "uc_cart_checkout_review()," the function which executes once you click submit on the checkout form, and drilling down from there.
Answer: Thanks to David's response, I was inspired to investigate my upgrade from uc 2.8 -> 2.9 and ran the update.php script. It seems it was not run at the time of the upgrade, so now that it has the problem is solved.
Comment: glad you figured it out in the end.


Setting up Outlook.com as mail server MX record trailing dot

Question: Outlook.com is allowing to connect your domain to their email servers.
To validate the domain they give you the following instructions:

In my domain registrar i've defined
mysite.org.il.     86400   IN      TXT     v=spf1 include:hotmail.com ~all
mysite.org.il.     86400   IN      MX      0       *******523fc85f4870.pamx1.hotmail.com

As they asked, and it doesn't work.
I have also tried to define *******523fc85f4870.pamx1.hotmail.com. with the trailing dot at the end and I saw that it automatically appends my fqdn to the end of the address. When I did that, the domain was verified correctly but occasionally it was de-verified (every time I refreshed it was either verified or not-verified)
What is the correct way to define it ?
Adding my complete record set:
mysite.org.il.  86400   IN  NS  ns1.sitesdepot.com.
mysite.org.il.  86400   IN  NS  ns2.sitesdepot.com.
mysite.org.il.  86400   IN  A   220.127.116.11
ftp.mysite.org.il.  86400   IN  CNAME   mysite.org.il.
www.mysite.org.il.  86400   IN  CNAME   myapp.herokuapp.com.
mysite.org.il.  86400   IN  TXT v=spf1 include:hotmail.com ~all
mysite.org.il.  86400   IN  MX  0   ******6aea9523fc85f4870.pamx1.hotmail.com

Answer: The syntax of DNS names that appear in zone files is that that if a final dot is not given, the current $ORIGIN is appended to the name. So when you define:
***.org.il.    IN   MX   10 mx.example.com

the meaning of this is that the MX record contains the name "mx.example.com"+whatever the value of $ORIGIN is at the time. Since the default $ORIGIN is the name of the zone, that means you're probably actually defining:
***.org.il.    IN   MX   10 mx.example.com.***.org.il.

So you certainly want to use the final dot in this context.
If you have the problem that "occasionally it was de-verified", then you might have some problem with your DNS setup. Check if your secondary nameservers are up to date and serving the same, correct, information as the primary. Related to this, make sure you didn't forget to update the SOA serial number when you updated the primary.
Comment: Thank you. How do I check the primary and the secondary nameservers are synced ? What's the SOA serial number ?
Comment: Using an online tool, I did see that nameserver SOAs do not agree on the serial number. This can be because of all the experiments I did and that I changed it recently and the change hasn't yet arrived from the master nameserver...
Comment: To check the serial number, use `dig @ ***.org.il. soa`. It should match between the primary and all secondaries. If your secondaries are configured correctly, they should get notified automatically when you increment the serial number on the primary and reload the zone.


PHP will not write file to directory via command prompt executed script but will write when executed in browser

Question: I will execute this command in Command Prompt
php C:\xampp\htdocs\dl.php

These are the properties of my htdocs directory:

However, under the sharing tab, I have write permissions under all users:

I've restarted apache after each permission modification with no success.
How do I fix this?
My PHP script downloads an XML file via an API and writes the XML file into the root directory of the server. When I execute www.mydomain.com/dl.php, the downloaded XML is written into the root directory; however, when I execute the PHP file (dl.php) via the command prompt, it will not write the downloaded file into the root directory.
PHP file:
$today = date("F j, Y").".xml";
$ch = curl_init ("");

$fp = fopen("ipod_car_connectors2.xml", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);

Comment: Possibly a current working directory problem. Are you specifying full path inside your code? Would be good to see the code as well.
Comment: What is the problem in the first place? What doesn't work that makes you try this?
Comment: @djdy see edit, I updated with code
Comment: add `ini_set('display_errors', 'on');` and `error_reporting(E_ALL);` to the top and tell us what you see from the command line.
Comment: Warning: curl_setopt(); supplied argument is not a valid File-Handle resource in C:\xampp\htdocs\dl.php on line 16
Answer: Try changing it to:
$fp = fopen("c:\xampp\htdocs\ipod_car_connectors2.xml", "w");
Answer:   The solution was to escape slashes


How can I upload and read an unmanaged file?

Question: On a custom form I have a file field. Having chosen the file and clicked Submit, I'm trying to find how to access and read the uploaded file. I have no need to move or save it, I simply need to open it and use fgetcsv on it.
I've looked at the online examples I can find, but they seem to either deal with managed files or moving and saving unmanaged ones. The Examples module seems to only have a placeholder with regards to the file example.
Answer: Maybe have a look at the CSVimportForm.php in xurizaemon/csvimport sample module. I wrote the D8 version. There an unmanaged uploaded CSV file gets read line by line. This happens in a batch process to prevent a timeout when you process a CSV with let's say a million lines.
The file gets uploaded to the temp dir and will be added to the files table as a temporary file. We make a copy of the file to the public files dir and let the garbage collector delete the original upload. You need to put the file somewhere on the server to read it in PHP. You don't have access to the browser in PHP. You then can delete the file when you are done.
Comment: A note for anyone who wants to access an unmanaged file without moving it. Use file_save_upload, and note that if saving it in temporary://, it is there even if an ls doesn't show it.


Cumulative probability in R

Question: The probability density function I have is as following:

Now, I want to rewrite the cumulative probability function bellow into R.

The variables ($S$, $\mu$, $\sigma$) are constant variables. For $t$ i.e. t <- seq(0.1,1,0.1)
How the cumulative probability would look like in R? Non of my solutions yields desired output!
EDIT:
f1 = function(t,S,sigma,mu){((mu*t+S)/(sigma*sqrt(t)))}
f2 = function(t,S,sigma,mu){((mu*t-S)/(sigma*sqrt(t)))}

1-(pnorm(f1(t,S,sigma,mu),mu,sigma,1,0)-exp(-(2*S*mu/sigma^2))*pnorm(f2(t,S,sigma,mu),mu,sigma,1,0))

This kind of gives me reasonable results but not sure if correct.
Comment: This is not a CDF as it does not converge to 1 if t goes to infinity.
Comment: Max - (i) what do you mean by cumulative probability if not CDF? (ii) Where do your equations come from? Are you sure you have them right?
Comment: You are right! What I need is cumulative probability and not CDF!
Answer: A CDF is defined as non-decreasing, right continuous function F, with

$\lim_{x\to -\infty}F(x)=0,$ and
$\lim_{x\to +\infty}F(x)=1.$

I am just stating the obvious here, but when we let $t<0$ we have already a problem as your real-valued function contains square roots of t. Similarly, we need $\sigma >0$ and perhaps a lot of other things.
In either case, I will just go ahead and assume you know what you are doing, and show you the code you asked for.
# custom cdf
custom.cdf <- function(S,sigma,mu,t)
{
    q1 <- pnorm((mu*t + S)/(sigma*sqrt(t)))
    q2 <- pnorm((mu*t - S)/(sigma*sqrt(t)))
    e.term <- exp(-((2*S*mu)/(sigma^2)))
    res <- q1 - e.term*q2
    return(res)
}

# set parameters
S <- 1
sigma <- 1
mu <- 2

t <- seq(0.1,1,0.1)
plot(t,custom.cdf(S,sigma,mu,t),typ="l")

I have chosen a larger support to see a bit more of the curve. Check the formula (mine and yours) for any mistakes.
t <- seq(1e-6,1,1e-6)
plot(t,custom.cdf(S,sigma,mu,t),typ="l")

Comment: Shouldn't q1 <- pnorm((mu*t + S)/sigma*sqrt(t)) be pnorm((mu*t+S)/(sigma*sqrt(t)))? As sqrt(t) is also in the denominator
Comment: Yes, spot on. I was getting even more spectacular outputs here :)
Comment: Yes that's correct. Thanks! I will edit and get rid of the graphic.
Answer: This would implement your function in R. What part of the output didn't make sense when you tried?
 cumulative = function(t){
      S = somenumber
      mu = somenumber
      sigma = somenumber
      cd = pnorm((mu*t+S)/(sigma*sqrt(t)))-exp(-2*S*mu/sigma^2)*pnorm((mu*t-S)/(sigma*sqrt(t)))
      return(cd)
    }

That being said, what are your parameter values? For combinations I've tried, this seems like a decreasing function of t.
Comment: I'm just trying to replicate someone elses work but don't have the complete workouts so I'm second guessing some things here.
Comment: My solution (see EDIT) provides me with the desired outcome (same as yours just with the 1-(pnorm...) so something must be missing here. In general your answer is correct. Thanks.
Comment: @Max Your problem is in the pnorm call. You call pnorm(f1(...),mu,sigma,0,1) so you're not computing from a N(0,1) distribution, but from a N(mu,sigma) distribution. Also by including the 1,0 in your call, you are reversing the calculation, pnorm(2,mu,sigma,0,0)=1-pnorm(2,mu,sigma,1,0)
Comment: @Max And we dont get the same results, atleast not when I tried to compare the two.

Cumulative probability in R


Quando testando meu web API C# ASP.NET localmente no Fiddler ele me retorna um erro 404

Question: Estou criando um sistema de controle de estoque com integração de aplicativo android,a conexão está sendo feita por meio de um Web Service API. Contudo eu não consigo testar os metódos que existem nele para ver os resultados retornados,estou usando o Fiddler mas sempre que chamo a url por ele o mesmo retorna-me o erro 404 not found. A linguagem de programação usada é o C# e estou usando do ASP.NET 4.6.
Muito obrigado desde já. Por favor se alguém tiver pistas ou noção mais profunda aceito ajuda urgente.
Segue abaixo Screenshots do Project Explorer,do Erro do Fiddler assim como alguns Códigos
Controller:
using System;
using APITeste.Models;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace APITeste.Controllers
{
    public class PessoaController1 : ApiController
    {
        private static List<Models.Pessoa> _pessoas = new List<Models.Pessoa>();
        // GET: api/Pessoa
        public IEnumerable<Models.Pessoa> Get()
        {
            return _pessoas;
        }

        // GET: api/Pessoa/5
        public Models.Pessoa Get(int id)
        {
            return _pessoas.FirstOrDefault(pessoa => pessoa.ID.Equals(id));
        }

        // POST: api/Pessoa
        public void Post([FromBody]Models.Pessoa value)
        {
            _pessoas.Add(value);
        }

        // PUT: api/Pessoa/5
        public void Put(int id, Models.Pessoa value)
        {
            var pessoa = Get(id);
            if (pessoa != null)
            {
                pessoa.Nome = value.Nome;
                pessoa.Sobrenome = value.Sobrenome;
            }
        }

        // DELETE: api/Pessoa/5
        public void Delete(int id)
        {
            var pessoa = Get(id);
            if (pessoa != null)
                _pessoas.Remove(pessoa);
        }
    }
}

Model:
namespace APITeste.Models
{
    public class Pessoa
    {
        public int ID { get; set; }
        public string Nome { get; set; }
        public string Sobrenome { get; set; }
    }
}

Fiddler Debugger:

Solution Explorer:
Comment: Dica: Selecionar o código e clicar **`Ctrl`** + **`K`** deixa ele formatadinho.
Comment: Tente renomear `PessoaController1` para `PessoaController`
Comment: cara.....eu mal acredito,eu só precisei tirar o 1 como vc falou....e o Fiddler conseguiu ler ele. Eu te juro que to a 3 dias quase sem dormir tentando resolver isso,muito obrigado pela ajuda.
Answer: Isso acontece porque o controller pessoa está com o nome PessoaController1.
Os controllers precisam ter apenas Controller no final do nome.
Renomeie a classe PessoaController1 para PessoaController.
Obs.: Renomear a classe, o arquivo é indiferente.


Allow a node to have many dates attached to it

Question: I am stumped trying to figure out how to set up a node to have many dates attached to it without having to just add a lot of date fields to it.
The scenario is that we have a show, and that show occurs on multiple days at different or multiple times each day.
I'd like to be able to have a content type of 'Show' with a date field and then just add multiple dates to it. However, the Date field doesn't seem to support multiple values.
How do I make this work?
Comment: Turns out the answer is relatively simple - as long as you don't choose a Widget for the Date field that handles repeating dates, the 'Number of Values' field appears and you can choose 'Unlimited'.

So choosing:
Select List with Repeat options; or
Text Field with Date Pop-up and Repeat options.

will not allow you to have multiple values. Any other options should be OK.
Answer: Just answering this myself so it doesn't count towards the unanswered total.
Turns out the answer is relatively simple - as long as you don't choose a Widget for the Date field that handles repeating dates, the 'Number of Values' field appears and you can choose 'Unlimited'.
So choosing either of the following Widget types:

Select List with Repeat options; or
Text Field with Date Pop-up and Repeat options

will not allow you to have multiple values. Any other options should be OK.
Answer: Office hours is a module that can help you. It's built for entering complex opening hours for a physical place. It minded for a per week display, but it does support some custom entries, by entering week numbers but this is not well docented
I'm not sure how well it will work for your case, but it can at least give you a head start.
Comment: Thanks googletorp - a good suggestion but I've managed to get the default Date field to do what I need.
Comment: @marblegravy Can you please post your solution of Date field? Thanks
Comment: @PreritMohan - See the accepted answer above. That's how I solved it.


Trying to keep leading 0's in Excel

Question: I have a string that I am concatenating that comes from an auto generated number and a product code. Such as AW-003-B
="AW"&A2&C2
How do I keep the leading 0's in even past 10 and 100 etc so it doesn't become something like AW-00103-B?
Thanks
Answer: Try,
<code>="AW"&TEXT(A2, "-000-")&C2
</code>

Trying to keep leading 0's in Excel


CreateUserAndAccount method - SimpleMembership Provider

Question: I have 2 questions:

Why am I getting that exception? I want to create a row in my User Table (it has 6 columns: Name, Role, Email, Group, Id, SoftwareVersion) and in the Membership table. The primary key is the pair Id-SoftwareVersion. The code:

code
What's wrong?

Is it possible add more row (with CreateUserAndAccount) by changing the id? Right? Example: try to add a row with "Administrator" as UserName when an entry already exists in the DB with the same name (but I remember the primary key is the pair Id-SoftwareVersion).

My User class:
<code>public partial class User
{
    public User()
    {
        this.dfcs = new HashSet<Dfc>();
        this.fids = new HashSet<Fid>();
        this.histroyDeliverRequests = new HashSet<Histroyrequest>();
        this.histroyProposalRequests1 = new HashSet<Histroyrequest>();
    }

    public string Name { get; set; }
    public string Role { get; set; }
    public string Email { get; set; }
    public string Group { get; set; }
    public int Id { get; set; }
    public short SoftwareVersion { get; set; }

    public virtual ICollection<Dfc> dfcs { get; set; }
    public virtual ICollection<Fid> fids { get; set; }
    public virtual ICollection<Histroyrequest> histroyDeliverRequests { get; set; }
    public virtual ICollection<Histroyrequest> histroyProposalRequests1 { get; set; }
    public virtual Software Software { get; set; }
}
</code>
Answer: I am thinking you should omit the Id, when inserting into the User Table, as I would think that the Id would auto increment, when inserting a new record?
Comment: Yes, it's an auto increment field. Anyway I've got the same exception omitting the Id.
Comment: Could you post your USER class please.
Comment: Yes, sure. It's a auto generated class since I'm using the EF with model-first approach


ASP.NET GridView CommandField Update/Cancel does not wrap

Question: My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.
<asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/>

What renders is the shown in the following image (after I click on the Edit button).

As you can see I am trying to have the Cancel link show up a new line and my question is how do you do what? If I change the ButtonType="Link" to ButtonType="Button", I get it rendering correctly as shown below.
alt text http://i38.tinypic.com/2pqopxi.jpg
I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.
Answer: If you use a template field it will give you complete control over the look of your page, but it requires that you use the CommandName and possible CommandArgument properties, and also using the GridView's OnRowCommand.
The aspx page:
<asp:GridView id="gvGrid" runat="server" OnRowCommand="gvGrid_Command">
 <Columns>
  <asp:TemplateField>
   <ItemTemplate>
    Some Stuff random content

    <asp:LinkButton id="lbDoIt" runat="server" CommandName="Cancel"  CommandArgument="SomeIdentifierIfNecessary" />
   </ItemTemplate>
  </asp:TemplateField>
 </Columns>
</asp:GridView>

The code behind:
protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)
{
 if(e.CommandName=="Cancel")
 {
   // Do your cancel stuff here.
 }

}
Answer: Don't use a command field, use a TemplateField and put your command button in that with a line break (br) before it like you want.
Comment: Thanks for the reply Bryant. However, it doesn't seem to work for me.

1- I can't find a way to bind only to the Update button in the CommandField

2- you cannot put a CommandField inside an ItemTemplate or EditItemTemplate. What also worries me is why this works for buttons and not links! Bug?


How to open Android Play Store settings page programmatically

Question: I want to open Play store Setting page.though I know how to open play store
final String appName = "";
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+appName)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="+appName)));
    }

but I want to open play store setting(to redirect user to auto update
  option) page that look like this image

How to do this.Is there any intent for this?
Answer: You can do that using this :
try {
      Intent intent = new Intent("com.google.android.finsky.activities.SettingsActivity");
      intent.setClassName("com.android.vending", "com.google.android.finsky.activities.SettingsActivity");
      startActivity(intent);
    }
    catch(Exception e) {
      e.printStackTrace();
    }

Answer: You may use the App Intent Intercept to find the intent for the PlayStore Settings-Activity.
I guess you can just run the app to start tracking and then open PlayStore and go to settings. Intent Intercept should show you the called Intents.
Comment: Well, there is probably no public Intent avaiable to this Activity, I'm afraid.
Comment: I have installed that app but could not find intent to settings of Play store but it is showing others apps intent. Could you please post the intent of settings of play store if possible?


Finding whether a relation is transitive, reflexive and symmetric.

Question: Let's say we have set: $A = \{1,2,3,...,10\}$, and there is a relation $M=P(A)-{\phi}=\{X | X\subseteq A, x\neq \phi\}.$
And there is this relation:

$T$ is defined as: $\{X,Y\}\in T$ iff  $\{X,Y\}$ is a partition of $A$.

So to find out whether it's transitive, I first tried to find the result of the relation $M$, and then found it to be almost impossible and impractical, as calculating $2^{10}$ of subsets is not the best idea, and the by using this I could calculate the $R^2$, but that's not the case this time.
Then I tried finding whether it's Symmetric, but because I couldn't calculate $M$, as I think I can't also find $M^{-1}$.
And.. I am pretty sure it's not reflexive as it can't have the Identity because it's the $P(A)$ of this set, meaning there isn't a set like this one: $\{1,1\}$.
I would like to get some assistance \ explanation on finding whether a relation is reflexive, symmetric, and transitive.
Comment: The word "group" means something specific in mathematics.
Comment: @Shaun oh sorry, English is not my native learning language, and we're naming it as "Group" and not "set" in my native learning language.
Answer: $M$ isn't a relation, it's the universe on which $T$ is a relation.
Since $\{X,\,Y\}$ is only a partition of $A$ only if $X\cap Y=\emptyset$, in general $(X,\,X)\notin T$, so $T$ isn't reflexive.
Since $\{X,\,Y\}=\{Y,\,X\}$, $T$ is symmetric.
If $(X,\,Y)\in T$ and $(Y,\,Z)\in T$ then $X=A\setminus Y=Z$, so $(X,\,Z)=(X,\,X)\notin T$ (becaise $\emptyset\cup\emptyset\ne A$), so $T$ isn't transitive.
Comment: Oh thanks! Now that makes sense, I have been breaking my brain for the last few hours and found no way of how to answer it.


If Simpson's paradox occurs, then is the stratified variable a confounder?

Question: Let $f(a,b,c,d) := ad - bc$.
Does there exist positive integers $a,b,c,d,a^\prime, b^\prime,c^\prime,d^\prime$ such that
$$f(a,b,c,d) >0,f(a^\prime,b^\prime, c^\prime, d^\prime) > 0,  f(a+a^\prime, b + b^\prime, c+ c^\prime, d+d^\prime) < 0 \text{ and } \qquad (*)$$
$$f(a + c, a^\prime + c^\prime, b + d, b^\prime + d^\prime) \neq 0?$$

Motivation. Two boolean variables $X$ and $Y$ are positively associated if $\mathrm{rate}(X \mid Y) > \mathrm{rate}(X \mid \neg Y)$, negatively associated if $\mathrm{rate}(X \mid Y) < \mathrm{rate}(X \mid \neg Y)$, and associated if they are either positively associated or negatively associated. Here $\mathrm{rate}(A \mid B) := \#(A \wedge B)/\#B$. Given a contingency table,
$$\matrix{\phantom{XX} & Y & \neg Y}$$
$$\matrix{X \\ \neg X}\matrix{a & b \\ c & d}$$
i.e. $\#(X \wedge Y) = a, \#(X \wedge \neg Y) = b, \#(\neg X \wedge Y) = c$ and $\# (\neg X \wedge \neg Y) = d$,
the variables $X$ and $Y$ are positively associated if and only if $f(a,b,c,d) := ad - bc > 0$ and negatively associated if and only if $f(a,b,c,d) < 0$.
Given a third boolean variable $Z$, Simpson's paradox is said to occur if the sign of the association is reversed upon stratifying along a third boolean variable $Z$, i.e. if $X \wedge Z$ is positively associated to $Y \wedge Z$, and $X \wedge \neg Z$ is positively associated to $Y \wedge \neg Z$, but $X$ is negatively associated to $Y$ (c.f. $(*)$ above).
A variable $Z$ is said to confound the association between $X$ and $Y$ if $Z$ is associated to $X$, and $Z$ is associated to $Y$. Typically, stratification is done as a means of controlling for a variable $Z$ which confounds the association between $X$ and $Y$. If Simpson's paradox occurs, then does the stratified variable $Z$ necessarily confound the association between $X$ and $Y$? In particular, the above question asks whether if Simpson's paradox occurs, is it necessary that the stratified variable $Z$ is associated to $X$.
Answer: The two following matrices $M$ and $M'$ do the job:
$$M=\left[\matrix{3&9\cr1&6\cr}\right]\>,\qquad
M'=\left[\matrix{6&1\cr9&3\cr}\right]\ .$$
Then
$$\det M=\det M'=9>0,\qquad\det(M+M')=\det\left[\matrix{9&10\cr10&9\cr}\right]=-19<0\ ,$$
and
$$\det\left[\matrix{a+c&a'+c'\cr b+d&b'+d'\cr}\right]=\det\left[\matrix{4&15\cr15&4\cr}\right]\ne0\ .$$
Comment: Thanks, Professor Blatter! We also have $\det \left[ \matrix{ a + b & a^\prime + b^\prime \\ c + d & c^\prime + d^\prime}\right] = \det \left[ \matrix{12 & 7 \\ 7 & 12} \right] \neq 0$. Therefore the stratified variable is a confounder in this example.


How to end on first async parallel task completion in Node?

Question: I have a list of tasks that I want to run in parallel using https://github.com/caolan/async.
I want the program to proceed (probably through a callback) after the first of these parallel tasks is complete, not all of them. So I don't think the naive
async.parallel([task1, task2], callback)

works for me.
Alternatively I could spawn two tasks and cancel the incomplete one, but I can't figure out how to do that using async either.
Thanks!
-Charlie
Comment: `async` cannot cancel a task once it's started it; after that, it can only wait for it to finish or ignore it. The ability to cancel would have to reside with the task or the object that owns it. Something akin to [`XMLHttpRequest`'s `.abort()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#abort()).
Comment: That fact means I have to try a different approach - thanks for the info!
Answer: Parallel Race
You can get async to initiate the final callback by returning an error that evaluates as true but isn't actually an error.
I've put together an example that uses -1 as an error code.  In the final callback I check the error value and if it's not -1 then it's an actual error.  If the error value is -1 then we'll have a valid value in results.  At that point, we just need to remove extra elements from results of the other async functions that have not completed yet.
In the below example I've used the request module to pull html pages and the underscore module to filter the results in the final callback.
var request = require('request');
var _ = require('underscore');

exports.parallel = function(req, res) {
  async.parallel([
    /* Grab Google.jp */
    function(callback) {
      request("http://google.jp", function(err, response, body) {
        if(err) { console.log(err); callback(true); return; }
        callback(-1,"google.jp");
      });
    },
    /* Grab Google.com */
    function(callback) {
      request("http://google.com", function(err, response, body) {
        if(err) { console.log(err); callback(true); return; }
        callback(-1,"google.com");
      });
    }
    ],
    /* callback handler */
    function(err, results) {
      /* Actual error */
      if(err && err!=-1) {
        console.log(err);
        return;
      }
      /* First data */
      if(err===-1) {
        /*
         * async#parallel returns a list, one element per parallel function.
         * Functions that haven't finished yet are in the list as undefined.
         * use underscore to easily filter the one result.
         */
        var one = _.filter(results, function(x) {
          return (x===undefined ? false : true);
        })[0];
        console.log(results);
        console.log(one);
        res.send(one);
      }
    }
  );
};

Remaining Function Results
When you setup async#parallel to work like this you won't have access to the results of the other asynchronous functions.  If you're only interested in the first one to respond then this isn't a problem.  However, you will not be able to cancel the other requests.  That's most likely not a problem, but it might be a consideration.
Comment: Nice solution, thanks for the code Daniel! Unfortunately the two tasks I was trying to run are large, so it's computationally expensive to let the ignored one finish. I will probably end up breaking the tasks into smaller chunks, so that I can spare the wasted cycles of either letting it finish ignored (like this design) or just waiting for both to finish.
Answer: The async.parallel documentation says:

If any of the functions pass an error to its callback, the main callback is immediately called
  with the value of the error.

So you could return an error object from all of your parallel functors, and the first one to finish would jump you to the completion callback. Perhaps even your own special error class, so you can tell the difference between an actual error and a "hey I won" error.
Having said that, you would still have your parallel functions running, potentially waiting for callbacks to complete or whatever. Perhaps you could use async.parallelLimit to make sure you're not firing off too many tasks in parallel ?
Having said all that, it's possible you are better served by trying another method from the async library for this task - firing off parallel tasks then having these tasks race each other may not be the best idea.


Contagem De Tempo Para Jogada (Threads)

Question: O necessário para responder a pergunta está em comentários no código:
using System;
using System.Threading.Tasks;

class Program
{

    static void Main(string[] args)
    {
        player1.Start();
        t.Start();

        while (t.IsAlive); //A intenção seria depois que o Thread t acabar se a Thread player1
                            //ainda estiver ativa o jogador perde a rodada.
                            //gostaria também de que se a Thread player1 já acabou
                            //a Thread t pode se encerrar.
        if (player1.IsAlive) player1.Abort(); Console.Write("\nSeu Tempo Acabou");
    }

    static void player()
    {
        Console.Write("Player1 Escreva Algo (Nao Deixe Passar 10 Segundos): ");
        str += Console.ReadLine() + " ";
        Console.Write(" {0}", str);
    }

    static void tempo()
    {
        System.Threading.Thread.Sleep(10000); //10 sec = 10.000 milisec
    }

    static String str = "";
    static System.Threading.Thread player1 = new System.Threading.Thread(player);
    static System.Threading.Thread t = new System.Threading.Thread(tempo);

}

Ex: Em jogos de xadrez você tem um tempo disponível para movimentar sua peça, se você não movimentar dentro de por exemplo 30 segundos você perde sua jogada e é a vez do próximo jogador (Ai mostraria a mensagem), agora se você movimentar sua peça antes do tempo, você apenas passa a vez para outro jogador sem perder nada. a ideia é +/- essa.
Answer: Usando a classe Task é fácil fazer o que pretende:
class Program
{
    static void Main(string[] args)
    {
        String str = null;

        //Objectos que permitem cancelar as Tasks
        var tokenSourceTempo = new CancellationTokenSource();
        var ctTempo = tokenSourceTempo.Token;
        var tokenSourcePlayer = new CancellationTokenSource();
        var ctPlayer = tokenSourcePlayer.Token;

        //Cria a task que espera 10 segundos até
        Task.Factory.StartNew(
            () =>
            {
                Thread.Sleep(10000);

                if (ctTempo.IsCancellationRequested != true)
                {
                    tokenSourcePlayer.Cancel(); //Cancela a task player
                    Console.Write("\nSeu Tempo Acabou\n");
                }
            }, ctTempo);

        //Cria a task player
        var taskPlayer = Task.Factory.StartNew(
            () =>
            {
                var key = new ConsoleKeyInfo();

                Console.Write("Player1 Escreva Algo (Nao Deixe Passar 10 Segundos): ");

                while (key.Key != ConsoleKey.Enter)//Aceita teclas até a tecla enter ser usada
                {

                    key = Console.ReadKey();
                    ctPlayer.ThrowIfCancellationRequested();//Se a task player foi cancelada aborta
                    tokenSourceTempo.Cancel();//O player teclou algo, cancela task tempo
                    str += key.KeyChar;//Constroi string
                }

            }, ctPlayer);

        try
        {
            taskPlayer.Wait();// Espera enquanto o player tecla algo
            Console.Write("\nVocê escreveu: {0}\n", str);
            Console.ReadKey();
        }
        catch (AggregateException e)//Quando a task player é cancelada é lançada uma Exception
        {
            if (taskPlayer.IsCanceled)
            {

            }
        }
    }
}

Você terá agora de ajustar às suas necessidades.
Utilize ctrl+F5 para testar se tiver a utilizar o Visual Studio.
Comment: Não sei se isso realmente serve é pq to meio confuso para mim mas, para min está parecendo que sempre depois que passar os 10 segundos ele vai mostrar "\nSeu Tempo Acabou" eu quero que isto só aparece se o jogador não digitar nada.
Comment: Não tinha entendido isso assim. Vou editar a resposta. O que quer que aconteça depois do jogador digitar algo?
Comment: Bom só faça o seguinte se o usuário informar algo beleza coloque em str e feche o programa, se ele não informar nada em 10 segundos diga que seu tempo acabou e pause o programa com um ReadLine() e depois feche.
Comment: Como eu trataria o caso em que por exemplo o player tecla algo e depois apaga ? neste caso também deveria ser mostrada a mensagem.
Comment: Descobri um bug mt loco kkkk se você digitar por exemplo asd e depois ir apertando backspace ate fazer com que o cursor chegue na palavra 'player1' depois é só vim apertando a setinha para a direita e ver acontecer kkk
Comment: Para isso teríamos de usar `Console.ReadLine()` em vez de `Console.ReadKey();`. Nessa situação só será considerado que o jogador digitou algo após este teclar ***enter***, ou seja, o tempo está contando até ser teclado ***enter***
Answer: Bom, criei algumas classes para ficar mais fácil de se entender.
Os comentários lhe ajudarão a entender o fluxo.
using System;
using System.Threading;

namespace Pt.Stackoverflow
{
    class Program
    {
        static void Main()
        {
            // nova partida
            var match = new Match(new Player("Player 1"), 60);

            //Ação customizada que será executada quando o usuário digitar algum texto
            match.OnPlayerInput += input =>
            {
                Console.WriteLine("Usuário escreveu: \"{0}\"", input);
                match.Finish();
            };

            //Ação customizada que será executada quando a partida for encerrada,
            //ou seja, por tempo ou pela chamada do método Finish() e não pelo fechamento da Aplicação.
            match.OnMatchEnd += () => Console.WriteLine("Tchau!");

            match.Start();
        }
    }

    class Match
    {
        ///
        /// Tempo em segundos.
        ///
        public uint Time { get; private set; }
        ///
        /// Player atual
        ///
        public Player CurrentPlayer { get; private set; }
        ///
        /// Chamado quando o usuário escreve algo.
        ///
        public event Action<string> OnPlayerInput;
        ///
        /// Chamado quando a partida termina.
        ///
        public event Action OnMatchEnd;

        private AutoResetEvent _autoEvent;
        private TimerCallback _tick;
        private Timer _timer;
        private readonly Thread _matchThread;

        private const int AGORA = 0, SEGUNDO = 1000, MINUTO = 60000;

        ///
        /// Criar uma nova partida
        ///
        /// <param name="player">Jogador atual</param>
        /// <param name="time">Tempo da partida</param>
        public Match(Player player, uint time) {
            CurrentPlayer = player;
            Time = time;

            _matchThread = new Thread(() =>
            {
                Console.WriteLine(">> {0} Escreva Algo (Nao Deixe Passar 10 Segundos): ", player.Name);
                On_PlayerInput(Console.ReadLine());
            });
        }

        ///
        /// Inicia a partida
        ///
        public void Start()
        {
            if (Time == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Esta partida já foi encerrada.");
                Console.ForegroundColor = ConsoleColor.White;
                return;
            }

            Console.Clear();
            Console.ForegroundColor = ConsoleColor.White;

            // Usado para fazer com que o timer seja repetido.
            _autoEvent = new AutoResetEvent(false);
            // Callback do Timer
            _tick = Tick;
            // Timer disparado imediatamente e chamado a cada segundo
            _timer = new Timer(_tick, _autoEvent, AGORA, SEGUNDO);

            //Capturar do input do usuário
            _matchThread.Start();

            Console.WriteLine(">> Partida Iniciada.");
        }

        ///
        /// Termina a partida
        ///
        public void Finish()
        {
            _timer.Dispose();
            _autoEvent.Dispose();
            Time = 0;

            if (OnMatchEnd != null) OnMatchEnd();
            Console.WriteLine(">> Partida concluída.");
            Console.Read();
            _matchThread.Abort();
        }

        ///
        /// Chamado a cada segundo passado
        ///
        /// <param name="stateInfo"></param>
        private void Tick(Object stateInfo)
        {
            //Console.WriteLine(">> Tempo atual da partida: {0}s", Time);
            if (--Time == 0) Finish();
        }

        ///
        /// Chamado quando o usuário digitar um texto (após apertar Enter)
        ///
        /// <param name="input">Texto digitado</param>
        private void On_PlayerInput(string input)
        {
            //Console.WriteLine(">> Usuário escreveu: {0}", (CurrentPlayer.Input = input));
            if (OnPlayerInput != null) OnPlayerInput(input);
        }
    }

    class Player
    {
        ///
        /// Nome do jogador
        ///
        public string Name { get; set; }
        ///
        /// Texto digitado pelo jogador
        ///
        public string Input { get; set; }

        public Player(string name) { Name = name; }
    }
}

Answer: Voltei no código e percebi que foi só mudar a função void player() que funcionou exatamente como eu queria, então ficou assim:
static void player()
{
    Console.Write("Player1 Escreva Algo (Nao Deixe Passar 10 Segundos): ");
    str += Console.ReadLine();
    Console.Write("\"{0}\"", str);
    t.Abort();
}

E também mudei isso:
while (t.IsAlive);
if (player1.IsAlive) { player1.Abort(); Console.Write("\nSeu Tempo Acabou"); }

Para isso:
while (t.IsAlive);
System.Threading.Thread.Sleep(1);
if (player1.IsAlive) { player1.Abort(); Console.Write("\nSeu Tempo Acabou"); }

Quando ocorre t.Abort() na Thread player1 o while(t.IsAlive) da Thread da main é encerrado.
Porque quando ele saia do while (t.IsAlive); e ia para: if (player1.IsAlive)
não sei porque player1 continuava Alive mesmo depois de passar da linha t.Abort(); ai quando chega no if (player1.IsAlive) ele validava como true, sendo que player1 já tinha acabado.
Ai resolvi colocando 1 milissegundo entre o while e o if.
Mas também gostei muito das outras respostas, coloquei a minha aqui só para mostrar mais uma saída.

Contagem De Tempo Para Jogada (Threads)


Probability conditional on a parameter?

Question: This is a definition of the sufficient statistic from Wikipedia.

A statistic $t = T(X)$ is sufficient for underlying parameter $θ$ precisely if the conditional probability distribution of the data $X$, given the statistic $t = T(X)$, does not depend on the parameter $θ$, i.e.,
  $$
\text{Pr}(x|t,\theta) = \text{Pr}(x|t)
$$

I have a trouble to interpret the definition. I don't understand the meaning of the probability conditional on a "parameter" $\theta$. How can knowing the value of a parameter make a difference on the probability distribution? If $\theta$ is a "parameter", which is not a random variable so has no uncertainty, should $Pr(x|\theta) = Pr(x)$ always? For example, let's consider throwing an unfair dice. The probability of each face may be considered as a parameter. The result of the experiment throwing the dice does not depend on my knowledge on the probabilities of each face. The experiment is physically determined and my knowledge on the dice has nothing to do with the outcomes. So conditioning on $\theta$ is meaningless and we have trivially $\text{Pr}(x|t,\theta) = \text{Pr}(x|t)$ for any $t$ and $\theta$. What is my misconception here?
Comment: In essence, your description below the quote is that of a sufficient statistic, so perhaps your question is what is *not* a sufficient statistic?
Answer: If your issue is with the use of a conditioning symbol "|" instead of a semi-colon or an index in the notation of a family of distributions
$$\text{Pr}(x|\theta)\qquad\text{vs.}\qquad \text{Pr}(x;\theta) \qquad \text{vs.}\qquad\text{Pr}_\theta(x)$$
a first answer is that it is a matter of notations and that once one has clearly set a notation for this family it can be used as such. (Notation-wise, using $\text{Pr(x)}$ for a distribution should be discouraged as it does not apply to continuous and mixed random variables.) The distribution (and the associated density) are dependent on the value of $\theta$, meaning that two different $\theta$'s [should] lead to two different densities. This function is thus defined conditional on the chosen value of $\theta$ and one could not use it without knowing this value of $\theta$.
A second answer is that a conditional distribution sets the conditioning variable to a fixed value. In a conditional density $f(x|y)$ the value $y$ is constant while $x$ varies on the state space $\mathcal{X}$, e.g., $\mathbb{R}$. The value of $y$ taken by the conditioning variable $Y$ thus determines the function [of $x$] and for all purposes acts like a parameter. There is thus no [pragmatic] distinction to be made between $y$ and a parameter $\theta$ when using this conditional density. Furthermore, if $\theta$ becomes random, as for instance in a Bayesian analysis, adopting the conditional sign on $\theta$ makes notations coherent [with a joint distribution on $x$ and $\theta$].
Answer: First of all the distribution of x is not actually a distribution but a family of distributions. You know assume a form of x which is a function of $\theta$ but you do not know the value of $\theta$.
This is similar with the family of normal distributions $N(\mu,\sigma^2)$ where you don't know the value of parameters versus standard normal distribution $N(0,1)$. Now what means $P(x|\theta)$ ? This is actually the distribution function, remember that the conditional formula is read "probability of x given the value of theta".
Now the formula for sufficient statistic says if you know the value of statistic and the one of the parameter the distribution you determine for x is the same as the one determined for x if you knew the value of statistic only. So knowing the statistic is enough (sufficient) to determine the distribution of x. Or otherwise said, the statistic can be used to estimate the parameter entirely, without a need for additional information.
In your example with dice you assume a distribution family multinoulli, but you do not know the parameters. If you estimate the parameters values with a statistic and you determine the same distribution for the dice as if you would knew the parameters value then the statistic used for inference is sufficient.
One final word about what means determine in the previous paragraph. Of course you cannot determine exactly the parameters values, the statistic is built from sample, so it contains limited information. The determination here refers to the procedure itself. Everything is valid at limit, if you would have an infinite sample and so on.

Probability conditional on a parameter?


select id from table and distinct column y

Question: I have the following sql:
SELECT `id` FROM `exchange` WHERE `photo` = 1 ORDER BY `id` DESC LIMIT 18

How can I only get distinct location values?
For example doing this but it returns an error:
SELECT `id`, distinct(`location`) FROM `exchange` WHERE `photo` = 1 ORDER BY `id` DESC LIMIT 18

Example table:
id    location

1        7
2        8
3        4
4        4
5        2
6        32

Example result (when LIMIT 5):
6,5,4,2,1
Answer: DISTINCT works for the whole row, not for the value of each column. Remove the column ID and you will have unique location.
SELECT distinct `location`
FROM `exchange`
WHERE `photo` = 1
ORDER BY `id` DESC
LIMIT 18

UPDATE 1
You can use AGGREGATE FUNCTION like MAX() and grouped them by their ID. Try this again,
SELECT location, MAX(ID) ID
FROM exchange
GROUP BY location

Comment: I need to select the id to then create the member class
Comment: can you please add sample records and results? :D
Comment: results for what? and the table has about 30 columns
Comment: your desired result, don't include all column, just the essential part only.


Change fills of a lot of shapes in code in vb.net

Question: This time I'm developing a windows store app and I've got a problem when I'm trying to change the fill of a lot of rectangles in code. The shapes are too many to name them separately and change their fill separately (There's at least 150 rectangles). They're placed inside a canvas, but Canvas.Children gives me a UIElement value which is not what I want(I want Xaml.Shapes.Rectangle, which I can change their fill). So, any ideas? Thanks a lot.
David,
2015-08-27
Answer: Try this :
(Edit : Just noticed the vb.net tag; this code is in C#. But the idea is to loop through all the elements inside Canvas.Children and check whether it's a Rectangle, and if it is then change it's Fill)
<code>foreach(UIElement child in MyCanvas.Children)
        {
            if(child.GetType()== typeof(Windows.UI.Xaml.Shapes.Rectangle))
            {
                ((Rectangle)child).Fill = new SolidColorBrush(Windows.UI.Colors.AliceBlue);
            }
        }
</code>
Comment: Thanks, that looks work. just need a little time to convert the code.


Estou querendo gerar 4 valores aleatórios de uma array. Como posso fazer?

Question: Estou querendo gerar 4 valores aleatórios de uma array. Já tentei usar o Math.random, mas fica em um loop infinito...
import React, { useState, useEffect } from "react";
import api from "../../services/api";

export default function Popular() {
  const [AllServices, setService] = useState([]);

  useEffect(() => {
    api.get("/").then((response) => {
      setService(response.data);
    });
  }, []);

    return (

        {AllServices.slice(0, 4).map(service => (

{service.title}

              grade
              {service.rating} · {" "}
              {service.category}

        ))}

    );
}

Comment: @Danizavtz Não entendi, poderia me explicar melhor?
Comment: Gostaria de saber o intervalo do sorteio dos número, são numero aleatórios de zero a dez?
Comment: @Danizavtz Ah, sim. De 0 a 8.
Comment: Onde queres usar esses valores aleatórios? em vez de `.slice(0, 4)` para encurtar a array? ou queres ter uma array com numeros aleatórios dentro? e quantos? e de 0 a 8?
Comment: @Sergio Em vez do .slice(), quero puxar 4 valores aleatórios do array. Seria de 0 até o tamanho do array, no caso 8.
Comment: Ok, e com o slice (como está na pergunta) tens um loop infinito como referes ou funciona bem?
Comment: @Sergio Consegui resolver o loop infinito, agora é só a questão de gerar os 4 valores aleatórios
Comment: @Sergio Funcionou, muito obrigado!
Comment: Note que esse método produz resultados viciados. Fiz uma resposta que serve para obter resultados aleatórios, caso isso seja um requerimento importante.
Answer: Podes fazer isso assim (notas nos comentários do código):

const getRandom = (arr, nr) => arr
  .slice() // criar uma cópia para não mudar a array inicial
  .sort(() => 0.5 - Math.random()) // misturar
  .slice(0, nr) // retirar N elementos da nova array misturada

const teste = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(getRandom(teste, 4));
console.log(getRandom(teste, 4));
console.log(getRandom(teste, 4));

No teu código React poderia ficar assim:
import React, { useState, useEffect } from "react";
import api from "../../services/api";

const getRandom = (arr, nr) => arr
  .slice() // criar uma cópia para não mudar a array inicial
  .sort(() => 0.5 - Math.random()) // misturar
  .slice(0, nr) // retirar N elementos da nova array misturada

export default function Popular() {
  const [AllServices, setService] = useState([]);

  useEffect(() => {
    api.get("/").then((response) => {
      setService(response.data);
    });
  }, []);

  return (

      {getRandom(AllServices, 4).map(service => (

{service.title}

            grade
            {service.rating} · {" "}
            {service.category}

      ))}

  );
}

Answer: A resposta aceita funciona, mas possui dois pequenos problemas. O primeiro, e maior, é que produz k-permutações com probabilidades não uniformes. Testando essa função várias vezes, fica claro que o resultado é viciado. Frequentemente, os números obtidos são próximos entre si. Se você realmente quer uma k-permutação uniforme dentre todas as possíveis, então é preciso usar outro algoritmo.
O outro problema (menor) é a performance, tanto em espaço de memória quanto em tempo de execução. O método sort é tipicamente executado em tempo quadrático O(n²), e isso se manifesta quando o array original é muito grande (com mais de centenas de milhares de elementos). Ele também copia o array original desnecessariamente, como veremos.
A solução para ambos problemas é usar uma versão adaptada do algoritmo de Fisher–Yates. Fisher–Yates serve, a princípio, para embaralhar uma sequência de N números de maneira uniforme, sempre contando que Math.random também é uniforme no intervalo [0, 1).
Dessa forma, temos a implementação a seguir:
const algoritmoFisher = (array, number) => {
  const copy = array.slice();
  const { length } = array;

  for (let i = length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = copy[i];
    copy[i] = copy[j];
    copy[j] = temp;
  }

  return copy.slice(0, number);
};

const algoritmoFisherAdaptado = (array, number) => {
  const shuffle = new Array(number);
  const { length } = array;

  shuffle[0] = array[0];

  for (let i = 1; i < number; i++) {
    const j = Math.floor(Math.random() * (i + 1));
    shuffle[i] = shuffle[j];
    shuffle[j] = array[i];
  }
  for (let i = number; i < length; i++) {
    const j = Math.floor(Math.random() * (i + 1));
    if (j <= number - 1) {
      shuffle[j] = array[i];
    }
  }

  return shuffle;
};

Pode-se testar o desempenho e observar a falta de uniformidade do algoritmo ingênuo no demo que fiz no CodeSandbox.


Como faço para alterar a imagem de cada item da minha lista ?

Question:
Quero Alterar a imagem de cada item da minha lista.. como faço ? Agradeço a compreensão eis que não tenho muita experiência. Obrigado. Meu código Abaixo.
<code> import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.EditText;
 import android.widget.ListView;
 import br.gestaoBd.BancoDeDados.ProdutoDao;
 import br.gestaoBd.Beans.ItemDoPedido;
 import br.gestaoBd.Beans.Produto;
 import br.gestaoBd.listaadapters.ProdutoAdapter;
 import java.util.ArrayList;

 public class ListProdutos extends Activity implements  AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

ListView lista;
ArrayList<Produto> produtos;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_produtos);
    lista = (ListView) findViewById(R.id.listview);
    lista.setOnItemLongClickListener(this);
    lista.setOnItemClickListener(this);
    atualizar(null);
}

public void atualizar(View view) {
    ProdutoDao proDao = new ProdutoDao();

    produtos = proDao.getListagem("");
    lista.setAdapter(new ProdutoAdapter(getBaseContext(), produtos));
    setTitle("Lista de produtos(" + CadPedido.getTotal() + ")");
}

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadProdutoIntent = new Intent(this, CadProdutos.class);
    cadProdutoIntent.putExtra("Produto", produtos.get(position));
    startActivity(cadProdutoIntent);
    return true;
}

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    final ItemDoPedido itemAdicionar = new ItemDoPedido();
    itemAdicionar.setProduto(produtos.get(position));
    itemAdicionar.setValorUnitario(produtos.get(position).getPrecoDeVenda());
    // get prompts.xml view
    LayoutInflater layoutInflater = LayoutInflater.from(ListProdutos.this);
    View promptView = layoutInflater.inflate(R.layout.input_qtdeitem, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ListProdutos.this);
    alertDialogBuilder.setView(promptView);

    final EditText edQtdeAddItem = (EditText) promptView.findViewById(R.id.edQtdeAddItem);

    // setup a dialog window
    alertDialogBuilder.setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    itemAdicionar.setQuantidade(Double.parseDouble(edQtdeAddItem.getText().toString()));
                    CadPedido.getItensDoPedido().add(itemAdicionar);
                    ListProdutos.this.atualizar(null);
                    Log.i("AULA", "Finalizou");
                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //dialog.cancel();
                        }
                    });

    // create an alert dialog
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 0, 0, "Continuar");
    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == 0) {
        Intent intent = new Intent();
        intent.setClass(ListProdutos.this,
                CadPedido.class);

        startActivity(intent);
    }
    return super.onOptionsItemSelected(item);
}

}
</code>
Meu Adapter:
<code>   import android.content.Context;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.BaseAdapter;
   import android.widget.ImageView;
   import android.widget.TextView;
   import br.gestaoBd.Beans.Produto;
   import br.gestaoBd.R;
   import java.util.List;

   public class ProdutoAdapter extends BaseAdapter {

private Context context;
private List<Produto> produtos;

public ProdutoAdapter(Context context, List<Produto> produtos) {
    this.context = context;
    this.produtos = produtos;
}

public int getCount() {
    return produtos.size();
}

public Object getItem(int position) {
    return produtos.get(position);
}

public long getItemId(int position) {
    return produtos.get(position).getId();
}

public View getView(int position, View convertView, ViewGroup parent) {
    Produto produto = produtos.get(position);

    LayoutInflater layout = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = layout.inflate(R.layout.linhapro, null);

    //Log.i("AULA", "Montou:" + produto.getDescricao());
    //Log.e("ERRO", "Valor da variavel estava nullo!");

    ImageView imgImageView = (ImageView) view.findViewById(R.id.imageView1);
    imgImageView.setImageResource(R.drawable.sem_foto);

    TextView edDescricao = (TextView) view.findViewById(R.id.textView1);
    edDescricao.setText(produto.getDescricao());

    TextView edPreco = (TextView) view.findViewById(R.id.textView2);

    edPreco.setText(String.valueOf(produto.getPrecoDeVenda()));
    return view;
}
}
</code>
Peço encarecidamente que sejam bastante específicos .. Muito Obrigado Colegas !
Comment: Creio que seja apenas adicionar um resource da sua imagem na pasta drawable, e substituir ali em  `R.drawable.sem_foto` para `R.drawable.seuResource`.
Answer: Primeiro é estruturar sua class Produto, saber o que ela possui se é nome,preço,imagem e etc... Sabendo disso você cria ela com construtores e get e set. E saber também se essa imagem vai ser local ou de um servidor remoto. Exemplo:
<code>public class Produto{

public Produto(){}

private String nome;
private Float valor;
private String urlImagem; // ou caso local private int IdImagem;

metodos de get e set aqui...
</code>
}
Depois na sua class ProdutoAdapter no metodo getView
<code>    ImageView imgImageView = (ImageView) view.findViewById(R.id.imageView1);
imgImageView.setImageResource(produto.getIdFoto); //caso a imagem seja local (esse id é como se fosse isso: R.drawable.minhaImagem)

TextView edDescricao = (TextView) view.findViewById(R.id.textView1);
edDescricao.setText(produto.getDescricao());

TextView edPreco = (TextView) view.findViewById(R.id.textView2);
edPreco.setText(String.valueOf(produto.getPrecoDeVenda()));
</code>
Lembrando quando se trabalha com imagens no Android é sempre bom ter cuidados com a memória do celular do usuário pois é alocado uma grande quantidade de memória e ocorre o erro FATAL EXCEPTION: main java.lang.OutOfMemoryError.
E mais caso seja Imagens de um servidor procure tutoriais na internet que existe bastante caso faça e tenha dúvidas poste aqui e alguém vai tentar te ajudar
Comment: Estou fazendo como sugeriu e ele não reconhece o getIdFoto que no meu caso está nomeado como IdImagem pois é assim que está na classe Produto.. @Alessandro Barreto
Comment: Qual erro ela dá? certifique-se de ser um valor int porque R.drawable.tuaImagem é um valor inteiro
Comment: ele não reconhece o getIdImagem .. diz que não pode encontrar a variável @Alessandro Barreto
Comment: Mas esse erro ocorre quando você compila o projeto e monta o apk? Como você está passando as imagens para a class Produto?  É no seu Produto Dao?
Comment: Sim pelo ProdutoDao .. na verdade ele não chega a reconhecer o getIdImagem , não chega nem a compilar