Tuning the lowest bass string a hair flat

Question: I was listening to Abbey Road but it's just Bass and it sounds like the low E string is a hair flat in a lot of the songs. How did they get away with that?
When I was in the pep band many years ago playing guitar, the bass player told me he did the same thing deliberately. I didn't really challenge him, but I've never done the same even after picking up the bass. Does it somehow give the horns more latitude to be slightly flat, or something? Or is it just superstitious baloney?
In summary, is there any good reason to tune the lowest string of the bass instrument a hair flat?
Comment: It's my understanding that the extreme ends of the piano, both high and low, are also intentionally made "out of tune". As to why ....
Comment: The effect of string thickness on the piano causing inharmonic partial and that being compensated for by *stretch tuning* is a factor for both high and low notes on the piano. It could be that the low E string on a bass is thick and stiff enough that a bit of stretch tuning helps there. But a lot of bass tones, including McCartney's don't have a lot of the upper partials very audible.
Comment: On the piano, my understanding is that the overtones of the lowest strings are not harmonic because they're so stiff and not *string-like*. So they're detuned slightly so the overtones of low octaves don't clash so much. ... Maybe being slightly out could create a chorusing effect with the guitars and make the tonic chord sound fatter?
Comment: Late note: John says that's the Rikki in his answer below & research shows he's right. Having been a Riiki player for over 40 years [mine is a mid 70's 4001], I perhaps ought to have recognised the sound - but even re-listening, it doesn't sound like any Rikki I've ever played. Possibly wired mono or just front pickup [which I've never done] & that heavy compressor is throwing me. Or he had flat-wounds… idk… Anyway - Rikkis can suffer from high nut. I fixed mine so long ago, I'd almost forgotten ;)
Comment: Does the lead answer (by Miguel Zapata) on this Quora thread lend any insight? [Why do bass guitars always sound slightly off-key and out of tune even if they have been perfectly tuned?](https://www.quora.com/Why-do-bass-guitars-always-sound-slightly-off-key-and-out-of-tune-even-if-they-have-been-perfectly-tuned)
Comment: @Aaron - a strong pluck may *initially* make the pitch sound slightly higher - same with guitar, just watch the tuner needle - but very soon, any note will settle to its real pitch. Not convinced that low B strings are floppier. Mine aren't. On the OP's  video, sounds to me like the lower strings are in tune, but the higher notes are out. In fact, some of the playing sounds pretty amateur.
Comment: Listening to only the first 30s of that, the first time he hits the bottom string, a fretted G, it's sharp - so that theory goes straight out of the window. I didn't check the rest of it to see if he had a bad zero fret he was compensating for.
Comment: @Tetsujin - wherever the zero fret was, isn't that a reference point that the whole intonation works from? So if that's out to the rest of the frets, is that what you mean?
Comment: If the zero fret [or nut, whichever] was flat to the rest of the neck, it would make sense to tune slightly flat to pull the fretted notes in. I'd always consider that in the late 60s tuning was somewhat more 'optional' than it is these days.  "Close enough for jazz" ;-))
Comment: @Tetsujin - is that the right way? Flat open string - wouldn't you tune it a little sharp?
Comment: Not if you wanted your F to be right. Crappy old guitars [in which I include 1960's Hoffners ;) have a tendency to be high at the nut, making E flat, F sharp, then getting better up the neck, if the intonation's right. Of course, he could afford to get it fixed… but did he? [This is all pure speculation anyway, I didn't listen through enough to be sure] Or he could have just hit that first low G a bit too hard. I switched it off at that point.
Comment: FWIW, I used to tune my lowest string flat because when I would hit it, it would be sharp at the begining.
Answer: Thanks for a great question. Being a bassist and an admirer of Paul and the Beatles it was great to hear isolated bass tracks from the Abbey Road album.
In answer to your summary question, there really is no good reason to tune the low string on a bass flat. Doing that defeats the purpose of trying to play in tune. Assuming your bass is intonated properly if you play notes of the same pitch on different strings with that method the notes on the E string will be flatter than the same notes on other strings. Where is the logic in that? I can play devil's advocate and say why just the E string? Why not all of them gradually slightly more than a P4th apart from each other? Imagine what that would sound like.
As for Abbey Road, I did a flex pitch analysis of Come Together amd Something in Logic Pro and made some interesting discoveries.
Come Together
The tuning is better and the tone is more pure which makes me think he used his Rickenbacker for this song. The D string is a little flat in relation to the others but aside from that the bass is pretty much in tune.
Something
This has to be the Höfner. The notes are darker and more warbly, especially the low notes. The notes fretted high on the neck play sharp and the open strings play flat so the intonation is off. Also on the E string notes there is a pitch dive after the initial attack, probably a characteristic of the short scale instrument and the hollow body. Check out the pitch analysis of the chromatic descending line in the bridge:

The E string is very flat and I'm sure it is not intentional because the fretted notes are more in tune than the open strings. I'm guessing he tuned using the 5th fret method and that actually might have been a good thing.
I remember Paul saying the Höfner had some tuning issues. It's amazing how we don't really notice it much in context though. I'm sure the guitar going through the Leslie and the organ background help it all blend togehter.
In conclusion I know pianos use stretch tuning, where the octaves are tunes at intervals slightly larger than an octave so the low end is a bit flat and the high end is a bit sharp. The reason for this is the unique characteristics of that instrument. It would be pretty difficult to emulate that on a bass. Maybe a bass can be tuned a few cents flat overall to try and match the low end of the piano, say if they are going to be playing unison lines but not just the E string IMO.
Comment: If the action on the Hofner was pretty awful (= high), then tuning the open strings a tad flat would put fretted notes back in tune, do you think? Not sure if digital tuners were around at that time, so tuning to each other was the standard way, and with no keyboard to reference, any old where used to do. As so many '60s bands did.
Comment: @Tim High action could be the cause of the upper register notes being sharp. I believe Paul said he liked a fairly high action. His sound suggests he played on the hard side which can alter pitch too. The Hofner has a floating bridge so a very slight accidental nudge can take it out of correct intonation as well. As far as tuning goes, Abbey Road (the album) has piano, Rhodes or organ on just about every song so I'm sure they matched them or at least used tuning forks for reference.
Comment: @Tim I also wanted to mention the open E on Something actually registered as a D# 46 cents sharp! A little more than "a tad", huh? Also, to me  action that's too low is just as or more awful as high action but then again I play a lot of upright...
Comment: At least low action won't take a fretted note out of tune - unless it catches the string on the next fret up! That D# was on the way to being E, almost, be fair...
Comment: @Tim if you look at my pitch analysis it looks like it started out as an E!
Comment: The stretched piano tuning is due to the harmonics of the strings being out-of-tune: Piano strings are not ideal strings, they are very thick for their length, so they behave a bit like vibrating, tensioned rods. This shifts the frequencies of the harmonics up. So, for an octave to sound perfect on the piano, it has to be stretched from the 2x factor to match the first overtone of the low string to the fundamental of the high string. The too short strings at the low end and, and the too thick strings at the high end of the scale need much more stretching than the better balanced center strings
Comment: That said, bass strings are also relatively thick and short for their frequencies, especially on a short scale bass, so the same kind of stretching results when you tune the bass strings relative to each other.
Comment: @cmaster-reinstatemonica Regarding the stretching you say results when you tune, there are several different ways to tune a bass, such as 5th fret to open string, matching harmonics on adjacent strings, electronic tuner, tuning fork(s). Which results in this stretching, the harmonics? Also, are we talking cents or fractions of a cent?
Comment: @JohnBelzaguy Frankly, I do not know how strong this effect is on bass strings, but it should be comparable to a piano (similar string length). The effect kicks in with harmonics tuning. Frets do not care about harmonics and using them stretches the string. A good setup has the fret position correct for the effect of this stretching, but frets are inherently imprecise. For the piano, the answer is the railsback curve, which is depicted in https://commons.wikimedia.org/wiki/File:Railsback2.png . This gives a tuning shift between the E and A note that you have on a bass as around 8 cents.
Answer: The range of the bass never necessitates this tuning complication well known from piano tuning.  The "hair" would end up so thin, for a bass, so as to have no effect whatsoever and I have never seen anyone to do this as an explicit tuning step.  But it may be implicit in our tuning methods.
I don't find the idea entirely absurd for a fretless plucked instrument with an extra low (and relatively short) lowest string.  Am I calling the E string relatively short?  Yes I am, it's meant relatively to its thickness. There are two ways to make a string sound extra low.  Either you make the string longer, but then the bassists need to grow orchestral player's big hands and perhaps even make uncomfortable detours into their C extensions.  Or you alter the weight/stiffness ratio but that makes the string relatively thicker, which is the same thing as making it "relatively shorter".
A string has the shape of a thin cylinder.  The thinner it is, the closer it is to a line segment.  A line segment has harmonics at integral multiples of the base frequency; a thin cylinder has them a tiny bit further apart of each other.  Especially the F2/F1 ratio is affected.
The E string is not normally played in the thumb position because there it becomes a thick enough cylinder that it's no longer perfectly in tune even with its own harmonics (thus sounding a bit muddy).  So it usually ends up used only for notes too low to be played on any other string.  Its overtones have to be in tune with those higher strings' fundamentals and overtones, while its own fundamental is "free" to be tuned wherever, as long as it is not audibly out of tune with its own overtones (a condition which is only approximately reachable, and not alterable by ordinary tension based tuning).  In fact, a common bass tuning technique tunes the 4th harmonic of E to match the 3rd harmonic of A, which would, if executed perfectly, result in the thicker string's fundamental ending up a super-thin hair flat compared to the thinner string's fundamental.  Won't that affect all of E, A, D strings equally?  Yes it would theoretically all of them, but the thickest cylinder would be affected the most.  So if anyone would ever barely perceive or barely measure the effect, it would be probably on the E string.
Won't the same effect be encountered on a cello as well?  Well, there are two differences here.  One is psychoacoustic.  We are better at detecting pitch differences by ear in the cello range than in the contra octave.  The fundamental frequency is always physically much "louder" than any of its overtones, but we might have quite a bit more of a tolerance for the fundamental to be a little bit off on the E string (because it is so low), without any such tolerance for the pitch of any of its simultaneously present overtones (also coming from the E string, not just from sympathetic resonance of anything else).  The other reason (as Edward has pointed out) is that bowing, as opposed to plucking, provides stable energy transfer to the string, therefore the phase of all the harmonics isn't synchronized among themselves just at the beginning of the tone, but continuously (which is called mode locking).  So the harmonics are no longer stretched apart from each other when using the bow, they have to compromise (weighted by energy, thus favoring the fundamental).  And the bass gets tuned specifically for pizzicato performance more often than any other instrument in the violin family.
Where does fretlessness come in?  Well, any of the above, imperceptible as it is, is sure to drown, on the physical level, in intonation inaccuracies (finger position, finger force angle, action height).  But fret positions on a cheap instrument can mess up with intonation even more.  So tuning methods which have to rely on anything other than open strings and their overtones will have their own bigger problems to balance than non-integral ratios between harmonics.  Tuning is an exercise in compromises, so as to offend the ear the least.
TL;DR - The tuning method matters.  When I'm tuning the E string using pizzicato flageolets, or when I'm tuning the bass to match a particular piano, my ear probably locates the pitch of the E string by its overtones more than by its fundamental, and the fundamental does indeed end up a tiny bit flat compared to the fundamental of any other string, while still providing the optimal tuning for subsequent pizzicato play.
Comment: Also, a bowed cello is not inharmonic, as the bowing motion phase-locks the harmonics. [Source](https://newt.phys.unsw.edu.au/jw/harmonics.html)  The difference is not purely psychoacoustic.
Comment: "The range of the bass never necessitates this tuning complication well known from piano tuning."  [This image](https://en.wikipedia.org/wiki/File:Railsback2.png) says that we expect a piano's low B (which appears on a standard 5 string bass) to be about 30 cents flat, and the low E would be about 20.   [(See Also)](http://www.synthmind.com/ch5.html) Considering that an electric bass is more inharmonic than a piano (citation needed), we should expect stretch tuning to be a concern for bass tuning.  So why don't we stretch?  I'm not sure, but my bass sounds most in tune slightly flat...
Comment: @Edward - The range of a typical piano, is a little over 7 octaves of open strings.  Even a six stringed bass can't get close to that.  However, whenever I play bass and piano together, I shamelessly tune the bass 1-1 to the piano, consequently my bass ends up those 20 cents flat on the fundamental, too.  I can't hear that but I can see that on my tuner (using a fairly complicated procedure).
Comment: Matching a piano's tuning exactly would give a stretch from about -30 to 0 cents, compared to -30 to +30 for the piano's full 7+ octave range.  Yes, that's smaller, but is that insignificant?
Comment: @Edward - Yes I think so.  My only experience is with a standard 4 stringed upright, -20 to 0 cents per your image.  I can't find solid numbers on human pitch resolution ability around contra G (50 Hz); this is probably highly individual, but probably a magnitude worse than what the right hand typically plays on a piano (300 Hz to 1000 Hz).  I don't think I can resolve 20 cents down in the former range, while I could detect 3 cents harmonically up in the latter range.  Guess which frequencies I will be matching if tuning plucked strings by ear.
Comment: And that's exactly the reasoning for stretched tuning.  20 cents flat at 50Hz is insignificant, but having the upper harmonics in tune is important, and you achieve that by tuning (roughly) 20 cents flat.
Comment: @Edward - Right.  But other days I use a frequency based tuner which has has sort of precision of about 4 cents (1 Hz near 440 Hz) and the end result works for me, too.  Weeelll... the tuner uses an autocorrelation algorithm with high and low pass filters.  I could reconfigure it so that it would stop hearing the overtones and see what would happen then.  But I still believe that the pitch freedom on the bottom end is just optional.  I don't need to take advantage of it for an instrument playing mere 3 octaves.


I can't center align my image border radius with the text

Question: How to center text with the image having border-radius of 50%, horizontally.
Below is the code:

Kristen Wu

.box{
border-radius: 50%;
display: flex;
height: 40px;
align-items: center;
text-align: center;
margin-top: 20px;
}

Answer: Can you upload an image of what the expected outcome should look like?
To center the image within your div tag, you can achieve this by applying:margin: 0 auto; in your .box class.
This is equivalent to the following:
margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;

Basically centering your image horizontally.
Comment: Oops That didn't work.  I mean the text would be just beside the image border radius. I already attached the image in y question. Check it
Comment: There are no images attached.
Answer: I'm sorry if my answer is not right, because i catch your mean is to make align center. Maybe it can help

<!DOCTYPE html>

<title>Web Page Design</title>

Kristen Wu

Answer: The easiest way to align something to centre in HTML is the center tag.
You can use that to centre anything. And the code you wrote for border radius is also correct.
PS. center is the right spelling for the code. IF you write centre, it wont work


How to make sure a clojure variable is of the right Java type

Question: java-code XSSFRow row = sheet.getRow(p);
clojure-code (def row (.getRow sheet p))
How do we make sure that row is of type XSSFRow ?
Comment: I would like to see the title more descriptive; e.g. "How to make sure a clojure variable is of the right Java type". I could edit it myself, but I prefer to let the questioner decide.
Answer: Clojure is dynamically typed, so the type of a var/value is determined at runtime.
If you want to make sure a value is of a certain class, you could make the following assertion:
(assert (= (class row) XSSFRow))

Or, more concisely (thanks to opqdonut):
(assert (instance? XSSFRow row))

This does not check for exact class, but for any superclass:
(instance? Object row) ;=> true

Comment: Or more concisely `(assert (instance? XSSFRow row))`
Answer: Notice that there is a way to specify type hints for the compiler using metadata. In some forms you can insert the following constructions:
(let [^String str-val (do-something)] ...)
(def ^double y)
(defn f [^int int-arg ^"[[I" 2d-int-array] ...)

note the ^type expression. This is shorthand for specifying one element of metadata, that is, :tag key in metadata map.
Now the compiler can optimize the code, directly resolving calls to java methods instead of reflection now when it knows exact type of var.
There is an example on clojure.org: http://clojure.org/java_interop#Java%20Interop-Type%20Hints . It suggests, and I think it is right, not to overuse type hints, since they just clutter the code and are generally not needed for adequate performance.
Comment: On the other hand, if your code is only going to work with an XSSFRow (i.e. will fail if passed something else), then I think the type hint is good for documentation purposes, and the fact that the compiler doesn't have to generate reflection code is a nice incidental bonus.


Como apagar dados Modal Bootstrap na segunda vez - ASP.NET MVC 5

Question: Quando eu abro Modal na segunda vez, o elemento de áudio continua o mesmo.
Já fiz upload de áudio novo e ainda continua o áudio antigo.
Por favor segue abaixo o meu código.

        @Html.LabelFor(model => model.Voice )

        @Html.TextBoxFor(model => model.Voice, new { @class = "form-control", @type = "file" })

Html5 Audio:
    <audio controls style="width: 400px;">
        <source src="@Url.Action("StreamUploadedSong")" type="audio/mp3" />
        Your browser does not support the audio element.
    </audio>

Javascript:
    $(function () {

        $.ajaxSetup({ cache: false });
        $("a[data-modal]").on("click", function (e) {
            //hide dropdown if any (this is used wehen invoking modal from link in bootstrap dropdown )
            //$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');

            $('#myModalContent').load(this.href, function () {
                $('#myModal').modal({
                    //backdrop: 'static',
                    keyboard: true
                }, 'show');

                //bindForm(this);
            });
            return false;
        });
    });

O problema é:
public FileStreamResult StreamUploadedSong() // não entra aqui na segunda vez com modal bootstrap
{
}

Na segunda vez ele deveria entrar ação Public StreamUploadedSong ()
Porque não está trabalhando certo ?
Answer: Isso acontece porque a src que você define url já foi carregada, ao abrir novamente a modal, você não está recarregando o objeto do player ou seu conteúdo, apenas exibindo novamente na tela do usuário.
Atribua um identificador ao seu elmento Audio:
 <audio id="audioPlayer" controls style="width: 400px;">
    <source src="@Url.Action("StreamUploadedSong")" type="audio/mp3" />
    Your browser does not support the audio element.
</audio>

E após abrir a modal execute o método load(), isso deve ajudar:
   $(function () {

    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {
        //hide dropdown if any (this is used wehen invoking modal from link in bootstrap dropdown )
        //$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');

        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                //backdrop: 'static',
                keyboard: true
            }, 'show');

            $("#audioPlayer").load();

            //bindForm(this);
        });
        return false;
    });
});


