Why did we never simplify key signatures?

Question: I understand that the key signature indicates what are the exact notes represented on the staff lines and spaces and thus tells us the diatonic scale in which the music is composed, which in turns gives us a clue about which key the music is composed in.
E.g a key signature with two sharps tells me that the music will probably mainly use the notes of the D major scale (D E F♯ G A B C♯) so the music will probably be in the key of D or one of its related modes.
Now, I can imagine that back in those days, it would have been very cumbersome for a composer to have to write four or more accidentals with a quill and ink on every row of the staff.
Yet, it seems to me that unconventional key signatures are hardly used (I've never come across one personally) so a key signature of four sharps will always be the same set of four notes, to the point that all musicians have to memorize the "order of sharps" and the "order of flats".
My question is: why was the key signature notation never simplified?. Why did we never decide to use symbols instead of listing accidentals, e.g just write "4♭"  instead of actually writing the four flats?
Comment: If there are 4 sharps in the key sig, writing those 4 sharps once on each line was probably less than all the times they appeared in the music so it was actually a time saver.
Comment: Look in the Real/Fake books, and see that the key sigs are often written only on the first lines.
Comment: Not sure I understand the question. To use computer programming terminology : You want a *compiler* to open out (compile) the key-signature into the score inline — Right?
Comment: So what if we are in F minor. Do we write F minor in the same way we would have written A♭ ?  If so do we assume that the E is flat or natural?
Comment: F minor has a key signature of four flats.  But non-diatonic notes, particularly the sharpened 7th, are even more common in minor keys than in major ones.  (And they're pretty common in major keys!)
Comment: Here is an [old answer](https://music.stackexchange.com/a/89958/13649) — with somewhat more divergent views than I'm seeing here
Comment: I don't agree, that something saving effort for the writer but increasing the burden on the reader of the score can be called a *simplification*. Considering the frequency of the respective process (in addition to the lost fine-tunability mentioned in some answers) it no longer seems an improvement at a ll.
Comment: I used to have to read music handwritten by the composer. He put say, 4 sharps at the start, but never in their correct places. Suffice to know the piece had 4#, so was in E/C#m. Wouldn't be anything else! And why is one # not even *in* the stave?!
Comment: @JimM - even if there are 4bs, and a piece is indeed in Fm there's no assumption - either or both could appear.
Comment: For illustration: The meaning of a trill has changed from leading with the auxiliary note in baroque, to the later trill which leads with the written note. The reason was that the _interpretation_ changed. Conversely, some beginner publications write out the composer's intention in full, rather than leave the student to interpret e.g. grace notes. If you simplify something, you necessarily omit information, leaving the reader to make their own, sometimes incorrect or inappropriate, interpretation.
Answer: Actually, it seems to me that designating the key by a letter instead of the arrangement of sharps or flats is not simplifying the process. Simply stating the intended key by letter  and accidental ignores the need for information that many less advanced musicians need to know in order to make sense of what is written in the sheet music. I can look at a key signature and quickly understand which notes need to be sharped or flatted without even considering the name of the key, but knowing which notes are sharped or flatted can tell me the name of the key so this is the method generally used to identify the key. Otherwise a less skilled musician would need to look up the sharps and flats of a given key in order to know how to play the piece. The point that strikes me as most important when playing music, is knowing where the accidentals appear, more important than actually knowing the name of the key itself. Thanks for the question.
Comment: @bta  You are correct that for a given key for a song (for the pianist), the other instruments will have to play in a different key, but speaking as one who played an instrument other than a C instrument, we didn't really consider anything other than the key that our music was in.  (Key of G for a Bb instrument still only has 1 sharp, even though it sounds like we are playing in the key of F, with 1 flat).  Sorry if I misunderstood what you said, but the whole transposing thing is important to me; I used to sight-transpose off of the piano/SATB music, so lots of dealing with keys/transposition
Comment: Another hurdle: instruments are tuned to different keys, so the set of accidentals associated with (for example) the key of D is different for a trombone that it is for an oboe.  This is a significant increase in cognitive load for an instrumentalist, particularly one that plays multiple instruments.
Comment: @bta That's actually less of an issue. A given key will have the same arrangement of sharps or flats.  Different instruments, however, will be told to play in different keys.  For example, the pianist would be told to play in the key of A, while the trumpet player will be told to play in the key of B.  That's effectively what already happens, though we get told the arrangement of the sharps and flats, rather than just the key.
Answer: I believe it's not simplified for some reasons:
1st: Music notation is an orthodox practice which has kept its standardization globally for common understanding. The Boethian notation (alphabet notes A, B, C, D...) was developed as early as the 6th century, but key signature as we known today was developed in the 16th century. Musicians could have chosen to use the Boethian notation instead accidentals at the start of the piece, as you suggest, but they didn't. Why? I think the 2nd reason justifies it.
2nd: When we are reading a score, it's sometimes helpful to check the accidentals at the beginning of the stave row. We may known by heart that the key of E major has 4 accidentals, but how fast do we remember the order (F#, C#, G#, D#) while we are reading at first sight? Sometimes a quick look at the accidental on the staff line helps us to remember, it's helpful to have those accidental cues. And how about chromatic passing notes where we have to signalise natural accidents, then back to sharps/flats, etc? Wouldn't it become confusing, especially in late Romanticism? So I think this notation has been designed for facilitating the musical reading.
3rd: How about modulation? We could notate the music is in E major, but it could soon change to its relative (C# minor). Perhaps it would be misleading to have something affirming the tonality to be E major. Then this becomes a harmonic matter.
These are only suggestions, but I hope it makes sense.
Comment: In addition to these reasons: (4) Not all music is written in the major/minor system. For example, both ancient music and some modern jazz use other modes. In the OP's suggested system, we would need a different notation for every mode. (5) Music can have obscure clefs and movable clefs, and an orchestral score can have a whole bunch of transposing instruments. Given the key signature for the part, it's always easy to locate the tonic.
Comment: Isn't this a misuse of the term "accidental'?  "In music, an accidental is a note of a pitch (or pitch class) that is not a member of the scale or mode indicated by the most recently applied key signature."  So the sharps or flats in the key signature are not accidentals.  Or is it a reference to this usage? "Sometimes the black keys on a musical keyboard are called accidentals (i.e., sharps or flats), and the white keys are called naturals."
Comment: @BenCrowell well, in practice, pieces in e.g. D-Dorian are very often still written with a ♭ in the signature (even if that requires putting a ♮ before every B note). So, having only systems for every major and every minor key (and accidentals) _would_ be sufficient, albeit not necessarily as convenient.
Comment: @BenCrowell it would be perfectly possible to simply key signatures without regard to mode.  Key signatures already suffer from a complete lack of information about mode, so a simplified system that failed to indicate mode would not detract from the system we have today.  For example, you could replace the current system with a single integer plus a flat or sharp sign, so that (for example) `2♯` means D major or B minor. Or you could institute a system that *does* convey more information, by writing (for example) `DM` or `Bm` or `Ed` for a key signature of two sharps.
Answer: The traditional style of key signatures is pretty close to optimal for the music written from about 1700 to 2000 or so.  During the 1700-1800 (give or take a few decades), it was traditional style was to use 1 less sharp or flat than the piece would now call for. Thus Bach's "Dorian Fugue" is really in D minor with all the Bbs accidentally notated.
Bartok experimented with mixed sharps and flats for notating Eastern European modes. In general, remembering the (generally one-off) key signature wasn't easier than reading a few extra accidentals.
Several articles have suggested using two flats and a sharp for pieces in a minor mode. However, other articles counted the number of accidentals needed using the traditional notation (using the key signature of the relative major) and using two flats and one sharp (on steps 3,6, and 7 respectively) wasn't much different. The minor mode is basically 5 notes (steps 1,2,3,4,5 normal and steps 6 and 7 mutable) so it doesn't seem to matter much which notation was used. The number of raised 6th and 7th steps is about the same as the number of lowered sixth and seventh steps. As many pieces (from the 1600 onward) did modulate from minor to its relative major and vice versa quite a bit, the traditional notation (relative major's key signature) works well overall.
Comment: A lot of questions get posted about why musical notation has not been simplified to remove irregularities and redundant information. And the answer is almost always this - because the traditional system is pretty close to optimal. It is the irregularities and redundancies that allow experienced musicians to navigate quickly and accurately without losing their place.
Comment: The first paragraph is surely incorrect (or incomplete). The Dorian mode on D has B naturals, so if a B-flat is required it would be indicated as an accidental. The piece might *actually* be in D minor, but only because of the accidentals (and as they are accidentals, and not part of the key signature, it's not in D minor).
Comment: I think that's right. The traditional system has been simplified (or at least modified) towards optimality. One problem is that there are several criteria for optimality (economy, precision, ease of reading, ease of writing or printing, etc.), and in general, optimizing one does not yield good results for the others.
Comment: @AndrewLeach This is the "Dorian notation" for (what we would now call) minor keys with flats. Bach actually switches from Dorian notation into Aeolian/modern notation between the fantasia and the fugue sections of the Chromatic Fantasia & Fugue BWV 903.
Comment: What changed in 2000?
Comment: @Beanluc People stopped caring as much about writing out music in general, I suppose? :P
Answer: I think the basic answer is that the vast majority of classical music used notes beyond the diatonic scale, and even in pop music today it's still pretty frequent to have chromatic notes.
Thus, if you're playing in the key of D major, and there's a C-natural, you need to write C♮ with the natural sign.  If this continues for several measures (as sometimes happens with a temporary modulation), it's helpful to have a reminder at the beginning of each staff system that says, "Oh, yeah, C♯ is still the default."  The more chromatic music gets, the harder it can become to remember what the "default" sharps and flats are in the key signature, so having a periodic reminder is helpful.
Also, even if you're in one key, the notation can be harder to understand for music beginners, who may not make immediate connections between the sharps and flats notated on each line and the key of a piece.  This is particularly problematic in minor, where the 6th and 7th scale degrees also tend to move about and can contain various accidentals.  Beginners in music are often taught about "natural minor" and "melodic minor" and "harmonic minor," but actual minor key music tends to use a lot of accidentals on those 6th and 7th degrees.  Again, having a visual reminder on each staff of the accepted defaults can be helpful.
And it's often visually more helpful to see those sharps or flats on the lines and spaces where they actually occur (and can sometimes be cancelled with naturals or added to with additional accidentals).  In fact, it was still accepted practice at times even in the 18th century (and later) to include those key signature sharps and flats on every place in the staff that they'd occur -- for example, a piece in D major in treble clef might mark the F♯ both on the top line of the staff and in the bottom space.  In that sense, modern notation has simplified key signature notation a bit.
(Just as a historical note, part of the reason for that previous practice was because clefs were not particularly fixed in their staff positions until some point in the seventeenth century.  It was quite common for clefs to move up or down by a line or more, even multiple times in the same piece.  Performers reading a score needed to be able to immediately reorient themselves on every line of a score to where the clef was and therefore where the notes were. So having default sharps and flats marked on each staff line or space was also helpful in orienting to each staff line.  We've dispensed with some of the other notational practices needed back then, such as the custos, a symbol that often looked a bit like a checkmark and appeared at the end of each staff system to tell the performer which note was the first note at the beginning of the next system.  Again, this was needed at a time when clefs could move about freely, and performers needed to immediately know how the notes from one line of music connected to those on the next line.)
All of that said, modern practice is inconsistent.  Sometimes things like fake book lead sheets will dispense with the practice of writing the key signature on every line, merely giving it once at the beginning.  (Often they also omit the clef except for the first line.)
It really all depends on how much consistency you have.  In a mostly diatonic piece of music that remains in one key, I agree that one could easily just write "D major" on the top line and everything should be clear.  However, the more chromaticism, key changes, etc. that occur, the more it is helpful to have visual reminders of what the current default sharps and flats are.
On the other extreme, many 20th century composers who began to write highly chromatic and atonal music sometimes dispensed with key signatures altogether, instead preferring merely to note all accidentals when they occur.  If you really wanted to simplify music notation, that practice would actually be most helpful, I think -- any note without an accidental is assumed to be natural, and when sharps or flats occur, they must be written before every note.  That would make music notation more accessible to beginners and be consistent across styles of music that are diatonic, highly chromatic, or even atonal.  However, that practice would require even more notated sharps and flats than our current practice of putting key signatures on every system, so it's unlikely to be adopted anytime soon.
Comment: An observation, not a criticism. Those # and b at the beginning of each line aren't *accidentals* - they're there on purpose! They unfortunately do get called accidentals, but they simply constitute the *key signature*. Accidentals are all the extra ones needed to cancel that pesky key signature (and other accidentals...)!
Comment: @Tim: yes, you're right. I used the word "accidental" as a shortcut, since there's no concise term for "default sharps or flats included in a key signature."  I thought about that as I was writing and decided not to worry about it, but I'll edit to be clearer.
Comment: The custos was never *needed;* it's really just a courtesy.  Granted, it is more useful when the clef is changing, but whether the clef changes or not it helps by visually identifying the interval between the last note of one line and the first of the next.  I frequently write them into my scores.
Comment: @phoog - If you haven't, I'd encourage you to try to sing chant from 12th century notation without a custos.  Then try to reach a 15th-century vocal part in original mensural notation without custodes.  I've done some of both.  When clefs are jumping all around on each line, they are incredibly *helpful*, albeit (I agree) strictly not necessary.  (I find it odd to think of it as "identifying the interval between the last note of one line and the first of the next" - it literally is showing you what the next note is. Thinking of it as an "interval" is a rather modern perspective.)
Comment: @Athanasius I've done those things.  And as I've said, I find the custos helpful even in modern notation.  But what's the point of showing the next note when you can simply look at the next line?  The benefit of the custos has always struck me as showing the *interval,* that is, the distance from the previous note to the next, which is far less obvious across staves (again, even if they use the same clef).  The concept of intervals is hardly modern. It permeates Guido's work, so it's not a stretch to imagine that reading intervals as such was an important part of the benefit of his system.
Comment: @phoog: It's not necessary for very skilled singers. It is incredibly helpful for less experienced ones. And yes, obviously Guido talked about intervals between pitches, but I'm not aware of where he discusses the "interval" as an abstract notion between the notation of two consecutive staff systems. That's what I assumed you were discussing in terms of "interval" (e.g., this staff is pitched a "third" down/up from the previous one or whatever). Now that I re-read your comment, I understand you were referring to the literal interval between the two notes, which makes more sense to me. Sorry.
Comment: No need to apologize!  I was referring to the conditioning whereby we associate visual distance on a musical staff with pitch distance.  This for me is the biggest benefit of the custos, though surely others process music notation through different cognitive circuits than I do.  I tend to read relatively, which is a great benefit when reading music in transposition and in different clefs.  Others read more absolutely.
Comment: @phoog: I read relatively too in that situation. In fact, when looking at early notation, I almost don't care what the identity of pitches are if I'm singing -- I just care about where the semitones lie (which clefs are helpful with). I think I just misunderstood your point -- I tend to look at the custos and see "the next note" which I then reorient to in its place on the next system.  You seem to focus more on reading the interval between the two notes across the systems by using the custos. Makes perfect sense to me.
Answer: Actually, for your 4 sharps example, the key doesn't have to be E major. It could be C♯ minor, or any other mode.
Key signatures don't actually specify the tonal center of a piece. They simply define a set of seven pitch classes that are going to be written without accidentals. I've got no evidence that this is historically why they never simplified it, but if I had to argue right now against specifying the tonal center within the key signature, this is what I'd write.

The key signature is better left as is because tonal centers are often
  ambiguous or poorly defined, and it is much more efficient to specify
  a set of basic diatonic notes than to try to define the subjective
  tonal center of a piece of music.
Answer: The only real reason is "convention changes slowly, if it changes at all".
For example, consider how much worse are the flaws of time signatures: time signatures are misleading to beginners (6/8 usually has two beats in a bar, not six), and fundamentally ambiguous in many cases (7/8 could be two or three beats arranged in any order of longs-and-shorts). There are well-known solutions to both of these problems that have been used in widely-published music (2/♩. and 3+2+2/♪); despite this, 6/8 and 7/8 are still the standards, because despite their flaws, they mostly work. You only need to tell a student once, "no, sorry, 6/8 is two dotted crotchet beats"; and note grouping conventions convey beats in unusual time signatures.
Key signatures are very easily readable, and very flexible (as you say, the freedom to notate unusual key signatures is very rarely used -- but it is used). They may be slightly inefficient to write, but the flaw is not enough to sway people away from a notation that they are used to reading. It is not surprising, given how slowly time signatures evolve, that key signature notation has also been relatively static.
Answer: Perhaps a better alternative to writing 'A-flat' would be '4 flats', the point being that at least for a long time in the history of music, 4-flats always meant B-flat, E-flat, A-flat, D-flat. So when you look at the key signature you just see that there are 4 flats, you don't actually need to see which lines and spaces are indicated, because they are always the same. However 4-flats doesn't necessarily mean A-flat major, it could mean f-minor, so that is a reason to prefer '4 flats' over 'A-flat'. The question here is - over the few centuries when 4 flats always meant the same 4 notes being flatted, why wasn't the convention adopted of just saying '4 flats' - this would have been a convenience for the composer and copyist, if not particularly for the performer. I agree with Peter Smith above that probably the answer is just conservatism; the advantages of adopting a different notation were not that great, and everyone was used to the existing system.
Answer: As you suggested in your question the reason is historical. A very long time ago the only "key signature" was a single flat. That was back in the modal system, the Medieval period. As harmony developed into the major/minor system, the notion of "key" and key signatures developed.
Obviously key signatures work most clearly when the harmony is diatonic. The more music becomes chromatic the more accidentals and/or key signature changes are needed. Getting into modern harmony some music simply dispenses with key signatures and all sharps and flats are written throughout a score.

...My question is: why was the key signature notation never simplified? e.g just write « A♭ » instead of four flats?

So, this...

...versus this...

What problem does that solve?
It seems to only trade one "problem" for another.
Writing <code>Ab</code> tells me the tonic, so I don't have to wonder if the tonality of four flats means <code>Ab</code> major, <code>F</code> minor, <code>Bb</code> Dorian, etc. But it doesn't tell me the specific tones that get the flats (Bb, Eb, Ab, Db.)
Writing the four flats on staff for the key signature tells us the specific tones, but it doesn't tell us the tonic.

...unconventional key signatures are hardly used

Well, if they are unconventionally they wouldn't be used often. But occasionally you can see them, like this for a Freygish scale...

The reason key signatures are still used is lots of music is still fundamentally diatonic and the chromaticism typically encountered isn't that much of a strain on the system.
Answer: Let's suppose that notation was changed at some point in the past. But at that point 100% of sheet music already out there was still in the old notation. So musicians would have had to learn the old notation too, anyway. Even decades or centuries later, until the old sheets were completely replaced, people would have had to learn and use both notations.
Comment: That is generally a good argument for "why change isn't done", however in case of signatures it doesn't really carry much weight. It _would_ be feasible to have a different notation and teach that to beginners. Then later, just memorising a translation table for what the old notation means in terms of the one the student is already familiar with would be easy enough (it's literally just discrete replacements in an "alphabet" of ~10 symbols). In comparison, switching between e.g. notation and guitar-tabulature is highly nontrivial, still many teachers will teach both.


2 groups (patient/control), 3 continuous variables. How to test for difference between the groups for each variable & how to quantify the difference?

Question: For two groups (patient and control, 20-30 participants in each group) I have data on 3 biomarkers. The variables are continuos and not normally distributed.
I want to see in what biomarker the difference is the most and the least pronounced.
I am fairly new in statistics and can not find the right test to run.
Thankful for your suggestions!
Comment: Addition: What I have tried so far is to run a Mann-Whitney test to see if there actually is a difference between the groups. However, I fail to find a test to quantify the difference in each variable, to be able to compare and see what variable shows the biggest difference.
Answer: There are many topics that are appropriate for getting "spot help" on this forum as you see when you look at today's questions.  This is not actually one of them.  Your research involves many, many statistical issues requiring a great deal of study for success to be around the corner.  Or partner with a biostatistician quickly.  Also be prepared to find that the sample size is too small to allow even an experienced biostatistician to do very much.  The adequacy of the sample size depends on the signal:noise ratio in the response variable.
Comment: Thank you for taking your time to answer my question!
This is acutally a exercise-example given to me. I see that there are many issues to overcome. But for me, as a novice in this learning opportunity, is there some test that could be done to asses what biomarker differs the most between the groups? Like I mentioned above, I have tried the Mann-Whitney, which I understand tests the null hypothesis, and from that I have interpreted that there is only significant change in one of the biomarkers between the groups.
Comment: I don't think it's possible to make progress on this problem without understanding statistical models, but if the response variable is binary (meaning that your sample size is far, far too small), you can compute 3 concordance probabilities (c-index; area under the ROC curve) and confidence intervals for them.  These are [0,1] translations of the Wilcoxon statistic and measure pure discrimination ability.
Comment: I do not understand how the response variable (in this case a continuous biomarker) can be binary? And what do you mean when saying "meaning that your sample size is far, far too small"? I am sensing I do not have a solid enough statistical background for this.
Thank you again.
Comment: Yes work with a biostatistician.  But most biostatisticians would not know the Peter O'Brien trick in this case.  Predict the probability of being in the second group as a function of 3 predictors (the 3 biomarkers).   Then do a global test of no association with at least 3 degrees of freedom.  This tests whether there is a signal from any of the 3 markers in predicting group membership.
Comment: If you don't find evidence that at least one of the markers is associated with group (using this chunk test), then stop.  If you do, then you can use the partial tests from the regression model (binary logistic model) to see which biomarkers adds predictive information to the other two.
Comment: I will look into this! Again, thanks a lot for your adivse.
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.


Scroll long text on OLED display

Question: How to scroll a long text on an 128x64 OLED display
am using Adafruit_SSD1306 driver
This code only displays "This" because the text is too large to fit on the display, but when i scroll the text only "This" is scrolling not the rest of the text
<code>display.setTextSize(5);
display.setTextColor(WHITE);
display.setCursor(0,16);
display.clearDisplay();
display.print("This is a long long text");
display.display();
delay(1);
display.startscrollleft(0x00, 0x0F);
</code>
Comment: Scrolling will scroll what is displayed on the screen. The rest of your text isn't.
Comment: yes i see that, but how can i get long text to scroll ?
Comment: I don't really know. I don't think you can do that with the SSD1306 library, and i'm unsure the uno (if that's the one you're using) has enough memory to store all of the rendered text.
Answer: Scroll and wrap around long text lines on a ssd1306 display:
This code is from YT which does this beautifully. My version below works on a ssd1306 128x64 display. Temporary text strings for demo purpose only.
It displays 5 lines, the first is stationary. All the remaining scroll. The next line is text size "2". The others are size "1".
<code>/* https://www.youtube.com/watch?v=sTYPuDMPva8
   Set the appropriate screen size in the Adafruit_SSD1306.h by uncommenting
   one of the two following lines.

   //#define SSD1306_128_64 ///< DEPRECTAED: old way to specify 128x64 screen
   //#define SSD1306_128_32 ///< DEPRECATED: old way to specify 128x32 screen
*/

   #include <Adafruit_GFX.h>
   #include <Adafruit_SSD1306.h>

   Adafruit_SSD1306 display(4);

   char message[]="297M LstWyPt, 345M StPt, rec#89";
   int x, minX;

  void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setTextWrap(false);
  x = display.width();
  minX = -12 * strlen(message);  // 12 = 6 pixels/character * text size 2
  }

  void loop(){

   display.clearDisplay();
   display.setCursor(0,0);
   display.setTextSize(1);
   display.print("Sat:13  03:56:32  67%");// GPS # Satellites, Time, % Batt chg
   display.setTextSize(2);
   display.setCursor(x,10);
   display.print(message);
   display.setCursor(x,28);
   display.setTextSize(1);
   display.print("Press #1 New StPt, 2 RecWayPt, Cur 32.567, -102.456");
   display.setCursor(x,38);
   display.setTextSize(1);
   display.print("Press #1 New StPt, 2 RecWayPt, Cur 32.567, -102.456");
   display.setCursor(x,48);
   display.setTextSize(1);
   display.print("Press #1 New StPt, 2 RecWayPt, Cur 32.567, -102.456");
   display.display();
   x=x-8; // scroll speed, make more positive to slow down the scroll
   if(x < minX) x= display.width();
}
</code>
Answer: You can solve this by either:

Continuously redrawing the entire frame buffer, or
Shifting the framebuffer contents left and rendering a column worth of text (just a fraction of a character) on the right.

The SSD1306 chip provides commands to enable both continuous scrolling and 1 pixel scroll. For our purpose of scrolling long text, the continuous scroll is not useful, as we want to scroll exactly one pixel. Therefore, we need to use the 1 pixel scroll command. The commands take the same parameters, except for the first opcode byte. For some reason in the widely circulated (and pretty old) datasheet online, the 1 pixel scroll command is missing, but it is there in HW.
<code>#define CMD_CONTINUOUS_SCROLL_H_RIGHT       0x26
#define CMD_CONTINUOUS_SCROLL_H_LEFT        0x27
#define CMD_ONE_COLUMN_SCROLL_H_RIGHT       0x2C
#define CMD_ONE_COLUMN_SCROLL_H_LEFT        0x2D
</code>
Use the latter two.
Answer: As i have been dealing with my 64x48 oled display for several days, the ssd1306 comes with a 128x64 RAM, and supports scrolling cyclically, as the panel you are using, there is no spare RAM for buffering new data to the RAM spaces outside the active area, so i think you can follow this: put one column, scroll one column(or multiple columns) and wait for action done by delay method, put next column(s)...
Good Luck!
Comment: What is your question?
Comment: Um - this is an answer, not a question!

Scroll long text on OLED display


Add role on custom register form

Question: I'm using the default register form on a custom page, which I want to use to set a specific role for the user who registers using that custom page.
Now I need to know how I add this specific role when the user registers.
Can I use like, the submit funcion for the custom form function, and then use user_multiple_role_edit()?
But how di I get the $uid?
What's best?
Comment: You could use Rules module to achieve that. http://drupal.org/project/rules
Comment: How would I use it for this matter? Using the reg.form URL, or what?
Comment: I try to prepare a Rules example for you. There is also http://drupal.org/project/autoassignrole but I don't think it is ready for D7.
Comment: autoassignrole works good with D7.
Answer: Here is my solution based on my favorite Rules module ;)
These 2 rules below automatically assign a predefined role to a user who registers to your website using a promotional link and code.
Important: Before importing these 2 rules:

backup your site :P
replace example.com with your domain name
replace 11 with your role id number
replace code=promo1 with your secret promotional code

You can import rules via this page on your website:
/admin/config/workflow/rules/reaction/import
Rule 1:
{ "rules_auto_assign_role_1" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "11" : "11" } } } },
      { "data_is" : {
          "data" : [ "site:current-page:url" ],
          "value" : "http:\/\/example.com\/user\/register?code=promo1"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user?code=promo1" } } ]
  }
}

Rule 2:
{ "rules_auto_assign_role_2" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
      { "AND" : [
          { "NOT user_has_role" : {
              "account" : [ "site:current-user" ],
              "roles" : { "value" : { "11" : "11" } }
            }
          },
          { "data_is" : {
              "data" : [ "site:current-page:url" ],
              "value" : "http:\/\/example.com\/user?code=promo1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "11" : "11" } }
        }
      }
    ]
  }
}

Comment: Oh, thank you so, so much! I'll give it a go as fast as I can. Thank you!
Comment: Hi again, I don't have any promotional code, I just have a certain URL for this reg. form: example.com/cv-register. And I want the role to be added to users registering using that form.
Comment: This is just an example. Instead of the promo code you should modify the url "value" in both rules the way you want so that only users who register via form url as defined in Rule 1 will be redirected to a url as defined in Rule 2. I would suggest to check kind of a token code to make it more secure and to make sure visitors cannot easily hack this solution. This token code should be generated in Rule 1 and checked in Rule2. Otherwise a visitor could just open http://example.com/user?code=promo1 to get the role assigned.
Answer: So I did it like this:
 1. I skipped the usage of role 1 and just used the altred register form to redirect the new user to the user page with a secret query in the url.
 2. Then I used rule 2 and changed the query to the one I was using, changed the static URL to a relative one, and finished the rule of by redirecting the user to another page so he/she wouldn't see the secret query in the URL.

Add role on custom register form


Entity reference to role

Question: I want to add an Entity Reference field to a Group Type entity, referencing User Roles.
When I add a Entity Reference > Other > Roles field, the creation/edition form of this Group Type throws the attached errors:

Despite they're not usual, does Entity Reference fields to user roles work properly?
Answer: It seems that there is a bug in Opigno LMS about configuring entity forms for groups, so the error I reported previously is not related to the reference field.
Just for completion, I reported the bug for OpignoLMS here: https://www.drupal.org/project/opigno_lms/issues/3414721
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Thanks bot, I edited it following this recommendation.

Entity reference to role


Como fazer migrations e versionamento com banco de dados firebird?

Question: Recentemente achei este site Flyway DB onde, pelo que entendi, é possível criar migrations e controlar a versão do banco de dados. Porém acho que não suporta o Firebird. Existe alguma ferramenta similar com suporte ao firebird? Ou é possível usar o Flyway DB de alguma maneira com firebird?
Comment: André, esse suporta o Firebird: http://www.liquibase.org/index.html (http://www.liquibase.org/databases.html)
Comment: Muito obrigado pela ajuda!
Comment: O liquibase pode atender a sua demanda?
Comment: Pelo que entendi me parece ser um pouco complicado de usar. Preciso estudar um pouco mais sobre ele. Mas eu usei o Entity Framework com SQL e me lembro de que lá eu criava migrations que continham as alterações feitas no banco. O liquibase segue a mesma ideia?
Answer: Sim o liquibase segue a mesma idéia. Basicamente é criar changesets dentro do liquibase e executá-lo para que os updates sejam realizados.
Comment: Coloque o link do liquibase ou, melhor ainda, um exemplo de como fazer isto com ele :)
Comment: Alexandre podes completar a resposta aqui? basicamente explicando um pouco mais e dando exemplos?


