What chord is "A7+4"?

Question: That's how it's notated and I think it's a really unusual notation.  Could that be a synonymous notation for "A7sus4"?

The key signature is E-flat.
Comment: Is this from printed music? If yes, it would help to see the chord/measure before and after. (Including any accompanying music notation, if present.)
Comment: Perfect. Knowing the song as well is immensely helpful!
Comment: Thank you!  Added a screen shot for context - it didn't occur to me how useful it would be.
Comment: This is a lead sheet. You can interpret that chord however you want, as long as you're happy with the result and you're in agreement with the rest of your band.
Comment: @Tim I don't think I'd want to be in a band where the members can't even agree on the changes.
Comment: Thanks, @PiedPiper, for adding the key signature (which isn't even shown in the image and which I also didn't think to provide!)
Comment: @PiedPiper - point is, because the 'chord' is so contentious, there'll probably be no concensus!
Comment: @PiedPiper - who would? But faced with an odd chord name like this, there'd be at least some disagreement as to what should be played - mainly as it's not an acccurate chord name!
Answer: This answer assumes that 7#11 chords are equivalent to 7b5 chords, and it uses the two symbols interchangeably. I acknowledge that there are in fact some pedantic differences between the two, but for the purposes of this answer, those differences are unimportant.
I am also working under the assumption that the perfect fifth of the chord is always going to be omitted from a 7#11 chord, thus the only possible contrast between 7#11 and 7b5 arises from the spelling of one of the notes. I do not think it wise to delineate the two here. In the same spirit, the tritone sub for Eb7 would be "more correct" spelled as Bbb7 rather than A7, but that is a topic for another day and I'm not willing to die on that hill either - I'm picking my battles!
This question was updated to include context. The section below is my original opinion on what the chord symbol "A7+4" could mean in isolation:
What does A7+4 mean (by itself)?
This is a really unusual chord symbol, so the interpretations are not going to be easy. In my view, it is likely that one of three possibilities was intended. I have italicized strategically to show what effect the "+4" part of the symbol has on the chord in each example:

A7+4

A augmented dominant seventh chord with an added fourth
A dominant seventh chord with an added augmented fourth
A dominant seventh chord with an added fourth