What files/directories should I add to .gitignore when using Poetry, the Python package manager?

Question: I'm using a very new Python package manager called Poetry.
It creates several files/directories upon creating a new project (environment), but I'm not sure which one I should add to .gitignore for the best practice.
Say I create a new poetry project by doing this:
$ poetry new foo_project
$ cd foo_project
$ poetry add numpy
$ ls

There are:
tests (directory)
foo_project (also a directory)
pyproject.toml (a file that specifies installed packages)
poetry.lock (a lock file of installed packages)
README.rst (I don't know why README is created but it just shows up.)

I usually add tests/, foo_project/, poetry.lock and README.rst because they seem to be dependent on the machine the project was created. Also, I seem to be able to reproduce the environment only with pyproject.toml so that's another reason I ignored all other files/directories.
However, it's just my hunch and unfortunately, I can't find any official guide what I really should add to .gitignore on the official documentation.
It just bugs me that I don't know for sure what I'm doing. Which ones should I add to my .gitignore?
Answer: Also moved to poetry quite recently.
I would say you should not add any of: tests/, foo_project/, poetry.lock or README.rst to your .gitignore. In other words, those files and folders should be in version control. My reasons are as follows:
tests/ - your tests should not be machine dependent (unless this is a know limitation of your package) and providing the tests for others is how they test a) the installation has worked and b) any changes they make don't break past features, so a pull request becomes more robust.
foo_project/ - this is where your python module goes! All you .py files should be inside this folder if you want poetry to be able to build and publish your package.
poetry.lock - see https://python-poetry.org/docs/basic-usage/ where it says:

When Poetry has finished installing, it writes all of the packages and the exact versions of them that it downloaded to the poetry.lock file, locking the project to those specific versions. You should commit the poetry.lock file to your project repo so that all people working on the project are locked to the same versions of dependencies (more below).

README.rst - although this one is perhaps more a personal thing, this is the file that becomes your package readme if you use poetry for publishing your package, e.g. to PyPi. Without it you're package will have an empty readme. I have two readmes one .md (for GitHub) and one .rst (for PyPi). I use the GitHub readme for developers/users and the PyPi for pure users.
Comment: That's "should not add any of ... to your .gitignore"? You should add them to your repo, sort of thing.
Comment: Is there a typo? You say "I would say you should not add any of", and then proceed to list things, along with reasons that you _should_ add them.

Thanks for the reasoning, btw.
Comment: Do you likewise have any books on reading comprehension you could recommend me? I seem to be needing it ;)

(I read the title of the question and your answer, didn't bother with @user8491363's specifics)


Change p-inputSwitch label and style

Question: I would change the style of p-inputSwitch component of Primeng library
I would get something like this:

Here's my code :

SEARCH BY

Business group

Borrower

I started by deleting labels but width changes also and I don't know how to increase it
Answer:
I started by deleting labels but width changes also and I don't know how to increase it

Override PrimeNG ui-inputswitch class :
.ui-inputswitch {
  width: 80px !important;
}

See Plunker
Answer: just but the input switch in  a div and adjust this class to your need

      .smaller-switch {
        transform: scale(0.8);
    }

Answer: you can replace your div element with following

Change p-inputSwitch label and style


What Is Piano Music With Two 'Great Staves'?

Question: I have some music here - 'Five Australian Christmas Carols' pretty old, prior decimal currency which was about 1960.
Words and music.
Laid out in four staves.  Bass and Treble Clefs.  Twice.
Top pair have the words between them.  Bottom pair doesn't.   The parts are almost identical.
What is the purpose of this layout?
Comment: My guess is that the top two staves are SATB voice parts, and the bottom two are a piano arrangement to go with them.
Comment: Can you submit a picture? My original guess was a four-hand piano score, but your description might not match that.
Answer: My guess based on it being a carol and your description of the notation.
The words and top two staves are for 4 vocal parts (Soprano and Alto on one stave & Tenor and Bass on the other stave).  The other two staves are for 1 to 4 voices played on an instrument such as a piano, church organ or played by a small group of musicians on strings capable of covering the pitch range.
That they are similar could be to help the congregation sing in tune.
Comment: Very sorry not to have acknowledged and/or responded to these posts.  In particular I should have supplied a picture.