Visual Studio 2010 $(PlatformName) macro incompatible with MSBuild.exe

Question: I have a C# project in Visual Studio 2010 with this in the pre-build event command line:
echo "$(Configuration)" - "$(PlatformName)" - "$(Platform)"
exit 1

and the results are:
"Debug" - "AnyCPU" - "AnyCPU"

even though the macro section of that window suggests that PlatformName should appear as Any CPU in this case (with a space): https://i.stack.imgur.com/yzplE.png (even though MSDN seems to suggest that there is no space at http://msdn.microsoft.com/en-us/library/42x5kfw4.aspx).
msbuild /property:Configuration="Debug" /property:Platform="AnyCPU"
1>MyProgram.sln.metaproj : error MSB4126: The specified solution configuration "Debug|AnyCPU" is invalid.

What's going on here? Unfortunately, "AnyCPU" is not a valid platform on the command line, so I am unable to proceed. The above works just fine with /property:Platform="Any CPU" (with a space).
Is there another macro I can use, or some flag for MSBuild to accept the platform anyway?
Answer: It looks like you've hit MSBuild bug 503935:
Report:

The msbuild Platform property has a different value for Any CPU
  depending upon whether you are building the solution or building a
  project.
Solution use Platform="Any CPU" - space
Project use Platform="AnyCPU" - no space