What are the points for and against these interpretations?
1: The "+" symbol should normally mean "augmented fifth", so the symbol A+7 (sometimes A7+) indicates an augmented seventh chord. The first possibility on the list uses that standard logic, and then interprets the "4" separately as an added note.
This is probably the most standard and literally correct method of parsing this notation, but this particular chord symbol is very rare and there are some arguments for other interpretations. If this is the right way to read the symbol, the chord should be [A C# D Ex G]. Unusual to have the perfect fourth rub against the major third, and especially with an augmented 5th, but not technically impossible. Seems like the kind of chord one gets by vainly trying to include a bunch of non-chord-tones and suspensions into the chord symbol.
2: The "+" symbol can also be read to only mean "augmented", which normally gets attached to the fifth by default. With this reading, the added fourth takes the augmented quality since the "+" precedes the "4", and the resultant sonority is [A C# D# E G]. The augmented 4th (or diminished fifth) is a very common extension on the dominant chord in jazz music (which happens to be a genre where weird chord symbols are common), and almost certainly a jazz musician would take the liberty of omitting the perfect fifth.
The resulting altered dominant voicing is very common, and this sonority also takes the form of the French augmented sixth chord (Fr+6) in classical analysis. However, A7+4 is not a good symbol to represent this voicing if this was the desired chord. For jazz, something like A7(#11) or A7(b5) would be best - parentheses optional.
3: Here, the "+" symbol is used erroneously in place of "add" notation, simply asking the player to add the fourth to the dominant seventh chord. The resulting chord would be played [A C# D E G].
While a theoretically valid (if a bit uncommon) chord in its own right, this would be a notation mistake. It is unadvisable to use a "+" symbol to mean "add", since it is already in standard use for augmented fifths. If "add" was desired, there are many better alternatives such as A7add4, A7add11, A7(4), A7(11), or even A7/11. It is not uncommon for beginners to assume the "+" means "add" (read: check your author's credibility!), and in context it might work for some familiar audiences, but this is generally not accepted as far as chord symbol conventions go.

In-depth analysis using the context of the song:
With the new information (this chord lands on "bow" in the song "Somewhere over the Rainbow" in the key of Eb), it is possible to deduce much more about the intended chord:
Knowing that the chord progression is more like Eb % % % G-7 % E-7 "A7+4" Abmaj7 [...], the chord is undoubtedly supposed to be the altered dominant chord A7#11 (or Bbb7#11, possibly). This is what I described in example #2 previously. Since this answer is getting quite long-winded, I'll repeat that: to play this song, play this as A7#11, or [A C# D# G].
How can we be so sure?
First, let's examine the surrounding harmony. Recognizing the fact that E-7 and A7 make a ii-V in the key of D major, which is a tritone away from the target chord Ab in the next measure, is crucial. Thus, our progression is something like:

I       %        %           %     |
iii-7   %   sub(ii/IV)   sub(V/IV) | IV ...

These are tritone substitutions for secondary dominants. They look confusing in RNA symbols, but all that's happening is the arranger is making a nice "ii-V-I" progression aimed at the IV chord, then replacing the ii and the V with chords rooted a tritone away. This is pretty standard jazz harmony. The voice leading is smooth and chromatic while also maintaining functional harmony patterns.
The idea that this mystery A chord should be A7#11 makes a lot of sense. In fact, 7#11 chords are symmetrical at the tritone, so this will have the same notes as an Eb7#11 chord. An Eb7 chord would be the normal dominant that points to our target Ab - that's what we substituted for in the first place! Additionally, the melody note Eb is actually a chord tone of an A7#11 chord (enharmonically speaking), which is a fact that gives this theory a lot of weight. This A7#11 is so logical that it renders the other interpretations unthinkable - neither one includes the melody note, nor do they make much sense in this (or any) context.

Questioning the effectiveness of this chord symbol:
Does the "+" have to mean "augmented fifth"?
I think it's safe to say that we've sorted out what the symbol was supposed to mean in the music. But was it a good chord symbol to use for that desired sound? I argue that this was a poor decision by either the editor or whomever is responsible for writing up the chord labels. In my experience, the "+" symbol is solely used to describe an augmented 5th. By contrast, when the sharp eleventh  or fourth is desired, it is represented as "#11" or "#4".
Almost all chord tones take their modifications via accidentals in the chord symbol; for example, when the ninth of a dominant chord is lowered, its chord symbol is 7b9. The eleventh, in my experience, follows this rule like all of the other extensions do. The only exceptions are:

The root, which it goes without saying  will never change,
3, whose information is deduced from the symbol for the seventh,
5, which can be changed with "+", "°", "ø", or with accidentals like the rest of the extensions,
7, which is changed with "maj", "m", "-", "-(maj)", "", et cetera.

There is such thing as an augmented 6th chord, and it actually does use the + symbol for the raised sixth, but that is archaic usage that dates back to the figured bass tradition and I have yet to experience musicians use the + sign for "sharp" in modern chord-labelling contexts. In any case, the 11th cannot be changed by the "+", and the lack of contradictory instructions is strong evidence that "+" should apply to the 5th since the base chord type should be "+7". After all, what would "C+maj7" mean if the "+" could be applied to either the 5th or the 7th? Only when applying the standard nomenclature does it become clear that the 5th is augmented and the 7th and 3rd are major.
How should the piece be played?
According to standard chord nomenclature, the use of the "+" symbol indicates unambiguously that the 5th of the chord is to be raised by a half-step. For that reason alone, #1 in my original post should theoretically be the "correct" way to play that chord symbol. However, context indicates that this was obviously a mistake in the notation rather than an intentional call for a ridiculous chord. "Theoretically correct" does not mean anyone would actually do this, nor does it mean you should try to play it that way. But it is still bad practice to write like this because it makes the music unnecessarily hard to read. I can't think of a single reason not to call this chord one of the universally agreed-upon labels: 7#11 or 7b5.

Further Reading / References:

The Wikipedia article on altered chords never acknowledges the use of "+" for sharpened intervals other than the 5th.
Hello Music Theory has an altered section of their chord naming info page that prescribes only accidentals for alterations.
Music Novatory actually does prescribe the use of "+" in their chord symbols page; however, this is for something they put in a section called "Chromaticism" and it appears that they use these for every single interval above the root. The website also prescribes some strange non-traditional analysis tools like motrixes, proper tones, and common tones. Go ahead and read up on this, since I just gave it a glance, but I would consider this kind of theory to be outside of the domain of standard jazz chord nomenclature.
Dobrian's list of jazz chord symbols looks to be a fairly large collection of chord symbols for jazz music. However, the "+" symbol only appears for the augmented triads and augmented 7th chords.
jazz-library.com has an article listing chord symbols; as before, the "+" character only appears in the augmented triads and augmented seventh chords. Certainly no "+" symbols for augmented 4th alterations.
guitarcommand.com has an [article on altered chord theory], and the "+" character stays within its scope as the augmented 5th quality marker.
I like to include some native SE content in my research; this Music: Practice and Theory answer does mention use of +/- as an alternative to #/b when altering chord tones. Unfortunately, no references have been provided for this, and the example given is for a sharpened 9th rather than a sharpened 4th, although I will concede that it is very likely that the fourth would follow the same pattern as the ninth given that it is enharmonic to the eleventh.
Another of M:P&T's very own posts caught my attention by using the symbol "+6(b9 #9 #11)". Sadly, this can only mean [1 3 #5 6 b9 #9 #11], as this symbol was being used to describe the chord built on the leading tone of the harmonic minor scale.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/130110/discussion-on-answer-by-user45266-what-chord-is-a74).
Answer: The + here means #: that is, A7#4. In fact, were it really accurate, it would be A7b5. The Eb in the melody is the b5 relative to the A chord (#4 being D#). It's understood in this case that the #4 replaces the normal fifth of the chord (E).
The E-7 moving to A7b5 is a sort of tritone substitution for a ii-V progression (Bb-7 Eb7) leading to the AbMaj7 that follows.
Here'a possible voicing. Notice how the notes in the chords descend.

Notes in parenthesis are not part of the descending pattern

Top notes:     (D)  D  C#   C
"Alto" notes: (Bb)  B  A    Ab
"Tenor" notes:  G   -  -    -  (stabilizing pitch)
Bottom notes:   F   E  Eb  (Eb)
Comment: A7#4 ≠ A7b5. The scales these two chords are derived from are very different. A7#4 comes from either a diminished or a lydian dominant scale (both of which include a perfect 5th along with a raised 4th), whereas A7b5 would derive from an altered scale which does not include a perfect 5th.
Comment: #4 could also imply a lydian sound
Comment: @Daniel I agree that A7#4 ≠ A7b5 in general. But A7#4 doesn't always imply a ♮5, does it? I thought A7#4 could come from altered or whole tone scales, too (as in A7#4#5). I think Aaron's interpretation of the A7#4 as being equivalent to A7b5 is very reasonable in this context. I think he's providing an analysis based on the context of this song, which is a sound way to answer the question. I've made a case that the notation A7#4 is intended to convey ambiguity about the 9th & 13th, but honestly I think it's basically equivalent to Aaron's answer, because we both recommend the same voicing.
Answer: Tldr; You probably shouldn't be adding a 9th or 13th (or even potentially a 5th) to this chordinsert 10 caveats, which is why it's written as A7♯4 instead of A7♭5 or A7♯11. The + means ♯, and this is A7♯4.
An important PSA: in jazz, a well-written chord symbol does more than simply spell out the notes. It provides information about the underlying harmonies, which is especially important because the notes A-C♯-E♭/D♯-G could convey many different harmonies (altered, Lydian dominant, half-whole diminished, whole tone, etc.). The band needs to be on the same page when they see an altered chord in a lead sheet. That's why we can't conflate harmonically equivalent spellings.
There's really only one answer: Given all of this, @Aaron is absolutely correct that A7+4 means A7♯4. The + is the same as # here.
How to interpret other answers: Other answers make some attempts to determine whether this particular instance of A7♯4 is equivalent to A7♯11 or equivalent to A7♭5, but that depends entirely on context and won't be true in all cases. Some answers argue that A7♯4 is always the same as A7♯11 or A7♭5, and I disagree with those answers.
Here are the main differences, in general [insert 10 more caveats about how rules are meant to be broken]:

A7♯11: This implies harmonies with a natural 9 and natural 5 (like Lydian dominant).
A7♭5: This is very different from A7♯11 because it implies harmonies with a b5 and often implies alterations on higher extensions too (♭9, ♯9, ♭13). Examples include the altered scale and whole tone scale.
A7♯4: This is more flexible and a little ambiguous. Often it's equivalent to A7♯11, but sometimes it implies whole tone (as in A7♯4♯5) or half-whole diminished. Other times (and this is the correct interpretation here, I think), it's the best way to convey "play the note between D and E and don't add upper extensions like the 9th or 13th." For example, you'll notice that Aaron's example of how to voice this chord doesn't include a natural or sharped 5, doesn't include a 9th, and doesn't include a 13th.

How to figure out the answer: Go to the piano and play the 3 measures in question ("somewhere over the rainbow") 3 times. On each pass, try a different voicing (shown below) for A7♯4. In all 3 passes, play Emin as E-G-D in the RH and just E in the LH.

voice A7♯4 with a B Maj upper structure triad (2nd inversion) in the RH and A-C♯-G in the LH
voice A7♯4 with an Eb Maj upper structure triad (1st inversion) in the RH and A-C♯-G in the LH
voice A7♯4 with C♯-G-D♯ in the RH and A-G in the left hand

Similarly, trying adding a 5th to the A7#4 chord. Which sounds best?

adding the ♮5 (e.g., E-A-C♯-D♯ in the RH)
adding the ♯5 (e.g., F-G-C♯-D♯ in the RH)
adding neither (e.g., C♯-G-D♯ in RH)

Really, they all sound good, and it's a subjective judgment call. However, some are more exotic than others, and given that A7♯11 isn't explicitly written, playing a B Maj upper structure triad may clash with what the rest of the band is doing. Because of the ambiguity about the 5th, 9th, and 13th, I think this notation of A7♯4 is supposed to convey a simpler voicing in this particular case.
Caveats: If someone were improvising over this, it would be silly to simply avoid playing the 9th and 13th. So, they will usually have some flexibility to decide which scale/harmony they want to use. The band would generally follow along, unless a band leader specifically said something like "treat that as whole tone."
Comment: Can you clarify what you mean by "reputable"? Part of the challenge in jazz is that the most reputable sources (much more so than many websites) are the great jazz musicians. Also V7#4 doesn't get much attention. Part of what's happening in this answer is using knowledge about V7#11 and V7b5 chords, as well as knowledge about underlying scales, to make inferences about V7#4 chords. For example, if we want a V7 chord that is constructed from H-W dim and contained a #4, we can't use V7#11 or V7b5; V7#4 would be required. Also, V7#4#5 is a valid chord, which must be distinct from V7b5.
Comment: Can you provide a reference from a reputable source discussing 7+4 (not 7+11) chords and how they differ from 7-5 chords?
Comment: @PiedPiper, don't get me wrong--I think it's always fair to ask for a reference, but what you're looking for may not exist. But given all that, is there something specific you're wanting support for? Because while we won't find an article by Christian McBride detailing the differences between V7#4 and V7b5, it may be possible to find references that pertain to specific, small pieces. That said, there's no guarantee I will be able to find them quickly. I couldn't even tell you where I learned this specific information. I've read all of Levine's and Aebersold's books,
Comment: ...but honestly I think more of my theory knowledge came from in-person lessons or classes with reputable musicians.
Comment: @PiedPiper, here's another piece: one way I'm thinking about the difference between #4 and #11 is through the context that higher extensions often imply lower extensions. So 7#11 generally implies a 9th, too, which we always make natural. From this convention, 7#4 doesn't carry that same implication.
Comment: I'd never seen 7+4 before (I think it's a mistake) but your answer suggests it's something standard, so it must be discussed elsewhere and I'd interested to see where. I have no idea what your musical background is, so please ignore the word 'reputable'.
Comment: @PiedPiper I completely understand what you meant by reputable, and again I think it's a fair thing to request. If you're looking for lead sheets with 7+4, I think they show up with some regularity in Jamey Aebersold pocket changes, and even in some real books. They're not that uncommon. Someone in another comment said that they're interchangeable with A7#11, and that's true for some publishers.
Answer: The other answers are so long!
For brevity's sake:
A7+4 would mean "A dominant seven, augmented fourth" which is an enharmonic spelling of A7♭5 "A dominant seven, flat five", an augmented fourth being enharmonically equivalent to a diminished or "flat" fifth.
Given the E♭ in the notated melody, I would think A7♭5 would be the more appropriate name.
Also, if you use smooth, step-wise voice leading, the tones descend from E natural in Em to E♭ in A♭Δ. Spelling the in between A7+4 chord so that the line is E♮ D♯ E♭ seems an awkward way to show a descent with a repeated tone. Overall, the harmony of the opening is a move from I to IV where E♭ the tonic is common to both chords. Actually, it's a tonal degree whether I or IV is tonicized. It seems odd to enharmonically respell a tonal degree as D♯ when the harmony is just chromatic decoration.
Comment: Agreed that the Eb note found in the melody would be the same pitch as '+4', then 'b5' may be a better name. However, +11 (#11) is also a standard jazz chord - although - that would mean the melody note ought to be D#, maybe?
Comment: @jdjazz, sure, but I gave _two_ reasons.
Comment: @jdjazz, what I genuinely misunderstand is why you think the same point in Aaron's answer is fine, your words: "I think Aaron's interpretation of the A7#4 as being equivalent to A7b5 is very reasonable in this context.", but it's "conflating enharmonic chord spellings without reason" in my answer.
Comment: `#4` that too wasn't actually necessary. I wrote directly that it's an "augmented fourth". No need to change `+4` to a `#4` to make that point. And my point about appropriateness is clearly about the `Eb` in the melody. Anyway, I removed the part about `7b5` being more common, that doesn't really matter.
Answer: There won't be a ♯4 or a ♭5! True, + means ♯.
Funnily enough, Big band has just re-started after 18 months, and this piece is one of the first we looked at.
Albeit in a different key (B♭), that bar is Dm7 - Bm7 E9(♯11). Transposing to Gm7 - Em7 A7+4. That A7+4 should be, according to my chart, A9(+11).Or A9(♯11). It produces a chromatic dropping of the lower notes in the chords for the preceding and next bar (not shown on my pno copy, but heard from bass and trombones).
It's not usual to have ♯4, but ♯11 is commonplace. Rather like ♯2 or ♭2 isn't seen, whereas ♯9 and ♭9 are. That puts the altered note an octave away from a note it would clash with.
In my chart, being 9(+11) means there would be 1,3,5,♭7,9, and the ♯11 available to be played by many different instruments.

What chord is "A7+4"?


IDispatchMessageInspector to log plain-text soap messages?

Question: I've written a WCF IDispatchMessageInspector, so I can log incomming and outgoing messages. But I'm not sure how to get a nicely-formatted XML string to log.
My code looks something like this:
<code>        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
        request = buffer.CreateMessage();
        Log("Received", request.ToString();
        return null;
    }
</code>
The result of this logging includes things like "ampersand lt;" and some sort of binary-encoded data.
How do I get something that looks like a standard soap XML document? I know this should be obvious, but I'm just too dense to figure it out.
Thanks.
Dan
Answer: Is there any specific reason you are not using the .Net build in tracing functionality with an XmlTextWriter output?
If no specific reason, have a look at http://msdn.microsoft.com/en-us/library/ms730064.aspx
Hope this helps,
Answer: Here is a working example
<code>public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
    MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
    request = buffer.CreateMessage();

    XDocument doc;

    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriter writer = XmlWriter.Create(ms);
        request.WriteMessage(writer);
        writer.Flush();
        ms.Position = 0;

        doc = XDocument.Load(ms);
    }

    if (SaveLog != null)
    {
        LogSaveFileEventArgs logEventArgs = new LogSaveFileEventArgs(doc, false);
        SaveLog(this, logEventArgs);
    }

    request = buffer.CreateMessage();

    //The return value can be any object that you want to use for correlation purposes;
    //it is returned to you as the correlationState parameter in the BeforeSendReply method.
    return null;
}
</code>


Is it possible to convert strings like 'John' and 'Jane' to numeric values but keep them readable as 'John' and 'Jane'

Question: Question is all in the title.  I am trying to Union two blocks, one is numeric and one is a string.  I understand that you can't union those together.  Converting all my numbers to text is doable, but not ideal because then my output is text instead of numeric.  My question is: is it possible to do the opposite of that, convert the text fields into numeric values but keep them readable as 'John' and 'Jane'.
Comment: @lad2025 ur reputation is cool. 55,555...
Comment: binary and octal are numeric. You could implement a function to convert you string to either one of those. Or you could [implement a function like this](https://stackoverflow.com/questions/24375773/replace-each-letter-with-its-ascii-code-in-a-string-in-pl-sql?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) to have it spit out the ASCII character codes for the string (assuming no unicode here).
Comment: Looks like you want translation table `name | numeric value`
Comment: Ultimately though they won't be "Readable" until they are converted back. There is no way around that unless you convert them to some numeric only 1337 speak. I'm also thinking you'll want an indicator in your UNION output to tell you whether it's text converted to numeric or just a boring old number for translating it back when you are done.
Answer: Use base 62 instead of decimal. With base 62 you can use all your letters (lower case and upper case) as numbers.
0 - 0
...
9 - 9
a - 10
...
z - 35
A - 36
...
Z - 62

Easy peasy.
Comment: In this example I would have to convert the base 62 back to text to write out full words though, correct?
Answer: It really sounds like you're going about this wrong. You don't say enough about your application, but you're trying to union together a text and numeric column. I'm imagining something like this:
SELECT t1.my_numeric_column
  FROM mytable1 t1
UNION ALL
SELECT t2.my_varchar2_column
  FROM mytable2 t2

And as you say, this doesn't work. What you should be doing is this:
SELECT TO_CHAR( t1.my_numeric_column )
  FROM mytable1 t1
UNION ALL
SELECT t2.my_varchar2_column
  FROM mytable2 t2

You say this is "not ideal because then my output is text instead of numeric", but if you're displaying this text somewhere (and you don't say where or how), then your output is text, not numeric.
Either that or the problem that you're trying to solve isn't well defined here.


C# Creating Objects from a text file - System.NullReferenceException

Question: I have a task to complete and I can't figure out what i have done wrong and whether the instances of the objects are not created at all or whether there is no reference to the array of elements. Error: System.NullReferenceException.
The task is to initiate 20 objects from a text file, each line represents a instance of an object. The program should read the file create each object and update an array of pointers to pin to newly created object.
So far, the code runs the text file and converts string into appropriate type. It also looks like it initialises the objects and points them to the livestocks[] array. However when trying to run any object related methods, I get the null reference error. The requirement is to use the array to create the new objects.
Any help would be really appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Livestock[] livestocks =  new Livestock[20]; //array of 20 pointers to Livestock.

            String textLine;
            String[] livestockContent; //array of Livestock textfile content

            //The task of this progrgam is to read the file line by line
            try
            {
                TextReader textReader = new StreamReader(@"C:\...file.txt");
                while ((textLine = textReader.ReadLine()) != null)
                {
                    livestockContent = textLine.Split(','); //The line could be splitted to words
                    int _ID = int.Parse(livestockContent[0]);
                    string _livestockType = livestockContent[1];
                    int _yearBorn = int.Parse(livestockContent[2]);
                    double _costPerMonth = double.Parse(livestockContent[3], CultureInfo.InvariantCulture);
                    double _costPerVaccination = double.Parse(livestockContent[4], CultureInfo.InvariantCulture);
                    double _amountOfMilk = double.Parse(livestockContent[5], CultureInfo.InvariantCulture);

                    if (_livestockType != null )
                    {
                         for (int i = 0; i > 20; i++)

                            livestocks[i]  = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

                      //Console.WriteLine("Creating a new: " + livestocks[0]);
                      //Console.WriteLine("Livestock ID is: " + ID);

                    }
                    else
                    {
                       for (int i = 0; i > 20; i++)
                            livestocks[i] = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

                      livestocks[9].GetID();
                    }
                }//end of while //end of reading the file and initiating objects
            }//end of try
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }// end of catch
           Console.ReadKey();
       }//end of main method
    }// end of class
}//end of namespace