I guess Emma has answered it fine and here's the picture:  https://imgur.com/a/mKGQJNl


Reject Incoming Call in Flutter

Question: How to detect and reject incoming calls in flutter  even if the app is in background. Any help will be appreciated.
Comment: did you solve that? I'm trying to build an app that will show more details about person which is calling to you (based on incoming call phone number)
Comment: I didn't find any related plugin in flutter. I used [Platform Channel](https://flutter.dev/docs/development/platform-integration/platform-channels) for my task.
Comment: Is there a chance to share that code? I'm trying to create app that will show additional info about caller. The main problem is to start app when call starts or at least leave app on background.
Comment: I'm sorry I don't actually have code  with me and that was not working properly too. May be this class could be helpful for you [PhoneStateListener Class](https://developer.android.com/reference/android/telephony/PhoneStateListener).
Answer: Package:
https://pub.dev/packages/notification_incoming_call
Docs:
import 'package:flutter/material.dart';
import 'package:notification_incoming_call/notification_incoming_call.dart';
import 'dart:async';
import 'package:uuid/uuid.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _uuid = Uuid();
  var _currentUuid;
  var textEvents = "";

  @override
  void initState() {
    super.initState();
    listenerEvent();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> listenerEvent() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      NotificationIncomingCall.onEvent.listen((event) {
        print(event);
        if (!mounted) return;
        switch (event!.name) {
          case CallEvent.ACTION_CALL_INCOMING:
            // TODO: received an incoming call
            break;
          case CallEvent.ACTION_CALL_START:
            // TODO: started an outgoing call
            // TODO: show screen calling in Flutter
            break;
          case CallEvent.ACTION_CALL_ACCEPT:
            // TODO: accepted an incoming call
            // TODO: show screen calling in Flutter
            break;
          case CallEvent.ACTION_CALL_DECLINE:
            // TODO: declined an incoming call
            break;
          case CallEvent.ACTION_CALL_ENDED:
            // TODO: ended an incoming/outgoing call
            break;
          case CallEvent.ACTION_CALL_TIMEOUT:
            // TODO: missed an incoming call
            break;
          case CallEvent.ACTION_CALL_CALLBACK:
            // TODO: only Android - click action `Call back` from missed call notification
            break;
          case CallEvent.ACTION_CALL_TOGGLE_HOLD:
            // TODO: only iOS
            break;
          case CallEvent.ACTION_CALL_TOGGLE_MUTE:
            // TODO: only iOS
            break;
          case CallEvent.ACTION_CALL_TOGGLE_DMTF:
            // TODO: only iOS
            break;
          case CallEvent.ACTION_CALL_TOGGLE_GROUP:
            // TODO: only iOS
            break;
          case CallEvent.ACTION_CALL_TOGGLE_AUDIO_SESSION:
            // TODO: only iOS
            break;
        }
        setState(() {
          textEvents += "${event.toString()}\n";
        });
      });
    } on Exception {}
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.call,
                color: Colors.white,
              ),
              onPressed: () async {
                this.makeFakeCallInComing();
              },
            ),
            IconButton(
              icon: Icon(
                Icons.call_end,
                color: Colors.white,
              ),
              onPressed: () async {
                this.endCurrentCall();
              },
            ),
            IconButton(
              icon: Icon(
                Icons.call_made,
                color: Colors.white,
              ),
              onPressed: () async {
                this.startOutGoingCall();
              },
            ),
            IconButton(
              icon: Icon(
                Icons.call_merge,
                color: Colors.white,
              ),
              onPressed: () async {
                this.activeCalls();
              },
            )
          ],
        ),
        body: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints viewportConstraints) {
            return SingleChildScrollView(
              child: ConstrainedBox(
                constraints: BoxConstraints(
                  minHeight: viewportConstraints.maxHeight,
                ),
                child: Text('$textEvents'),
              ),
            );
          },
        ),
      ),
    );
  }

  Future<void> makeFakeCallInComing() async {
    await Future.delayed(const Duration(seconds: 7), () async {
      this._currentUuid = _uuid.v4();
      var params = <String, dynamic>{
        'id': _currentUuid,
        'nameCaller': 'Hien Nguyen',
        'appName': 'Callkit',
        'avatar': 'https://i.pravatar.cc/100',
        'handle': '0123456789',
        'type': 0,
        'duration': 30000,
        'extra': <String, dynamic>{'userId': '1a2b3c4d'},
        'headers': <String, dynamic>{'apiKey': 'Abc@123!', 'platform': 'flutter'},
        'android': <String, dynamic>{
          'isCustomNotification': true,
          'isShowLogo': false,
          // 'ringtonePath': 'ringtone_default',
          'backgroundColor': '#0955fa',
          'background': 'https://i.pravatar.cc/500',
          'actionColor': '#4CAF50'
        },
        'ios': <String, dynamic>{
          'iconName': 'AppIcon40x40',
          'handleType': '',
          'supportsVideo': true,
          'maximumCallGroups': 2,
          'maximumCallsPerCallGroup': 1,
          'audioSessionMode': 'default',
          'audioSessionActive': true,
          'audioSessionPreferredSampleRate': 44100.0,
          'audioSessionPreferredIOBufferDuration': 0.005,
          'supportsDTMF': true,
          'supportsHolding': true,
          'supportsGrouping': false,
          'supportsUngrouping': false,
          'ringtonePath': 'Ringtone.caf'
        }
      };
      await NotificationIncomingCall.showCallkitIncoming(params);
    });
  }

  Future<void> endCurrentCall() async {
    var params = <String, dynamic>{'id': this._currentUuid};
    await NotificationIncomingCall.endCall(params);
  }

  Future<void> startOutGoingCall() async {
    this._currentUuid = _uuid.v4();
    var params = <String, dynamic>{
      'id': this._currentUuid,
      'nameCaller': 'Hien Nguyen',
      'handle': '0123456789',
      'type': 1,
      'extra': <String, dynamic>{'userId': '1a2b3c4d'},
      'ios': <String, dynamic>{'handleType': 'number'}
    }; //number/email
    await NotificationIncomingCall.startCall(params);
  }

  Future<void> activeCalls() async {
    var calls = await NotificationIncomingCall.activeCalls();
    print(calls);
  }
}

Reject Incoming Call in Flutter


Complex roots of Complex polynomal

Question: Apologies if this is a repeated thread I just couldn't quite find anything that helped.
how do I go about finding the complex roots of a complex polynomial?
such as
$$x^3 + (1-i)x^2 + (1-i)x - i$$
any advice would be great thanks
Comment: Why not use Horner?
Answer: There is a general formula for that. However, in this case you can also notice, that $x=i$ is clearly a solution, and then divide the polynomial by $x-i$ to get:
$$\left(x-i\right)\left(x^{2}+x+1\right)=0$$
The other two roots can then be found by solving $x^2+x+1$

Complex roots of Complex polynomal


Combining wind staves for conductor's score

Question: I'm trying to engrave a score, and I'm working on setting up the wind staves. There are two flutes, so what I would like to happen is passages where they play mostly in unison to be displayed on one stave, and passages where they do not play in unison or at a large difference in pitch to be displayed on two separate staves. I would also like that when there is only flute 1 or flute 2 playing, that they be displayed as Voice One on their own staff. I can do the first two using the example from the Hiding Staves article in the manual. But I haven't found a way to make the third requirement (which in an ideal world would happen by itself when one of the staves is empty) possible.
Here's what I have so far. In this example, the notes on the fourth system should ideally be displayed as Voice One, with the staff name "2." completing the "Fl. 2." label.

Which is generated by:
\version "2.24.1"

fluteOne = \relative c'' {
  \time 2/4
  \repeat unfold 8 {c2} \break
  \repeat unfold 8 {c2} \break
  \unset Staff.keepAliveInterfaces
  c'8 a d e | f e d c
  \set Staff.keepAliveInterfaces = #'()
  \repeat unfold 6 {c2} \break
  \repeat unfold 8 {R2}
}

fluteTwo = \relative c'' {
  \time 2/4
  \repeat unfold 8 {a2}
  \repeat unfold 8 {a2}
  \repeat unfold 8 {d,2}
  c'8 a d e | f e d c | c8 a d e | f e d c |
  \repeat unfold 4 {R2}
}

\score {
<<
  \new GrandStaff \with {
    \consists Keep_alive_together_engraver
    \alterBroken stencil #'(#t) SystemStartBrace
    \override InstrumentName.X-offset = -6
    instrumentName = "Fl."
    shortInstrumentName = "Fl."
  }
  <<
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      \consists Merge_rests_engraver
      instrumentName = \markup {
        \column
        \string-lines
        "1.
         2."
      }
      shortInstrumentName = \markup {
        \column
        \string-lines
        "1.
         2."
      }
      \override VerticalAxisGroup.remove-layer = 3
      keepAliveInterfaces = #'()
    }
    <<
      \fluteOne \\ \fluteTwo
    >>
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      instrumentName = "1."
      shortInstrumentName = "1."
      \RemoveAllEmptyStaves
      \override VerticalAxisGroup.remove-layer = 2
      keepAliveInterfaces = #'()
    }
    <<
      \fluteOne
    >>
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      instrumentName = "2."
      shortInstrumentName = "2."
      \RemoveAllEmptyStaves
      \override VerticalAxisGroup.remove-layer = 2
      keepAliveInterfaces = #'()
    }
    <<
      \fluteTwo
    >>
  >>
>>
  \layout {
    mragged-left = ##t
    indent = 2\cm
    short-indent = 1\cm
    #(layout-set-staff-size 20)
    \context {
      \Score
      \override Stem.french-beaming = ##t
      %rehearsalMarkFormatter = #format-mark-box-numbers
      %\override Beam.whiteout = ##t
      %\RemoveAllEmptyStaves
    }
  }
}

I have a hunch that it has something to do with the keepAliveInterfaces, but I'm not sure how to make it work, help would be really appreciated.
Comment: Are you sure this is a good approach?  In my experience, it's more standard to keep them always condensed onto a single stave (at least, exceptions are very rare, and your (2) certainly wouldn't need to be broken out as two staves), and this is easier to read since it makes the grouping of staves much more consistent.
Comment: @PLL you're probably right. I'm just thinking about passages where the voices cross, or where the dynamics aren't in sync; in those cases I feel like the stave gets crowded very easily.
Answer: How about making use of \partCombine?
\version "2.24.1"

fluteOne = \relative c'' {
  \time 2/4
  \repeat unfold 8 {c2} \break
  \repeat unfold 8 {c2} \break
  \unset Staff.keepAliveInterfaces
  c'8 a d e | f e d c
  \set Staff.keepAliveInterfaces = #'()
  \repeat unfold 6 {c2} \break
  \repeat unfold 8 {R2}
}