Response:

Posted by Microsoft on 11/2/2009 at 7:22 PM
Thanks for taking the time to send us your feedback.
Unfortunatley, having just shipped Beta 2, it is too late in the cycle
  to make adjustments at this point. It makes perfect sense that we
  should make these two the same. Looks like we should use "AnyCPU"
  consistently for both. We also need to make sure that we are backward
  compatible, so we will have to take this in consideration.
In the next round, we hope to be doing work around the solution, and
  we can perhaps fix this during that cycle. For this cycle, I am
  resolving this bug as "Won't Fix".
Thanks,
Chuck England
Visual Studio Platform Program Manager - MSBuild

Final Resolution:

Closed as Won't Fix
Comment: Hmm, guess that's it then. An `if` statement in a batch file takes care of it for the time being.


What is a TXT record with the form ms=msXXXXXXXX used for?

Question: I've noticed that some domains have a TXT record with the form ms=msXXXXXXXX, where each X is decimal digit.
For example ms=ms97284866
What is this kind of TXT record used for?
Answer: They are usually used by automated validation procedures whose purpose is to detect wheter you are the rightful owner of a domain; they will ask you to create a TXT record with a specific text string in the domain DNS zone, and then check if the requested record is actually there; if you were able to create it, it's safe to assume you own (or at least manage) that domain.
A record in the form ms=msXXXXXXXX is typical of the procedure used for domain validation by Microsoft Office 365.
Comment: References for it: [External Domain Name System records for Office 365](https://technet.microsoft.com/en-us/library/hh852557.aspx) and follow the link for "Gather the information you need to create Office 365 DNS records" to see how the msXXXXXXX txt records are used.
Comment: updated url: [External Domain Name System records for Office 365](https://support.office.com/en-us/article/External-Domain-Name-System-records-for-Office-365-c0531a6f-9e25-4f2d-ad0e-a70bfef09ac0)
Answer: This signifies that the domain is an Office 365 tenant.
Comment: Well, technically it only signifies it was validated as usable by Office 365 *at some point in time*, and then someone left the record there (which becomes completely useless after validation is performed). It says nothing about Office 365 actually being in use (as opposed to, f.e., the MX record pointing to Exchange Online).


Display custom user profile field as name in articles

Question: I would like to display the custom user profile field name as the author's name in articles, instead of the user's username. How can I do this without modifying code of my template or Drupal itself?
I saw solutions for Drupal 7 but I'm using Drupal 8. I found custom modules for Drupal 7 or earlier and code modification ways. Both seems wrong to me because the mentioned modules aren't updated nor it feels correctly to me to change code to achieve this quite basic task.
Answer: You can use the Realname module to override the display name with the values of one or more fields:

The RealName module allows the administrator to choose fields from the
  user profile that will be used to add a "real name" element (method)
  to a user object. Hook_user is used to automatically add this to any
  user object that is loaded. It will also optionally set all nodes and
  comments to show this name.
Comment: So there is really no other way than RealName module which is in release candidate 1 phase right now for Drupal 8? This feels bad :/. I had expected bigger flexibility of Drupal 8.
Comment: Why would you need bigger flexibility? Realname is a relatively small module and any other module implementing the same functionalty would ver very similar. There is no need for another module.


Robust Residual standard error (in R)

Question: I have a question regarding to the concept of robust standard errors. What I found about that topic is, that one can estimate the robust standard error for regression coefficients to eliminate problems with heteroscedasticity (when one wants to interpret a model). I want to know if there is a way not only to determine robust standard errors of coefficients but also of the standard error of the overall regression (residual standard error). When its possible, how can I calculate such a value in general?
Because I'm using R its also interesting for me if there is a R-function for this problem (I only know the sandwich-package for the normal robust SE of the coefficients).
Thanks.
Comment: Is it still the policy of Cross Validated to refer problems relating to statistical packages to StackOverflow?
Comment: It depends, @CesareCamestre. If the question is about how to *use* R, such that an explanation of the ideas w/o reference to R, or demonstrated w/ different software, eg Stata, would not answer the question, then it belongs on SO. But if the issue is w/ understanding the ideas, then it can stay here, even if they as about R as well. (Which of the above applies to this Q is not clear to me yet.)
Comment: Welcome to the site, @Meiner. It is not clear to me if you are wondering about the nature of sandwich estimates, or if you are *only* wondering about another way to implement them in R. If the latter, this question would be off-topic for CV (see above), but on-topic on [Stack Overflow](http://stackoverflow.com/). If your question is about the underlying ideas, please edit to clarify; if it's about implementation in R, flag your Q & we'll migrate it for you (*please don't cross-post, though*).
Comment: Do you mean forming confidence bands for predicted values or creating something like a global test for all regression parameters against a null intercept-only model?
Answer: If you are interested in the conditional mean $\mathop{\mathbb{E}} \bigl[ y_j|X_j \bigr] = X_j' \beta$, where $X_j$ may be in or out of sample, then of course you can get the standard error for that as the square root of
$$
X_j' \, \hat v[\hat \beta] \, X_j
$$
where $\hat v[\hat \beta]$ is the heteroskedasticity-corrected/sandwich variance estimator. But that conditional mean is rarely of huge interest; I believe you are interested in characterizing what the whole distribution of $y_j = X_j + \varepsilon_j$ may have looked like. Without knowing more about the distribution of $\varepsilon_j$ you, of course, won't be able to say much about what the variance of $y_j$ will be.

Robust Residual standard error (in R)


Can the order of files be changed when iterating a directory using boost::filesystem?

Question: I have inherited some code using boost's directory_iterator:
for (directory_iterator fileIt{currDir}; fileIt != directory_iterator{}; ++fileIt) {
  // Do stuff with files
}

and I would like to process the files in a particular order (simple alphabetical sorting would do). Is there any way to achieve this, i.e. to enforce the iterator to give me files according to some sorting instead of the default?
Comment: Would putting in a container, sorting it and using it work?
Comment: @GauravSehgal That's my fallback plan if there isn't a nicer way to do this... :)
Answer: You need to sort it yourself because the order of directory entries obtained by dereferencing successive increments of a directory_iterator is unspecified:
std::vector<boost::filesystem::path> paths(
      boost::filesystem::directory_iterator{"."}
    , boost::filesystem::directory_iterator{}
    );
std::sort(paths.begin(), paths.end());
for(auto const& path : paths)
    std::cout << path << '\n';

Comment: May be worth mentioning that [filesystems do not generally handle well directories with more than 10000 files or so](https://stackoverflow.com/a/466596/412080). So that loading all filenames from a directory into a vector should not be a concern, because something else would probably break first.
Comment: https://www.boost.org/doc/libs/1_71_0/libs/filesystem/doc/tutorial.html#Using-path-decomposition


Required for Publishing

Question: For my drupal I want an article always to have an image when it's published, however the authors do no have the rights to upload images (due to copyrighting issues, I only let this be done by a few people who have access to our photo partner, just to be sure that people don't download images from google)
So I want the image field to be required when publishing, but if I put it on required, then the authors have to fill it in during the draft as well, and they don't have the access for it.
I found the following module:
https://www.drupal.org/project/required_for_pub
But it requires a module "content" which I can't seem to find anywhere.
Does anyone have a suggestion for me?
Thank you very much
Comment: Is your website Drupal 6 or 7? The module you linked is for Drupal 6 only.
Comment: It's Drupal 7. You can see in the 'view all releases' that there is also a Drupal 7 module, but it's in dev.

PS: if you know another module, that's fine by me too, I don't exactly need this 1, any module who can make a field required only when publishing will do.
Answer: You can use the required by role module: https://www.drupal.org/project/required_by_role to make sure the publishers have to add an image. The downside is publishers will need to upload an image, even when not publishing.
Comment: Thank you Maarten, this is perfect for me.
You've helped me a lot!

Required for Publishing


What machine learning/deep learning technique to use for a data set consisting of 2D plane

Question: I'm new to machine learning/deep learning field. In an assignment I've been given a data set of 1000 data points. Each data point is a 2D place of dimension 1024 x 1024. In each plane there are some points marked as class-0 (x) and some points marked as class-1 (o). A simple diagram below.
data point #1

        (0,1024)                          (1024,1024)
            |--------------------------------|
            |          x                     |
            |        xx                      |
            |         x                      |
            |        x    o                  |
            |              x                 |
            |         x      x               |
            |                  o             |
            |                                |
            |                                |
            |                                |
            ----------------------------------
           (0,0)                           (1024,0)

data point #2

        (0,1024)                          (1024,1024)
            |--------------------------------|
            |                                |
            |        xo                      |
            |         o                      |
            |        x                       |
            |                                |
            |         x                      |
            |                  o             |
            |                   xxx          |
            |                                |
            |                                |
            ----------------------------------
           (0,0)                           (1024,0)

etc.

We know the Cartesian coordinate (x,y) of each labeled point.
What ML/DL technique should I use to make prediction for unlabeled data point like this.
unknown data point

        (0,1024)                          (1024,1024)
            |--------------------------------|
            |          .                     |
            |        ..                      |
            |         .                      |
            |        .                       |
            |       .                        |
            |      .                         |
            |                  .             |
            |                                |
            |                ..              |
            |               .                |
            ----------------------------------
           (0,0)                           (1024,0)

Any help is appreciated.
Comment: What attributes of the input would allow you to determine whether a sample is class 1 or class 0? Distance from some marker? Vertical or horizontal position? Something else? Do you know that there is a relationship between the information you have and class membership?
Answer: It sounds like you're asking about coming up with a good representation for the input.
You could rasterize these point sets as you've done above and use a 2D convolutional architecture. Alternatively you could use a continuous convolution model or a PointNets-like architecture on the raw point sets.


sharing or referencing an instance of one class in another classes object

Question: I am writing a program that contains several classes and I am trying to access class A instance from class B. I am using setA() and getA() for A'a data member and I am using the same for class B. In class B I also have a function that gets the member from A via the getA() function call. I then want to compare if A's member is the same as B's member.
class A {
    private:
        int a;
    public:
        void setA(int a);
        int getA();
}

class B {
    private:
        int b;
    public:
        void setB(int b);
        int getB();

        bool compareA_B(){
            A a.getA(); //   <- this is a new object A
            B b.getB();
            if(a == b)
                return true;
            else
                return false;
        }
}

When I call setA() in my main function by A a_in_main.setA(2) this A is a different instance than the one above with the arrow.
My question is how do I access the correct instance of A in the B function compare()?
I kind of think I need to use pointers but I am not sure. I have been looking all over the internet and I can't find anything concrete.
I edited this post and I hope this is more clear.
Comment: You'll need a pointer or reference. I'd start with `shared_ptr`s for now since they'll avoid you having to deal with object lifetime issues.
Answer: When declaring int a you are declaring that the class' instance will hold an int, not a reference to one.
When you're setting you also do the same in the function by passing the argument by value (which most likely copies in real world scenarios), so even if it was a pointer internally you could end up with your "reference" referring to a newly made copy.
Your member, and the signature of the functions handling it, need to be pointers or references of some flavor to an int, which will store the memory address it's located at, and when compared will compare memory locations and not the value stored in it.
The syntax for a pointer to a value of some type is type* var.
int* var, int *var, int * var are all equivalent, you will find it expressed all ways depending on the author.
You might also, depending on what the intended use of that member is, want to ensure it can't alter the data it points to const int* var.
It sounds like you're very early on in learning C++, some beginner books or YouTube videos might help. Wrapping referenced values in classes before you know how to make a pointer might be a sign of trying to run before being able to walk.
Comment: just to clarify are you suggesting that I declare `int a` as a pointer so `int * a` and then edit `compareA_B()` to `compareA_B(int* )` and should I change my `int getA()` to `int * getA()` and then I can pass that to the edited `compareA_B` function? I figured I need to use pointers but I wasn't certain the proper way of doing it. Thanks for the response I will try this right away.
Comment: If you want to compare whether both refer to the same address in memory (e.g. changing one affects the other), then yes, you need to switch that member (and the signatures of functions managing it) to a pointer (`int* a` as suggested). `int a` would get you (and compare) the value stored there, and not where it's stored.


Insert into from select with multiple columns and multiple tables

Question: I need to create a SQL Trigger with Insert Statement selecting multiple columns from different tables . Something like this:
CREATE OR REPLACE TRIGGER ACTIV_TRG
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
    INSERT INTO ACTIVITIES values (
    (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
    TR.ACCOUNT,
    TR.EVENT,
    SELECT TRAN_ID ,
    TRAN_DT ,
    TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX',
    CURRENT TIMESTAMP
)
END;

The issue is when I tried to select more than one column in the sub query.
I know if I separate the Sub Query like this :
(TRAN_ID  FROM ACTIV_DEL where TRAN_ID = 'XXX'),
(TRAN_DT  FROM ACTIV_DEL where TRAN_ID = 'XXX'),
(TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX'),

will work but definitely there must be a better and efficient way to do this.
Thanks in advance.
Definitely, there must be a better solution than this:
CREATE OR REPLACE TRIGGER ACTIV_TRG
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
   INSERT INTO ACTIVITIES values (
   (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
   TR.ACCOUNT, ---> FIELD FROM TRANS_LOG (TRIGGER SOURCE)
   TR.EVENT,   ---> FIELD FROM TRANS_LOG (TRIGGER SOURCE)
   SELECT TRAN_ID  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   SELETC TRAN_DT  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   SELECT TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX',  ---> REPETING SELECT
   CURRENT TIMESTAMP
)
END;

Answer: I would do the insert with the following select:
    SELECT (SELECT MAX(SEQNBR) FROM ACTIV_LOG where TRAN_ID = 'XXX'),
        TR.ACCOUNT,
        TR.EVENT,
        TRAN_ID ,
        TRAN_DT ,
        TRAN_LN,
        CURRENT TIMESTAMP
        FROM ACTIV_DEL
        where TRAN_ID = 'XXX'

Comment: Thanks Mary but the thing is that I  also need 3 columns from another sub Query:  SELECT    TRAN_ID ,
    TRAN_DT ,
    TRAN_LN  FROM ACTIV_DEL where TRAN_ID = 'XXX',
    CURRENT TIMESTAMP
Comment: @Bill_Buckner I think this covers perfectly your issue, since it is doing a select to the table ACTIV_DEL
Comment: Mary- but the thing is that I can't use the insert in that way because table ACTIV_DEL might not has record and I'm still need to insert the values of the table(TRANS_LOG
) affected in the trigger.
Comment: @Bill_Buckner I would check if the value exists in ACTIV_DEL if it doesn't exist I would insert a null value in those fields instead of doing the select  (check if exists [link](https://stackoverflow.com/questions/6922048/db2-for-ibm-iseries-if-exists-statement-syntax))
Comment: That's a good approach but we are running in DB2 and does not support conditional INSERT.
Answer: Something like this?
CREATE OR REPLACE TRIGGER ACTIV_TRG
AFTER INSERT ON TRANS_LOG
REFERENCING NEW AS TR
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
    INSERT INTO ACTIVITIES
        SELECT (SELECT MAX(f0.SEQNBR) FROM ACTIV_LOG f0 where f0.TRAN_ID = f1.TRAN_ID),
        TR.ACCOUNT,
        TR.EVENT,
        f1.TRAN_ID ,
        f1.TRAN_DT ,
        f1.TRAN_LN,
        CURRENT TIMESTAMP
        FROM ACTIV_DEL f1
        where f1.TRAN_ID = 'XXX'

END;

Comment: The issue is that table ACTIV_DEL might not has record and I need to insert the values of the table(TRANS_LOG ) affected in the trigger no matter if can't get TRAN_ID ,TRAN_LN and TRAN_ID from ACTIV_DEL table.


(ionSelect) not invoking on ion-select-option

Question: I am trying to get the index value of the selected item from dropdown.
In order to do that, this is the code I am trying:
  <ion-select  okText="Okay" cancelText="Dismiss" [(ngModel)]="dropdown1" (ionChange)="onSelectChange($event)" >
    <ion-select-option *ngFor="let list of goalList;let i=index;" (ionSelect)=" myfun(); myIndex = i" value="{{list.docid}}">
      {{list.personalEmail}}
    </ion-select-option>
  </ion-select>

I was never getting myIndex number, so I tested by adding a function. The function is never invoked.
I searched and found this solution but it was working on ion-option for Ionic 3, but this is not working on ion-select-option in Ionic 4.
Comment: for interest sake, why do you need the index value? Perhaps there is another approach the the problem which will solve the issue
Comment: i have got the value using the array and value, initially i was thinking one way :)
Comment: glad you got it sorted :)
Answer: One option is to set the ion-select-option value as an object as below with the docid and index, this way the object with the docid and index will bind to the ngModel and will be accessible on the ionChange event.detail.value
<ion-select okText="Okay" cancelText="Dismiss" [(ngModel)]="dropdown1" (ionChange)="onSelectChange($event)">
    <ion-select-option *ngFor="let list of goalList;let i=index;" [value]="{docid:list.docid,index:i}">
      {{list.personalEmail}}
    </ion-select-option>
</ion-select>


Atualizar preço dentro de um box com jquery

Question: Tenho uma página com vários boxes contendo algumas informações e o preço do produto, uma URL e um select, quando a pessoa selecionar uma opção diferente no select o preço do produto vai ser alterado. Procurei na internet e encontrei alguns exemplo que poderiam funcionar, no entanto entanto funcionava somente em um bloco.
Por exemplo nesse servidor 01, tem esse valor de 30 e uma URL, mas ao selecionar a opção linux esse valor alterar e também a URL.

.boxe{
float:left;
border: solid 1px #ccc;
margin:15px;
padding:15px;
min-width:135px;
text-align:center
}
.boxe .valor{
font-size:18px;
margin: 15px 0;
font-weight:700;
}

.boxe .url{
display:block;
margin-top:15px;
}

        Servidor 01

30

    <select>
        <option>Linux</option>
        <option>Windows</option>
    </select>

        Comprar

        Servidor 02

45

    <select>
        <option>Linux</option>
        <option>Windows</option>
    </select>

         Comprar

        Servidor 03

50

    <select>
        <option>Linux</option>
        <option>Windows</option>
    </select>

         Comprar

Answer: Bem simples isso, dispare um evento ao mudar o SO, e capte a url e o valor, preencha os dados:

$(document).on('change','.SO-select',function(){
  var val = $(this).val();
  var box = $(this).find(':selected').data('box');
  var url = $(this).find(':selected').data('url')

  $('.SO-valor[data-box="'+box+'"').html(val);
  $('.SO-link[data-box="'+box+'"').attr('href',url)
});
.boxe{
float:left;
border: solid 1px #ccc;
margin:15px;
padding:15px;
min-width:150px;
text-align:center
}
.boxe .valor{
font-size:18px;
margin: 15px 0;
font-weight:700;
}

.boxe .url{
display:block;
margin-top:15px;
}

        Servidor 01

30

    <select class='SO-select'>
        <option value='30' data-box='1' data-url='url-linux'>Linux</option>
        <option value='50' data-box='1'data-url='url-windows'>Windows</option>
    </select>

        Comprar

        Servidor 02

45

    <select class="SO-select">
        <option value='45' data-box='2' data-url='url-linux-2'>Linux</option>
        <option value='55' data-box='2' data-url='url-windows-2'>Windows</option>
    </select>

        Comprar

        Servidor 03

50

    <select class="SO-select">
        <option value='40' data-box='3' data-url='url-linux-3'>Linux</option>
        <option value='50'  data-box='3' data-url='url-windows-3'>Windows</option>
    </select>

        Comprar

Comment: Caramba, quem sabe sabe rsrs, cara não teria uma forma de simplificar isso? pois no que eu vou precisar existe muito blocos, se for usar uma função para cada bloco fica trash, uma forma que ele identifica automaticamente o boxe usando apenas uma função, tem como isso?
Comment: Tem sim, assim que eu tiver um tempinho ja atualizo a resposta a tarde.
Comment: Blz cara, valeu mesmo
Comment: e aí cara, tudo bem? conseguiu atualizar?
Comment: Da uma olhada, só ver o attr 'data-box' que vais entender o mecanismo
Comment: valeu mesmo cara, muito obrigado


Como Desabilitar um dos itens de um TlistBox!

Question: Queria Saber ser tem como Desabilitar um dos itens de um TlistBox.
E já tentei das seguintes maneiras e não tive Sucesso.
ListBoxMenu.ItemIndex(0).Enabled := False;
ListBoxMenu.ItemIndex[0].Enabled := False;

Quando eu ponho essas Linhas apresenta essa msg.

[dcc32 Error] UntPrincipal.pas(6420): E2016 Array type required

Já tem tentei pesquisar sobre no site da http://docwiki.embarcadero.com/ mais não encontrei nada que me ajudasse.
Answer: De acordo com a documentação, a propriedade ItemIndex, especifica o Index do Item selecionado. Logo, ela retorna um inteiro e não o Item em si.
Para recuperar o item você pode usar o método ItemByIndex, ou a propriedade ListItems.
Ficando assim:
ListBoxMenu.ItemByIndex(0).Enabled := False;

ou assim
ListBoxMenu.ListItems[0].Enabled := False;

Isso considerando que você está usando Firemonkey, que da uma liberdade maior de trabalhar com os itens pelo fato dos mesmo serem TListBoxItem.
Agora se estiver usando VCL onde os itens da ListBox são as linhas de uma TStrings.
Ai complica. Se for este o caso sugiro que remova o item da lista ao invés de tentar desabilitar.
Comment: Não Teria com ao menus mudar a cor de cada item do TListBox?


SVG Resize Image out of aspect ratio

Question: I'm trying to figure out how to take a complex SVG file and easily resize it to anything id like. Say I want a 100x100 SVG image to be 5x30 I'd like it to resize to that with out any cropping.
I want to do this using only the SVG document or by embedding it into another SVG file. I'm having a lot of trouble achieving this.
For Example:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentScriptType="text/ecmascript" zoomAndPan="magnify" contentStyleType="text/css" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" version="1.0">
  <image x="0" y="0" width="516.3034" xlink:href="http://upload.wikimedia.org/wikipedia/commons/e/e5/Tux_chico.svg" xlink:type="simple" xlink:actuate="onLoad" height="777.2853" preserveAspectRatio="xMidYMid meet" xlink:show="embed" />
</svg>

This is only cropping the image when what I wish to accomplish is the embedded image gets shrunk to fit inside the viewbox.
Answer: Use percentage for the image element:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" zoomAndPan="magnify" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
  <image width="100%" height="100%" xlink:href="http://upload.wikimedia.org/wikipedia/commons/e/e5/Tux_chico.svg" preserveAspectRatio="xMidYMid meet">
</svg>

Or use the viewBox coordinate system:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" zoomAndPan="magnify" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
  <image width="100" height="100" xlink:href="http://upload.wikimedia.org/wikipedia/commons/e/e5/Tux_chico.svg" preserveAspectRatio="xMidYMid meet" />
</svg>

These two ways may differ slightly if the viewBox aspect ratio doesn't match the viewport since percentages are based on the viewport size. If you don't care about the image aspect ratio you can stretch the image to fit the given size by using preserveAspectRatio="none".

SVG Resize Image out of aspect ratio


Did people use DAWs or Trackers first in the 90s?

Question: I wanted to know what the average home user was using for computer based music production back in the day. I was under the impression that mainly trackers were used in the early 90s to create MODs and S3Ms. Such as:
https://en.wikipedia.org/wiki/Music_tracker
https://en.wikipedia.org/wiki/Scream_Tracker
(Shout out to PSI and the legendary Future Crew from Finland)
https://en.wikipedia.org/wiki/Impulse_Tracker
But were people using DAWs back then (I think midi existed back then?) or did DAWs only become popular in the late 90s when vsts became popular?
Answer: People did use DAWs in the 90s, but in the early to mid 90s, the few DAWs that existed were generally only used by professionals. That is because the processing power of computers was not enough to handle the digital signal processing that even a basic DAW needs, and hard drive systems were not fast enough to stream audio in real time, so DAW systems required both software and dedicated hardware.
In 1991, Pro Tools was released, which was a DAW that could record and playback both MIDI and audio, with up to four simultaneous audio tracks. By 1994, dedicated "DSP farm" cards and SCSI RAID hard drive arrays brought the maximum possible track count up to 64. Pro Tools was the first widely popular DAW in professional studios, even though the very first digital hard disk recorder system was released in 1978. Also in 1991, Cubase first supported audio but it required TDM hardware (created by the makers of Pro Tools) for DSP.
Home studios didn't generally go digital until the late 90s. I myself used a tracker on the Amiga 3000UX in 1992 - 1993, just to make fun little tunes. In 1995, I took a class on MIDI sequencing based around Cakewalk, which at the time was only a MIDI sequencer. At that time, home studios mostly relied on 4 and 8 track analog cassette tape deck recording (like the Tascam Portastudio line). Other MIDI-only software in the late 80s and early 90s included MOTU Digital Performer.
I can't find the exact date, but definitely by 1998, Cakewalk software could record and mix several tracks of simultaneous audio without requiring dedicated DSP hardware (called "native"). I recall using Cakewalk as a mixdown destination for an analog 4-track recording sometime in 1996 or so. Also in the late 90s, Sonic Foundry's Sound Forge software, Bias Peak (released in 1996), Digital Performer, and Cubase (which added native audio processing in 1996) all could record, edit, and mix two or more tracks of audio on a regular home PC. Propellerhead Reason and Sonic Foundry (later Sony) Acid and Vegas were notable software releases at the end of the millennium, with Acid and Reason being the software that popularized looping, prior to Ableton releasing Live in 2001.
The first release of the Steinberg VST specification and SDK was in 1996, but the popularity of ASIO and the VST plugin format actually took a while to catch on. Some competing systems were proprietary, like MOTU's MAS system and Digidesign's (the makers of Pro Tools) Audio Suite and TDM systems. Other plugin formats were OS-based, like Microsoft's DirectX and Apple's Audio Units. As far as I know, DirectX is not used by DAWs today, but Apple Audio Units continues to be a major plugin format despite only being available on MacOS systems. My first DAWs in 1997 - 2002 were Cakewalk and Sony Vegas, which both relied heavily on the DirectX plugin format and were therefore Windows-only packages.
So the answer to your question is that DAWs did not even become available to the home user until the mid to late 90s, and it wasn't until the early 2000s that VST started to displace DirectX on Windows as the most popular plugin format. And on MacOS to this day, VST is not needed (although it is available). I myself use several DAWs for various purposes on a Mac and I never use the VST or ASIO standards for anything.
Also note that there were digital audio systems that were not computer based that had popularity in the 90s. For smaller studios and home studios, the Alesis ADAT format, released in 1992, allowed up to 64 tracks of digital audio to be recorded on several ADAT tapes, that were the same physical format as VHS video tapes. Jagged Little Pill by Alanis Morissette was recorded on ADAT.
The Otari RADAR dedicated multitrack hard disk recorder was first released in 1993, but was priced generally out of reach of the home studio crowd. Like ADAT, you couldn't mix or apply effects with a RADAR unit, it was just a digital version of a 24-track tape deck. So you still had to have an analog mixing console and any outboard effects to make a mix. From that point of view, it was a very expensive system, but being able to erase the hard disk and perform non-linear editing without having to cut tape or having tape wear out or having to calibrate tape heads was a big advantage.
Comment: Ahh... this takes me back ;) Cubase Audio was actually 1991, on Mac+TDM, but it was rare as hen's teeth. I remember demoing the CBX D3/D5 system in Frankfurt 96 & the joy when the VST native system came out a year later.


Assign textfield to each checked option in a checkboxes field

Question: Lets say I have a checkboxes field and when I check one of the options, I would like a textfield to appear so I can assign a number (quantity) to it. Every option I check would have its own textfield.
For example, I have a "Fruits" field and I want to be able to say how many of each fruit I have. So it would be something like that:
<code>[x] Apple (3)
[] Grape
[x] Orange (2)
</code>
Is there any module that does something similar to that?
Edit:
Another thing that would do the work for me would be a select list of numbers for each option. So by default the options are like that:
<code>[0] Apple
[0] Grape
[0] Orange
</code>
So I can simply change the number of fruits in each option by selecting in the dropdown.
Answer: The conditional fields module should be suitable for this

Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is "dependent", it will only be available for
  editing and displayed if the state of the "dependee" field matches the
  right condition.
Comment: Well, I don't think it will work if I have a variable number of options and I want to have a field assigned to each one of the checked options. That would work if I wanted a single textfield (or a defined number of fields) to appear when I check any option. Please correct me if I'm wrong.
Comment: You said about variable number of options but each of these options have a name (Apple, Grape, Orange and so on). By which way you want to assign this names?
Comment: These options are actually nodes and I use a view for filtering them. So any time I add/delete a node, the number of options will change. That's why I can't create a defined number of fields and trigger each one of them when a option is checked.
Comment: How do you implement connection between nodes and Fruit field(s)?
Comment: This is just an example, but each fruit in this case is a node... and the title is the fruit name


Não estou a conseguir criar uma Div dinamicamente JjQuery

Question: Sou principiante no que toca a Javascript e jQuery e estou a tentar criar uma div dinamicamente, o meu objetivo é criar um bootstrap Alert sempre que o botão é pressionado mas não estou a conseguir que isso aconteça...
<button id="myBtn">Click Here</button>

Este é o script:
$("#myBtn").click(function() {
   $(this).after(
       '
'+
            '<button type="button" class="close" ' +
                    'data-dismiss="alert" aria-hidden="true">' +
                '×' +
            '</button>' +
            'Password Changed' +
        '
');
});

Answer: Para criar uma div com Jquery, é muito simples:
    $('
', {
    id: 'minhaDiv',
    class: 'minhaClasse',
    'outro-atributo': 'meuValor'
}).appendTo('body');

E você acrescenta isso a um onClick, fica a teu critério.
Comment: você pode passar variáveis para dentro dos valores dos atributos, um exemplo seria:
let meuValor = 'valor1'
    $('', {
    html: meuValor,
}).appendTo('body');
Comment: Claro. Vamos resolver o seu problema de criar um alert:
primeiro você cria a div com Jquery:
let minhaDiv = $('');
depois você acrescenta um conteudo a ela, as suas classes bootstraps:
minhaDiv.addClass('alert alert-success alert-dismissable');

e você joga essa div criada para dentro de algum lugar, certo? pode ser o body:
minhaDiv.appendTo('body');

Se você quiser criar um input e colocar dentro dessa div, é o mesmo processo, mas você coloca no final um appendChild();

http://api.jquery.com/append/
Comment: no Jquery, se usa o .html('texto aqui dentro') para escrever alguma coisa no estilo label ou descrição de um botao, voce faria o seu $('').html('texto do botao');
Comment: E como é que eu mudo o conteudo dessa Div ou o innerHTML suponho?
Comment: Não entendi o que quis dizer com passar variáveis para dentro dos atributos, poderia explicar de outra forma por favor?
Comment: Muito obrigado pela explicação mas tenho mais uma dúvida, como é que eu faço para colocar um texto como o "Password Changed" que eu tenho no meu exemplo? Obrigado :)
Answer: Você pode manter o html separado o js colocando assim:

    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">
        ×
    </button>
    Password Changed

<button id="myBtn">Click Here</button>

e no js assim:
$("#myBtn").click(function() {
    $('.alert').show();
});

mas lembre que quando você clica no X do alert ele remove o conteúdo e não é possível mostra-lo novamente. Para que isso não ocorra você pode adicionar um link ou botão que apenas oculta o alert.
Aqui tem um exemplo sem remover o alert

$("#myBtn").click(function() {
  $(".alert .mensagem").html('Sua mensagem aqui');
  $('.alert').show();
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  ×

<button id="myBtn">Click Here</button>
Comment: No exemplo do alert, você pode usar o mesmo alert para diversas mensagens e manter o html separado do js. Assim você não precisa criar o conteúdo, mas é possível sim criar o conteúdo, porém o ideal para manutenibilidade do código é manter separado. Você precisa realmente criar o conteúdo novo ou apenas alterar o texto da mensagem?
Comment: O objetivo é criar div's dinamicamente e não só uma, existe alguma forma de fazê-lo da forma que você explicou?
Comment: Preciso somente alterar o texto da imagem.
Comment: Alterei o ultimo exemplo manipulando a mensagem
Comment: É isso mesmo que eu precisava, obrigado :)


DataGridView Row Color Doesn't Change

Question: Hello im working on Windows Form Applications but i have a problem. We are using data grid view and if row's if one column or more is empty, i want to highlight it. I dont know why but my code doesn't work. Here its my code;
 public Form1()
    {
        InitializeComponent();
        var dtCombined = PopulateCombinedDatatable();
        dataGridView.DataSource = dtCombined;
        HighlateIfEmpty();
    }

    public string[] FindFilePath()
    {
       //OPERATIONS
    }

    public DataTable PopulateCombinedDatatable()
    {

       //MY OPERATIONS
    }

    public void HighlateIfEmpty()
    {
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                if ((string)cell.Value == string.Empty)
                {
                    cell.Style.BackColor = Color.BlueViolet;
                    cell.Style.SelectionBackColor = Color.Aquamarine;
                    row.DefaultCellStyle.SelectionBackColor = Color.BlueViolet;
                    row.DefaultCellStyle.ForeColor = Color.Yellow;
                    row.DefaultCellStyle.BackColor = Color.Aquamarine;
                }
            }
        }
    }