Comment: I very much doubt you are using C# 2.
Comment: Change `i > 20` to be `i < 20` for both `for loops`. Or better yet, `i < livestocks.Length`
Answer: Here you are null checking the _livestockType variable, but in case its null you add it to the object.
I would say that you are passing _livestockType as null to the object and trying to access it in the methods, and a NullReferenceException is thrown because of that
if (_livestockType != null )
{
     for (int i = 0; i > 20; i++)

        livestocks[i]  = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

  //Console.WriteLine("Creating a new: " + livestocks[0]);
  //Console.WriteLine("Livestock ID is: " + ID);

}
else
{
   for (int i = 0; i > 20; i++)
        livestocks[i] = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);

  livestocks[9].GetID();
}

Comment: I have followed both of your suggestions CaveCoder  and have changed the condition to _livestockType = "Cow". And Hayden changed the operator to < and all my methods are running now. Thank you so much for your help!


error in checkout page using PHP

Question: I creating a site for online shopping cart using PHP. I did everything but my question is when i checkout the items, only one item will stored in database. But i need to store all selected items records
This is my checkout.php code
<?php
//Pay success insert into databace

if(isset($_POST['pay_success']))
{
    $all = array('product_name'=>$p_code, 'product_name'=>$p_name, 'total_amount'=>$amount);
    $columns = implode(",",array_keys($all));
    $escaped_values = array_map('mysql_real_escape_string', array_values($all));
    $values  = implode(",", $escaped_values);
    $sql = "INSERT INTO pay_success ('$columns') VALUES ('$values')";
    if($sql==true)
    {
        echo "Success";
    }
    else
    {
        echo "error".mysql_error();
    }
}