fluteTwo = \relative c'' {
  \time 2/4
  \repeat unfold 8 {a2}
  \repeat unfold 8 {a2}
  \repeat unfold 8 {d,2}
  c'8 a d e | f e d c | c8 a d e | f e d c |
  \repeat unfold 4 {R2}
}

\score {
<<
  \new GrandStaff \with {
    \consists Keep_alive_together_engraver
    \alterBroken stencil #'(#t) SystemStartBrace
    \override InstrumentName.X-offset = -6
    instrumentName = "Fl."
    shortInstrumentName = "Fl."
  }
  <<
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      \consists Merge_rests_engraver
      instrumentName = \markup {
        \column
        \string-lines
        "1.
         2."
      }
      shortInstrumentName = \markup {
        \column
        \string-lines
        "1.
         2."
      }
      \override VerticalAxisGroup.remove-layer = 3
      keepAliveInterfaces = #'()
    }
    \partCombine \fluteOne \fluteTwo
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      instrumentName = "1."
      shortInstrumentName = "1."
      \RemoveAllEmptyStaves
      \override VerticalAxisGroup.remove-layer = 2
      keepAliveInterfaces = #'()
    }
    <<
      \fluteOne
    >>
    \new Staff \with {
      \override InstrumentName.X-offset = -3
      instrumentName = "2."
      shortInstrumentName = "2."
      \RemoveAllEmptyStaves
      \override VerticalAxisGroup.remove-layer = 2
      keepAliveInterfaces = #'()
    }
    <<
      \fluteTwo
    >>
  >>
>>
  \layout {
    mragged-left = ##t
    indent = 2\cm
    short-indent = 1\cm
    #(layout-set-staff-size 20)
    \context {
      \Score
      \override Stem.french-beaming = ##t
      %rehearsalMarkFormatter = #format-mark-box-numbers
      %\override Beam.whiteout = ##t
      %\RemoveAllEmptyStaves
    }
  }
}

Comment: @ValérieThibault Yes you can customise the text: `\set Staff.soloIIText = #"2 solo"`,  see this page: https://lilypond.org/doc/v2.24/Documentation/notation/multiple-voices#automatic-part-combining
Comment: Oh cool! that does work, although it's not exactly what I had in mind. Is there a way to customize the text it displays? Say if I wanted it to say "2 solo" or something like that?


understanding "this" inside a plugin

Question: First of all I'm sorry but I'm a really big beginner.
I dont really understand the "this" in the jquery plugin, was looking a lot but couldn't really find any answer.
here is my plugin (im making this only for practice)
jQuery.fn.hoverPlugin = function(){

    var element = this;

    $(element).animate({"opacity" : ".5"});

        $(element).hover(function(){
            $(element).stop().animate({"opacity" : "1"});
        }, function() {
            $(element).stop().animate({"opacity" : ".5"});
        });
};

the call
$("img").hoverPlugin();

My problem is this way it adds the animate effect on all images. It's okay if animates on all images on the page load, but when I place the mouse over an image, it animates all.
If I write it in the simple way
$("img").animate({"opacity" : ".5"});

        $("img").hover(function(){
            $(this).stop().animate({"opacity" : "1"});
        }, function() {
            $(this).stop().animate({"opacity" : ".5"});
        });

It works the way I want.
So if a more experienced developer could explain to me how can I make this in my plugin? I would be really happy.
Thank you
Answer: That's because this in the .hoverPlugin function is referencing the $('img') used to call it:
jQuery.fn.hoverPlugin = function(){
    var element = this;

    $(element).animate({"opacity" : ".5"});

    $(element).hover(function(){
        $(element).stop().animate({"opacity" : "1"});
    }, function() {
        $(element).stop().animate({"opacity" : ".5"});
    });
};
$(document).ready(function(){
    $("img").hoverPlugin();
});

http://jsfiddle.net/ww7gg/
If you try that with console open, you'll see what I mean.
If you just change to this:
$(element).hover(function(){
    $(this).stop().animate({"opacity" : "1"});
}, function() {
    $(this).stop().animate({"opacity" : ".5"});
});

http://jsfiddle.net/ww7gg/1/
It works.
And this is better:
jQuery.fn.hoverPlugin = function(){
    this
        .animate({"opacity" : ".5"})
        .hover(function(){
            $(this).stop().animate({"opacity" : "1"});
        }, function() {
            $(this).stop().animate({"opacity" : ".5"});
        });
};

You don't need element, just use this and chain.
http://jsfiddle.net/ww7gg/2/
Comment: really big thanks, for your help, now i understand, and thanks for spearing time on my question.
Answer: On your plugin:
var element = this; is a jquery Collection of element(s):
jQuery.fn.hoverPlugin = function(){
    var collection = this.animate({"opacity" : ".5"}); //Fade all elements to .5 opactiy.

    collection.each(function() {
        var element = this; // Single element from the collection
            $el = $(element); //Create 1 jquery object and re-use it on the events.

        $el
            .hover(function(){
                $el.stop().animate({"opacity" : "1"});
            }, function() {
                $el.stop().animate({"opacity" : ".5"});
            });
    });

};

Answer: jQuery.fn.hoverPlugin = function(){

    var element = this; //this is already wrapped as jquery object e.g it will refer to $("img") in your case

    element.animate({"opacity" : ".5"});

        element.hover(function(){
            element.stop(true,true).animate({"opacity" : "1"});
        }, function() {
            element.stop().animate({"opacity" : ".5"});
        });
};

and use it
$("img").hoverPlugin();

understanding "this" inside a plugin


Manipulating a column in pandas dataframe

Question: I have a pandas dataframe as below:
data = {'A' : [1,2,3],
        'B' : [2,17,17],
        'C1' : ["C1", np.nan,np.nan],
        'C2' : ["C2", "C2",np.nan]}

# Create DataFrame
df = pd.DataFrame(data)

Dataframe:
    A   B   C1  C2
0   1   2   C1  C2
1   2   17  NaN C2
2   3   17  NaN NaN

I am creating a variable "C" based on the below logic and code
If any of C's(C1, C2, C3..) has the value "C"= value from C's(C1, C2, C3....).
df['C'] = df.filter(regex='C\d+').stack().groupby(level=0).agg(','.join)

Result:
    A   B   C1  C2  C
0   1   2   C1  C2  C1,C2
1   2   17  NaN C2  C2
2   3   17  NaN NaN NaN

Now, I want to perform below logic
If "C" has more than 1 values(say C1, C2) for any row, create a new row and append 2nd value. So I want my output to look like below:
    A   B   C1  C2  C
0   1   2   C1  C2  C1
0   1   2   C1  C2  C2
1   2   17  NaN C2  C2
2   3   17  NaN NaN NaN

Comment: why has the first row `C1`?
Comment: Because perviously the vaue of C was C1,C2, now I want to have row for each C1 and C2
Answer: We can do it by use explode then concat
s=df.filter(regex='C\d+').stack().groupby(level=0).agg(list).explode().to_frame('C').join(df)
s=pd.concat([s,df[~df.index.isin(s.index)]],axis=0,join='outer',ignore_index=True,sort=False)
s
Out[62]:
     C  A   B   C1   C2
0   C1  1   2   C1   C2
1   C2  1   2   C1   C2
2   C2  2  17  NaN   C2
3  NaN  3  17  NaN  NaN

Comment: I am getting ```AttributeError: 'Series' object has no attribute 'explode'``` error
Comment: @ShanooS this is after pandas 0.25, please update your pandas
Answer: you could do:
 df.merge(df.melt(['A','B'],value_name= 'C').dropna().drop('variable',axis = 1),how = "left")
   A   B   C1   C2    C
0  1   2   C1   C2   C1
1  1   2   C1   C2   C2
2  2  17  NaN   C2   C2
3  3  17  NaN  NaN  NaN

Comment: I don't want to specify ['A','B'], as the dataframe has about 30 vars.
Comment: @Shanoo you can simply replace `['A','B']` with `df.columns[~df.columns.str.match('^C')]` or even `df.columns.str.extract('^([^C])',expand = False).dropna()`
Comment: Ya I can use `df.columns.str.extract('^([^C])',expand = False).dropna()`
Comment: But this doesn't work if we have another column which starts with C, say 'CFG'
Comment: @Shanoo then use `df.columns[~df.columns.str.match('^C\\d+')]`
Comment: @Shanoo `df.columns.str.extract('^([^C]\\D*)',expand = False).dropna()` also works
Answer: You can just df.explode(...), try:
#please note I aggregate it into list, not string
df['C'] = df.filter(regex='C\d+').stack().groupby(level=0).agg(list)

df=df.explode("C")

Outputs:
   A   B   C1   C2    C
0  1   2   C1   C2   C1
0  1   2   C1   C2   C2
1  2  17  NaN   C2   C2
2  3  17  NaN  NaN  NaN


How long and how much is each contract of the four main NBA on TNT hosts?

Question: What is the length and amount of each of the following's contract with TNT?
Charles Barkley
Kenny Smith
Ernie Johnson
Shaquille O'Neal
Answer: This is taken from various websites, so anyone is free to correct me if I'm wrong.
Charles Barkley: $1 million/year and has been with TNT for 13 years and his contract is due to expire in 2018.
Kenny Smith: $1 million/year
Ernie Johnson (host): $2.7 million/year
Shaquille O'Neal: $1 million/year
Sources: Charles Barkley, Contracts, Extention


Modeling kind-of-random discrete events in a set period of time

Question: I'm looking to consider models which provide a probability distribution of the number of tweets from a given account by a certain point in a week (e.g. noon on Tuesday) given a the set of events part way through the week. From the "undergraduate statistics" level of complexity, a Poisson distribution seems like an appropriate start.
Given that a part of a week has passed, however, what are possible models which can take into account an unusually active week, extra weights like popularity of a tweet, the possibility of an event triggering a lull, or other more complex phenomena? NN's seems like they should be capable of this. How can discrete events and progress through a time period be encoded as NN inputs? Is there a general name for this problem?
Meta-note: looking for a set of starting points for this as a research project rather than concrete solutions.
Comment: How much data do you have? I would start with something simpler than nn, such as poisson regression (possibly corrected for overdispersion)
Answer: I haven't seen your repost on Cross Validated or Data Science, so I'll offer an answer here.
Your problem seems like a good fit for Bayesian modeling. A priori, you start off with a distribution over $\lambda$, the parameter for your Poisson distribution, representing your beliefs in what number of tweets are likely.
As you receive information, you can use Bayes rule to update your beliefs in $\lambda$, allowing you to incorporate events or a particularly active week.
$$P(\lambda | events) = \frac{P(events | \lambda) P(\lambda)}{P(events)$$
Comment: @Andrey askes for neural network....
Comment: "Meta-note: looking for a set of starting points for this as a research project rather than concrete solutions.", and "I'm looking to consider models which provide a probability distribution..." I think it's reasonable to offer alternative models than NNs.
Comment: This is good, too. Although other answers involving NN's would be "more correct". Sorry I haven't gotten a chance to re-post. I've set aside some time to look into Cross Validated and Data Science and post there today.


Spring Boot create Database from entites with hibernate dont work

Question: im created entities and want to create a embedded h2 database with tables and columns from this entities.
Thats my application.yml file:

intellij logs the correct sql statements from hibernate (so it runs atleast):

but my connected database shows empty in intellij:

what do i wrong?
Answer: You are using an im-memory database.
That means if you "connect" from the application you have a different database as when you "connect" from Intellij.
Comment: In springboot (default) we can overcome! Logs print (devtools!? H2 console!) a (uuid-based) jdbc url, which points exactly to the used db instance..


Unhide a tooltip when hovering on another one

Question: I got a Jquery query. It may be super simple for some of the jquery gurus here. So I have these list of services on the left and a tooltip icon on the right. On hovering, it displays info related to the particular service. I manage to get the tooltip from another Stackoverflow post. But my client wants the first tooltip to hover on page load. I manage to get that as well from Stackoverflow.
Although where I am stuck at is, how to hide the first tooltip when someone hovers on the other ones.
I got this code to display tooltip on hover
$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});

