When tuning a guitar, why is it only in tune for a moment?

Question: I am still very new to learning guitar (specifically, Classical fingerstyle). While this is the first time I am doing this "seriously", I HAVE tried to learn guitar before, just very badly (and usually with crappy instruments that have been handed down and mistreated by family). I am currently using a tuner app on my phone, although I just ordered a nicer clip-on tuner (Snark SN-2). In the past I've used other mic'd chromatic tuners.
I'm just curious why it is, when tuning, that when you get a note "perfect" it's only exactly in tune for a moment after the string is struck. After that moment, the tuner starts to frequency wobbling sharp and flat around the ideal tuning.
What causes that to happen? I've read a bit about tuning now trying to find out, and everyone just seems to repeat that it's the note played originally that has to be as close to exactly in tune as possible, and not to worry about afterwards.
What confuses me is that the string length never changes, so the wavelength shouldn't change. The frequency may slow down as the string stops vibrating as fast... but why would it sometimes go up too? Maybe I'm thinking about it wrong?
Wouldn't this affect sustained long notes, or is it mostly imperceivable by the ear?
Comment: There's a wide range of opinions on how often to use a visual tuner while playing. I'm firmly in the "don't use it very often camp". Remember, music isn't notes written on a page or a wavy line on the tuner- it's *sound*. Follow your ears at all times (not just when you're tuning before you start playing) and you'll always be in tune.
Comment: @musical_coder: I believe tuners were invented precisely due to the fact that not all people have a good ear and can tune properly. Tuning is also quite tedious to listen to. While obviously one should use one's ears, a diatribe against tuners isn't likely to a) be heeded or b) make progress for music in general.
Comment: Just for one aspect: the frequency changes not only with **length** of the string (even this is the most visible factor), but also with the **tension**. Tuning a guitar string will not change the length, but only the tension. I don't assume your are interested in the formula?
Comment: @musical_coder easy to say, but I can't tell by ear if something is in tune or not so I find a visual tuner useful!
Comment: It's fine to use a tuner to get your ears started in the right direction, but just wanted to make the point not to let a visual tuner be the end-all. People sometimes forget to wean themselves off of it. I agree that overall, this is a good question to ask about tuning and the physics of sound.
Comment: possible duplicate of [When tuning a guitar, how should I strike the strings?](http://music.stackexchange.com/questions/940/when-tuning-a-guitar-how-should-i-strike-the-strings)
Comment: See especially [this answer](http://music.stackexchange.com/a/941/6556) with its link to [Guitar Tuning Nightmares Explained](http://www.endino.com/archive/tuningnightmares.html).
Answer: Plucking a string increases its tension momentarily. This tension drops rapidly as the vibration dies out. This causes the pitch to drop slightly as the string vibrates. It's an inherent limitation of plucked string instruments but it's OK, it's part of the sound we know and love.
Also, unlike the ideal mathematical model, strings vibrate in two dimensions. Since the change in tension is more pronounced in one dimension than the other, we're actually hearing two sounds. This causes some harmonics to get cancelled while others become more pronounced. As the frequencies of these two vibrations shift relative to each other, the harmonics that get cancelled or become pronounced also change. This causes a slight chorusing or flanging effect. It's also an inherent limitation of plucked string instruments but it's also OK, it's also part of the sound we know and love.
Digital tuners are not perfect. These changes in harmonic distribution and drop in volume cause them to misread the exact pitch. This is probably the reason why you see some "wobbling" that follows the initial pitch drop.
Comment: @MattMcNabb Plucking the string as gently as possible will make it less sharp. Also, plucking it near the middle of the string will emphasize the fundamental note more and overtones less, which will create less confusion for your tuner. On an electric guitar, rolling off the tone knob also helps.
Comment: FWIW, tone drop occurs with bowed instruments as well once the bow is removed from the string.  The tone can sharpen as the bow forces a crescendo, too.
Comment: can you elaborate on how to pluck or how to interpret the digital tuner's output in order to get as close to the exact pitch as possible?
Comment: @Matt: try gently resting a finger of your left hand at the half-way fret and releasing as the string is plucked. This mutes some harmonics and can give a tone that is easier to tune.
Comment: A rather nice demo is to hang a piece of string so it hangs between two points with a slight sag in the middle, tie another piece of string to the midpoint of the first, and hang a small weight from the second, and start it spinning in a circle.  The rotation will subside as the weight shifts toward swinging in a diagonal line, then the rotation will reverse, then the weight will swing on the other diagonal, etc.  Something similar can happen on the guitar since the ends don't restrict vertical and horizontal movements quite the same way.
Answer: I've noticed this and I really think it's simply due to the fact that over time the loudness of the note tapers off, so the tuner is less able to accurately pickup the tone with its microphone.
Answer: You should tune it a little sharp not just the exact note, because this is going to happen over and over again.
Why?

because the tuning pegs use to turn by their own (it depends on the quality of the gears), you can't notice it because it takes time, take in count that you add tension to the strings every time you play.
I hope this helps
BTW
if you are learning, like me! I give you and advice. take this course https://www.coursera.org/course/guitar is free!
Comment: IF your machine heads are moving on their own, you need to repair or replace them. This is not natural -- assuming you're not mistaking the up vs. down hysteresis in the gearing.
Comment: If you tune sharp, you are out of tune with anyone else who isn't tuned sharp. If your instrument drifts flat, that just means that you need to retune more often, and as Carl said, get your instrument repaired.
Answer: I've noticed a drop in tune in two places when I change my strings.  1: After I change a string and move on to the next one.  2: It drops again after I cut the excess string off after I'm done changing them all.
I've found that after getting the string to pitch, tune it up a half-step and some change.  This helps compensate the loss on my electric with standard gibson bridge and my Blueridge acoustic.
Hope this helps.  Now go play!
Answer: The fact you have picked up on this shows you have a good ear, here are some tips to make your guitar ring like an angel :)
Make sure you have a good tuner that is accurate, (doesn't have to be expensive). Read plenty of reviews on it don't just go buy one.
Always tune turning up, if you overshoot go back and start again. This makes sure there is no tension unreleased, more so for older strings when they start to click when tuning.
Tune at temperature, tune it so you can play without irritation, then tune again once you have warmed up the guitar. (don't annoyingly tune in front of people, unless you have a muting tuner)
Tune according to playing style. If you are going to be picking really hard and quickly, the note that stands out the most is the one you want to tune for. If you need lots of resonance then its the ringing I tune for.
How long after picking, My favourite spot to tune to is about 1 second after picking it medium to gentle. No earlier as its to sharp, no later as it starts to go flat.
.
--Expert Level--
If your guitar is tuned well, keep tuning it and let the other strings resonate (i.e. don't mute them). You will hear a rise and fall (like a wobbling) in the volume of the harmonics (the high pitched ringing noise).
You can finer tune by aiming to reduce the speed it rises and falls. Sometimes I've re-tuned my guitar, with my tuner saying every string is in tune both before and after, and can still hear an improvement! Other times I have tuned a guitar so the tuner says its slightly out of tune, but it sounds better with my tuning because it is tailored to the guitar. Although this improves lots of open string and low down chords, it can make higher up notes slightly out of tune. (this is purely open string, not the harmonic tuning method).
Answer: An important factor is the loudness of the string. This doesn't change the note, of course, but the tuner will be only sensitive to so much of the string's "note life"- that is:
You pluck the string. The attack in the note tells the tuner to start 'listening' for a note.
The tuner can gather something while the signal is clear and strong.
As the note dies away (quickly on a classical guitar), the tuner can't get a clear signal anymore, as perhaps other background noises start to interfere, and the tuner starts to wander.
So you're likely to get a good reading while the note is loud, and less so as the note dies away. On an electric guitar with plenty of sustain, this "moment of clarity" can be many seconds, but on a classical guitar with nylon strings, the decay can be much quicker.
Also with an electric guitar, outside noises play no part because the connection is electric, not acoustic. With a classical guitar, you're presumably using the mic in your phone (or tuner) to gather the note, meaning it'll pick up other noises.
The clip-on tuners use vibration instead of a microphone. My experience (a Snark) is that these go a long way towards helping with background noise as the vibration is more clear.


Understanding examples of subfield and prime subfield of a finite field

Question: I have already taken a look at this answer. Somehow it did not answer my question.
As I can find, in various literatures,

A lecture note, Definition 4.1:
Let
$F$
be a field. A subset
$K$
that is itself a field under the operations of
$F$
is called a
subfield
of
$F$.
Another lecture note, Section 7.4.2: A subfield $G$ of a field $F$ is a subset of the field that is itself a field under the operations of $F$.

Now, if we consider the operations of the field to be  $+ \bmod n$ and $\times \bmod n$. We find that $\mathbb{Z}_2$ and $\mathbb{Z}_5$ are both fields under these operations.
But in order to get a good feeling of subfields, we try to  consider $\mathbb{Z}_{3^2} = \mathbb{Z}_9$. We find that this not a field under the afore stated operations.
Not all the non-zero elements, notably 3 and 9 ($\gcd(3,9) \not=1$ and $\gcd(6,9) \not=1$), do not have multiplicative inverses.
Indeed, as Wikipedia states,

Even though all fields of size $p$ are isomorphic to $\mathbb{Z}/p\mathbb{Z}$, for $n \ge 2$ the
  ring $\mathbb{Z}/p^n\mathbb{Z}$ (the ring of integers modulo $p^n$) is not a field. The
  element $p$ $(\bmod\ p^n)$ is nonzero and has no multiplicative inverse.

Looking for examples, we find one here for $GF(2^3)$. This is based on polynomials.
Now, coming to my original point on (understanding) subfield or prime subfield
of finite fields, please tell me,

Whether it is totally impossible to construct purely numerical examples of
fields of size $p^n$.
Given a (non-numerical) field of size $p^n$, (one can be found in page 90 (16) of this document), what is the best way to identify the subfield(s) and prime subfield? I appreciate an answer which nurtures my intuition, not a theoretical one which puts me deep in difficult mathematical terms.
Comment: What is a "purely numerical example"?
Comment: Consider the following. When you do calculations involving $\sqrt2$ you, at least more often than not, don't use its "numerical value". Instead you use the property that it satisfies the equation $(\sqrt2)^2=2$. Similarly you don't use a "numerical value" of the imaginary unit $i$. You simply use the knowledge that it satisfies the equation $i^2=-1$. Similarly, when you calculate in $\mathbb{F}_4=\{0,1,\beta,\beta+1\}$ you base your calculation to the bit that $\beta^2=1+\beta$. In the other finite fields you do something similar.
Comment: @HagenvonEitzen Examples involving numbers only and *not* polynomials involving indeterminates.
Answer: Let me address your first question. First, I want to argue that there is no precise meaning of "involving numbers only". For example, given a finite field $F$ of size $4$ constructed in the usual manner (quotient of a polynomial ring over $\mathbb{Z}/2\mathbb{Z}$), I can choose a set of numbers, say
$$S=\{37,\tfrac{5}{19},\pi,e\}$$
and, choosing a bijection of $S$ with $F$, use transport of structure to give $S$ the structure of a field. The field structure does not depend in any way on what the underlying set is "made of".
However, along the lines of what I think you are ultimately after, you can obtain finite fields of any possible order using larger rings of integers. For example, $\mathbb{Z}[i]/(3)$ is a finite field of size $9$, and $\mathbb{Z}[i]$ consists of very reasonable numbers,
$$\mathbb{Z}[i]=\{a+bi\mid a,b\in\mathbb{Z}\}.$$
Now let me addressr your second question. Let's use $\mathbb{F}_p$ to mean $\mathbb{Z}/p\mathbb{Z}$, a finite field of order $p$ - it is a very common notation that is slightly less cumbersome, but doesn't mean anything different, they are exact synonyms.
A finite field of order $p^n$ is often constructed by taking the polynomial ring $\mathbb{F}_p[x]$, choosing an irreducible polynomial $f\in \mathbb{F}_p[x]$ of degree $n$, and then making the field
$$F=\mathbb{F}_p[x]/(f).$$
Now, the division algorithm for polynomials tells you that each equivalence class in this quotient can be uniquely identified by a representative of degree $<n$. In other words,
$$\begin{align*}
F&=\{a_0+a_1x+\cdots +a_{n-1}x^{n-1}+(f)\mid a_0,a_1,\ldots,a_{n-1}\in\mathbb{F}_p\}\\\\
&=\left\{\,\overline{a_0+a_1x+\cdots +a_{n-1}x^{n-1}}\,\;\middle\vert\;a_0,a_1,\ldots,a_{n-1}\in\mathbb{F}_p\right\}\\\\\\
&=\{a_0+a_1\overline{x}+\cdots +a_{n-1}\overline{x}^{n-1}\mid a_0,a_1,\ldots,a_{n-1}\in\mathbb{F}_p\}
\end{align*}$$
Letting the symbol $\alpha$ be a stand-in for $\overline{x}$, you can think of $F$ as being $\mathbb{F}_p$ with a new element "$\alpha$" added in, where $\alpha$ is a root of $f$, and you can write $F=\mathbb{F}_p[\alpha]$.
Now, the prime subfield of $F$ is just the "constant" polynomials, i.e. the ones with no $\alpha$'s in them:
$$\text{the prime subfield of }F=\{a_0+0\alpha+\cdots+0\alpha^{n-1}\mid a_0\in\mathbb{F}_p\}$$
and for each divisor $d\mid n$, the unique subfield of $F$ of order $p^d$ is the collection of polynomials in $\alpha$ whose terms are those of exponents that are multiples of $n/d$:
$$\text{the subfield of }F\text{ of order }p^d=\{a_0+a_1\alpha^{n/d}+\cdots+a_{d-1}\alpha^{(d-1)n/d}\mid a_0,a_1,\ldots,a_{d-1}\in\mathbb{F}_p\}$$
(clearly, the above set has cardinality $p^d$, because it takes $d$ elements of $\mathbb{F}_p$ to specify a given element of the above set, namely, each of the coefficients of the powers of $\alpha$. To see that it is a field, remember that $(a+b)^p=a^p+b^p$ in a field of characteristic $p$.)
Answer: There are only few candidates (up to isomorphism) for prime fields: $\mathbb Q$ and $\mathbb Z/p\mathbb Z$ with $p$ prime.
If we assume  that $F$ is finite, we can clearly identify it as the set
$$\{0,1, 1+1,\ldots, \underbrace{1+1+\ldots+1}_{p-1}\}\subseteq F$$
where $p$ is determined by the fact that $\underbrace{1+1+\ldots +1}_p=0$.
If $E$ is a subfield of $F$, then $F$ is also a vector space over $E$.
Especially, if $E$ is the prime field we conclude that $|F|=p^n$, the elements of $F$ can be written as $n$-tuples of elements of $\mathbb Z/p\mathbb Z$, addition is componentwise as expected, but multiplication is not so easy to describe. For example, we can view $GF(8)$ as the set
$(\mathbb Z/2\mathbb Z)^3$ with componentwise addition complicated
$$(a,b,c)+(d,e,f)=(a+d,b+e,c+f) $$
and the somewhat  and arbitrary multiplication
$$(a,b,c)\cdot(d,e,f) = (ad+bf+ce,ae+bd+bf+ce+cf,af+be+cd+cf).$$
You are free to work with this as definition and spend an afternoon verifying the field axioms. But life is really easier if you identify $a,b,c)$ with $a+bX+cX^2$ and consider polynomials in $\mathbb Z/2\mathbb Z[X]$ modulo $x^3+x+1$ and get the field properties for free.
Again, if $E$ is a subfield, then we conclude $|E|=p^m$ for some $m$ as well, and as $F$ is a vector space over $E$, we conclude $p^n$ is a power of $p^m$, i.e. $m$ divides $n$. As $3$ is prime, there are no subfields of $F=GF(2^3)$ other than the prime field and $F$ itself.
One can show that the multiplicative group of $F$ is cyclic (if one works with polynomials, $X$ is an obvious generator) and each subfield $E$ corresponds to a subgroup of this cyclic group, i.e. is generated by some $X^d$ with $d|n$. In the above example $GF(8)$, the multiplicative group has order $7$, hence no nontrivial subgroups, hence we see once again that there are no subfields apart from $F$ and the prime field.
Answer: If you want interesting examples of finite fields and subfields, characteristic 2 offers Grundy numbers, otherwise known as Nimbers, whose arithmetic is explored in JH Conway "On Numbers and Games".
They arise as the values of impartial games, and so as genuine "numbers" rather than constructions by polynomial, and come with arithmetic operations which arise from game-theoretic constructions.


Ajax not working in IE for form post

Question: I have a form that performs dynamic calculations and posts to Pardot simultaneously.  The ajax code works in all browsers except IE.  Is there any reason it won't work in IE?  Here is the code:
$('#greenQuote').submit(function(e){
    e.preventDefault();
    premium();

    var theData = $(this).serialize();

    $.post('http://go.mysite.com/l/34381/2014-05-19/hr8w', theData).success(function(data){
    });
});

I have also added the following code and tested after viewing responses to other similar questions, but have had no luck.  It was placed above the "$.post."
$.ajaxSetup({cache:false})

Comment: What error is being thrown in IE?
Comment: what version of jquery and IE?
Comment: @user3524193 - have you used IE 9's developers tools to see what the response is to the request?
Comment: What happens if you comment out everything except your ajax ($.post) call? Does it work then?
Comment: @dragonslovetacos - then the form would be submitted normally (without ajax) and you'd probably also get an undefined variable error for 'theData'.
Comment: @Joe - I don't see an error in Developer Tools.
Comment: @ps2goat - IE Version 9.  jQuery v1.11.1.
Answer: The following edits were made to the original code.  I have also added an additional script to my page. This code is hosted by CDNJS and can be found at:  http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.2/jquery.xdomainrequest.min.js.
$('#greenQuote').submit(function(e){
    e.preventDefault();
    premium();
    var theData = $(this).serialize();

    //Eliminates "No Transport" Error in ie
    jQuery.support.cors = true;

    $.ajaxSetup({cache:false});

    if('withCredentials' in new XMLHttpRequest())
    {
        //alert("CORS supported (XHR)");
        $.post('http://go.mysite.com/l/34381/2014-05-19/hr8w', theData);
    }
    else if(typeof XDomainRequest !== "undefined")
    {
        //alert("CORS supported (XDR)");
        $.ajax({
            type: 'POST',
            url: 'http://go.mysite.com/l/34381/2014-05-19/hr8w',
            data: theData,
            dataType: 'json'
        });
    }
});

Answer: Not an answer, but wanted to elaborate on my comment.
What happens if you do this...
$('#greenQuote').submit(function(e){
    e.preventDefault();

    $.post('http://go.mysite.com/l/34381/2014-05-19/hr8w', $(this).serialize()).success(function(data){
console.log(data);
    });
});

I only ask, is if the JS is not getting to your ajax request, there might be something in your premium() method that is causing the system to give up.
Comment: No luck. Still the same thing and no errors are showing up in ie dev tools.
Comment: I removed the premium() function and it still did not work.  It is definitely processing the entire code, as I placed a success alert at the very end of the code and received it upon submitting the form.  Also, there are no errors in ie developers tools.  I'm not sure where to go from here.

Ajax not working in IE for form post


Get only property from object has only one property JQuery

Question: How to get only property js object. When I used $('body') it will return sometimes in object form and other times return only a property so how can I perform my task on that property. like..
$('body').html();

// it will return in object
// []
// or sometime it will return only
//
// if it will return in object so i got some error like.

Uncaught TypeError: $(...).html is not a function

How can I make the return property consistent? Because I want to use this in some condition and I can't use it like this if I want to use it every time in object or only one property.
If it returns in object I want to use eq() but I don't know when it return in object form and when it return only property then how can I use eq() because is not use with only property.
Comment: Have you tried my answer?
Answer: sometime means nothing in code. If there is another code that defined $ (which probably what is happen), you can replace the jQuery $ function with something like $j.
var $j = jQuery;

That's how you can be sure that a jQuery object will return, then you can use eq without worry.
For example:
$j('your_selector').eq(0);

Live example

var $j = jQuery;

console.log($j('div').eq(0).html());

Test Text

Comment: i was try this, but i can't use eq() everytime ,because i don't know when it return multiple selector or single. if it return more than one element so can't use other element.
Comment: `eq()` is an example. My point is that now `$j` replace the `$` so you shouldn't worry if any other library use `$` as variable. As I understood it's your problem. Isn't?


Precision with Taylor Expansions

Question: when you take a 1st order taylor expansion of a function, so:
$$f(a) + f'(a)(x-a)$$
does that mean that if the result is only accurate to one decimal place?
so for a value a.bcd, d would be the uncertain value?
Edit: changed from second order to first due to an error that another user pointed out
Answer: Normally, I would see that called a first-order approximation, not a second-order one. It means that as $x \to a$, the error in this approximation goes to 0 more rapidly than $x$ goes to $a$. More precisely:
$$ \lim_{x \to a} \frac{f(x) - \left( f(a) + f'(a) (x-a) \right)}{x - a} = 0 $$
Understanding the error is an important thing to learn in calculus! When you learned Taylor series, you should have also learned formulas for the remainder of a truncated Taylor series.
If $f$ is twice differentiable at $a$, one way to describe the error is similar to that of the mean value theorem:
$$ f(x) = f(a) + f'(a) (x-a) + R(x, a) $$
where
$$ R(x,a) = \frac{1}{2} f''(\xi) (x-a)^2 $$
and $\xi$ is some value between $a$ and $x$. (The precise value of $\xi$, of course, depends on both $x$ and $a$) Commonly, one can find upper bounds on the value of $f''(\xi)$: for example, if $f''(x)$ is an increasing function and $x > a$, you know $f''(a) < f''(\xi) < f''(x)$.
Making use of the remainder term is an important skill when it is important to know how good your approximations are when using Taylor series!
Answer: The error term of an $n$th order Taylor expansion is  $\frac{1}{(n+1)!} f^{(n+1)}(\xi) (x-a)^{n+1}$ for some $a<\xi<x$. Since $\xi$ depends on $a,x,n$; you cannot really tell much about the error in general: can only say things in function-by-function basis.
In real life, what you mostly (i.e. for functions whose $n+1$th derivative is reasonably smooth function) see is that the error after retaining $n$ terms of a Taylor series goes as $a^{n+1}$: i.e. if $a=10^{-2}$, you'll roughly gain 2 decimal places of accuracy by adding one more term in your Taylor series.
Comment: If you know n, a and x and know that a<xi<x, you can estimate the maximim error calculating the error term with xi=x
Answer: Nope, try with $e^x$ with $x=1$...
$$e = 1 + 1 + \frac{1}{2!} + \frac{1}{3!} + ...$$
taking only the first two terms, you get $2 \ne 2.71$
Comment: isn't the proper taylor expansion for e: e + 0 + 0 +....?
Comment: @kjh Well, I mean the expansion for $e^x$ using $x=1$
Comment: then the expansion would still be: e^x + (e^x)(x-a) + ((e^x)(x-a)^2)/(2!) ...wouldn't it?
Comment: so with the first two terms you'd get 1 + e.  it'd still be off, I see what you're getting at.
Comment: @kjh No, not 1+e... look at the last example here: http://en.wikipedia.org/wiki/Taylor_series#Examples

Precision with Taylor Expansions


Does the group of rationals under addition have a basis?

Question: I'm trying to determine whether $\mathbb Q$ under addition has a basis. My naive idea, based on what I have covered so far, would be to try and show that if we assume $\mathbb Q$ has a basis then it would be finitely generated which I believe would then lead to a contradiction. But I don't think this is a valid approach and I'm not sure what other approaches I could take.
I'd appreciate some ideas/approaches about determining whether $\mathbb Q$ has a basis or not :)
Comment: As a Z-module its not free (has no basis) as demonstrated by the link.
Comment: What do you mean by a "basis" in this context?  That's not normally a group theoretic concept.  If you are thinking of $\mathbb Q$ as a vector space over itself, then of course it has a basis (any non zero element).
Comment: As a Z-module ?
Comment: A vector space is defined over a scalar field.
Comment: It seems like [this](https://math.stackexchange.com/q/1390737/28900) may be what you're trying to do.
Comment: I am talking about a basis in the same sense that every finitely generated abelian group has a basis. I believe what @CameronBuie is referring to.
Comment: But as you remark, $\mathbb Q$ is not finitely generated.
Comment: Not even *two* nonzero elements of $\mathbb Q$ can be linearly independent over $\mathbb Z$: take $p/q, r/s\in\mathbb Q\setminus\{0\}$, then $rq(p/q)-ps(r/s)=0$, with $rq, ps\in\mathbb Z\setminus\{0\}$. Thus, whatever set you come up with, it won't be a base.
Comment: @lulu  Yes, I just mean a basis in the sense that there is a set $\{x_i\}_{i \in I}$ generating the group $Q$ where the elements are linearly independent with coefficients from $\mathbb Z$. I am not sure if this relates to modules since I have not covered them yet.
Comment: @Hai: it's not true that every finitely generated abelian group has a basis. The ones that do are exactly the free (equivalently, torsion-free) ones. $\mathbb{Q}$ does not have a basis either: it's not generated by one element but any two elements are linearly dependent.
Answer: You haven't defined what a "basis" is.
Here's, however, a statement showing that $\mathbf{Q}$ is far to having a basis as abelian group for any reasonable notion of basis as group:

For every generating subset $S$ of $\mathbf{Q}$, for every finite subset $F$ of $S$, the subset $S-F$ generates $\mathbf{Q}$.

(I assume that a basis would at least have the property that it's a generating subset in which no element is redundant; the above shows it can't exist.)
The claim is true: indeed, the quotient $H=\langle S\rangle/\langle S-F\rangle$ is a finitely generated quotient of $\mathbf{Q}$. Hence, if nonzero, it admits for some prime $p$ a cyclic group $C_p$ of order $p$ as quotient. But since $p\mathbf{Q}=\mathbf{Q}$, it cannot admit $C_p$ as quotient, so $H=0$, that is, $\langle S-F\rangle=\langle S\rangle$.


tinyxml2 load xml errorID 10

Question: I'm working on a project in C++ using tinyxml2.
I have an issue with the xml parsing , I get an errorID 10 and the error message is "XML_ERROR_PARSING_TEXT" when the file is loaded.
This is the following xml in question:
<Game>
  <Window>
    <width>600</width>
    <height>500</height>
    <background>joliBackgroundDeGael.jpg</background>
  </Window>
  <Square>
    <Mario>
      <size>
        <width>30</width>
        <height>15</height>
      </size>
      <speedPerFrame>5</speedPerFrame>

        <stop>stopMario.jpg</stop>
        <run>runMario.jpg</run>
        <jump>jumpMario.jpg</jump>

    </Mario>
  </Square>
</Game>

The xml file is valid in the W3C validator.
So I think the problem is not here, but maybe here :
void parseXML::getDoc()
{
    this->doc.LoadFile(this->path);
    if (this->doc.ErrorID() != 0)
    {
        printf("load file=[%s] failed\n", this->doc.GetErrorStr1());
        printf("load file=[%s] failed\n", this->doc.GetErrorStr2());
    }
}

When I look in the LoadFile function with a breakpoint, I see that the load file is the same as below.
Here the complete code :
#include "caracteristique.h"
#include <iostream>

#include <direct.h>
#define GetCurrentDir _getcwd

using namespace tinyxml2;

const char* parseXML::path = "XMLType.xml";

void parseXML::getDoc()
{
    this->doc.LoadFile(this->path);
    if (this->doc.ErrorID() != 0)
    {
        printf("load file=[%s] failed\n", this->doc.GetErrorStr1());
        printf("load file=[%s] failed\n", this->doc.GetErrorStr2());
    }
}

int parseXML::getWindowHeight()
{
    if (this->doc.Error())
        this->getDoc();

    XMLElement *root = this->doc.RootElement();
    if (!root)
    {
        XMLElement *window = root->FirstChildElement("Window");
        if (!window)
            std::cout <<  window->FirstChildElement("height")->FirstChild()->ToText() << std::endl;
    }
    return 0;
}

An idea ?
Thanks for your help,
Answer: Don't forget that the LoadFile method load AND parse your file. If your file doesn't follow xml standards, the method will fail and return FALSE. You should verify that none of your xml attributes contains special caracters like (,),/,\ for exemple. There's a small example on that page: Tiny XML Parser Example
Here's the exemple with tiny modifications:
#include "tinyxml.h"

#include <iostream>
#include <string>
using namespace std;

void Parcours( TiXmlNode* node, int level = 0 )
{
    cout << string( level*3, ' ' ) << "[" << node->Value() << "]";
    if ( node->ToElement() )
    {
        TiXmlElement* elem = node->ToElement();
        for ( const TiXmlAttribute* attr = elem->FirstAttribute(); attr; attr = attr->Next() )
            cout << " (" << attr->Name() << "=" << attr->Value() << ")";
    }
    cout << "\n";

    for( TiXmlNode* elem = node->FirstChild(); elem; elem = elem->NextSibling() )
        Parcours( elem, level + 1 );
}

int main( int argc, char* argv[] )
{
    TiXmlDocument doc("C:/test.xml" );
    bool loadOkay = doc.LoadFile();
    if ( !loadOkay ) {
        cerr << "Could not load test file. Error='" << doc.ErrorDesc() << "'. Exiting.\n";
        return 1;
    }
    Parcours( doc.RootElement() );
}

You could try it with a xml document like this:
<Parent>
    <Child1 test="program" />
    <Child2>
        <Node number="123456789" />
    </Child2>
    <Child3>
        <Hello World="!!!" />
    </Child3>
</Parent>

I tried it and it worked well, you only have to execute the code passing the name of the file in the first argument.

tinyxml2 load xml errorID 10


How to disable view source option in Chromium Embedded?

Question: Is it possible to disable view source option in Delphi Chromium Embedded ?
I haven't found anything suitable in properties/methods list.
Answer: There are no direct settings or events allowing to hide Chromium popup menu items. However you have at least few options how to continue, you can for instance:
1. Tell user that the View source option is forbidden and decline the action
You can decide what action will you allow or decline in the OnMenuAction event handler, where if you assign True to the Result parameter the action is declined. The following code checks that you have performed the view source action and if so, decline the action and show the information message:
type
  TCefMenuId = TCefHandlerMenuId;

procedure TForm1.Chromium1MenuAction(Sender: TObject;
  const browser: ICefBrowser; menuId: TCefMenuId; out Result: Boolean);
begin
  if menuId = MENU_ID_VIEWSOURCE then
  begin
    Result := True;
    ShowMessage('View page source is not allowed!');
  end;
end;

2. Fake the menu item to something custom by changing menu item's caption with its action
You can take advantage of the menu item for something else by changing the menu item's caption and executing some custom action. The following sample code shows how to change the view source menu item into the about box menu item:
type
  TCefMenuId = TCefHandlerMenuId;

procedure TForm1.Chromium1GetMenuLabel(Sender: TObject;
  const browser: ICefBrowser; menuId: TCefMenuId; var caption: ustring;
  out Result: Boolean);
begin
  if menuId = MENU_ID_VIEWSOURCE then
    caption := 'About my application...';
end;

procedure TForm1.Chromium1MenuAction(Sender: TObject;
  const browser: ICefBrowser; menuId: TCefMenuId; out Result: Boolean);
begin
  if menuId = MENU_ID_VIEWSOURCE then
  begin
    Result := True;
    ShowMessage('About box...!');
  end;
end;

3. Create you own custom page (frame) popup menu
You can create your own popup menu, but you need to consider that this menu is quite hardcoded, so you will need to maintain it if you'll need to have it the same with each new version of Delphi Chromium wrapper. Here is the code how to create the page menu without view source menu item:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Menus, cefvcl, ceflib;

type
  PCefMenuInfo = PCefHandlerMenuInfo;

type
  TForm1 = class(TForm)
    Chromium1: TChromium;
    procedure FormCreate(Sender: TObject);
    procedure Chromium1BeforeMenu(Sender: TObject; const browser: ICefBrowser;
      const menuInfo: PCefMenuInfo; out Result: Boolean);
  private
    PageMenu: TPopupMenu;
    procedure OnNavigateBackMenuItemClick(Sender: TObject);
    procedure OnNavigateForwardMenuItemClick(Sender: TObject);
    procedure OnPrintMenuItemClick(Sender: TObject);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.OnNavigateBackMenuItemClick(Sender: TObject);
begin
  Chromium1.Browser.GoBack;
end;

procedure TForm1.OnNavigateForwardMenuItemClick(Sender: TObject);
begin
  Chromium1.Browser.GoForward;
end;

procedure TForm1.OnPrintMenuItemClick(Sender: TObject);
begin
  Chromium1.Browser.GetFocusedFrame.Print;
end;

procedure TForm1.Chromium1BeforeMenu(Sender: TObject;
  const browser: ICefBrowser; const menuInfo: PCefMenuInfo;
  out Result: Boolean);
begin
  if menuInfo.typeFlags = MENUTYPE_PAGE then
  begin
    Result := True;
    PageMenu.Items[0].Enabled := browser.CanGoBack;
    PageMenu.Items[1].Enabled := browser.CanGoForward;
    PageMenu.Popup(menuInfo^.x, menuInfo^.y);
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  MenuItem: TMenuItem;
begin
  PageMenu := TPopupMenu.Create(Self);
  MenuItem := TMenuItem.Create(PageMenu);
  MenuItem.Caption := 'Back';
  MenuItem.OnClick := OnNavigateBackMenuItemClick;
  PageMenu.Items.Add(MenuItem);
  MenuItem := TMenuItem.Create(PageMenu);
  MenuItem.Caption := 'Forward';
  MenuItem.OnClick := OnNavigateForwardMenuItemClick;
  PageMenu.Items.Add(MenuItem);
  MenuItem := TMenuItem.Create(PageMenu);
  MenuItem.Caption := '-';
  PageMenu.Items.Add(MenuItem);
  MenuItem := TMenuItem.Create(PageMenu);
  MenuItem.Caption := 'Print';
  MenuItem.OnClick := OnPrintMenuItemClick;
  PageMenu.Items.Add(MenuItem);
  Chromium1.Load('www.stackoverflow.com');
end;

end.

Footnote
The type definitions used in all code samples are there because I've noticed that some version of Delphi Chromium has wrong event handler definitions.
Answer: Probably things changed over years, today a direct method exists:
uses
  ceflib;

[..]

implementation

procedure TForm1.Chromium1BeforeContextMenu(Sender: TObject;
  const browser: ICefBrowser; const frame: ICefFrame;
  const params: ICefContextMenuParams; const model: ICefMenuModel);
begin
  //model.Clear;
  model.Remove(Integer(MENU_ID_VIEW_SOURCE));
end;

You can use model.Clear if you want to completely get rid of popup menu.


How to find what caused an AUTO_REPAIR_NODES event in GKE

Question: We've had a whole bunch of AUTO_REPAIR_NODES events suddenly occur on a previously stable GKE cluster, and can't figure out why.
We found this page: https://cloud.google.com/kubernetes-engine/docs/how-to/node-auto-repair#repair_criteria
and the suggested items are:

Node reports NotReady multiple tinmes
Node does not return any status checks multiple times
Node's boot disk is full for too long.

We've checked the logs, and not found any logging messages for NotReady.
We've checked the pods on the suddenly auto-repaired nodes, and they were getting traffic prior to the auto-repair event, and all of them were still returning traffic. So presumably that means that the node itself hasn't lost all connectivity.
We've checked the ephemeral disk usage on all of the nodes, and none of them have gone above 16gb (using the default boot disk size of 100gb, meaning that the ephemeral disk limit is 50gb, so we're definitely still far away)
So basically, we've got no idea what else to check, and also don't know where to check.
Any suggestions from anybody please?
Thank you
Answer: Do you have master logs enabled for your cluster? The controller manager would give you more clear picture.
Another potential cause is webhooks. If they prevent any system pods from being deployed properly, the nodes will end up in a not ready state with the message "CNI plugin not initiated". Therefore, my suggestion would be to check the users defined webhooks scope and remove the kube-system namespace if included.
If you have a controller log available, please paste it here. I can then help you further.


host client script gets empty string response from dockerized server script

Question: I'm running Docker Version 17.06.2-ce-mac27 (19124) on mac osx.
I'm trying to run a simple python server script using socket in a container and a client script in the container host.
It seems like the client script can connect to the port but not trigger the server script.
When I run the client script from outside the container, I get an empty response:

port_test_server$ ./echo_client.py
Received ''

and there is no output from the server script running in the container.
when I run the client script from inside the container I get the expected response

port_test_server$ docker container exec 7c7d1fb7e614 ./echo_client.py
Received 'where there is love there is life'

and the expected output from the server script running in the container:

port_test_server$ docker run -it --expose 8887 -p 8887:8887 ptserver
Connected by ('127.0.0.1', 38694)

So the server script is running in the container, and the client script run from outside the container is connecting to the port, but it seems like the server script is not being trigerred.
Here is the code:
Docker file: (copies echo_client.py and echo_server.py in to workdir)
FROM debian:jessie-slim
ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update && apt-get install -y locales \
    && localedef -i en_US -c -f UTF-8 en_US.UTF-8
ENV LANG en_US.utf8

RUN apt-get update && apt-get install -y libssl-dev libsnappy-dev python python-pip python-dev gcc git curl
RUN easy_install --upgrade pip

RUN mkdir /test_wd
WORKDIR /test_wd
COPY . /test_wd
RUN chmod +x *.py
RUN ls
CMD ./echo_server.py

Server script echo_server.py:
import socket

HOST = localhost  # Hostname to bind
PORT = 8887  # Open non-privileged port 8888

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while 1:
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)
conn.close()

Client script echo_client.py:
import socket

HOST = 'localhost'  # Set the remote host, for testing it is localhost
PORT = 8887  # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('where there is love there is life')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Docker command to run the container:

port_test_server$ docker run -it --expose 8887 -p 8887:8887 ptserver
Answer: One way to solve the issue is to start the container using a host network mode
docker run -it --expose 8887 -p 8887:8887 --network host ptserver

In that case, localhost will resolve to the host machine ip address.
Comment: Not yet had to use the host network myself but that is very handy to know! Ty @yamenk
Comment: Yamenk, Using your suggestion, I get a connection refused error.  Doing docker ps shows the port mapping to be empty, and the port bindings shown using docker inspect shows "8887/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "8887"
                    }
                ]


Without jQuery tell information from external css file or internal stylesheet

Question: I want to use javascript without jQuery or any other JS library to return styles from internal/external styleshet

Comment: If you want to know what styles apply to a given object from either directly applied styles or stylesheet styles, then you can use `getComputedStyle()` as described [here](https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle) in MDN.
Answer: use it like this var es=getStyle(document.getElementById("someId"),"background-color");

function getStyle(Elm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(Elm, "").getPropertyValue(strCssRule);
    }
    else if(Elm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = Elm.currentStyle[strCssRule];
    }
    return strValue;
}


SSL - how to make both http and https work

Question: I have set up a Drupal 6 site on a dedicated server, and enabled SSL through the "Matrix" control panel which was installed on it.
The problem is now, the site ONLY loads pages from https. Most of the images wont load either, I presume this is related to the same thing. Ideally I want both http and https to work, then I can sort out the redirects for pages that need to be secure.
The error presented on attempting to load a regular http page is:

<code>**Bad Request**

Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.
</code>

Can anyone point me in the right direction?

Edit:
In sites-enabled/domainname.co.uk there is a <VirtualHost> set up for the IP of the server, using port 80 like so:
<code><VirtualHost xx.xx.xx.xx:80>
        ServerName xx.co.uk
        ServerAlias www.xx.co.uk
        ServerAdmin firstname.lastname@example.com
        DocumentRoot /home/default/xx.co.uk/user/htdocs
        ErrorLog /home/default/xx.co.uk/user/logfiles/error_log
        TransferLog /home/default/xx.co.uk/user/logfiles/access_log
        php_admin_value open_basedir /tmp:/home/default/xx.co.uk
        SuexecUserGroup xx matrixdomain
        ScriptAlias /cgi-bin/ /home/default/xx.co.uk/user/htdocs/cgi-bin/
        AddHandler server-parsed .shtml
        AddType text/html .shtml
        <Location />
                Options +Includes
        </Location>
# Begin user directives <--
# --> End user directives
</code>
Would I need to make another one for 443?
In ports.conf I have

NameVirtualHost *:80
Listen 80

<IfModule mod_ssl.c>
    # SSL name based virtual hosts are not yet supported, therefore no
    # NameVirtualHost statement here
    Listen 443
</IfModule>
Answer: Seems that your Apache httpd is misconfigured and tries to serve HTTPS on the HTTP port (take a look at your virtual host configuration for the Drupal site) or you are using a scheme like http://example.com:443/ to access your Drupal installation, which will not work either.
Comment: The matrix control panel was doing a horrible job, wiping it out and doing the set up manually fixed the issue.
Comment: In sites-enabled/domainname.co.uk I have a  set up for the IP of the server, using port 80 (e.g. 220.127.116.11:80). Would I need to make another one for 443?
Comment: Yes. And additionally the new VirtualHost has to contain some directives (see http://httpd.apache.org/docs/2.2/ssl/ssl_howto.html) to enable SSL for it.
Answer: HTTP should be served on port 80
HTTPS should be served on port 443
Your site should work on: http://www.domain.com
https://www.domain.com.
It could be one of a few things:

You are manual specifying the port, EG if you visit http://www.domain.com:443/, this would normally fail
The web server is configured incorrectly and is for some reason service SSL content on port 80. This would not normally happen unless there is a bug or something in your control panel. Have you restarted apache?
In the drupal configuration, it is set up that the website URL is "http://www.domain.com:443". This would always forward you to this location even if you type http://www.domain.com in your browser.
You have Drupal Secure Pages installed but is configured incorrectly. If you have it installed, visit https://www.domain.com/admin/build/securepages to configure it.

I think that summarizes what the issue could be, let us know your solution!
Answer: +1 Use the Secure Pages module (if you're not already)
Cheers
Comment: Am using that, but it's one step ahead of where I am now - I need to get the server to work on 80 before I can start picking pages to redirect...
Answer: i thing follow doc will help u

Blockquote

Apache: Redirect http to https Apache secure connection – force HTTPS Connections
Let us say you have webmail sub-domain called http://mail.chida.in and you would like to redirect it to https secure connection i.e. https://mail.chida.in.
This will help you protect user privacy and sensitive information such as username and password remotely.
So how do you configure your Apache web server so that you prevent your web sites from being accessed without encryption?
Redirect http to https Apache Configuration
First make sure Apache is configured for HTTPS connection and necessary SSL certificates are installed.
No non-ssl access i.e. only accept https connections
Now open httpd.conf or .htaccess file (mod_rewrite not required):
vi httpd.conf
Append following line :
Redirect permanent / https://mail.chida.in/
Any request made to http://mail.chida.in will goto https://mail.chida.in/
Save and close the file. Restart the Apache:
/etc/init.d/httpd restart
This is easiest way to ensure that your normal user never use plain text HTTP protocol to send data. Now this makes it much harder to sniff sensitive data.
Force webmail login over SSL https session
So if you want force users to access their webmail through https, add following configuration to .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Make sure you have something as follows in httpd.conf (mod_rewrite support):
LoadModule rewrite_module modules/mod_rewrite.so

Blockquote


Rotate theta=0 on matplotlib polar plot

Question: I have the following example code:
import numpy as np
import matplotlib.pyplot as plt
import random

data_theta = range(10,171,10)

data_theta_rad = []
for i in data_theta:
    data_theta_rad.append(float(i)*np.pi/180.0)

data_r = random.sample(range(70, 90), 17)

print data_theta
print data_r

ax = plt.subplot(111, polar=True)
ax.plot(data_theta_rad, data_r, color='r', linewidth=3)
ax.set_rmax(95)
# ax.set_rmin(70.0)
ax.grid(True)

ax.set_title("Example", va='bottom')
plt.show()

...which produces something like this:

...but I would like to set theta=0 to the 'West'. So something like:

Any ideas how to do this with matplotlib (I made the pic below in powerpoint) ?
Comment: A small side note: `numpy` provides handy functions for angle conversions: `data_theta_rad = np.radians(data_theta)`
Answer: Simply use:
ax.set_theta_zero_location("W")

More info in the documentation of matplotlib.
Comment: i get: AttributeError: 'PolarAxesSubplot' object has no attribute 'set_theta_zero_location'...maybe my module is not up to date???
Comment: Whats version of matplotlib are you using? You might have to update, I'm using 1.3.1 and it works fine.
Comment: i'm a little embarassed to say, but I don't know how to find this out
Answer: A more flexible way:
ax.set_theta_offset(pi)
You can rotate the axis arbitrarily, just replace pi with the angle you want.

Rotate theta=0 on matplotlib polar plot


Condition that a quadratic function may be resolved into two linear factors

Question: If we are given a general quadratic function in $x, y$, there is a condition that it can be resolved into two linear factors of the form $ax+by+c$. I found the following proof for this.
If we have a quadratic function
$$f(x, y) = ax^2 + 2hxy + by^2 + 2gx + 2fy + c$$
To factorize this, it is sufficient to find the roots of the equation:
$$ax^2 + 2hxy + by^2 + 2gx + 2fy + c = 0$$
Considering this to be a quadratic in $x$ and applying the quadratic formula yields
$$x = \frac{-(hy + g) \pm \sqrt{(hy+g)^2 - a(by^2 + 2fy + c)}}{a}$$
$$\implies ax + hy + g = \pm \sqrt{(hy+g)^2 - a(by^2 + 2fy + c)}$$
Now, it is claimed that if $f(x, y)$ is the product of two linear factors the quantity under the square root sign must be a perfect square ie. the expression must be resolvable in to two identical linear factors.
As the expression under the square root is a quadratic in $y$ we can set its discriminant equal to zero and get the condition.
However, why must the expression be a perfect square if the quadratic has two linear factors? I was not able to exactly understand the reason behind it.
If we can write
$$f(x, y) = (px + qy + r)(p'x + q'y + r') = 0$$
Then
$$px + qy + r = 0 \implies ax + hy + g = (a-p)x + (h-q)y + (g-r)$$
which should mean that the quantity under the radical is a perfect square. However, I am not sure if this is the correct reason. Moreover, how do we go the other way, I have proved that if the quadratic is resolvable into two linear factors then the quantity under the square root is a perfect square. How do I prove the converse?
Answer: Going with your last paragraph (with a notation change for readability) suppose $f(x,y)=(px+qy+r)(sx+ty+u).$ Multiplying things out and fitting it into $ax^2 + 2hxy + by^2 + 2gx + 2fy + c$ we have
$$a=ps,\ h=(pt+qs)/2,\ b=qt,\\ g=(pu+rs)/2,\ f=(qu+rt)/2,\ c=ru.$$
Then (with the aid of some algebra software!) it turns out that
$$(hy+g)^2-a(by^2+2fy+c)=(1/4)(rs-pu+(qs-pt)y)^2.$$
So the discriminant under the radical is automatically a square when $f$ factors into two linear terms. (This assumes $a \neq 0$ so we have a genuine quadratic in $x$ at the start.)
I haven't looked yet at going from discriminant a square backwards to the linear factorization. Maybe someone else can do that, but I'll try for something soon.


Java List stream anyMatch returning incorrect result

Question: I have a JPA class 'Project' which has a list of 'Employee' and the getEmployeeList() returns the list of Employees.
public  class Project implements Serializable {

    @ManyToMany(targetEntity=Employee.class)
    private List<Employee> employeeList;

    public List<Employee> getEmployeeList() {
        return this.employeeList;
    }
}

public  class Employee implements Serializable {
    @Basic
    private EmployeeType type;

    public EmployeeType getType() {
        return this.type;
    }
}

public enum EmployeeType implements Serializable{
  EDITOR,
  AUDITOR,
  ADMIN,
  INACTIVE
}

I have an Employee with type 'Auditor' and when I run the following
for(Employee e: p.getEmployeeList()){
     if(e.getType()==EmployeeType.AUDITOR)
         found=true;
 }

it returns true which it should, but when I run
(p.getEmployeeList()).stream().anyMatch((e) -> (e.getType()==EmployeeType.AUDITOR))

it returns false
What am I doing wrong?
Comment: Try tossing a `.peek(System.out::println)` into the stream before your `anyMatch()` to see what's actually being fed in.
Comment: He's comparing enum variables so shouldn't it work like that ? The code seems fine to me even if it has unecessary parenthesis `p.getEmployeeList().stream().anyMatch(e -> e.getType() == EmployeeType.AUDITOR)` is ok too.
Comment: yeah your right.  I'm going to remove the comment.
Comment: Are you sure `p.getEmployeeList()` doesn't return an empty list? If it does, `found` will hold its initial value (which perhaps you initialized to true by mistake) without entering the loop at all, but anyMatch will return false.
Comment: my initial value of `found` is false, and I ran the loop and the anyMatch on the same dataset so it should return the same result.
Comment: `(p.getEmployeeList()).stream().peek(e -> System.out.println(e.getType()))` or `p.getEmployeeList().stream().forEach((Employee e) -> {
                            System.out.println(e.getType());});` does not print anything, but `p.getEmployeeList().size()` prints the correct value. And i just found out `p.getEmployeeList` returns an IndirectList and IndirectList does not have a stream function but i am not getting any error stating the function does not exist.
Comment: but if do `ArrayList employeeList = new ArrayList(p.getEmployeeList());` and call `System.out.println(employeeList.size());` ,
 `employeeList.stream().forEach((Employee e) -> System.out.println(e.getType()));` and

`employeeList.stream().anyMatch(emp-> (emp.getType()==EmployeeType.AUDITOR));//returns true` it returns the correct value.
Comment: using  equals() or equalsIgnoreCase() insted of == could works.
Answer: Solution - change the return type to arraylist
public ArrayList<Employee> getEmployeeList() {
    return new ArrayList<>(this.employeeList);
}

Answer: Update your EclipseLink version, this bug is already fixed!
Bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=433075
Update to version 2.6.0 or higher: http://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink/2.6.0


Erro SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Question: Estou tentando criar uma api na minha aplicação, porém está me retornando o seguinte erro: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Estou utilizando o Zend Framework 3.
<?php header('Content-type: application/json; charset=utf-8');
echo json_encode(array("teste"=>"123"), JSON_UNESCAPED_UNICODE);

Será que alguma configuração do Zend está dando conflito?
Answer: tente assim:
use Zend\Json\Json;
$data = array("teste"=>"123");
echo Json::encode($data);

ou se estiver usando Zend-Diactoros
$data = array("teste"=>"123");
return new JsonResponse($data,200);


How do I properly animate pushing a view controller with a transparent navigation bar and toolbar?

Question: In my app's navigation controller, I want to push a view controller with a clear navigation bar and toolbar. When the first view controller appears again, I want the navigation bar and toolbar to have their default appearances again.
I turned on Slow Animations in the simulator settings so you can see how it looks:

The areas above the navigation bar and underneath the home indicator don't look quite right during the transition because there's nothing there, while the actual navigation bar and toolbar fade out.
Also, when popping the controller, the toolbar appears instantly. This especially looks bad when dismissing it interactively with the swipe back gesture.
I might be able to get it to look good using the new UIBarAppearance classes in iOS 13, but I want to continue to support older versions of iOS.
This is the code I have so far. These methods are inside the detail view controller. Also I don't want to really set the background color to white, but get the default blurred appearance, even in dark mode, but am not sure what to set it back to.
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    func doThings() {
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.backgroundColor = .clear
        navigationController?.navigationBar.barTintColor = .clear

        navigationController?.toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .bottom, barMetrics: .default)
        navigationController?.toolbar.setShadowImage(UIImage(), forToolbarPosition: .bottom)
        navigationController?.toolbar.backgroundColor = .clear
        navigationController?.toolbar.barTintColor = .clear
    }

    guard self.navigationController?.topViewController === self else { return }
    let animationsWereQueuedSuccessfully = self.transitionCoordinator?.animate(alongsideTransition: { [weak self] context in
        guard self != nil else { return }
        doThings()
    }, completion: nil)

    if animationsWereQueuedSuccessfully != true {
        doThings()
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    func doThings() {
        navigationController?.navigationBar.setBackgroundImage(nil, for: UIBarMetrics.default)
        navigationController?.navigationBar.shadowImage = nil
        navigationController?.navigationBar.backgroundColor = .white
        navigationController?.navigationBar.barTintColor = .white

        navigationController?.toolbar.setBackgroundImage(nil, forToolbarPosition: .bottom, barMetrics: .default)
        navigationController?.toolbar.setShadowImage(nil, forToolbarPosition: .bottom)
        navigationController?.toolbar.backgroundColor = .white
        navigationController?.toolbar.barTintColor = .white
    }

    let animationsWereQueuedSuccessfully = self.transitionCoordinator?.animate(alongsideTransition: { [weak self] context in
        guard self != nil else { return }
            doThings()
    }, completion: nil)

    if animationsWereQueuedSuccessfully != true {
        doThings()
    }
}

Answer: I would suggest doing a custom transition. It sounds like you need more power than a default push. Here is a medium article.
https://medium.com/chili-labs/custom-navigation-transitions-f791ff0a46aa


alertmanager filter by tag (timescale backend)

Question: I am using alertmanager configured to read from a timescale db shared with other Prometheus/alertmanager systems.
I would like to set/check alerts only for services including a specific tag, therefore wondering how could I configure prometheus to apply only for specific tags?
This is what currently I am using:
# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets: ['localhost:9093']

remote_write:
  - url: https://promscale.host:9201/write

remote_read:
  - url: https://promscale.host:9201/read
    read_recent: true
...

I found there is an option alert_relabel_configs but is unclear for me the usage of it.
Any ideas?
Answer: FYI, alert_relabel_configs are used for alert relabeling to alerts before they are sent to the Alertmanager
To use alert_relabel_configs below is the example to add a new tag on matching the relabel config set:
   alert_relabel_configs:
    - source_labels: [ log_level ]
      regex: warn
      target_label: severity
      replacement: warn

Note: The alerts are only changed when sent to alertmanager. They are
not changed in the Prometheus UI.
To test the relabel config online you can use https://relabeler.promlabs.com/
If you are using Prometheus Operator configuring alert relabeling rules should be done in additionalAlertRelabelConfigs of PrometheusSpec, more details: https://github.com/prometheus-operator/prometheus-operator/issues/1805


tinymce generated ugly styling output

Question: I've used tinymce for quite a while now (simple setup) and it has been doing quite a nice job getting things styled nicely with the basic styling options - bold, italic, lists and so on. Sometimes though, I guess when users copy-paste their texts to tinymce textbox from word or something styling gets completely ugly, like in this example below. Is there a way to limit the styling to basic ones that refer to the buttons in simple setup?

df

tinymce generated ugly styling output


How to debug whitelisted Chromecast

Question: I have completed Google's form to enable my device to be whitelisted and have been provided with an AppID.
I have followed the procedures outlined here to try and debug the device with no success:
https://developers.google.com/cast/developing_your_receiver#debugging
I am able to ping my device by the IP, but connecting to port 9222 results in failure.  Telnet to that port is also unsuccessful.
Does anyone know why this might not be working?  I must be missing something simple.
Comment: Validate the device serial number, eg. Z can be mistaken for a 2, and O for 0.
Comment: @Gatada very true. I mistook a 6 for an 8
Comment: The link is broken.
Answer: The problem was that my Chromecast device was not sending the serial number to Google.
I was able to get it to work by enabling the sending of the devices serial number in the Windows settings utility (changing this setting in the android app didn't seem to work).  After changing the setting I rebooted the device, and now I can connect on port 9222.  I am not sure why this isn't in the developer walk through... or maybe I missed it?
Comment: Actually it is, I found it here as almost the first thing to do: https://developers.google.com/cast/whitelisting
Comment: When you say you can connect on 9222, does that mean you are connecting via telnet?  I can ping my chromecast, but cant telnet to it, or connect via browser on that port.  I do have the option selected to send the serial number.  Of course I have no way of knowing that the serial number google has on file actually matches.  Wish they had an actual portal to manage devices and appid's for the chromecast.
Comment: Same issue as Anthony's. Can ping to the dongle, can cast a Youtube video via curl, but cannot connect Chrome to port 9222.
Comment: I just want to reiterate...make sure to reboot after updating the settings in the Chromecast app. It seems like the settings save when clicking the done button, but are not applied until a reboot.
Answer: I only got this option when I opened "Options" in the Google Cast Extension inside Chrome and then clicked on the blue icon about a dozen times very quickly.  Suddenly a new option appeared at the bottom where I could enter the hostname of my whitelisted URL:

I also made sure that "send serial number" was enabled in the Chromecast.app (and make sure to reboot!)

Now, I am able to hit port 9222 in a browser and can see my app at http://{my-chromcast-ip}:9222/. I can use dev tools in Chrome to debug, refresh the page, inspect on-screen elements, etc.
Answer: Something else that I haven't seen others mention yet.  If you're going to the right IP and getting the link to remote debugging, but you don't see your source, elements, etc.  It could be blocked by security settings.  This stumped me for a while until I noticed a small shield icon in my url bar.  Click on this and allow it to load sources.  Once I did that everything populated as expected.
Comment: Every time I return to chrome cast development, I forget this one! Everything seems to work, but no logs, elements etc. appear until you do this. Thank you brockoli.
Answer: I struggled a bit with this one. I think some things might have changed with the last firmware update on the Chromecast. I could connect to port 9222 after I did the following:
Registered the custom receiver and host it on the outside of my network (on Google Drive:
https://support.google.com/drive/answer/2881970?hl=en)
Launch the receiver. I used the Chromecast example https://github.com/googlecast/CastHelloText-chrome
Make sure the app ID in chromehellotext.html is the one registered on your account.
When After this, I could connect to the debugging port.
The port is only open when your custom receiver is running on the Chromecast.
I also might be useful to enable debugging on the chrome extension. This will show what's going on between the Chromecast and sender:
https://developers.google.com/cast/docs/chrome_sender
Answer: I realize that this is an ancient question, however my answer might help people searching in the future.
Simply rebooting the Chromecast after having set up my details in the Cast console helped for me.
Answer: You must cast to a custom receiver first (at least once) before trying to access the IP with debug port. Otherwise debugging won't be enabled.

How to debug whitelisted Chromecast


I need to tell if a function is Frechet differentiable

Question: So I have the function $$f(x,y) =\begin{cases}
xy\frac{x^2-y^2}{x^2+y^2} & (x,y) \neq (0,0),\\
0 & (x,y)=(0,0).
\end{cases}$$ I need to tell if the function is Frechet differentiable and why.
I tried to find out something on the internet but I couldn't manage to solve it.
Can you please help me with this?
Answer: Since $f_x(0,0)=fY(0,0)=0$ we have to investigate if
$$g(x,y):= \frac{f(x,y)}{\sqrt{x^2+y^2}} \to 0$$
as $(x,y) \to (0,0).$
An easy eatimation gives
$$|g(x,y)| \le \frac{|xy|}{\sqrt{x^2+y^2}}$$
Since $2|xy| \le x^2+y^2$, we derive
$$|g(x,y) \le \frac{1}{2}\sqrt{x^2+y^2}.$$
Conclusion ?


Excel VBA connectting outlook to create folder in rootfolder

Question: iw ant to create folder in outlook it contains set of accounts but i need to create folder in particualer email account using Excel VBA.
kInldy help me on this.
Comment: Does this answer your question? [Get reference to additional Inbox](https://stackoverflow.com/questions/9076634/get-reference-to-additional-inbox)
Answer: It seems you need to automate Outlook from Excel VBA and create a folder in a profile. The Automating Outlook from a Visual Basic Application article describes all the required steps for that.
If you have got several accounts configured in the Outlook profile you can use the Stores object which represents a set of Store objects representing all the stores available in the current profile. For example:
Sub EnumerateFoldersInStores()
 Dim colStores As Outlook.Stores
 Dim oStore As Outlook.Store
 Dim oRoot As Outlook.Folder

 On Error Resume Next

 Set colStores = Application.Session.Stores

 For Each oStore In colStores
   Set oRoot = oStore.GetRootFolder
   Debug.Print (oRoot.FolderPath)
   EnumerateFolders oRoot
 Next
End Sub

Private Sub EnumerateFolders(ByVal oFolder As Outlook.Folder)
 Dim folders As Outlook.folders
 Dim Folder As Outlook.Folder
 Dim foldercount As Integer

 On Error Resume Next

 Set folders = oFolder.folders
 foldercount = folders.Count
 'Check if there are any folders below oFolder
 If foldercount Then
   For Each Folder In folders
     Debug.Print (Folder.FolderPath)
     EnumerateFolders Folder
   Next
 End If

End Sub

A profile defines one or more email accounts, and each email account is associated with a server of a specific type. For an Exchange server, a store can be on the server, in an Exchange Public folder, or in a local Personal Folders File (.pst) or Offline Folder File (.ost). For a POP3, IMAP, or HTTP email server, a store is a .pst file.
You can use the Stores and Store objects to enumerate all folders and search folders on all stores in the current session. Since getting the root folder or search folders in a store requires the store to be open and opening a store imposes an overhead on performance, you can check the Store.IsOpen property before you decide to pursue the operation.
Once the Store object is found, you can use the GetDefaultFolder or GetRootFolder of the Store class to find the folder where a new folder should be created.
Finally, you may find the Storing Outlook Items page helpful.
Comment: HI thank you for you replay,
Comment: actually i m using below code but dont know how to add default folder for particular account, kindly help me regarding that.
Comment: You can iterate over accounts in Outlook by using the `Namespace.Accounts` property. The [Account.DeliveryStore](https://learn.microsoft.com/en-us/office/vba/api/outlook.account.deliverystore) property returns a `Store` object that represents the default delivery store for the account.


Is there an association between the work status of the college students and the challenges facing them?

Question: So I am supposed to do a study about the online learning obstacles. now the research question is as stated as follows:"Is there an association between the work status of the college students and the challenges facing them? in other words, Are the two categorical variables in this case dependent?". I have 2 questions the first one is related to work status with 3 options( full time-worker. part time worker, no work) and the second one is the obstacles with 4 options ( Electricity, Environmental Distraction, job responsibilities and technical issues). So i did the survey and sent it to 50 participants as requested. the data is categorical so i need to use chi square in order to check for the association however when i tabulated the results as in the attachment below,
So when I obviously I cannot use the chi square test because there are many cells with expected frequencies less than 5. thus I cannot use the chi square and i was not allowed to increase the number of responses so I would get higher expected values .( N=50 is allowed only)
Therefore what test shall I do and how?
Additionally it was stated that "Collecting numeric data and limiting the amount of data makes analysis at this level easier. Your hypothesis has a direct result on what kinds of data will be collected. We can only analyze data that can be summarized with either a mean or a proportion" what does that mean and what hypothesis shall I put.
thank you in advance and I am sorry for the many questions but I am still at the entry level of statistics.
Comment: [See Frank's answer here](https://stats.stackexchange.com/questions/14226/given-the-power-of-computers-these-days-is-there-ever-a-reason-to-do-a-chi-squa).  If you apply a correction to the test statistic, you can perform a chi-square test which has accurate p values eben when the expected cells are below 5.
Answer: In this response by Frank Harrell on the subject on Chi Square tests.  His recommendation is to adjust the test statistic in these cases by a factor of $(n-1)/n$.
In your case, the classic chi square test statistic is 21.68.  The adjustment is to multiply by 49/50, yielding 21.24 (a very minor correction indeed).  The p value for such a test on 6 degrees of freedom is 0.00165.
The data you've collected do not support the null hypothesis of no relation between job status and challenge faced.
Comment: Can you copy that link here?
Comment: @kjetilbhalvorsen Done
Answer: In the version of chisq.test in R, there is an option
to use sparse data to simulate an approximate P-value:
e = c(1,2,8)
d = c(3,2,7)
j = c(12,1,0)
t = c(4,2,8)
TBL = rbind(e,d,j,t)
TBL
  [,1] [,2] [,3]
e    1    2    8
d    3    2    7
j   12    1    0
t    4    2    8

chisq.test(TBL, sim=T)

        Pearson's Chi-squared test with simulated p-value
        (based on 2000 replicates)

data:  TBL
X-squared = 21.683, df = NA, p-value = 0.0009995

So you can reject the null hypothesis that the the two categorical
variables are independent at the 1% level of significance.
Comparing your observed counts with expected counts based on the null
hypothesis, it seems that the largest discrepancies are in the row
for 'Job responsibilities'.
You could 'collapse' the table by combining the remaining levels
of that categorical variable to 'other' and applying chisq.test to
the resulting $2 \times 3$ table. Even if the original test had needed
no help from simulation to give a highly significant P-value, it seems
worthwhile knowing that the 'Job' row is significantly different from
the others:
k = e + d + t      # collapsing
TBL.2 = rbind(k,j)
TBL.2
  [,1] [,2] [,3]
k    8    6   23
j   12    1    0
chisq.test(TBL.2)

         Pearson's Chi-squared test

data:  TBL.2
X-squared = 20.597, df = 2, p-value = 3.368e-05

Warning message:
In chisq.test(TBL.2) : Chi-squared approximation may be incorrect

Even the collapsed table gives one 'expected' count that is too small
according to the usual rules, but some statisticians would be willing
to overlook one small expected count when the other five are sufficiently
large.
chisq.test(TBL.2)$exp
  [,1] [,2]  [,3]
k 14.8 5.18 17.02
j  5.2 1.82  5.98

And, of course, in a formal report, you could mention that the simulated
version of this 'job vs. other' test shows a very small P-value.
chisq.test(TBL.2, sim=T)$p.val
[1] 0.0004997501

Notes:
(1) As you mention, this study was poorly designed. With only 50 subjects spread
across 12 cells of the original table, it doesn't take a genius to
guess that there will be some very small observed and (hence) expected counts.
(2) My personal opinion would be not to trust Campbell's 'correction' (suggested by Harrell) of the test statistic with data as sparse as yours. (Half of your expected counts are below $5.)$
I would reserve that approximation for a situation with only relatively few
'too-small' expected counts.
(3) It is worth mentioning that Fisher's Exact Test would give
a small P-value for your data. Again here, my personal preference is to reserve Fisher's test for $2 \times 2$ tables, where the rationale for its use is clear and easy to explain.
fisher.test(TBL)

        Fisher's Exact Test for Count Data

data:  TBL
p-value = 0.0002082
alternative hypothesis: two.sided

Comment: thank you for you guidance but there is a small detail i forgot to mention and I am sorry for that. we should test it at alfa=0.05 so this might differ right?
Comment: also where can I generate this fisher test? in other words, where are these codes written?
Comment: My version uses R. Other statistical software programs have it also. If the P-value is less than 0.05 (as above), then you can reject at level $\alpha = 5\%.$
Comment: so what statistical software do you use and is it free to download so i can try it myself?
Comment: As mentioned, everything in the Ans is computed using R, which is free to download for Windows, Mac, Unix.// Many help pages online; some reliable. `r-project.org`.
Answer: The chi squared test is actually just an approximation of Fisher's exact test, and the difference is negligible for large enough sample sizes. With smaller samples sizes where the approximation does not hold as well, just use Fisher's test. The only reason it's not more widely applied is because it's computationally expensive to do so, but that's not an issue with small sample sizes.
Answer: so can we say that the 2 categorical variables are associated , (dependent) since the p value=0.001 of fisher's exact test is less than 0.05?
.


On classical guitar, I press one string and it affects the adjacent open string that is needed for the chord or apreggio

Question: I want to fret one string and use the adjacent string as an open string, but there is no way on earth that my finger can NOT touch the open string. I think I'm a pretty normal adult.
I've seen people discuss this from every point of view and it is always (that I can find) about fretting one string nicely (trimming nails, posture, position, etc.) and never about not touching the adjacent string which needs to be open. I don't have a problem fretting, or intentionally muting the adjacent string. The problem is that I always touch the adjacent open string. Just take any finger and fret any string (pressing straight down) and tell you can do it without touching the adjacent string.
I'm using a classical, which has a wider neck. I have not had it setup, but it seems pretty good in that respect. It's not expensive but the neck is straight, the frets are flat and even. What else can I look at? I'm not taking lessons due to Covid and an answer of "lessons will sort this out" is fine.
(I'm new here and any comments on style are welcome.)
This seems like the answer:  https://www.theguitarlesson.com/guitar-lesson-blog/beginner-guitar-lessons/help-fat-fingers-muting-guitar-strings/
EDIT: It is the answer. All other answers I have seen just say "keep practising and you'll get it", but none of them say how you can "get it" when a single finger cannot physically fit on a fret without interfering with an adjacent open string. The linked article talks about that and makes it clear the answer is "keep practising" but also says why.
Comment: This is really just a matter of technique and practice. There's no secret and no short cut. And you're not unusual in having this trouble.
Comment: There are three answers to this question -- where you initially posted -- perhaps you could better explain why those aren't sufficient for what you're asking...?
Comment: If possible, a picture will help to reveal the exact problem.
Comment: Re 2: The link did provide an answer but I do not know if it is correct, so I'm hoping to get some answers either way - yes, I will get better, or no, I have a problem that no one else has. Thx
Comment: Re 1: No, I saw that one and the answers are not on point for the question, which, yes, is the same as mine. Thx
Comment: Thanks. (Can I point out this is the answer somehow?)
Comment: With regard to "fat fingers", the famous Andrés Segovia had the shortest, fattest fingers I've ever seen on a guitarist. They have been likened to a bunch of bananas by some!  An exaggeration but you can see the difference between him and John Williams https://static-secure.guim.co.uk/sys-images/Travel/Pix/pictures/2012/10/13/1350124720182/Williams-and-Segovia-010.jpg
Comment: It would have helped if you post a pic of your hand on the guitar as you play.  None of us can judge how large you fingers are relative to the guitar or even if you are playing correctly.  Your edit suggests that the link IS THE ANSWER and the the rest of us are not helping by saying practice.  But you are not giving us the data we need to help.
Comment: (Excuse my lack of experience.) What I was after was what most people said - practice will resolve this - but I really wanted to also know how it's possible that practice can resolve something that seems so physically impossible. So I understand that you *can* work your fingertips and technique to find a way around this. Of possible interest to others, I stumbled on one fix already - for the Am chord, I move finger 1 (string 2) up towards string 3 in order not to touch open string 1. It doesn't matter if I touch string 3 since it's beyond where I'm fretting string 3. Cool!!
Answer: It's all about proper posture & technique. Practice is important, but only if you practice the right thing. Here is quick summary

Most important: wrist position. Shove out the wrist as far away from as possible and make
sure the wrist is bent inwards as far as you can and then some more. The palm of your hand should be above the fret board as much as possible and NOT below the neck.  Initially, that's NOT a comfortable position so some stretching can help and it needs practice.
The whole idea here is that the finger tip comes directly from the top and is angled 90 degrees to the fretboard. Any other angle will make you touch the other strings. And yes, the nails on your fretting hand must be super short, otherwise, they get in the way and will angle the finger tip.
Correct guitar position: higher is generally  better. Angling the
neck upwards can also help. Note that there isn't a single best neck
angle, so being able to manipulate this while you are playing is
helpful to. All of this is in support of #1: proper wrist position & finger tip angle.

Here is the tricky part: You should ALWAYS control what you are doing with the "other" strings. Open strings will ring and accidentally touching an unfretted string can make unwanted noises. In most cases you WANT them actively muted, but sometimes it's nice to pick up the resonance of an open string to enrich a cord or fretted note and sometimes you must have it unmuted since you will be plucking the open string.
So you need to build a "vocabulary" of fretting techniques that controls not only what you fret, but also what you don't fret. The same three fretted notes can sound quite differently depending on what you do with the unused strings, which also means you need more than one way to play this.
Answer: Without a picture, I'll try to narrow things down.
Start with the position of the guitar. The lower the whole guitar is against your body, the worse the problem will become. Sitting or standing, to alleviate your problem, hold it as high as possible. That means your hand can wrap under the neck more easily.
If it's on a strap, it is where it is. Sitting, move it left and right until your whole arm is away from your own body. Tilting the neck upwards will often help. And don't turn the guitar so you can see the fretboard better! That only exacerbates your problem.
Fingers: usually, especially in your scenario, the fingertips are what press the strings against the fingerboard. Not the pads (fingerprints). Nails don't need to be cut right back, as long as they don't get in the way. 1 or 2 mm is fine. Always press the strings as close to the fretwire as possible. That means not pressing as hard - and may be your problem. The harder you press, the more the finger squashes out - onto adjacent strings.
When possible, use the smallest fingers. For example, on an open A chord, middle, ring and pinky take up less room than index, middle and ring.On fretting a single note, same applies, on the proviso the finger used is practical.
Goes without saying that someone (a teacher?) watching what you, do will solve the problem much better, and you could do as I do, have a Zoom or Whatsapp lesson safely. And practising carefully and slowly getting each finger in place will always benefit. It may also be an idea to use, on particular chords, one finger for two strings, two fingers for three strings. I often, on a barre A shape, use one finger on three strings - without getting in the way of the other barred strings. Not easy initially, but works well eventually.
Comment: Thanks for this. It answers my question too, but I selected another because I thought it added a little more info that I was looking for. This is my first post here and I don't want to insult anyone by not acknowledging their time and help. Thanks!
Answer: It's impossible to judge without seeing the guitar, but maybe your action is way too high. The further your string needs to move to contact the fret, the deeper your finger needs to go beneath the plane of your open strings, and the more difficult it then becomes to avoid touching those open strings. Take it in for an inspection by a luthier, and leave it with them for any adjustments that they might prescribe.
Comment: Thanks for this comment about the action height. I will get that checked as soon as I can. Before that, while in lock-down, I am trying to round up a good mm ruler that I understand can be used for a rough evaluation.
Answer: Maybe you have unusually large fingers.  So choose a guitar that has a wider fret-board.   But guitarists come in all sorts of shapes and sizes, most of them get around this problem, either by technique or by adjusting the action of the guitar.
You have a classical guitar and say it seems set up well enough.  99% certain it's a technique problem then.   You may not be able to get to a teacher but there are pictures, videos, Zoom...     You could start by adding a brief video of you playing to the question.
Answer: Many classical guitarists fret the strings on part of the finger tip that is closer to the nail.  My father did this and developed calluses that sloped back from the tip towards the nail.  This is a little extreme but his playing was exceptional in his youth.  I tend to be right on the tip and I only go a little off in extreme cases, but not as a regular practice.  I have what I call "finger nipples", please pardon the risque terminology.  But the pad of my fingers really point out and can easily touch the vibrating strings.  You may not want to hear it but the other answers are on point by saying it's a matter of posture and practice.  It takes time and won't happen instantly, but you will find your way around the instrument and these issues tend to work themselves out in time.
Comment: Thank you for your answer. (And nipples are not risqué to me. Just a part of the body. :)


Unable to alter column name for a Hudi table in AWS

Question: I'm unable to alter the column name of Hudi table .
spark.sql("ALTER TABLE customer_db.customer RENAME COLUMN subid TO subidentifier") unbable to change the column name.
A clear and concise description of the problem.
I'm unable to alter the column name of Hudi table .
spark.sql("ALTER TABLE customer_db.customer RENAME COLUMN subid TO subidentifier") code is unable to change the column name.
Getting the following error when trying to change the column using above code:
RENAME COLUMN is only supported with v2 tables
To Reproduce
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.util.{GlueArgParser, Job}
import org.apache.hudi.DataSourceWriteOptions
import org.apache.spark.sql.functions._
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}
import org.apache.spark.{SparkConf, SparkContext}

import scala.collection.JavaConverters._
import scala.collection.mutable

object ReportingJob {

  var spark: SparkSession = _
  var glueContext: GlueContext = _

  def main(inputParams: Array[String]): Unit = {

    val args: Map[String, String] = GlueArgParser.getResolvedOptions(inputParams, Seq("JOB_NAME").toArray)
    val sysArgs: mutable.Map[String, String] = scala.collection.mutable.Map(args.toSeq: _*)

    implicit val glueContext: GlueContext = init(sysArgs)
    implicit val spark: SparkSession = glueContext.getSparkSession

    import spark.implicits._

val partitionColumnName: String = "id"
    val hudiTableName: String = "Customer"
    val preCombineKey: String = "id"
    val recordKey = "id"
    val basePath= "s3://aws-amazon-uk/customer/production/"

   val df= Seq((123,"1","seq1"),(124,"0","seq2")).toDF("id","subid","subseq")

      val hudiCommonOptions: Map[String, String] = Map(
        "hoodie.table.name" -> hudiTableName,
        "hoodie.datasource.write.keygenerator.class" -> "org.apache.hudi.keygen.ComplexKeyGenerator",
        "hoodie.datasource.write.precombine.field" -> preCombineKey,
        "hoodie.datasource.write.recordkey.field" -> recordKey,
        "hoodie.datasource.write.operation" -> "bulk_insert",
        //"hoodie.datasource.write.operation" -> "upsert",
        "hoodie.datasource.write.row.writer.enable" -> "true",
        "hoodie.datasource.write.reconcile.schema" -> "true",
        "hoodie.datasource.write.partitionpath.field" -> partitionColumnName,
        "hoodie.datasource.write.hive_style_partitioning" -> "true",
        // "hoodie.bulkinsert.shuffle.parallelism" -> "2000",
        //  "hoodie.upsert.shuffle.parallelism" -> "400",
        "hoodie.datasource.hive_sync.enable" -> "true",
        "hoodie.datasource.hive_sync.table" -> hudiTableName,
        "hoodie.datasource.hive_sync.database" -> "customer_db",
        "hoodie.datasource.hive_sync.partition_fields" -> partitionColumnName,
        "hoodie.datasource.hive_sync.partition_extractor_class" -> "org.apache.hudi.hive.MultiPartKeysValueExtractor",
        "hoodie.datasource.hive_sync.use_jdbc" -> "false",
        "hoodie.combine.before.upsert" -> "true",
        "hoodie.avro.schema.external.transformation" -> "true",
        "hoodie.schema.on.read.enable" -> "true",
        "hoodie.datasource.write.schema.allow.auto.evolution.column.drop" -> "true",
        "hoodie.index.type" -> "BLOOM",
        "spark.hadoop.parquet.avro.write-old-list-structure" -> "false",
        DataSourceWriteOptions.TABLE_TYPE.key() -> "COPY_ON_WRITE"
      )

      df.write.format("org.apache.hudi")
        .options(hudiCommonOptions)
        .mode(SaveMode.Overwrite)
        .save(basePath+hudiTableName)

        spark.sql("ALTER TABLE customer_db.customer RENAME COLUMN subid TO subidentifier")
  commit()
  }

  def commit(): Unit = {
    Job.commit()
  }

  def init(sysArgs: mutable.Map[String, String]): GlueContext = {

    val conf = new SparkConf()

    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    conf.set("spark.sql.legacy.parquet.int96RebaseModeInRead", "CORRECTED")
    conf.set("spark.sql.legacy.parquet.int96RebaseModeInWrite", "CORRECTED")
    conf.set("spark.sql.legacy.parquet.datetimeRebaseModeInRead", "CORRECTED")
    conf.set("spark.sql.legacy.parquet.datetimeRebaseModeInWrite", "CORRECTED")
    conf.set("spark.sql.avro.datetimeRebaseModeInRead", "CORRECTED")
    val sparkContext = new SparkContext(conf)
    glueContext = new GlueContext(sparkContext)
    Job.init(sysArgs("JOB_NAME"), glueContext, sysArgs.asJava)
    glueContext

  }
}

Steps to reproduce the behavior:

I'm using AWS glue job to run the above job.
In Dependent JARs path
hudi-spark3-bundle_2.12-0.12.1
calcite-core-1.16.0
libfb303-0.9.3
Run the above code.

Expected behavior
spark.sql("ALTER TABLE customer_db.customer RENAME COLUMN subid TO subidentifier") should be able to rename a column name. Could you suggest any other way to rename the Hudi column name.
A clear and concise description of what you expected to happen.
Change Column name of a hudi table
Environment Description

Hudi version : 0.12.1

Spark version :3.3

Glue Version : 4
Jars used:
hudi-spark3-bundle_2.12-0.12.1
calcite-core-1.16.0
libfb303-0.9.3

Storage (HDFS/S3/GCS..) :S3

Running on Docker? (yes/no) : no

Additional context
Add any other context about the problem here.
Stacktrace
Exception in User Class: org.apache.spark.sql.AnalysisException : RENAME COLUMN is only supported with v2 tables.
at org.apache.spark.sql.errors.QueryCompilationErrors$.operationOnlySupportedWithV2TableError(QueryCompilationErrors.scala:506) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.analysis.ResolveSessionCatalog$$anonfun$apply$1.applyOrElse(ResolveSessionCatalog.scala:94) ~[spark-sql_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.analysis.ResolveSessionCatalog$$anonfun$apply$1.applyOrElse(ResolveSessionCatalog.scala:49) ~[spark-sql_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.$anonfun$resolveOperatorsUpWithPruning$3(AnalysisHelper.scala:138) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:177) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.$anonfun$resolveOperatorsUpWithPruning$1(AnalysisHelper.scala:138) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper$.allowInvokingTransformsInAnalyzer(AnalysisHelper.scala:323) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.resolveOperatorsUpWithPruning(AnalysisHelper.scala:134) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.resolveOperatorsUpWithPruning$(AnalysisHelper.scala:130) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.resolveOperatorsUpWithPruning(LogicalPlan.scala:30) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.resolveOperatorsUp(AnalysisHelper.scala:111) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.resolveOperatorsUp$(AnalysisHelper.scala:110) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.resolveOperatorsUp(LogicalPlan.scala:30) ~[spark-catalyst_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.analysis.ResolveSessionCatalog.apply(ResolveSessionCatalog.scala:49) ~[spark-sql_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
at org.apache.spark.sql.catalyst.analysis.ResolveSessionCatalog.apply(ResolveSessionCatalog.scala:43) ~[spark-sql_2.12-3.3.0-amzn-1.jar:3.3.0-amzn-1]
Answer: I see you did't set spark.sql.catalog.spark_catalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog in your spark conf. This is needed to use relation V2, and benefit from the schema evolution feature.
Comment: Adding the below config helped me alter the column.  conf.set("spark.sql.catalog.spark_catalog","org.apache.spark.sql.hudi.catalog.HoodieCatalog")
conf.set("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension") plus this code spark.sql("set hoodie.schema.on.read.enable=true")
spark.sql("ALTER TABLE customer_db.customer RENAME COLUMN subid TO subidentifier") . The issue is resolved thanks.
Answer: So a few things:

As you are using Glue 4.0, you don't really need to add any external hudi jars. It supports Hudi version 0.12.1
Also most importantly, to enable hudi you actually need to add a Glue job parameter --datalake-formats with value hudi
You need to set spark.serializer=org.apache.spark.serializer.KyroSerializer and spark.sql.hive.convertMetastoreParquet=false, these parameters help Spark to handle Hudi tables correctly and these configurations can be set in SparkConf when you are initializing a SparkSession or can add these as job parameters in --conf with value spark.serializer=org.apache.spark.serializer.KyroSerializer --conf spark.sql.hive.convertMetastoreParquet=false

Also, you can get all these details from Glue documentation.
Comment: thank you for the suggestion, I'm aware of the datalake-format hudi option , my issue has been resolved by adding the config mentioned above in parsini answer.


Como inserir legenda em um gráfico linear com 3 vetores no eixo Y?

Question: x=['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
y=[]
z=[]
w=[]
for i in range (0,12,1):
    soma=np.sum(mprod[:,i])
    y.append(int(soma))
for j in range (0,12,1):
    estoque=np.sum(resultado[:,j])
    w.append(int(estoque))
for k in range (0,12,1):
    vendas=np.sum(totvendas[:,k])
    z.append(int(vendas))
plt.plot(x,y,'ro-',x,z,'go-',x,w,'bo-')
plt.title("Produção x Vendas x Estoque")
plt.grid(True)
plt.legend()
plt.xlabel("Mêses")
plt.show()

Comment: Qual é a saída que espera obter? Tem como colocar um exemplo?
Answer: troca
plt.plot(x,y,'ro-',x,z,'go-',x,w,'bo-')

por
plt.plot(x,y, 'ro-', label='y')
plt.plot(x,z, 'go-', label='z')
plt.plot(x,w, 'bo-', label='w')


How to read this math equation? $\sum_{i=0}^{n-2}(n-1-i)$

Question: I stumbled upon this in a book and am uncertain how to read it. This is in the context of describing run-time complexity of a computer algorithm.

$$\sum_{i=0}^{n-2}(n-1-i)$$
Answer: The symbol
$$
\sum
$$
means "sum". So this is a compact way of writing a long sum (addition) of a bunch of things. The sum has an index variable which starts somewhere and ends somewhere. For example,
$$
\sum_{i=1}^5
$$
means, start at $i=1$, and end at $i=5$, and add up all the terms.
Now for the full notation, with some examples:
$$
\sum_{i=1}^5 (i + 1)
$$
means the sum of five things, $(i+1)$ where $i$ starts at $1$ and goes up to $5$. So it's equal to
$$
(1 + 1) + (2 + 1) + (3 + 1) + (4 + 1) + (5 + 1).
$$
That evaluates to $2 + 3 + 4 + 5 + 6 = 20$.
Now we can do your example:
$$
\sum_{i=0}^{n-2}(n-1-i)
$$
This says to start at $i=0$, and end at $i = n-2$, and add up $n-1-i$. So it equals
$$
(n-1-0) + (n-1-1) + (n-1-2) + (n-1-3) + \cdots + (n-1-(n-3)) + (n-1-(n-2)).
$$
For example, if $n = 5$, then we get
$$
\sum_{i=0}^{3}(4-i) =
(4-0) + (4-1) + (4-2) + (4-3) = 4 + 3 + 2 + 1 = 10.
$$
Comment: Thank you. Is there a specific topic I could study more in depth to understand this more in-depth? I vaguely remember seeing it in Statistics but that was many moons ago
Comment: @TaylorClark The best place to start would be a discrete math textbook or class. I don't have a specific recommendation, but something like "introduction to discrete math for computer scientists" should turn up useful classes and resources.
Comment: @TaylorClark [This Wikipedia article](https://en.wikipedia.org/wiki/Summation) discusses summation notation and list many of the common identities. Since summation notation is just a short hand for repeated addition, you can treat it just as you would a series of terms. Associativity, distribution of multiplication, etc, all still hold.
Answer: Assuming that you are familiar with summation notation, the expression that you provided is to be interpreted as follows:
\begin{align}
\sum_{i=0}^{n-2} \left( n - 1 - i \right) &= (n-1-0) + (n-1-1) + (n-1-2) + \cdots + (n-1-(n-3)) + (n-1-(n-2)) \\
&= (n-1) + (n-2) + \cdots + (2) + (1)
\end{align}
This sum can be expressed slightly more succinctly by
$$
\sum_{i=0}^{n-2} \left( n - (i+1) \right) = \sum_{i=1}^{n-1} \left( n - i \right) = \sum_{i=1}^{n-1} i  = \frac{n(n-1)}{2}
$$
Note that $n$ is an unbounded or "free" variable defined by the context of the expression.


On accessing External applications such as Device Gallery and getting back to my application OnCreate() is called again

Question: I'm trying to create an application where there is a need of uploading images from my mobile. In this case, when I open my Gallery and choose a image and come back to my application, onCreate() is called again due to which the TextView, EditText and the booleans which I've used earlier are cleared.
I don't want this to happen, I want all the values to remain same and when I come back from Device Gallery to my own application. Can you please help me solving this issue?
Comment: how are you launching the gallery? I mean, with which Intent's FLAGS?
Answer:
In this case, when I open my Gallery and choose a image and come back to my application, onCreate() is called again due to which the TextView, EditText and the booleans which I've used earlier are cleared.

Presumably, your process was terminated while your app was not in the foreground. This happens quite a bit in Android. While it is a bit unusual for it to happen when launching a gallery-style app, it is not out of the question, particularly on devices with limited RAM.
Activities will be destroyed and re-created in other situations as well, such as the default behavior on a configuration change (e.g., rotating the screen, changing the language, putting the device into a dedicated car dock).
Use onSaveInstanceState() to save state information for these sorts of short-term scenarios.