?>

Note: This is only insert code and this code echo success but data's not insert
Comment: Then you should iterate with `foreach` or `for`  which contains insert query inside the loop.
Comment: Your `$escaped_values ` contains like `1,2,3` ?
Comment: Thank you for replaying me @SulthanAllaudeen Actually this code is echo success but not stored in database
Comment: Welcome, may i know what value you have in `$all`  can you `print_r` or `echo` it ?
Comment: $all = product_code , product_name, total_amount those are product details fetching from data base
Comment: `$result=mysql_query($sql);` Just put this line after ` $sql = "INSERT INTO pay_success ('$columns') VALUES ('$values')";`
Comment: thank you @  Sulthan Allaudeen it showing error like    "error-You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
Comment: Yes, pls show the full error
Comment: error -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''product_name,total_amount') VALUES ('Television DXT,701.35')' at line 1
Comment: Oh... why `product_name` twice ?
Comment: I guess `array('product_code'=>$p_code, 'product_name'=>$p_name, 'total_amount'=>$amount);`
Comment: now showing same error
Comment: thank you @ Sulthan Allaudeen
Answer: You are constructing only the Query and not executing the Query
So, You should have
$sql = "INSERT INTO pay_success ('$columns') VALUES ('$values')";
$result=mysql_query($sql);
if($result)
{
    echo "Success";
}
else
{
    echo "error".mysql_error();
}

But i strongly recommend you to use mysqli or pdo as mysql is depreciated
Update :
I guess you should constructed the $all
$all = array('product_code'=>$p_code, 'product_name'=>$p_name, 'total_amount'=>$amount);
Comment: error - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''product_code,product_name,total_amount') VALUES ('PD1002,Television DXT,701.35'' at line 1
Comment: Do you have `produce_code` ,`product_name` , `total_amount` coloumns in your table ?
Comment: Can you please do `echo $sql` and show me the output ?
Comment: sorry for delay@ Sulthan Allaudeen this echo INSERT INTO pay_success ('product_code,product_name,total_amount') VALUES ('PD1002,Television DXT,701.35')
Comment: Can you pls check whether it works for you `$sql = "INSERT INTO pay_success ('product_code','product_name','total_amount') VALUES ($p_code,$p_name,$amount)";` ?
Comment: error -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''product_code','product_name','total_amount') VALUES ('PD1002', 'Television DXT'' at line 1
Comment: ya ok can i send full document to your mail id
Comment: please check the mail
Answer:  $all = array('product_name'=>$p_code, 'product_name'=>$p_name, 'total_amount'=>$amount);

You should not use 'product_name' twice.
Answer: after
$sql = "INSERT INTO pay_success ('$columns') VALUES ('$values')";

line where is the sql excution function

mysql_query
Comment: errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''product_name,total_amount') VALUES ('Television DXT,701.35')' at line 1
Comment: you have to put a single quotes for each parameter passing
Comment: see this line ('Television DXT,701.35') should be
**('Television DXT' , '701.35')**

error in checkout page using PHP


Remove Blank Lines While Printing An Output

Question: I have this Java lexical analyzer algorithm that prints out each assigned token to every symbol. The output should print out on each and every individual line without any space in between. But mine does have spaces. I have tried to use trim() method, even replaceAll() method, nothing seems to work. Here is my Java code:
import org.w3c.dom.ls.LSOutput;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Lexer {

public static void Tokenize(String fileName) {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = reader.readLine()) != null) {
            line = removeComments(line);
            String[] tokens = tokenizeLine(line);
            for (String token : tokens) {
                System.out.println(token);
            }
        }
    } catch (IOException e) {
        System.err.println("Error reading file: " + e.getMessage());
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            System.err.println("Error closing file: " + e.getMessage());
        }
    }
    System.out.println("SYNTAX ERROR: INVALID IDENTIFIER NAME");

}