And I got this code to display the first one on page load
$(document).ready(function(){
    $('[data-toggle=tooltip-active]').tooltip({trigger: 'manual'}).tooltip('show');
});

Kindly please help.
Answer: Try destroying the tooltip on mouseenter and re-enabling it on mouseleave events of the other tooltips:
jQuery(function($) {

    $('[data-toggle=tooltip]').hover(function() {
        $('[data-toggle=tooltip-active]').tooltip('destroy');
    }, function() {
        $('[data-toggle=tooltip-active]').tooltip({trigger: 'hover'});
    });

});

Assuming you're using Bootstrap tooltip.
Comment: Hey David... that worked great but then when I hover back on the first one, it doesn't show the tooltip.. haha.. :)
I need to just hide it not destroy. I mean I want it to hide temporarily unless hovered on it again.
Comment: @JesseAlex Slightly altered my answer. Give it a try
Comment: Hey David, can you please help me with this post too?
http://stackoverflow.com/questions/32535860/jquery-script-doesnt-work-right-on-safari


Correlation coefficient of x and y

Question: If we have $$ X\sim Poisson(\lambda), Y|X = x\sim Binomial(x+1,p) $$ What is the
correlation coefficient of  X and Y?
So I used $$\rho=\frac{Cov(X,Y)}{\sqrt{Var(x)Var(Y)}} = \frac{E[X[E[Y|X]]-E[X]E[E[Y|X]]}{\sqrt{E[X](E[E[Y|X]^2] -E[E[Y|X]]^2)}}$$
Is this right? Because I got a wacky answer, and is there an easier way?
Answer: I wonder how you come up with your denominator because by Law of Total Variance:
$$\begin{align}\operatorname{var}(Y)&=\operatorname{var}(E[Y|X])+E[\operatorname{var}(Y|X)]=\operatorname{var}((X+1)p)+E[(X+1)p(1-p)]\\&=p^2\lambda+p(1-p)(\lambda+1)=p(\lambda+1-p)\end{align}$$
and $\operatorname{var}(X)=\lambda$. The numerator seems OK.
Comment: thank you so much!!

Correlation coefficient of x and y


Definir critérios para ordenar uma lista de listas

Question: Eu tenho uma lista de listas de strings.
Por exemplo uma lista, no qual as listas internas tem tamanho n=3:
listEx =  [['verde','preto','laraja'], ['rosa','lilás','azul'], ['bordô','cinza','branco'], [preto, roxo, amarelo]]

Se eu quiser ordenar a lista listEx, definindo como critério a posição 0 das listas interiores eu faço:
 lista = sorted(listEx, key = lambda x: x[0])

Porém o que eu desejo é definir um critério de desempate. Assim sendo, caso hajam duas listas com elementos iguais na posição 0, o critério de desempate deve ser a posição 1. Caso ainda assim persista o empate, tome por critério de desempate a posição 2. O mesmo vale até a posição n.
O impasse é que n é variável. Ou seja, dependendo da instância do problema, as listas internas tem cardinalidade diferentes. Porém, eu garanto que não haverão listas de tamanhos diferentes.
Talvez exista algo no Python como o qsort da linguagem C, em que crio uma função compara_elementos, podendo definir os meus critérios em forma de código.
Comment: Isso? https://pt.stackoverflow.com/q/347634/101
Answer: Uma forma é criar uma função de comparação "à moda antiga" (usada no Python 2), que recebe 2 elementos e retorna um número negativo se o primeiro é "menor", um número positivo se o primeiro é "maior", ou zero se forem "iguais".
Depois você usa functools.cmp_to_key, que converte esta função de comparação para uma key function, compatível com sorted:
def compare(list1, list2):
    for e1, e2 in zip(list1, list2):
        if e1 != e2:
            return 1 if e1 > e2 else -1
    return 0

import functools

listEx =  [
  ['verde','preto','laraja'],
  ['rosa','lilás','azul'],
  ['bordô','cinza','branco'],
  ['preto', 'roxo', 'amarelo'],
  ['azul', 'vermelho', 'roxo'],
  ['azul', 'vermelho', 'cinza']
]
lista = sorted(listEx, key = functools.cmp_to_key(compare))
print(lista)

Eu uso zip para percorrer as listas ao mesmo tempo, e vou comparando seus elementos (detalhe que zip vai parar quando a menor das listas tiver terminado, mas como você garante que todas têm o mesmo tamanho, isso não é uma preocupação). Se todos os elementos forem iguais, eu retorno 0. Se eles forem diferentes, eu retorno o respectivo resultado (-1 se o primeiro for menor, 1 se for maior).
O resultado é:
[['azul', 'vermelho', 'cinza'], ['azul', 'vermelho', 'roxo'], ['bordô', 'cinza', 'branco'], ['preto', 'roxo', 'amarelo'], ['rosa', 'lilás', 'azul'], ['verde', 'preto', 'laraja']]

Answer: Um jeito de realizar essa comparação é você juntar os elementos das listas internas em uma única string antes de comparar. Essa ordenação só será valida se o critério de desempate for ordem alfabética, assim quando os dois primeiros elementos for azul, ele vai comparando os próximos elementos pela ordem alfabética.
listEx =  [['cinza', 'roxo','amarelo'], ['azul','laranja','verde'],['bordô','cinza','branco'],  ['azul','amarelo','preto'], ['azul','amarelo','verde']]
cores_ordenadas = sorted(listEx, key = lambda x: str().join((x)))
print(cores_ordenadas)

Saída:
[['azul', 'amarelo', 'preto'],
 ['azul', 'amarelo', 'verde'],
 ['azul', 'laranja', 'verde'],
 ['bordô', 'cinza', 'branco'],
 ['cinza', 'roxo', 'amarelo']]


Evaluate $\int^{\pi/3}_0 \sin x \ln (\sec x)\text{dx}$

Question: $\int^{\pi/3} _0 \sin x \ln (\sec x)\text{dx}$
So far I have:
$u=\ln(\sec x), v'=\sin x$
$u'=\cos x, v=-\cos x$
$[-\cos x \ln (\sec x)-\int-\cos^2 x dx]^{\pi/3}_0$
Is this right so far?
Comment: The derivative of $\ln\sec x$ is $\tan x$
Comment: Rewrite $\ln(\sec x)=-\ln(\cos x)$, there's an obvious substitution you can use now.
Answer: Hint: better yet, try substituting $u=\cos{x}$. Then,
$$\begin{align}I&=\int^{\pi/3} _0 \sin x \ln (\sec x)\text{dx}\\
&=-\int^{\pi/3} _0 \sin x \ln (\cos x)\text{dx}\\
&=\int^{1/2} _1 \ln (u)\text{du}\end{align}$$
Comment: Thanks, very helpful! I got $[u \ln u - u]^{1/2}_1

(\frac{1}{2} \ln\frac{1}{2} - \frac{1}{2})-(\ln 1-1)

\frac{1}{2} \ln \frac{1}{2}+ \frac{3}{2}$, which is not the answer in the back: $\frac{1}{2}(1-ln2)$

Is my answer correct?

edit: my lines won't separate so it'll be hard to read, sorry...
Comment: @Jim It looks like you forgot to distribute negative sign. $-\frac12-(-1)\neq\frac32$.
Comment: Ah thanks, even so, I get $\frac{1}{2}(\ln \frac{1}{2}+1)$. Is this correct?
Comment: @Jim Think about the basic algebraic rules for dealing with logarithms: $\log\frac12=\log 1 - \log 2$. See it now?
Comment: Ah, thank you! I always forget to use that log law...


Why the focus on variance reduction for $R^2$?

Question: It seems to odd to me that we measure the explanatory power of a regression model in "percent of variance explained", or $R^2 = {\rm cor}(\hat{y},y)^2 = r^2$ even though we all know that variance is just an auxiliary quantity to compute the more meaningful measure of uncertainty which is the standard deviation. Risk in finance or uncertainty in prediction is measured by $\sigma$, not by $\sigma^2$. Knowing the reduction in variance in a regression model seems much less useful than the reduction in standard deviation.
In fact, whenever I try to explain $R^2$ to my students, I usually start by comparing the overall variation of y (as measured by $\sigma_y$) to the remaining variation around the regression line (measured by $\sigma_{\epsilon}$). That idea is adapted much more naturally than the comparison of the variances which really have no direct interpretation!
So I propose a new measure which is truly "the amount of standard deviation explained". We can quickly derive it:
$$
R^2 (=r^2) = 1 - \frac{RSS}{TSS} \Leftrightarrow 1 - \frac{\sqrt{RSS}}{\sqrt{TSS}} = 1-\sqrt{1-r^2}
$$
where RSS = "residual sum of squares" ($\approx \sigma_{\epsilon}^2$) and TSS = "total sum of squares" ($\approx \sigma_{y}^2$)
Comparing the traditional $r^2$ with the new measure $1-\sqrt{1-r^2}$ reveals that substantially stronger correlations $cor(\hat{y},y)$ are needed to result in similar "uncertainty reduction". For example, what one used to call a high value of $R^2 = 0.8$ explaining 80% of the variance, would have reduced the true uncertainty by merely 55%!
The graph below shows the stronger convexity of this alternative measure.

My question is twofold

What is the (historic?) reason that $R^2$—despite its shortcomings—has established itself as the main measure of uncertainty reduction reported in virtually every statistical software and textbook?
From a didactic perspective: what is a convincing way of explaining $R^2$ to (non stats majors) students in an introductory course on statistics? Would the "reduction in standard deviation"—as outlined above—not be easier to teach?
Comment: Why standard deviation rather than mean absolute deviation? I perceive mean absolute deviation as much more natural, while standard deviation is quite difficult to perceive (just look at the formula...). A loss function based on mean absolute deviation arises more naturally in trading, but would you have any example of a loss function based on standard deviation?
Comment: I dont understand, what is the question?
Comment: @RichardHardy see http://stats.stackexchange.com/questions/81986/mean-absolute-deviation-vs-standard-deviation
Comment: @flies, thanks, I am aware of that thread. Is there anything in particular in there that you wanted to attract my attention to?
Comment: no, I just thought it was a relevant discussion
Answer: There is nothing inherently wrong with measuring goodness-of-fit in a regression model with other monotonic transforms of the coefficient of determination, and indeed, there are several natural transformations that have useful interpretations.  Before getting to these, it is useful to note the desirable mathematical properties of the coefficient of determination, and how it arises.  The best way to understand this is to look at linear regression from a geometric perspective, where we consider the response and explanatory variables as vectors in Euclidean space.

Geometric analysis of the linear regression: You can find a geometric analysis of linear regression in O'Neill (2019).  Using OLS estimation in linear regression, the response vector is projected onto the column-space of the design matrix, which yields a predicted response vector in that column-space, and a residual vector that is perpendicular to that column-space (i.e., in the null space of the design matrix).  This gives the regression equation $(\mathbf{y} - \bar{\mathbf{y}}) = (\hat{\mathbf{y}} - \bar{\mathbf{y}}) + \mathbf{r}$ which decomposes the response deviation into a predicted deviation and a residual.  Since the residual vector and the predicted response vector are orthogonal under OLS estimation, this gives you a triangle of vectors that obey Pythagoras theorem, giving the decomposition:
$$\underbrace{\|\mathbf{y} - \bar{\mathbf{y}}\|^2}_{SS_\text{Tot}}
= \underbrace{\|\hat{\mathbf{y}} - \bar{\mathbf{y}}\|^2}_{SS_\text{Reg}}
+ \underbrace{\|{\mathbf{y}} - \hat{\mathbf{y}}\|^2}_{SS_\text{Res}}.$$
Geometric explanations of linear regression commonly show the triangle of vectors in the above decomposition, and note the resulting decomposition of the squared-norms of these vectors (i.e., the sums-of-squares).  One natural way to look at the goodness-of-fit of the linear regression model is to look at the shape of this triangular decomposition --- the smaller the residual vector (relative to the other vectors), the narrower the triangle and the better the fit of the model to the data.

Some useful measures of goodness-of-fit: There are several useful ways of looking at the goodness-of-fit, via the above decomposition of vectors (and the resulting decomposition of their squared-norms).  Most of these involve using a measure that is some monotonic transformation of the coefficient of determination, and so they all measure the same thing, but in a different way.  Here are some useful measures of the goodness-of-fit that are monotonic functions of the coefficient-of-determination:

Coefficient of determination: This statistic is defined as:$$R^2 \equiv 1 - \frac{SS_\text{Res}}{SS_\text{Tot}} = \frac{SS_\text{Reg}}{SS_\text{Tot}}.$$  As you point out, it measures the proportion of the variance that is "explained" by the explanatory variables.  Geometrically, this statistic shows the proportionate size of the squared-norm of the predicted deviation, relative to the total deviation.  The statistic is useful because it has a simple interpretation, and it has a simple geometric intuition.$$\text{ }$$

Regression vector angle: An associated measure of the goodness-of-fit is the angle $0 \leqslant \theta \leqslant \pi / 2$ between the response deviation vector and the residual deviation vector.  Using standard trigonometric rules, this vector angle is obtained by the formula: $$\cos(\theta) = \frac{SS_\text{Reg}}{SS_\text{Tot}} = R^2.$$  Thus, it is easily seen that this vector angle is a monotonic transform of the coefficient-of-determination (a higher value for the coefficient-of-determination gives a smaller vector angle).  This statistic is useful because it has a simple geometric interpretation --- a small vector angle means that the observed response deviation (from the mean) is close to the predicted response deviation (from the mean).$$\text{ }$$

F-statistic: Taking the number of data points and parameters as fixed, we can write the F-statistic for the goodness-of-fit of the regression in terms of the coefficient-of-determination:$$F = \frac{MS_\text{Reg}}{MS_\text{Res}} = \frac{n-m-1}{m} \cdot \frac{R^2}{1-R^2}.$$  Taking the number of data points and parameters as fixed, this statistic is a monotonic transform of the coefficient-of-determination.  This statistic is useful because it has a well-known distribution under the null hypothesis that the true regression coefficients are all zero.  It can therefore be used for hypothesis testing, to see if there is evidence of an association between the set of explanatory variables and the response.$$\text{ }$$

Explained standard deviation: Another useful measure of goodness-of-fit is the proportion of explained standard deviation, comparing the estimated standard deviation of the error terms and the response variables.  This is given by: $$W \equiv 1 - \frac{\hat{\sigma}_\varepsilon}{\hat{\sigma}_Y} = 1 - \sqrt{{\frac{MS_\text{Res}}{MS_\text{Tot}}}} = 1 - \sqrt{\frac{n-1}{n-m-1} \cdot (1-R^2)}.$$  Taking the number of data points and parameters as fixed, this statistic is a monotonic transform of the coefficient-of-determination.  It is similar to the statistic you propose to use, except that yours does not adjust properly for the degrees-of-freedom in the regression.

As you can see, there are several monotonic variations on the coefficient-of-determination that can be used as measures of goodness-of-fit.  These have different interpretations that are all quite useful in certain contexts.  The statistic you propose is somewhat similar to the explained standard deviation statistic above, but it fails to adjust properly for the degrees-of-freedom in the regression, so its interpretation would be a bit more difficult.  Nevertheless, it is a monotonic function of the coefficient-of-determination, so it can be used as a measure of goodness-of-fit.
Answer: Particularly for a class for non-majors, it's probably fine. Most likely your students think of standard deviation whenever you mention variance, anyway.
It also makes sense to me. The goal of regression is to reduce the variability. Sure, the variability of human height is quite large, but when you account for age and gender, the distribution narrows, and you have a better idea of how tall a 30-year-old woman is ("around 5'5" ish") than how tall a human is in general.
So if you're reducing the variance of the conditional response distribution, you're also reducing the standard deviation of the response distribution. Where I am not clear is when it comes to quantifying that reduction, since the square root of an unbiased estimator of variance is a biased estimator of standard deviation.
Answering explicitly:
1) Variance is a natural way of thinking about the spread of data, since it's the second central moment of a distribution. There's also a good estimator that is unbiased for every distribution with a defined variance. Taking the square root of that (amazingly) results in a biased estimate of standard deviation.
2) If you're reducing the variance, you're also reducing the standard deviation. I'm unsure about the math of everything, since there's that nasty issue of unbiased variance becomes biased standard deviation, but that level of detail wouldn't make it into the class for non-majors.
Answer: If $X_1,\ldots,X_n$ are independent random variables then
$$
\operatorname{var}(X_1+\cdots+X_n) = \operatorname{var}(X_1)+\cdots+\operatorname{var}(X_n).
$$
Other measures of dispersion, including standard deviation and mean absolute deviation, lack this property.
If follows that
\begin{align}
& \Big(\text{explained part of the variance} \Big) \\
& {} + \Big( \text{unexplained part of the variance} \Big) \\[6pt]
= {} & \Big( \text{total variance} \Big).
\end{align}
If not for that, would it make sense to speak of what percent of the dispersion is explained or unexplained?