Thanks...
PS : This code finds right columns and rows but not paint it
Comment: Please call the function a little later, maybe form the FormLoad or  FormShown event
Comment: It doesnt work :(
Answer: You should call this HighlateIfEmpty() in dataGridView1_CellFormatting event,
for your reference i added a link please go through it.
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx
Comment: But here it will be called over and over for for each cell !
Comment: Yes in `cell formatting` event it call for each cell so avoid foreach and try this,i hope it work for you.    private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1)
        {
            if ((int)e.Value == 3)
                e.CellStyle.BackColor = Color.Blue;
            if ((int)e.Value == 2)
                e.CellStyle.BackColor = Color.Red;
        }
}
Answer: I know this post is a bit old, but anyway . . .
On the DataGridView there is a DefaultCellStyle, inside this there is SelectionBackColor and SelectionForeColor properties.
The DataGridView uses a style inheritance idea, in case you find that the style you pick is not being applied.

DataGridView Row Color Doesn't Change


setting specific interval time on python

Question: I'm currently working on a Python project. The code will refresh at a specific time and fetch new records and update the database. What I'm trying to achieve is to refresh every 15 minutes or 30 minutes. The below code is good but only fetches new records once per day at 00.00am.
def check_schedule_task(self):
        # update group member list at 00:00 am every morning
        t = time.localtime()
        if t.tm_hour == 0 and t.tm_min <= 1:
            # update group member
            Log.debug('update group member list everyday')
            self.db.delete_table(Constant.TABLE_GROUP_LIST())
            self.db.delete_table(Constant.TABLE_GROUP_USER_LIST())
            self.db.create_table(Constant.TABLE_GROUP_LIST(), Constant.TABLE_GROUP_LIST_COL)
            self.db.create_table(Constant.TABLE_GROUP_USER_LIST(), Constant.TABLE_GROUP_USER_LIST_COL)