private static String removeComments(String line) {
    // Remove inline comments
    line = line.replaceAll("//.*", "");
    // Remove block comments
    Pattern pattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL);
    Matcher matcher = pattern.matcher(line);
    return matcher.replaceAll("");
}

private static String[] tokenizeLine(String line) {

    String[] tokens = line.split("\\s+ |(?=[\\[\\](){}<>=,;+-/*%|&!])|(?<=[\\[\\](){}<>=,;+-/*%|&!])");
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i].replaceAll("\\s+", "");
        if (token.matches("procedure")) {
            tokens[i] = "PROC";
        } else if (token.matches("int")) {
            tokens[i] = "INT";
        } else if (token.matches("[0-9]+")) {
            // Integer constant
            tokens[i] = "INT_CONST";
        } else if (token.matches("[(]")) {
            tokens[i] = "LP";
        } else if (token.matches("[)]")) {
            tokens[i] = "RP";
        } else if (token.matches("\".*\"")) {
            // String constant
            tokens[i] = "STR_CONST";
        } else if (token.matches("String") || token.matches("string")) {
            // String keyword
            tokens[i] = "STR";
        } else if (token.matches("if")) {
            tokens[i] = "IF";
        } else if (token.matches("for")) {
            tokens[i] = "FOR";
        } else if (token.matches("while")) {
            tokens[i] = "WHILE";
        } else if (token.matches("return")) {
            tokens[i] = "RETURN";
        } else if (token.matches("[;]")) {
            tokens[i] = "SEMI";
        } else if (token.matches("do")) {
            tokens[i] = "DO";
        } else if (token.matches("break")) {
            tokens[i] = "BREAK";
        } else if (token.matches("end")) {
            tokens[i] = "END";
        } else if (token.matches("[a-zA-Z][a-zA-Z0-9]*")) {
            // Identifier
            tokens[i] = "IDENT";
        } else if (token.matches("[=]")) {
            tokens[i] = "ASSIGN";
        } else if (token.matches("[<]")) {
            tokens[i] = "LT";
        } else if (token.matches("[>]")) {
            tokens[i] = "RT";
        } else if (token.matches("[++]")) {
            tokens[i] = "INC";
        } else if (token.matches("[{]")) {
            tokens[i] = "RB";
        } else if (token.matches("[}]")) {
            tokens[i] = "LB";
        } else if (token.matches("[*]")) {
            tokens[i] = "MUL_OP";
        } else if (token.matches("[/]")) {
            tokens[i] = "DIV_OP";
        } else if (token.matches("[>=]")) {
            tokens[i] = "GE";
        }
    }
    return tokens;
}
}

and here is my output.
LP
IDENT
RP

FOR
LP
IDENT
ASSIGN
INT_CONST
SEMI
IDENT
LT
IDENT
SEMI
IDENT
ASSIGN
IDENT
INC
INC
RP

RB
IDENT
ASSIGN
IDENT
MUL_OP

LP
IDENT
DIV_OP
INT_CONST
RP
SEMI

IF
LP
IDENT
RT
ASSIGN
INT_CONST
RP
BREAK
SEMI

LB

IDENT
SEMI

IDENT

IDENT
ASSIGN
STR_CONST
SEMI
SYNTAX ERROR: INVALID IDENTIFIER NAME``

Comment: Please don't write normal sentences, not even titles, in all upper-case. It's considered shouting, and it's very rude to shout at the people you want to help you.
Comment: why not print out in the tokenizeLine method?  I would assume that `String token = tokens[i].replaceAll("\\s+", "");` is giving you a blank line.  You can set some boolean value for all wanted `token.matches` parts and only print if a match was made.
Comment: @ScaryWombat i tried that and it still has blank lines
Answer: Either remove the empty strings in your tokenizeLine from the returned array before returning, for example by changing the return statement from:
return tokens;

to
return Arrays.stream(tokens).filter(Predicate.not(String::isBlank)).toArray(String[]::new);

or just print the non empty strings in your loop by checking before printing
for (String token : tokens) {
    if(!token.isBlank()) {
        System.out.println(token);
    }
}


enviar arquivo por ajax

Question: Tenho um formulário para preencher e gravar arquivos no banco passando os dados por ajax mas o arquivo não está a chegar.
O formulário:

$("#documento").click(function(e) {
  e.preventDefault();
  var text1  = $("#arqnome").val();
  var text2  = $("#arq").val();
  $.ajax({
      type: "POST",
      url: "arquivo.php",
      data: { documento: $(this).val(), arqnome: text1, arq: text2 }
  })
  .done(function(data){
      $("#documento_e").html(data);
      //$("#form")[0].form.reset();
  });
});
<form id="form_docs" method="post" enctype="multipart/form-data">

            Tipo de Arquivo:

            <input type="text" name="arqnome" id="arqnome">

            Selecionar Arquivo:

            <input type="file" name="arq" id="arq">

            <button type="button" id="documento" name="documento">Gravar</button>

</form>

A página que processa os dados:
include("banco.php");
if(isset($_POST['documento'])){
        $img = $_FILES["arq"]["name"];
        $ext = strtolower(strrchr($img, '.'));
        $imgn = str_replace($_POST['arqnome'],' ','_').$ext;
        $dest = $imgt . '_tmp/' . $imgn;
        move_uploaded_file( $_FILES['arq']['tmp_name'], $dest );

        pg_query($dbconn, "begin");
        $oid = pg_lo_import($dbconn, $imgt . '_tmp/' . $imgn);
        $sql = "insert into tabela(arqnome, arq, arqext) values('".$_POST['arqnome']."', '$oid', '$ext'");
        $res = pg_query($dbconn,$sql);
        pg_query($dbconn, "commit");

        unlink($imgt . '_tmp/' . $imgn);
}

Comment: Veja a sua resposta neste link: https://pt.stackoverflow.com/questions/9704/fazer-upload-de-arquivo-com-ajax
Answer:
Falta a variável $imgt
O ajax está enviando os dados de forma incorreta: com data:.... arqnome: text1 o php recupera usando $_POST e não com $_FILES
str_replace está errado

HTML + AJAX

<form id="form_docs" method="post" enctype="multipart/form-data">

            Tipo de Arquivo:

            <input type="text" name="arqnome" id="arqnome">

            Selecionar Arquivo:

            <input type="file" name="arq" id="arq">

            <button type="button" id="documento" name="documento">Gravar</button>

</form>

PHP
<?php

if(isset($_POST)){

        $img = $_FILES['arq']['name'];
        $arqnome = $_POST['arqnome'];
        $imgt="pasta";

        $ext = strtolower(strrchr($img, '.'));
        $imgn = str_replace(' ','_',$arqnome).$ext;
        $dest = $imgt . '_tmp/' . $imgn;

        if (move_uploaded_file( $_FILES['arq']['tmp_name'], $dest )) {
             echo "Upload efetuado com sucesso!";
        }  else {
             echo "Não foi possível realizar o upload, tente novamente";
        }

        //codigo
        //código

}
?>

Comment: Leo Caraciolo, a variavel $imgt é na verdade o caminho da pasta que está no meu script de origem e não alterei aqui por esquecimento, e realmente o replace estava ao modo postgre.Quanto ao script, funcionou direitinho. Obrigado