How to check for entity access when displaying views fields?

Question: I have a custom entity. There is an access callback defined in hook_entity_info() and it is called when I access the entity. Also in views when I select to display rendered entities, the entity is only shown when the user is allowed to see the entity.
However when I change the view to show 'fields' instead of 'rendered entities', the access callback is no longer called and users can see all fields (and properties) of the entity, regardless of any permissions. Looking at the executed query this makes sense, the field values are joined in and the entity is never really loaded.
So, how should one implement entity access for views when displaying fields (in Drupal 7)?
I've found How to check for entity type in Views when using hook_field_access?, but I assume that only works for joined fields and not for base entity properties, so that would be only a part of a solution.
Comment: Have you considered using a custom view_mode?
Comment: @Darvanen yes, but I need the system to be fool proof. So I cannot assume everybody will use rendered entities.
Comment: @Neograph734 That entity of yours is a node or something else ?
Comment: @mchar It is a custom entity constructed with the Entity API module.
Comment: I think (correct if I am wrong) that the solution to your issue is the implementation of [hook_node_grants](https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_grants/7.x) and [hook_node_access_records](https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access_records/7.x) but I am not sure if these hooks apply to custom entities (hopefully yes), at least this is the most efficient way to control access as far as it  concerns `nodes` in Drupal.
Comment: @mchar unfortunately there is no such thing for other entities, but thanks anyway :)
Answer: Presuming your entity providing module has Views integration already setup, and you're not worried about pagination, you can
invoke hook_views_pre_render() to iterate over the results and invoke your access callback for each entity in your base table and filter out entries that the user doesn't have access to:
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;

  // Iterate over View results for our custom entity
  if ($view->base_table == 'my_entity_base_table') {
    foreach ($view->result as $index => $row) {

      // Presuming eid is the entity PK
      $results = entity_load('my_entity_machine_name', array($row->eid));
      if (!empty($results)) {
        $entity = $results[$row->eid];

        // If the custom access callback returns FALSE, remove from results.
        if (!MYMODULE_my_entity_access_callback('view', $entity, $user)) {
          unset($view->result[$index]);
        }
      }
    }
  }
}

If pagination is a concern, it's a tougher problem; adjusting the view results break consistent offsetting (e.g. page 1 might return 4 results, page 2 might return 10 results). Plus, the results of SQL query can't adjust for information that is only known by executing PHP.
In those instances, you'll have to adjust your method (e.g. hook_views_query_alter() if the access callback is DB query based, altering your View pager options, etc.) to accommodate for the access callback manipulating the view.
Comment: Though this is definitely a start, it breaks the views pager (not 25 items per page but less, sometimes even 0). Is there a way to process this before the pagination is calculated?
Comment: It appears the pagination is already in the query: `... LIMIT 25 OFFSET 0`, so the only way to keep pagination working would be to act before the query is completed. But I cannot embed my access callback in the query. So it cannot be done?
Comment: I didn't even think about it since it wasn't mentioned. Anyway, the views object contains the `$query` property which pager property can be manipulated to reflect the altered count.
Comment: Neither did I Shawn, but I ran into it when implementing your solution. This doesn't quite work yet (you set the total amount of items to the amount the query returned, so it will never be bigger then the amount of items per page (25)). I'll try this with a separate count query to obtain the total amount of items.
Comment: Apologies, that was a hasty edit when I was crunched for time. I thought I'd previously solved this exact problem, but upon revisiting that code, it was instance where we could get by with having fuzzy pagination. I updated the answer accordingly.
Answer: In the end I've managed to find a working method which works in a similar way as the views does with nodes.
In hook_views_data() (or hook_views_data_alter()), make sure to add the access query tag table key. You can see Views does this for nodes as well in node_views_data().
$data['example_table']['table']['base'] = array(
  'field' => 'nid', // This is the identifier field for the view.
  'title' => t('Example table'),
  'help' => t('Example table contains example content and can be related to nodes.'),
  'weight' => -10,

  'access query tag' => 'my_entity_access' // <- Add this.
);

Then add your own implementation of hook_query_TAG_alter. This will alter every query where this tag is added. Because of our above alteration this will be automatically applied to all Views data listings, but the tag can also be added manually.
There are some great tricks in _node_query_node_access_alter() called from node_query_node_access_alter() (node modules implementation of hook_query_TAG_alter).
function mymodule_query_my_entity_access_alter(QueryAlterableInterface $query) {
  global $user;

  // Read meta-data from query, if provided.
  if (!$account = $query->getMetaData('account')) {
    $account = $user;
  }
  if (!$op = $query->getMetaData('op')) {
    $op = 'view';
  }

  // From here every query will be different depending on your own needs.
  // Since my entity has a privacy parameter that is either public or private,
  // I chose to implement this as follows:

  // Prepare a database OR.
  $or = db_or();

  // If the user has public view permissions, add it to the OR.
  if (user_access('view public my_entities', $account)) {
    $or->condition('example_table.privacy', 'public');
  }

  // If the user has non-public view permissions, add it to the OR.
  if (user_access('view private my_entities', $account)) {
    $or->condition('example_table.privacy', 'public', '<>');
  }

  // Add the compiled set of rules to the query.
  $query->condition($or);
}