self.wechat.fetch_group_contacts()

I tried the below but it's refreshing every second
def check_schedule_task(self):
            # update group member list at 00:00 am every morning
            t = time.localtime()
            if t.tm_min == 15 or 30 or 45 or 00:
                # update group member
                Log.debug('update group member list everyday')
                self.db.delete_table(Constant.TABLE_GROUP_LIST())
                self.db.delete_table(Constant.TABLE_GROUP_USER_LIST())
                self.db.create_table(Constant.TABLE_GROUP_LIST(), Constant.TABLE_GROUP_LIST_COL)
                self.db.create_table(Constant.TABLE_GROUP_USER_LIST(), Constant.TABLE_GROUP_USER_LIST_COL)
    self.wechat.fetch_group_contacts()

Answer: The line if t.tm_min == 15 or 30 or 45 or 00: is incorrect.
What you want to write instead is
if t.tm_min in (15,30,45,00):

Despite what you may think, your version is not how comparing to multiple values works in Python. The comparison will always evaluate to true since even if the first comparison is false, the rest of the values are truthy. You instead want to check if that list of number contains your variable.
Comment: You should also show the `if var==15 or var==30 or var==45 or var==00` approach.
Comment: if t.tm_min in (15,30,45,00):  > this works perfectly, thanks brother