enviar arquivo por ajax


Anular CSS da class ui-disable

Question: Tenho uma navbar como footer.
O primeiro elemento da navbar tem a classe ui-disabled para não ser possivel interagir com ele.
Aqui está o FIDDLE
HTML/JQuery

Opções

menu

Definições

Pergunta
Como se nota no fiddle, o primeiro elemento está mais desbotado que os dois seguintes. É possível, usando CSS e mantendo o primeiro elemento com a classe ui-disabled torna-lo idêntico aos restantes li's ?
Caso tenho sido pouco explícito: é possivel anular o CSS caracteristico da classe ui-disabled?
Comment: Uma solução seria você copiar o CSS da classe ui-disable, colocar no seu arquivo css com outro nome e associar essa nova classe ao seu li. Assim você poderia alterar o css dele sem perder a propriedade original. Já tentou isso? Ficaria algo como Opções
Answer: A diferença é que o disabled tem opacity: .3;, repondo a opacity para 1 resolve o problema.
Usando
$('[data-role="navbar"] li:first').css('opacity', 1);

resolve o problema.
jsFiddle: http://jsfiddle.net/u2d9ttym/6/
Se resolveres aplicar cia classe de CSS tens de usar !important; para sobrepôr a regra. Usando via JavaScript como referi em cima não é preciso pois aplicando no elemento ele tem prioridade.
Comment: Criei em **CSS** e resultou como disseste. Obrigado. Eu estava a tentar adicionar agora no **CSS** também o `pointer-events: auto !important;` para testar, mas o **CSS** não aceita. Sabes explicar-me porque? [FIDDLE](http://jsfiddle.net/u2d9ttym/8/)
Comment: @msm.oliveira o que queres que aconteça com `pointer-events: auto !important;`? qual é o comportamento que queres?
Comment: acabei mesmo agora de o resolver XD. obrigado
Comment: @msm.oliveira ok, boa! estive fora e só agora cheguei ao PC. Bom que já está resolvido.

Anular CSS da class ui-disable


libxmljs: scons command not found

Question: When I was trying to deploy my node.js app (with both nodejitsu and heroku), I got the same errors with libxmljs.
<code>> email@example.com preinstall /root/tmp/tmp-31613c7bs0y8/build/package/node_modules/twilio/node_modules/libxmljs
> make node

make: scons: Command not found
make: *** [node] Error 127
npm http 200 https://registry.nodejitsu.com/css-stringify
npm http 200 https://registry.nodejitsu.com/css-parse
npm http 200 https://registry.nodejitsu.com/is-promise/-/is-promise-1.0.1.tgz

> email@example.com preuninstall /root/tmp/tmp-31613c7bs0y8/build/package/node_modules/twilio/node_modules/libxmljs
> make clean

make: scons: Command not found
make: *** [clean] Error 127
npm http GET https://registry.nodejitsu.com/css-stringify/-/css-stringify-1.0.5.tgz
npm http GET https://registry.nodejitsu.com/css-parse/-/css-parse-1.0.4.tgz
npm WARN continuing anyway firstname.lastname@example.com preuninstall: `make clean`
npm WARN continuing anyway Exit status 2
npm ERR! email@example.com preinstall: `make node`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com preinstall script.
npm ERR! This is most likely a problem with the libxmljs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     make node
npm ERR! You can get their info via:
npm ERR!     npm owner ls libxmljs
npm ERR! There is likely additional logging output above.

npm ERR! System SunOS 5.11
npm ERR! command "node" "/opt/local/bin/npm" "install" "--loglevel=http"
npm ERR! cwd /root/tmp/tmp-31613c7bs0y8/build/package
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.14
npm ERR! code ELIFECYCLE
</code>
As you can see, it is failing within libxmljs's 'make node' and 'make clean' as the command 'scons' is not found. I have libxmljs installed in my app's node_modules directory, and 'scons' is located at "/usr/local/bin/scons".
I believe I have to ensure that the location of scons is in the path for the make environment of libxmljs but I don't know how to do that. Any help would be appreciated!
UPDATE: Following the advice from this question (Fail to deploy node.js application to heroku) I added libxmljs to the dependencies in package.json and added node_modules/ to .gitignore, that way heroku could have a look at the dependencies and install them itself. However, the exact same error occurred, which leads me to believe the root of the problem is not with my local environment, but something larger regarding libxmljs?
Answer: I was able to resolve my problem, although it wasn't really specifically about libxmljs. I also used the 'twilio' node submodule in my app, but listed its version as '0.0.0' in dependencies. I guess twilio 0.0.0 used libxmljs which wouldn't install when deploying to heroku, so I updated the twilio version number to the actual current version, and everything's good to go!

libxmljs: scons command not found


Can Entity Translate work on the node body?

Question: Problem
I'm using Entity Translate for the multi-lingual parts of my site, this allows me to use the language switcher. (I've enabled it for content, and then on the content type I've enabled field translation).
However the node body is not translatable.
Do I need to create a field and use that as the body, or have I set-up entity translation badly?
Answer: Ah turns out you have to enable translation for the field once you've enabled translation for the content type.
Open up your content type, edit the field you want to make translatable then head down to the bottom of the page.
You should see something like:
Field translation
Users may translate all occurrences of this field:

Body in Basic page
Body in Article
Body in Webform
Body in Test Content
Body in Upgrade & Search Token Product Display
Body in Blog post/Article
Body in Development Blog

Click on "Enable translation" and you're good to go.
Comment: What's that link in your answer?
Comment: Just some random letters, in Drupal it's an admin path, but it looks like a link. So to give it formatting to match the real one I just added a random link. Hmm perhaps that's confusing.
Comment: Totally, remove it please.
Comment: Cheers for that!


Python Tkinter: Inheritance Syntax or Reference mistake?

Question: I am beginner at python and I am trying to create a scoreboard-like GUI. I made an event to modify my stats by buttons depending on Combobox selection. There are 4 very small functions after widgets' code, the first one works as intended, the other 3 are similar but they affect only 3 last labels instead of Combobox selection labels. What do I miss there?
from Tkinter import *
import ttk

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master, relief="sunken", border=1)
        self.master = master
        self.box_list = []
        self.labels = []
        self.radiobuttons = []
        self.winlabels = []
        self.loselabels = []
        self.drawlabels = []
        self.create_widgets()
        self.grid()

    def create_widgets(self):
        for i in range(9):
            box = ttk.Combobox(self, state="readonly")
            box.grid(row=1+i, column=2)
            box["values"] = ("team A", "team B", "team C", "team D", "team E", "team F", "team G", "team H", "team I")
            box.current(i)
            self.box_list.append(box)
            box.bind("<<ComboboxSelected>>")
        for i in range(9):
            sv = 1
            selection = i
            radiobutton = Radiobutton(self, value=selection, text=selection+1, variable=sv,
                                      command=lambda i=i: self.rcr(i))
            radiobutton.grid(row=1+i, column=0)
            self.radiobuttons.append(radiobutton)

        self.headings = ("Classes", "Win Lose Draw", "Declare Result!")
        for i in range(3):
            label = Label(self, text=self.headings, relief="sunken")
            label["text"] = self.headings[i]
            label.grid(row=0, column=i*3+1, columnspan=3, sticky=E+W+N+S)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=4, sticky=E+W+N+S)
            self.winlabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=5, sticky=E+W+N+S)
            self.loselabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=6, sticky=E+W+N+S)
            self.drawlabels.append(stats)
        buttonwin = Button(self, text="Win", bg="green", command=lambda i=i: self.win(i))
        buttonwin.grid(row=1, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttonlose = Button(self, text="Lose", bg="red", command=lambda i=i: self.lose(i))
        buttonlose.grid(row=4, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttondraw = Button(self, text="Draw", bg="white", command=lambda i=i: self.draw(i))
        buttondraw.grid(row=7, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)

    def rcr(self, i):
        tr = self.radiobuttons[i]["text"]
        print tr

    def win(self, i):
        self.winlabels[i]["text"] += 1

    def lose(self, i):
        self.loselabels[i]["text"] += 1

    def draw(self,i):
        self.drawlabels[i]["text"] += 1

root = Tk()
root.title("Stats Tracker")
root.geometry("500x250")
app = Application(root)
root.mainloop()

Comment: You would need to be more specific than - *not working* .
Comment: Where your namespace ? Check this : http://stackoverflow.com/questions/32026492/how-can-i-make-the-button-text-change-from-text-to-an-empty-name-with-a-delay/32026778#32026778
Answer: For your radiobuttons, you should use a class attribute (RBval in my code) as a variable to control the selected value. You do not need to store all the radiobuttons in a variable.
And then, in your win, lose, draw functions you do not need to put the number of the selected radiobutton. You just read the value of RBval. In your code, i is always equal to 9 because it is the last value of i in your forloop.
There may be a lots of remaining issues in the code but here is a working version of your code:
from Tkinter import *
import ttk

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master, relief="sunken", border=1)
        self.master = master
        self.box_list = []
        self.labels = []
        self.radiobuttons = []
        self.winlabels = []
        self.loselabels = []
        self.drawlabels = []
        self.create_widgets()
        self.grid()

    def create_widgets(self):
        for i in range(9):
            box = ttk.Combobox(self, state="readonly")
            box.grid(row=1+i, column=2)
            box["values"] = ("team A", "team B", "team C", "team D", "team E", "team F", "team G", "team H", "team I")
            box.current(i)
            self.box_list.append(box)
            box.bind("<<ComboboxSelected>>")
        self.RBval = IntVar()
        for i in range(9):
            selection = i
            radiobutton = Radiobutton(self, value=selection, text=selection+1, variable=self.RBval)
            radiobutton.grid(row=1+i, column=0)
            self.radiobuttons.append(radiobutton)

        self.headings = ("Classes", "Win Lose Draw", "Declare Result!")
        for i in range(3):
            label = Label(self, text=self.headings, relief="sunken")
            label["text"] = self.headings[i]
            label.grid(row=0, column=i*3+1, columnspan=3, sticky=E+W+N+S)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=4, sticky=E+W+N+S)
            self.winlabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=5, sticky=E+W+N+S)
            self.loselabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=6, sticky=E+W+N+S)
            self.drawlabels.append(stats)
        buttonwin = Button(self, text="Win", bg="green", command=self.win)
        buttonwin.grid(row=1, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttonlose = Button(self, text="Lose", bg="red", command=self.lose)
        buttonlose.grid(row=4, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttondraw = Button(self, text="Draw", bg="white", command=self.draw)
        buttondraw.grid(row=7, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)

    def win(self):
        i = self.RBval.get()
        self.winlabels[i]["text"] += 1

    def lose(self):
        i = self.RBval.get()
        self.loselabels[i]["text"] += 1

    def draw(self):
        i = self.RBval.get()
        self.drawlabels[i]["text"] += 1

root = Tk()
root.title("Stats Tracker")
root.geometry("500x250")
app = Application(root)
root.mainloop()


What happens to requests in Instance Request Pending Queue when a backend instance gets terminated due to "Exceeded soft private memory limit"?

Question: I have B* instances running on App Engine(Python env) to serve user facing requests. Sometimes I see B* instances getting terminated due to Exceeded soft private memory limit
I understand that increasing the instance class will solve the issue but
I have few queries regarding requests that are present in the Instance Pending Queue !
Assume we have 2 instances of B* instance class and we call it let say => I-1, I-2

What will happen to those requests that are there in I-1 Instance Request Pending Queue after the I-1 instance gets terminated due to some reason? Will those requests gets evicted from the instance queue as this instance got terminated ?
Will the requests in Instance Pending Queue are Dequeued from the Instance Pending Queue for I-1 and will be put in I-2 Request Queue by the Request scheduler as soon as Request Scheduler finds that I-1 is shutting down due to some reason.

Any help regarding understanding these things will be highly appreciated !
Answer: Based on my external observations of how things work, I suspect there is only a single ingress queue (per service/module) from which requests are only handed to instances which can immediately handle them.
The actual parameters of this single queue (depth, waiting time, etc) would be the indicators driving the automatic/basic instance scaling logic for that service/module - starting and stopping instances.
In such architecture the death of an instance has absolutely no impact on the queued requests, they would simply be dispatched to other instance(s), either already running or specifically started to handle such request.
Note: this is just a theory, though.


Should I Save token securely in Memory or sqlite? or Please suggest

Question: I started to learn Android few days back and so far I am done with implementing Login Activity, Main Activity which extends abstract Base Activity.
Nav Bar item when clicked opens xml from Fragments.
I have a question about the token that I receive after successful login. This token is being used with each request to get data after successful login. Should I save the token in sqlite database securely or I should make a public property in Main Activity? Main Activity will always remain in memory as this will open fragments.
Comment: It fully depends on your App design. Will you ask for Login when the App is restarted? Will you save the session? How secure do you want it to be? SQLite can be extracted and read if a phone is rooted.
Comment: Be super careful when implementing solutions provided below. Most of what I read are not secure. Good luck.
Comment: Think about what happens if the token gets _leaked_. Is it usable on another device? Is it valid _forever_? Can the user logout and invalidate it? Is the information an attacker could obtain sensitive? It really all depends on how secure you want your app to be.
Comment: Storing in sqlite is not a good idea. If not set properly in the manifest the database can be exported. Easier still if the device is rooted.
Comment: you can use `sqlite database`
Comment: @JonZarate: Bounty is added. Kindly suggest your opinion.
Comment: @JonZarate What do you think is the best way to store securely things locally?
Answer: I can suggest 3 options:
1) you can save the token to the file, something like this:
public static void saveToken(Context ctx, String fileName, Object token) {
        if (token == null) {
            ctx.deleteFile(fileName);
        } else {
            ObjectOutputStream out = null;
            try {
                FileOutputStream fout = ctx.openFileOutput(fileName, 0);
                out = new ObjectOutputStream(fout);
                out.writeObject(token);
                fout.getFD().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (out != null)
                        out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

Make sure object token implements java.io.Serializable interface.
Usage before API level 24:
saveToken(appContext, someFileName, someTokenObject);

Usage with API level 24 and higher:
saveToken(appContext.createDeviceProtectedStorageContext(), someFileName, someTokenObject);

2) Use SQLCipher library for encrypted database.
3) You can encrypt your token using keystore system https://developer.android.com/training/articles/keystore.html
Answer: Use SharedPreferences and make sure you are using Context.MODE_PRIVATE this way only your app can access the data. SharedPreferences is a persistent store
e.g.
SharedPreferences prefs = context.getPreferences(Context.MODE_PRIVATE);
prefs.edit().putString("token", token).apply();
token = prefs.getString("token");

Why not to use SQLite:
SQLite is a database and is targeted at tabular data, a single token does not fit this use case.
Why not store in the main activity:
The main activity will not be around for the lifetime of the application install, it can be cleaned up by the OS at any time. It is not a persistent data store.
Answer:
Should I save the token in sqlite database securely or I should make a public property in Main Activity? Main Activity will always remain in memory as this will open fragments.

The Official Android documentation already answers your question in the section on called "Best practices for security and privacy". It gives the following statement:

If you have access to user data and can avoid storing or transmitting it, don't store or transmit the data

In other words, if you can avoid persisting then don't persist it.
You mentioned "public property" in your question which makes me wonder if the concept of visibility modifiers is not yet clear. The Java public and private modifiers are for controlling access to the members of your class. They have nothing to do with security as per this answer here.
If you do persist the token in memory, as a public field or otherwise, you may reduce your exposure slightly by storing the token in a char[] rather than a String. That also is detailed in this canonical answer.
Finally, if you do have to store the token, the sqlite database is not the correct place to do it. Instead, you should use the provided KeyStore which will make for more difficult extraction of the token in the case that the device is compromised. The link to the documentation above is complete with code examples. If this proves too difficult to use, there are some wrappers around it including Scytale.
Answer: 1) Store the token value within the base application singleton (where your application must be an instance of BaseApplication)
public class BaseApplication extends Application {
    // token
    private String token = null;
    public String getToken() {return this.token;}
    public void setToken(String token) {this.token = token;}
}

With the implementation above you will be able to set and get the token value from any activity/fragment. However the value is not persistent and it will be lost once the application ends.
Remark: If you are using the token for REST api access then you can store the token in the background service instance using a similar solution as above.
2) Use SharedPreferences - this is recommended way in case you want to store the token's value between application's runs.
Please see the answer from @Ryan.
Answer: You can use SharedPreferences to store token.it is available over application.
Answer: Better to use Sqlite or Realm. And store in Application memory and not in external memory. As for data residing in application memory we don't need to worry much about security. Saving in MainActivity is not a good solution, as once application closes, this will get cleared.
Storing in Shared Preference is also an option. But if user clears the cache from setting's this value will also get cleared. Realm Android Reference Link
Comment: Maybe you should comment the security aspects of each. AFAIK, both suggestions are vulnerable.
Comment: @JonZarate Then what's the solution in your mind? May I know, without vulnerability ?
Comment: There are some 3rd party libraries that make a database secure.
Answer: You can store it in Shared Preference as this one is token.
Now coming to the part of Security You can obviously use encryption for the shared preference.
There are already lots of open items available you can use below library for example
https://github.com/ophio/secure-preferences
Regarding keys that are in your java file to encrypt, You need to be sure you are applying proguard before you upload it to playstore.
In that manner now your token is fully secure with shared preferences.
In order to save it in sqlite than by decoding or root access your db file can also be accessed same as preferences. Regarding clear data from setting I think it will delete your sqlite data as well. Not sure about this though.
I hope it will help you out.
Comment: `You need to be sure you are applying proguard before you upload it to playstore` obscuring code doesn't mean it's safe. Not to mention ProGuard doesn't obfuscate Strings IIRC.
Comment: @JonZarate , it is possible to find but it is better idea.
Comment: @MushahidKhatri `It will be hard to find key if it is not static and proguard is applied` False. You just say things you do not know about all the time. `You just gone silent ` Why does it matter to you if I know a solution? Doesn't change the fact that your approach is vulnerable. Anyway, yes, I solved it, but it's useless to explain it to you, since you don't pay attention to what I say.
Comment: Can you take value for perticular String from Proguard applied code? Can you find in which class it is?
Comment: http://stackoverflow.com/questions/10220069/does-proguard-work-to-obfuscate-static-string-constants
Comment: @JonZarate , convert String into char array
Comment: @JonZarate, Yes its correct that it will not change string. You you will not be able to find where this string is, also why to declare it as static, Just declare private key in your shared preferences class(Secured Preference class)
Comment: @JonZarate And I think this is the only best option to store token rather than storing it in sqlite.
Comment: @MushahidKhatri It's the same to store it in SQLite and SharedPreferences in a rooted phone. Both equally vulnerable. The database has no protection and the SharedPreferences is a human readable XML.
Comment: @JonZarate That is what I wrote in my answer "In order to save it in sqlite than by decoding or root access your db file can also be accessed same as preferences." But to store in sqlite due to only one value you need to create db, You need to call db every time you need to fetch token. So better to use preferences as you will be using for other values as well. And encryption to preference will some how help to fetch data from xml to other, even device is rooted :)
Comment: @MushahidKhatri You are not paying attention to my messages. My first comment stated that your encryption key will not be secure. You can encrypt your key in DB or SharedPreferences, doesn't matter, if the key is hard-coded in your program.
Comment: @JonZarate, It will be hard to find key if it is not static and proguard is applied. Also I found that you are just telling its not proper, But some one has also asked you do you have solution than this? I am also asking you do you have solution than this? You just gone silent.
Comment: Don't give argument if you don't have any better solution.
Comment: @JonZarate If you have solved it than you would Probably have answered  before me. You didn't Proves all.
Comment: Dude that is what is stackoverflow is about! Sharing knowledge, fix problems!
Comment: @MushahidKhatri hahaha, no. I don't care about reputation, but if I see a bad answer I will say it. Keep Googling.
Comment: @JonZarate 'The fact that I am not sharing it, doesn't mean I don't have it. **Go search on Google like I did**' Who is googling?