Automatically run the workflow on the main repo when a submodule repo changes

Question: I have a repository that has a submodule repo, I want to run the workflow of the main repo in case of any submodule repo changes.
Any suggestions ?
Comment: hi, interesting, perhaps this might be of interest https://stackoverflow.com/questions/16511616/auto-populate-submodule-version-to-parent-module
Comment: How would the submodule change? Would it be manually? You could use a `paths` subtype in your workflow `on` trigger to run only when the submodule files are updated.
Comment: I mean if i do a change to the submodule repo, I want the workflow on the main repo to start running. I tried to use paths and give it a path of my submodule 'dir1/submoduledir ', but it doesn't work.
Answer: First, I should switch to the master branch.
cd otherrepo/
git checkout master

After making changes to the submodule repository, I should push these changes first.
cd otherrepo/
** making changes – Editing README.md file **
git add README.md
git commit -m 'editing README.md'
git push origin master

Then, push the main repository.
cd ..
git add otherrepo
git commit -m 'editing otherrepo submodule'
git push origin master


Implementing Minimum distance estimation

Question: Let $\mu$ and $\sigma$ be two parameters of interest characterising a normal distribution. From a theoretical model, I know that these two parameters are related to each-other according to
$$\pi=\Phi\left(\frac{\Phi^{-1} (\alpha)-\mu}{\sigma}\right)$$
where $\Phi(\cdot)$ is the CDF of the standard normal and $\pi$ and $\alpha$ are random variables, for which I observe a number of realisations (let me note the empirical realisations $\hat{\pi}_i$ and  $\hat{\alpha}_i$ for $i=1,2,..n$).
Based on this, I would like to estimate $\mu$ and $\sigma$ using minimum distance, namely
$$
\arg\min\limits_{\mu,\sigma}\sum^n_{i=1}\left( \hat{\pi}_i- \Phi\left(\frac{\Phi^{-1} (\hat{\alpha}_i)-\mu}{\sigma}\right)\right)^2 w_i
$$
for some vector of weights $\{w_1,w_2,..w_n\}$.
How do I implement that in STATA? If my understanding of the methods is correct, I believe I should be able to do this using the General Method of Moments. I tried using gmm in Stata, but it gave me an error message. Specifically, I tried
gmm (pi - normal((invnormal(alpha)-{mu})/{sigma})), instruments(pi alpha)

but received an error message saying
no non-missing values returned for equation 1 at initial values
Answer: You need to change the initial value of sigma. Default is zero, so you're dividing by zero and get missings at your initial values, as your error message indicates.
Answer: The gmm code provided in the OP is correct, but it requires an initial condition for $\sigma$. Here is a working example.
clear
set obs 10000
gen alpha       = rnormal()
gen alpha_cum   = normal(alpha)
scalar mu       = 2
scalar sigma    = 3
gen pi_real     = normal((invnormal(alpha_cum)-mu)/sigma)
gen error       = rnormal(0,1)
gen pi_observed = pi_real + error
gen z           = rnormal()

Running  gmm (pi_observed - normal((invnormal(alpha_cum)-{mu})/{sigma})), instruments(alpha_cum pi_observed) gives the error message: no non-missing values returned for equation 1 at initial values
Running  gmm (pi_observed - normal((invnormal(alpha_cum)-{mu})/{sigma=1})), instruments(alpha_cum pi_observed)
Gives
------------------------------------------------------------------------------
             |               Robust
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         /mu |   1.737236   .1612666    10.77   0.000      1.42116    2.053313
      /sigma |   2.702077   .2730999     9.89   0.000     2.166811    3.237343
------------------------------------------------------------------------------


Are $G(30,30)$ and $G(6,10,15)$ isomorphic?

Question: Here is a little problem if anyone could help me with it, it would be a lot appreciated

Let $G(k_1,k_2,...,k_r)$ the abelian group define as: $$\mathbb Z /k_1\mathbb Z \,\times \mathbb Z /k_2\mathbb Z \,\times ...\mathbb Z  /k_r\mathbb Z$$

We define: $G(30,30)$ and $G(6,10,15)$.
Can we prove using the Chinese reminder theorem that there is an isomorphism between this two groups?
Thanks in advance for your help.
Answer: The Chinese remainder theorem can be stated as
$$\mathbb{Z}/nm\mathbb{Z}\simeq\mathbb{Z}/n\mathbb{Z}\times \mathbb{Z}/m\mathbb{Z}$$
whenever $n,m$ are coprime. Or equivalently, in your notation
$$G(n\cdot m)\simeq G(n,m)$$
With that we have
$$G(30,30)=G(2\cdot 3\cdot 5,2\cdot 3\cdot 5)\simeq G(2,2,3,3,5,5)$$
$$G(6, 10, 15)= G(2\cdot 3, 2\cdot 5, 3\cdot 5)\simeq G(2,2,3,3,5,5)$$
and so they are clearly isomorphic.
Comment: Hello, can you explain why my question is closed .. I don't understand
Comment: @EmmaFlora because some people voted so. Sorry, I have no idea.
Answer: If you mean the following statement by Chinese Remainder Theorem, then yes, we can solve it by using it:

Theorem(Chinese Remainder Theorem): Let $m,n \in \mathbb{Z}^+$ such that $\gcd(m,n) = 1$. Then, the map $\phi: \mathbb{Z}_{mn} \to \mathbb{Z}_{m} \times \mathbb{Z}_{n}$ defined by $\phi([x]_{mn}) = ([x]_m, [x]_n)$ is an isomorphism.
Then, we have
$$G(6,10,15) = \mathbb{Z}_6 \times \mathbb{Z}_{10} \times \mathbb{Z}_{15} \cong \mathbb{Z}_{2} \times \mathbb{Z}_{3} \times \mathbb{Z}_{10} \times \mathbb{Z}_{15} \cong \mathbb{Z}_{2} \times \mathbb{Z}_{15} \times \mathbb{Z}_{3} \times \mathbb{Z}_{10} \cong \mathbb{Z}_{30} \times \mathbb{Z}_{30}$$
Note that, we are also using the fact that $G \times H \cong H \times G$ to interchange the terms of the product.


JWT and server side token storage

Question: Every article I've read vouching for the advantages of JWT state that one of these advantages is its ability for an auth system to be distributed across multiple servers. i.e . You aren't relying on a central repository of user auth details to do a lookup on every request.
However when it comes to implementation, I've read in many places that for added security you shouldn't just rely on the JWT signature verification itself, and that you should maintain a list of black or white list tokens generated by the server.
Doesn't this defeat the advantage I've listed above, as this list of tokens would need to be stored centrally where all servers can access it and it would require a lookup on each request?
How have people implemented this on their end?
Answer: You are making very good points in your question. Actually it would make sense to store an OAuth token at a central location in order to make it easier to implement signout/revoke functionality. If you just relied on the token signature you couldn't have possibly implemented such feature. Suppose that a user wanted to revoke an access token. In this case if you didn't have a central location/datastore for those tokens where you would have invalidated it and only relied on token signature, then the token would still have been valid.
So indeed, when you want to build more advanced systems that are dependent on OAuth tokens, a central store for those tokens is more than a must.

JWT and server side token storage


Not able to use useState()

Question: I am getting the following error every time I try to use react hooks in my funtiom:

TypeError: react__WEBPACK_IMPORTED_MODULE_1___default is not a
function or its return value is not iterable

Following is my code:
import './RouteDetails.css';
import useState from 'react';
...
...
..

export default function RouteDetails() {
    const [show, setShow] = useState(false);

    return(

                    <Row className="route-details-heading">
                        <Col className="d-none d-sm-block" md={4}>Route Name</Col>
                        <Col className="d-none d-sm-block" md={4}>Difficulty</Col>
                        <Col className="d-none d-sm-block" md={1}>Length</Col>
                        <Col className="d-none d-sm-block" md={1}>Time</Col>
                    </Row>

    )
 }