PHP Formatar tempo contendo letra no valor

Question: Exemplo: 2h53m23s
Gostaria que ficasse assim:02:53:23
Exemplo no meu codigo

<?php

valor_com_letra = "2h53m23s;

aqui a formatacao

echo $valor_com_letra; //resultado 02:53:23

;?>
Answer: Um jeito simples é fazer replace desses valores
Ex
str_replace('s','', str_replace(['h','m'], ':', $valor_com_letra));

Comment: Perfeito meu amigo obrigado ta !
Comment: So estou com um probleminha srrs  quando vem assim o valor : 58m26s gostaria que ficasse assim 00:58:26
Comment: no caso ele fica assim: 58:26 ai nao entra no sistema entendi
Comment: Você pode fazer um IF verificando a quantidade de caracteres. Se for 5 após o tratamento, você adiciona 00: na frente


Loading HTML templates synchronously

Question: I am trying to render a template a template in Typescript, which is not happening. Here's the code and the browser error:
class QuestionView extends Backbone.View{
    template: (data:any) => string;

    constructor(options?:any){
        var question = this;
        require(["text!add-new-question.html"],
            function(html) {
                question.template = _.template(html);
            }
        );
        _.bindAll(this, "render");
    }

    render(){
        var data = this.model.toJSON();
        var html = this.template(data);
        return this;
    }
}