Arithmetic sets problem

Question: I need help with a set problem
Given:
$$A=\{(\sqrt{n}+2) \in \Bbb Z \ /\ \ 16\le n^2 \le 1296 \}$$
$$B=\{({3m-2}) \in  A \ /\ \ 4 \le 4m+3 \le 17 \}$$
Calculate the value of :
$$n(A)\times n(B)$$
So far I've got into $$ A = \{-8;-7;-6;-5;-4;4;5;6;7;8\} $$
$$B= \{4;5;6;7;8\}$$
therefore
$$n(A) = 10$$
$$n(B) = 5$$
 However I don't know if this is correct as the result does not match any of the options given as answer.
Answer: Not quite: The symbol $\sqrt{n}$ usually refers to the nonnegative square root of $n$, so $A$ should only contain positive numbers. Now
$$\sqrt{1296} = \sqrt{6^4} = 36$$
so the smallest element of $A$ corresponds to $\sqrt{4} + 2$, while the largest corresponds to $\sqrt{36} + 2$; that is, it's equivalent to write
$$A = \{\sqrt{n} + 2 : 4 \le n \le 36\}$$
Comment: No, that is not the same because you don't restrict $\sqrt n$ to naturals so $2+\sqrt 5$ would be included. You are thinking in the right direction.
Comment: wouldn't it be the same to write $$ A = \{ \sqrt{n}+2 : 4 \le \sqrt{n}+2 \le 8 \} $$ ?
Comment: Okay so now after correcting I got
$$ A=\{4;5;6;7;8\} \ \& \  B = \{4;5;6;7;8\}$$ but the result of n(a)x n(b) still differs from the given options, Maybe i'm still doing it wrong? Thank you in Advance
Answer: Hint.  The symbol $\sqrt{\ }$ means the positive square root.  It doesn't mean plus- or- minus  unless you actually write $\pm$.

Arithmetic sets problem


Locally nilpotent derivations on noncommutative rings

Question: I am interested on LNDs on noncommutative rings, specially noncommutative polynomial rings. It is being hard to find via Google. Anyone know any reference?
Answer: Yes, here is a reference: http://www.math.wayne.edu/~lml/lmlnotes.pdf
These are some lecture notes by L. Makar-Limanov.