React and React-dom is of the same version. Can anyone please tell me what I am doing wrong here? Also, I am not using jest
Comment: Check [this](https://stackoverflow.com/a/36796281/2873538) and [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module).
Comment: The default export from `"react"` is conventionally named `React`, it's not the hooks.
Answer: Try importing useState like import { useState } from 'react'. It is not a default.

Not able to use useState()


Identifying orchestral sounds

Question: Following my previous question about new instruments in orchestras, I was listening to a few concerts and well, some write the instruments being used throughout the concert, others don't. Most don't. While listening, now and then I can hear different sounds and effects I cannot recognise. I can't understand what instrument is playing that, in what octave and how.
How can I understand what instrument is playing, in what range and what is the technique being used to develop this sound?
As an example suppose you have a viola and a violin or a trumpet and a trombone. At some point they really start sounding alike, but there are also different ways of extracting sound and sometimes instruments blend and it's hard to tell one from the other in a mix. I'm not having much problem dividing a rock or a pop song into voices but with classical instruments it's really difficult, especially saxophones. I can never tell how they extract some effect and if one is playing in the range of another I confuse them.
Comment: Listen to each instrument play solo pieces a lot and you'll start distinguishing.   Some brass instruments get confusing for me, but it's just because I've never spent much time listening to them. Sometimes you can tell by the type of part they're playing; violas usually get lower, less exciting parts (hey, it's true) whereas first violins tend to have shrill, higher, more melodic parts and second violins mirror the first violins in some cases, playing the same part an octave or tenth or whatever lower. Not always, though...
Comment: It's probably easier for you to distinguish rock instruments because you've probably listened to more rock music. Listen, listen, listen, listen and then do some more listening and I think you'll be telling violins from violas more clearly.
Comment: "I was thinking of trying to find those instrument players and speak to them about the sound and techniques but that's hard to do" A conductor one told the trumpeter who recorded the Star Wars film soundtrack that his playing was "much too gothic, I need it more Renaissance" and "too Rembrandt, I need it more Renoir." In reply, "Murphy calmly opened his trumpet case and produced a replica Colt 45 revolver that sounded like the genuine article. He "shot" the conductor and there was no further talk of Rembrandt." https://www.theguardian.com/music/2010/nov/29/maurice-murphy-obituary
Comment: So it all comes with listening only? I was thinking of trying to find those instrument players and speak to them about the sound and techniques but that's hard to do.
Answer: Here's a few options:

Listen to a lot of recordings, and become more familiar with the sound of each instrument. Alternately, listen to a lot of live music. I can tell the difference between a trombone and a french horn pretty quickly, because I've been sitting in front of a trombone section for six years.
Listen to recordings whilst following along with the score. If the piece is old enough, you will probably be able to find the complete score on http://imslp.org. It's legal, because the pieces are out of copyright. If this is possible, it's a really good option, because you can see how the piece is notated, then listen to the produced sound.
Watch recordings on YouTube, and actually see the musicians play. You can then see which section is playing visibly. The slightly pricier option is to go to actual orchestral concerts. I'm of the opinion that everyone should do this at least once, but it's not going to be cheap.
Join an orchestra or band. This does require you to play a suitable instrument. I was (am) a keyboard player, but I also picked up saxophone so that I could join a concert band. Pretty much all of my practical arranging knowledge comes from playing in this band, and listening to all of the ways that sound can be generated. Conversely, I don't know very much about string instruments, because I never play with them.
Talk to some players, or conductors, about sounds that you don't understand. This will be most effective if they've actually played the piece in question, but it can still give you pointers in the right direction.
Obtain a musical dictionary like this one. It lists a whole lot of instruments, along with their ranges and other details. It can be a handy reference. Nowhere near as good as using your ears, but it's cheap, and might give you a start.
Obtain some books on orchestration. This one, from Rimsky-Korsakov, has some interesting sections where he discusses the sound produced by various orchestral combinations, and includes lots of score extracts. It's out of copyright, so you can grab it from IMSLP. The original is in Russian, which I gather is not a problem for you, but there's an English translation as well.
Comment: I'd add **Join an orchestra** to the extensive list given above. You'll get to hear instrumental passages in isolation and together, and you'll also hear phrases that are appropriately written for each instrument.
Comment: SovereignSun - there are no French horns on Wish You were Here. There's a synth that sounds a bit brassy - but it's not a real horn.
Comment: Yeh i know about Rimsky-Korsakov books. I would like a printed version though, will try to look for it. Unfortunately it's quite expensuve to go to a concert here. I've had this wish for a long time. I also want to visit an organ hall. I can tell a french horn. Richard Wright from Pink Floyd often used it, especially in Wish you were here.
Comment: @BrianThomas Good call. I've added it in.
Comment: @BrianTHOMAS Actually you are talking about the studio album while I was refering to the concert version with orchestra. In the Wall by the way there are many interesting orchestra instruments.
Answer: In addition to the other suggestions I would recommend purchasing the orchestral score for a piece and listening to the recording while watching the score. You'll be able to tell what each instrument is playing and see what all the instruments are doing at one time. It's nearly impossible to pick out what every instrument is doing just by listening to a recording.
Comment: Please do not  add a signature to your post as stated in our [FAQ](http://music.stackexchange.com/help/behavior). Feel free to put it information like this in your profile.

Identifying orchestral sounds


System of equations with radical

Question: I was recently doing some calculations and I have an equation pair (system of equations) which I wouuld like to be able solve (preferrably manually?)
Can this system of EQs be solved easily with pen-and-paper /AND/ OR basic calculator? (not a super-duper-calculator)
My old calculator cannot handle 2nd degree simulatenous equations for example.
problem system of equations

eq1 : $0 + 272.91 + \frac{800x}{ \sqrt{(x^2+y^2+900)}} = 0$
eq2 : $ -471.5 + 682.22 + \frac{800y}{\sqrt{(x^2+y^2+900)}} = 0$

I already solved this equation using my highly advanced TI Nspire CX CAS calculator but I was a little bit disappointed at not being able to solve it with pen-and-paper.
I have some confidence in Wolfram Alpha's solutions though, because I was able to double check my earlier work done in pen-and-paper using the Wolfram Alpha's solution. My earlier work was accurate up to 2 decimal places which ought to be ok.
If you really want to know how I came up with the system of Equations.

eq1 represents (three coefficients of i-basevector summed together) = 0
eq2 represents (three coefficients of j-basevector summed together) = 0

According to Wolfram Alpha the results are
x= -11.3416
y= -8.75708
using those x,y  and some other background information, I was able to formulate the third vector exactly.
Then I calculated a vector sum with three vectors, and analyzed the vector sum by looking at the coefficients of the basevectors.
EDIT YES THERE WAS TYPO MINUS SIGN MISSING sorry it is supposed to be for

eq2 : $ -471.5 + 682.22 + \frac{800y}{\sqrt{(x^2+y^2+900)}} = 0$
eq2 : $ \leftrightarrow +210.72 + \frac{800y}{\sqrt{(x^2+y^2+900)}} = 0$
Comment: (1) Let $u=x^2+y^2$

(2) Solve for $u$ in each equation.

(3) Use the resulting expressions to solve for $x$ and $y$.
Comment: There is a strong preference on this site to use MathJax: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference. Second it can be solved, but it depends on what you mean by "easily"
Comment: i have found only complex solutions
Comment: is there a typo?
Answer: Hint:
Switching to polar coordinates, you can write
$$\frac{r\cos\theta}{\sqrt{r^2+900}}=a,\\\frac{r\sin\theta}{\sqrt{r^2+900}}=b.$$
Then
$$\tan\theta=\frac ba$$
and
$$\frac{r^2}{r^2+900}=a^2+b^2$$ leads to the solution.

System of equations with radical


Use Java API in Kotlin

Question: Is it possible to use a Java API in Kotlin. For example I want to use a Barcode Scanner API, which ist written in Java, in my Kotlin code. So how can I use the constructor? In Java it is new BarcodeScanner() how can I do this in Kotlin
Comment: Of course you can. Or simply, instead of `new` keyword which mentioned by another user, write your codes in `Java` class language (if you're beginner in `Kotlin`) then use `Code -> Convert java file to Kotlin file` and it will convert it to Kotlin which is a good place to start Kotlin and learning how it can be changed from java to kotlin.
Comment: [This](https://kotlinlang.org/docs/tutorials/mixing-java-kotlin-intellij.html) might be of some help.
Answer: Almost the same just without the new keyword.
val scanner = BarcodeScanner()

Use Java API in Kotlin


Como deixar um array vazio (apagar todos os elementos) em JavaScript?

Question: Tenho um array de objetos e quero deixar ele vazio, removendo todos os seus elementos. Como faço ?
let arr = [1, 2, 3, 4, 5];

Comment: É muito mais fácil e rápido você atribuir `[]` à variável que continha a lista de objetos. Se fizer questão de apagar um por um, poderia fazer um loop: while (matriz.length > 0) matriz.shift();
Comment: @JeanExtreme002, o método `Array.prototype.shift` não possui tais argumentos.
Comment: Você pode apenas atribuir um array vazio, como o exp falou, ou utilizar o método `shift` dessa forma: `array.shift(0, array.length)`.
Comment: como comentou o @epx, `nome-da-variavel = []` ou `nome-da-variavel.length = 0`
Comment: Obrigado pessoal pela ajuda
Comment: @LuizFelipe Oops, era `splice`. Eu confundi na hora, desculpa. Correção: `array.splice(0, array.length)`
Answer: Não importando os valores de um array, são métodos válidos para esvaziar um array arr:
Alternativa 1: Redefinir a variável (ou propriedade) com um array vazio
arr = [];

Esse código vai redefinir a variável arr para um novo array vazio. Note que a mesma coisa também pode ser feita se ele estiver definido em uma propriedade de um objeto.
É ideal se você não tem outras referências para o array original arr, uma vez que isso não modifica o array original, apenas o substitui por um outro novo e vazio.
É importante tomar cuidado com esta alternativa tendo em vista que, se você tiver referências ao array arr em outras partes do seu código, elas ficarão inalteradas. Em suma, utilize esta alternativa somente quando você não está mantendo outras referências ao array original — que não está sendo, de fato, esvaziado, apenas substituído em um (e não todos) determinado local.
Esta é a alternativa mais rápida.
E este código mostra o problema da referência se o devido cuidado não for tomado:

let arr1 = ['a', 'b', 'c', 'd', 'e', 'f'];
let arr2 = arr1;  // Referência à `arr1` em outra variável.

// Note que estamos apenas substituindo o valor da variável `arr1`.
// Não estamos, de fato, apagando nenhum dos elementos do array.
arr1 = [];

console.log(arr2); //=> ['a', 'b', 'c', 'd', 'e', 'f']

Vale observar também que, se o array tiver sido declarado com const, não é possível utilizar esta alternativa. No entanto, modificações ao array em si ainda são válidas, conforme explicado aqui e aqui.
Todas as soluções a seguir modificarão o array original (e, portanto, refletirão alterações em todas as referências).
Alternativa 2: Zerar a propriedade length
arr.length = 0;

Isso irá limpar o array existente ao setar sua propriedade length para zero. Basicamente, a propriedade length dos arrays é um setter que, quando alterado, é capaz de modificar o array para se adequar ao novo valor.
Alternativa 3: Array.prototype.splice
arr.splice(0, arr.length);

Utilizar o método Array.prototype.splice funcionará perfeitamente para remover todos os itens de arr. No entanto, como esse método retorna um array com todos os itens removidos, acabará retornando uma cópia do array original (já que todos foram removidos). Apesar disso, benchmarks demonstram que isso não implica em nenhum custo adicional em performance.
Alternativa 4: Utilizar Array.prototype.pop até esvaziar o array
while (arr.length) {
  arr.pop();
}

Essa solução utiliza o Array.prototype.pop para remover o último elemento do array. Utiliza-se o laço while para repetir a remoção dos elementos finais até que o array tenha sido completamente esvaziado.
Essa solução não é muito sucinta e também é a menos performática de todas as apresentadas.
Considerações sobre performance
De todos as alternativas apresentadas acima, 1 é a mais rápida, visto que não apaga o array de forma propriamente dita. Apenas modifica a variável que o continha com um novo e vazio array.
No entanto, quando apagar os elementos do array original é realmente necessário, as alternativas 2 e 3 são muito similares em performance e são significativamente superiores em relação à alternativa 4. Para resultados, referir a este benchmark.

Esta é uma adaptação deste excelente esforço coletivo (resposta) do Stack Overflow em Inglês.
Comment: Obrigado pela ajuda Luiz.


Redirecionar domínio .com.br para .com

Question: Possuo dois domínios: o principal é o .com e o secundário é o .com.br
Preciso fazer com que toda vez que acessem www.dominio.com.br ele redirecione para o www.dominio.com, até mesmo quando possui uma subpasta, por exemplo: www.dominio.com.br/teste redirecione para www.dominio.com/teste
O host que utilizo é o iPage.
Comment: Tudo bem amigo! Obrigado de qualquer forma!
Comment: Em qual linguagem está seu site?
Comment: Isso influencia em algo? É só uma página em HTML com um formulário, utilizando PHP para o envio do mesmo.
Comment: Influencia na minha resposta. Recentemente tive um problema como isso em uma plataforma que desenvolvi a base de C# e tenho um código pronto que faz as verificações e direcionamentos. Portanto infelizmente não consigo ajudar
Comment: Está usando servidor apache?
Answer: Possui .htaccess? Servidor apache?
Você poderia usar mod_rewrite para fazer isso.
<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]
</code>
http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html
Comment: Só para completar a resposta, aqui tem um tutorialzinho do iPage
https://www.ipage.com/support/tutorials/view_tutorial.bml?kbid=6104 Logo no começo ele mostra a tela onde editar o htaccess, e outras formas de redirecionar o teu domínio.
Comment: Obrigado amigo! Era isso mesmo!
Comment: Ok! Não esqueça de colocar as TAG que faltam para as suas perguntas. Abraço.

Redirecionar domínio .com.br para .com