Error:
Uncaught TypeError: Object #<QuestionView> has no method 'template' Main.ts:49
QuestionView.render Main.ts:49
(anonymous function) Main.ts:57

Update:
As pointed out below, this is happening because of the require functions returns after the the render is finished its execution. I've trying running with a setInterval() and it works. How can I make the require function a synchronous one?
Comment: I bet the `require` callback is returning after you're executing `var html = this.template(data);`. Since `template` hasn't been assigned to yet, it doesn't exist and throws that error.
Comment: You've got a point. How do I make this synchronous?
Answer: You should try using jquery-ajax insted of require.js
var ajxParam: JQueryAjaxSettings = {
   async: false, timeout: 200000,
   url: "http://somthing", dataType: "html",
   cache: false,
   success: (htmltext: any, textStatus: string, jqXHR: JQueryXHR) => {

   },
   error: (jqXHR: JQueryXHR, textStatus: string, errorThrow: string) => {
           // show error?
   }
}
$.ajax(ajxParam);
//you can bind your data here

Loading HTML templates synchronously


Using IBM Swift Sandbox and rangeOfCharacterFromSet

Question: I am trying swift on IBM's new Swift online Sandbox.
The following script is not running on that sandbox: http://swiftlang.ng.bluemix.net/
import Foundation

func palindromTest(s: String) -> Bool{
    let lower = s.lowercaseString
    let letters = NSCharacterSet.letterCharacterSet()
    let onlyLetters = lower.characters.filter({String($0).rangeOfCharacterFromSet(letters) != nil})
    let reverseLetters = Array(onlyLetters).reverse()

    return String(onlyLetters) == String(reverseLetters)
}

palindromTest("abc")

The sandbox prints the following error message:
/swift-execution/code-tmp.swift:7:48: error: value of type 'String' has no member 'rangeOfCharacterFromSet'
    let onlyLetters = lower.characters.filter({String($0).rangeOfCharacterFromSet(letters) != nil})

Did I forget to import something? Hope you can help me.
Thanks.
Answer: rangeOfCharacterFromSet is one of the many String methods
which are actually handled by NSString.
From this commit
to NSString.swift, it seems that support for rangeOfCharacterFromSet
was added only recently to the (non-Apple)  Foundation library,
so you cannot use it until the IBM Swift Sandbox is updated to use
a new Swift version.
Answer: FWIW, this works now in the Sandbox swiftlang.ng.bluemix.net/#/repl/aae5d1caf4e0a6232ff428c3a0160e6e98cba6ed913ce9176f2baee46d30cb1c
Answer: Lots of things have changed since these answers were given. I've updated Pat's Sandbox answer for Swift 3.1.1. Below is the code and a summary of the API changes.
Several methods in the standard library and Foundation have since been renamed:

Array: .reverse() → .reversed()
String: .rangeOfCharacterFromSet() → .rangeOfCharacter(from:)
(NS)CharacterSet: .lettersCharacterSet() → .letters

I also made a slight change, perhaps just from personal preference. Rather than use String.rangeOfCharacter(from:) I chose to use CharacterSet.contains(), which required I use String.unicodeScalars instead of .characters. Not sure about the performance tradeoffs in general, but I liked how cleaned things up.
import Foundation

func palindromTest(_ word: String) -> Bool{
    let letters = CharacterSet.letters
    let onlyLetters = word.lowercased().unicodeScalars.filter {
        letters.contains($0)
    }.map { Character($0) }
    let reverseLetters = onlyLetters.reversed()
    print("\(String(onlyLetters)) == \(String(reverseLetters))")
    return String(onlyLetters) == String(reverseLetters)
}

print(palindromTest("abc"))
// false

print(palindromTest("dud"))
// true


Grid.columns.editable not available where is wrong?

Question: I have a problem with kendoGrid with popup editing. It displays value of first column as a label in popup even when I set editable property to false.
columns: [
    {
        template: kendo.template('#: sys_index # '),
        width: 38,
        editable: false
    }, {
        title: 'System Name',
        field: 'SystemName'
    }, {
        command: ['edit', 'destroy'], width: 200
    }
]

rendered grid
grid popup
Comment: Welcame to stackoverflow. I redrafted your question to clarify your problem. If unnecessary label in grid popup is not your question, please edit it and specify your problem.
Answer: Editability determines if the field value can be modified, but it will still appear in both cases. A possible option is to remove the readonly content in the Grid's edit event.
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-edit
http://dojo.telerik.com/ItUvA
Assuming that the readonly content is in the first column...
edit: function(e) {
    var form = e.container;
    form.find(".k-edit-label").eq(0).remove();
    form.find(".k-edit-field").eq(0).remove();
}


Positioning moving  elements in the background using CSS

Question: OK, so I have these background
s which pan left and right using the jQuery plugin, spritely.
So, I was wondering what the best way to position them was.
I obviously have specified both of the two
s which each contains one background image to have a z-index: -1 so they appear behind everything else.
But I would like them to be one after another, row by row essentially in the background.
I just need to find out how to do that using CSS, so any ideas you guys have please let me know!
Thanks!
UPDATE:
Trying a jsFiddle here:
http://jsfiddle.net/uNmuf/
The only problem appears to still be the positioning...
For some reason I can't get it to work right yet..
UPDATE UPDATE:
Hey thanks a lot Pat, it actually works great!  Check out the jsFiddle and my page too!
http://www.marioplanet.com
Comment: Can u please post some code? the HTML block and CSS. you can use jsFiddle.com to make it easier for you and SO users to isolate the problem and we can fork your code.
Answer: I would position them absolutely with the first row starting at top: 0 and the second row at top: height_of_first_div.  Ideally height_of_first_div will be constant so you can hardcode it in the CSS, but if not, you could always use a snippet of jQuery to put it in the right spot onload.
The CSS would look something like this, assuming the
's are fixed height:
div.pan {
   position: absolute;
   z-index: -1;
   left: 0;
   top: 0;

   height: 100px;
}

div.row2 {
   top: 100px;
}

And the associated HTML:

You can see it in action here.


R - Remove all outliers at once

Question: I have a data set imported in R where I am trying to remove the outliers. I did it so far that I identified all outlier values with a boxplot and saved them in a variable.
outlier_values_2 <- boxplot.stats(myfileswoNA$smart_1_raw)$out  # outlier values.
boxplot(myfileswoNA$smart_1_raw, main="Outlier", boxwex=0.1)

hist(myfileswoNA$smart_1_raw)
summary(myfileswoNA$smart_1_raw)

Now I am trying to remove the lines with the identified outliers. I can do this with one certain value:
example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]

But what I would like to do is to remove all outliers at once, which are stored in the variable outlier_values_2
For example this way is not working:
example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]

Can anyone help me with this issue? Or does anyone have an idea?
Comment: If all outlier values are stored in `outlier_values_2`, try `myfileswoNA[!myfileswoNA$smart_1_raw %in% outlier_values_2,]`.
Comment: thanks @LAP your code is working fine!
Comment: maybe `myfileswoNA <- myfileswoNA[smart_1_rawmin(outlier_values_2 ),]`.
Answer: The answer from @LAP helped me with my problem.
Here is what he suggested:

If all outlier values are stored in outlier_values_2,
  try
  myfileswoNA[!myfileswoNA$smart_1_raw %in% outlier_values_2,]

R - Remove all outliers at once


How can you investigate a daily traffic drain?

Question: Running Amazon EC2 instance, t3.large tier. And observing interesting situation:

Every night (UTC+1 midnight) the same NetworkOut jump occurs. What are my options to investigate it?
The EC2 runs nginx and varnish only. Nginx access logs don't show anything like that. So it must be something different.
Answer: You can possibly make a script which periodically calls any tool like this (http://nethogs.sourceforge.net/) or similar others. Keep appending this output to a file with time info. Run this script as a daemon.
Next day you can see what is that "culprit" process.
This thread seems to have more such tools : Network usage top/htop on Linux
Comment: Thanks, among the tried ntop, ntopng, iftop nethogs was the most informative!
Comment: Now I wonder, what the heck is this: http://f.cl.ly/items/0d2I2k460S3Q3I2U1m3n/Screen%20Shot%202014-02-18%20at%2020.39.41.png


Existe uma diferença entre uma árvore binária perfeita e uma árvore binária balanceada?

Question: Como posso compreender uma árvore binária balanceada e uma árvore binária perfeita?
Answer: Sim, como o nome diz uma árvore binária perfeita tem todos seus nós uniformes, não tendo nenhum desbalanceamento, portanto sempre está ligados a 2 nós (exceto o último que evidentemente pode ter um só). Ela é perfeitamente balanceada. É muito trabalhoso para o algoritmo manter isto e não costuma valer o esforço. Algo assim:
<code>         5
       /   \
     3       7
   /   \   /   \
  1     4 6     8
</code>
A árvore binária balanceada admite um desbalanceamento de 1 nível. Pode ser assim:
<code>         5
       /   \
     3       7
   /   \       \
  1     4       8
</code>
Mais um nível abaixo do 8 não seria admitido e a árvore ficaria desbalanceada.
Coloquei no GitHub para referência futura.
Comment: Toda arvore perfeita é balanceada então?
Comment: Na sua arvore balanceada. Se retirar a folha 1 ela continua balanceada?
Comment: Sim, perfeitamente balanceada. Neste caso tirar continuaria balanceada, mas colocar depende do lugar, justamente aí em algum caso exigiria um rebalanceamento. A perfeita exige rebalanceamento em muitas situações porque só o último nível pode ficar desbalanceado (não tem como exigir que todos sejam).
Answer: Um adendo em relação a resposta do Maniero, é que uma árvore binária perfeita é sempre balanceada mas o contrário não é verdade. A principal característica de uma árvore perfeita é ter o número total de nós pertencente ao conjunto {1, 3, 7, 15, 31, 63, ..., 2^(n+1)-1}, sendo n altura, assim todas as folhas estarão no mesmo nível.
Uma árvore balanceada leva em conta o fato de balanceamento de cada nó, que pode assumir -1,0 ou 1, para obter o fator de um nó você faz a diferença da altura esquerda e direita desse nó.( Esse fator pode ser tratado como modular também pode-se admitir em alguns apenas 0 ou 1 apenas).
Recomendo esse site: https://sites.google.com/site/esdicapsi/estruturas-dinamicas/arvores-binarias
Esse vídeo: https://www.youtube.com/watch?v=YkF76cOgtMQ&list=PLxI8Can9yAHf8k8LrUePyj0y3lLpigGcl&index=21