Unable to receive and accept Video Calls using QuickBlox WebRtc in Android

Question: I am trying to implement WebRtc using QuickBlox in Android. Following the tutorial I have done the following coding. I am facing the following problems.

I don't think so my call is going from user A to User B.
I don't get notified of the incoming call(that may be because the call is not coming at all).
When I click the accept button I get the following error.

E/AndroidRuntime(11413): FATAL EXCEPTION: Thread-37793
   E/AndroidRuntime(11413): Process: com.example.testqb, PID: 11413
   E/AndroidRuntime(11413): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.quickblox.videochat.model.listeners.OnQBVideoChatListener.runOnVideoChatStateChangeUI(com.quickblox.videochat.model.objects.CallState, com.quickblox.videochat.model.objects.VideoChatConfig)' on a null object reference
   E/AndroidRuntime(11413):   at com.quickblox.videochat.core.objects.XMPPConnectionClient$CallingRunnable.sendNotAnsweredCallback(XMPPConnectionClient.java:173)
   E/AndroidRuntime(11413):   at com.quickblox.videochat.core.objects.XMPPConnectionClient$CallingRunnable.run(XMPPConnectionClient.java:158)
   E/AndroidRuntime(11413):   at java.lang.Thread.run(Thread.java:818)

My full code are as below:
I login on phone A using login1  button and B using login2 button. My full codes are as below.
   public class MainActivity extends ActionBarActivity implements OnClickListener,
    QBRTCClientSessionCallbacks, QBRTCClientConnectionCallbacks,
    QBRTCClientVideoTracksCallbacks {
Button sign_up, btn_login, btn_call, btn_recieve, btn_login2;
QBChatService chatService;
final QBUser user1 = new QBUser("temp151", "123456789");
final QBUser user2 = new QBUser("temp152", "123456789");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    QBSettings.getInstance().fastConfigInit("xxxx", "xxxxxxxx-",
            "xxxxxxx");
    sign_up = (Button) findViewById(R.id.sign_up);
    btn_login = (Button) findViewById(R.id.btn_login);
    btn_call = (Button) findViewById(R.id.btn_call);
    btn_recieve = (Button) findViewById(R.id.btn_recieve);
    btn_login2 = (Button) findViewById(R.id.btn_login2);
    sign_up.setOnClickListener(MainActivity.this);
    btn_login.setOnClickListener(MainActivity.this);
    btn_call.setOnClickListener(MainActivity.this);
    btn_recieve.setOnClickListener(MainActivity.this);
    btn_login2.setOnClickListener(MainActivity.this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.sign_up:
        QBAuth.createSession(new QBEntityCallback<QBSession>() {

            @Override
            public void onError(List<String> arg0) {
                // TODO Auto-generated method stub
                Log.i("error", "" + arg0);
            }

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub

                user1.setFullName("temp151");
                user1.setPhone("123456789");

                QBUsers.signUp(user1, new QBEntityCallbackImpl<QBUser>() {
                    @Override
                    public void onSuccess(QBUser user, Bundle args) {

                    }

                    @Override
                    public void onError(List<String> errors) {

                    }
                });

            }

            @Override
            public void onSuccess(final QBSession session, Bundle arg1) {
                // TODO Auto-generated method stub
                final QBUser user1 = new QBUser("temp151", "123456789");

                user1.setFullName("temp151");
                user1.setPhone("123456789");

                QBUsers.signUp(user1, new QBEntityCallbackImpl<QBUser>() {
                    @Override
                    public void onSuccess(QBUser user, Bundle args) {
                        user1.setId(session.getUserId());
                        if (!QBChatService.isInitialized()) {
                            QBChatService.init(MainActivity.this);
                            chatService = QBChatService.getInstance();
                        }
                    }

                    @Override
                    public void onError(List<String> errors) {

                    }
                });
            }
        });

        break;
    case R.id.btn_login:
        create_session();
        break;
    case R.id.btn_call:
        QBRTCTypes.QBConferenceType qbConferenceType = QBConferenceType.QB_CONFERENCE_TYPE_VIDEO;
        List<Integer> opponents = new ArrayList<Integer>();
        opponents.add(4319012); // QBUser ID

        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("user", "temp152");

        // Init session
        QBRTCSession session = QBRTCClient.getInstance()
                .createNewSessionWithOpponents(opponents, qbConferenceType);

        // Start call
        session.startCall(userInfo);

        break;
    case R.id.btn_recieve:

        // VideoChatConfig videoChatConfig =
        // QBVideoChatController.getInstance().callFriend(user2,
        // CallType.VIDEO_AUDIO, null);
        QBVideoChatController.getInstance().callFriend(user1,
                CallType.VIDEO_AUDIO, null);
        break;
    case R.id.btn_login2:

        QBAuth.createSession(user2, new QBEntityCallback<QBSession>() {

            @Override
            public void onError(List<String> arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(QBSession arg0, Bundle arg1) {
                // TODO Auto-generated method stub
                user2.setId(arg0.getUserId());
                if (!QBChatService.isInitialized()) {
                    QBChatService.init(MainActivity.this);
                    chatService = QBChatService.getInstance();
                }
                chatService.login(user2,
                        new QBEntityCallbackImpl<QBUser>() {

                            @Override
                            public void onSuccess() {
                                // success
                                Log.i("Login Successful", "Logged In");

                                create_SignallingManager();
                            }

                            @Override
                            public void onError(List errors) {
                                // error
                                Log.i("errors", "" + errors.toString());
                            }
                        });
            }
        });

        break;
    default:
        break;
    }

}

public void create_SignallingManager() {
    // TODO Auto-generated method stub

    QBChatService
            .getInstance()
            .getVideoChatWebRTCSignalingManager()
            .addSignalingManagerListener(
                    new QBVideoChatSignalingManagerListener() {
                        @Override
                        public void signalingCreated(
                                QBSignaling qbSignaling,
                                boolean createdLocally) {
                            if (!createdLocally) {
                                QBRTCClient.getInstance().addSignaling(
                                        (QBWebRTCSignaling) qbSignaling);
                            }
                        }
                    });

    QBRTCClient.getInstance().addSessionCallbacksListener(this);
    QBRTCClient.getInstance().addConnectionCallbacksListener(this);
    QBRTCClient.getInstance().addVideoTrackCallbacksListener(this);

    QBRTCClient.getInstance().prepareToProcessCalls(this);
    SessionCallback loginlistener = new SessionCallback() {

        @Override
        public void sessionCreated(InputMethodSession arg0) {
            // TODO Auto-generated method stub
            try {
                QBVideoChatController.getInstance()
                        .initQBVideoChatMessageListener();
            } catch (XMPPException e) {
                e.printStackTrace();
            }

        }

    };
}

public void create_session() {
    QBAuth.createSession(user1, new QBEntityCallback<QBSession>() {

        @Override
        public void onError(List<String> arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(QBSession arg0, Bundle arg1) {
            // TODO Auto-generated method stub
            user1.setId(arg0.getUserId());
            if (!QBChatService.isInitialized()) {
                QBChatService.init(MainActivity.this);
                chatService = QBChatService.getInstance();
            }
            chatService.login(user1, new QBEntityCallbackImpl<QBUser>() {

                @Override
                public void onSuccess() {
                    // success
                    Log.i("Login Successful", "Logged In");
                    create_SignallingManager();

                }

                @Override
                public void onError(List errors) {
                    // error
                    Log.i("errors", "" + errors.toString());
                }
            });
        }
    });
}

@Override
public void onCallRejectByUser(QBRTCSession arg0, Integer arg1,
        Map<String, String> arg2) {
    // TODO Auto-generated method stub

}

@Override
public void onReceiveHangUpFromUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onReceiveNewSession(QBRTCSession arg0) {
    // TODO Auto-generated method stub
    Map<String, String> userInfo = new HashMap<String, String>();
    userInfo.put("user", "temp152");

    // Accept incoming call
    arg0.acceptCall(userInfo);
}

@Override
public void onSessionClosed(QBRTCSession arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onSessionStartClose(QBRTCSession arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUserNotAnswer(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectedToUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub
    Log.i("connected to second user", "connected");
}

@Override
public void onConnectionClosedForUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailedWithUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onDisconnectedFromUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onDisconnectedTimeoutFromUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onError(QBRTCSession arg0, QBRTCException arg1) {
    // TODO Auto-generated method stub
    Log.i("Error", "" + arg1.toString());

}

@Override
public void onStartConnectToUser(QBRTCSession arg0, Integer arg1) {
    // TODO Auto-generated method stub
    Log.i("Connection", "connecting to user");

}

@Override
public void onLocalVideoTrackReceive(QBRTCSession arg0, QBRTCVideoTrack arg1) {
    // TODO Auto-generated method stub
    QBGLVideoView localVideoVidew = (QBGLVideoView) findViewById(R.id.localVideoView);
    VideoRenderer localRenderer = new VideoRenderer(new VideoCallBacks(
            localVideoVidew, QBGLVideoView.Endpoint.LOCAL));
    arg1.addRenderer(localRenderer);
    localVideoVidew.setVideoTrack(arg1, QBGLVideoView.Endpoint.LOCAL);
}

@Override
public void onRemoteVideoTrackReceive(QBRTCSession arg0,
        QBRTCVideoTrack remoteVideoTrack, Integer arg2) {
    // TODO Auto-generated method stub
    QBGLVideoView remoteVideoView = (QBGLVideoView) findViewById(R.id.remoteVideoView);
    VideoRenderer remoteRenderer = new VideoRenderer(new VideoCallBacks(
            remoteVideoView, QBGLVideoView.Endpoint.REMOTE));
    remoteVideoTrack.addRenderer(remoteRenderer);
    remoteVideoView.setVideoTrack(remoteVideoTrack,
            QBGLVideoView.Endpoint.REMOTE);

}

private VideoChatConfig videoChatConfig;
private OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {

    @Override
    public void onVideoChatStateChange(CallState arg0, VideoChatConfig arg1) {
        // TODO Auto-generated method stub
        videoChatConfig = arg1;
        switch (arg0) {
        case ACCEPT:
            // show call dialog
            Toast.makeText(MainActivity.this, "accept", 1000).show();
            break;
        case ON_ACCEPT_BY_USER:
            // your call was accepted

            QBVideoChatController.getInstance().onAcceptFriendCall(
                    videoChatConfig, null);

            break;
        case ON_REJECTED_BY_USER:
            // your call was rejected
            break;
        case ON_DID_NOT_ANSWERED:
            // opponent did not answer your call
            Toast.makeText(MainActivity.this, "not answer", 1000).show();
            break;

        case ON_CANCELED_CALL:
            videoChatConfig = null;
            Toast.makeText(MainActivity.this, "cancelled", 1000).show();
            break;
        // call was canceled

        case ON_CALL_START:
            // call started
            Toast.makeText(MainActivity.this, "call started", 1000).show();
            break;

        case ON_CALL_END:
            Toast.makeText(MainActivity.this, "end", 1000).show();

            // call finished
            break;
        }
    }
};

}

Answer: Tiny, what version of Android SDK are you using?
A new version of Android WebRTC SDK is to  be released on August 27-28 that should have these fixed.


Horn & Trumpet and Key Signatures

Question: In reading from 100 Orchestration Tips by Thomas Goss, I've come across a tip which I'm perfectly happy accepting, but (perhaps as I'm not a horn player nor a trumpet player) I do not understand.

34. Horn Key Signatures
"... concert horn and trumpet players prefer not to have key
signatures."
"... if you ask them what they really want, you'll get anything from a
polite suggestion to a lengthy dissertation on why key signatures are
irrelevant to horn. ..."

My question (primarily to horn players or trumpet players) is:

Why is it that key-signatures are 'irrelevant' to horn and trumpet?

I don't need a lengthy dissertation but if you could at least explain the crux or main reasons that key-signatures are not preferred, I would find that helpful.
Comment: I'd actually suspect the statement is false for trumpet players - all the concert band music I've seen has key signatures for trumpet, and so does the early 1900s-era Boosey & Hawkes-published sheet music for Elgar's Pomp and Circumstance Marches - but that very same Boosey & Hawkes sheet music has no key signatures for French horn throughout.
Comment: Surely that means the dots are clogged up with even more accidentals than normal?
Comment: @Dekkadeci you're probably right.  Natural trumpets didn't have the same tradition of having 10 or more transpositions available as did natural horns.
Answer: I play trumpet and horn, and have played both in orchestras for many years.
Both instruments used to not be fully chromatic (mainly playing their overtones) and so they'd be crooked into the key of the piece (usually). Thus, the part is transposed to read in C and the parts always end up with no key signature (or rather, the key signature of C major).
Now, I don't have any proof of this, but I strongly suspect what happened is that somebody studied a bunch of music from the 19th century and earlier, saw that parts never have a key signature, and concluded that "trumpets and horns don't use key signatures", which misses the point entirely. But they published that in some orchestration book, and it gets passed down and not questioned.
What's true is that, for better or worse, there is a tradition in classical orchestral music to eschew key signatures in trumpet and horn parts. What is NOT true is that the players themselves "don't read key signatures" or however the author in question wants to put it. Literally all other music for horn and trumpet uses key signatures. Brass quintets, wind ensembles, brass bands, jazz bands, musical theatre pits, etc. all use key signatures. And many modern classical composers are bucking the tradition and including key signatures in orchestral pieces too. So clearly, a player who is even remotely rounded is thoroughly used to reading key signatures and should have no problem with them whatsoever.
And obviously I don't know every trumpeter and hornist in the world, but I've never personally encountered anyone who is either so siloed into orchestral playing that they never encounter key signatures, or is such a zealot for tradition that they get angry about a modern composer using them. So I don't know who these players are that Thomas Goss interacts with, but they sound like clowns to me. Or maybe they're just doodling because they're orchestral brass players and they don't play much and they're bored?
In short, I fully support ditching any tradition based on old crooked natural trumpets and horns. These instruments are now fully chromatic and should be treated the same as the rest of the orchestra. And I may just be one guy, but Thomas Goss is also just one guy, and I at least play the instruments. As a direct retort to:

"... if you ask them what they really want, you'll get anything from a polite suggestion to a lengthy dissertation on why key signatures are irrelevant to horn. ..."

I really want consistency, and saying that key signatures are somehow "irrelevant" to horn makes no sense whatsoever.
Comment: So, from your experience Tip 34. is basically wrong; I should just ignore it.  Orchestral horn and trumpet players do indeed prefer key signatures.  Right?
Comment: @ElementsinSpace Again, I can't speak to what every person prefers, and apparently Goss has found a pocket of players that prefer no key signatures. But there really should be no problem using key signatures, and you have my blessing (FWIW) to roll your eyes at anyone who complains, should you ever even encounter one.
Answer: Like Dekkadeci, I'll note that the main body of the passage in question does not mention trumpets.

Why is it that key-signatures are 'irrelevant' to horn?

The tradition arose because natural horns always played as transposing instruments in the key of the piece; beginning in the late 18th or early 19th century, the transposition could change in the middle of a movement: if the piece moved to a new tonal area the horn would change to match, always being notated in C (for minor keys, the horn would be assigned a transposition to a closely related major key).  The practice of not using key signatures follows from this fairly, ahem, naturally.  Trumpets didn't change transposition as readily, and their parts are more likely to have key signatures, but if you search the internet for images you'll also find several of trumpets with sets of crooks.
If you look at older scores, you'll see notations like "muta in Sol" which means "change to G."  Originally, this meant inserting an extra length of tubing, or removing one, to change the length of the horn.  After valves became standard, the F transposition became standard, too, but the practice of not using key signatures remained.
Comment: This is definitely the answer for horn. One of the reasons horn is notoriously difficult among brass is horn players have to read all kinds of literature including natural horn and often transpose on the fly, unless they have time to make or get a transcription, which generally they learn not to need instead.
Comment: @ToddWilcox it was certainly the practice into the second half of the 18th century, probably a good deal into the 19th.  But keyed trumpets already existed in Haydn's day, so trumpeters were liberated, if you will, from the overtone series rather earlier.  Also, people seem to have been more conservative about horns: even a few decades after valved horns were well established, some composers continued to prefer natural horns.  I don't remember whom I've read this about, but it was definitely in the latter part of the 19th century.  Brahms, perhaps.
Comment: @Tim to change to the appropriate crook, they don't need to know what key anyone else is in; they just need to know what key _they_ are supposed to be in.  If everyone else is in D minor, one pair of horns might be in D and the other in F or B flat. They'd alternate notes depending on whose overtone series the note is in. The part might say _Corno 1° in Re_ at the beginning and then later _Muta in Fa_ or whatever, which means "take out the D crook and put in the F crook."  Later in the 19th century you could get some very eclectic combinations to support the increasing chromaticism.
Comment: So, early horns players would have a set of different crooks for the different keys? But wouldn't there have to be something (like in older scores) to tell them which key everyone else is in, so they could change to the apppropriate crook?
Comment: I have seen "natural" trumpet parts written, which I found confusing. And I can't remember where. But I don't think that carried through to modern notation in the same way that horn notation has.
Comment: @phoog Yes, I think you're remembering https://en.wikipedia.org/wiki/Horn_Trio_(Brahms)
Comment: @AndyBonner no, I don't know that piece.  I'll have a look.  I was mostly thinking about orchestral scores; if it was indeed Brahms I probably encountered it in connection with the German Requiem.
Comment: @phoog
Could you please expand on your last sentence?
Why it might be that despite the development of valves
and the standard usage of the F/Bb double horn,
it might _still_ make sense (or be useful) to maintain key-signature-less-ness for orchestral horn parts?
Comment: I guess the bit that I don't understand is, Why was/is it thought of as being without a key-signature, rather than being in the (written) key signature of C-major?
Comment: @ElementsinSpace I don't know; I guess it's just habit.
Answer: It's quite possible that those concert horn players are following an earlier music tradition where French horn parts were consistently not notated with key signatures, regardless of the home key of the piece.
Implying such a music tradition exists, the Boosey & Hawkes-published scores of Edward Elgar's Pomp and Circumstance Marches No. 1-4, which were all published in the early 1900s, all have no key signature for the horn parts throughout, regardless of the marches' home keys and key changes. (You can check these scores on IMSLP. Interestingly, the horn parts of Pomp and Circumstance March No. 5, which was first published in 1930 and should enter the public domain in the USA in 2026, do have key signatures.)
The closest I can find to concert trumpet players also not preferring key signatures are those Boosey & Hawkes scores similarly not having key signatures for parts for F trumpets (I'll note that I've never been in a concert band with a F trumpet, despite being in 3 school concert bands) and a claim I have heard that film music is often similarly not notated with key signatures, regardless of home key or number of key changes. I'll note that those Boosey & Hawkes scores all had key signatures for the trumpet parts for trumpets other than F trumpets, and all the concert band and marching band sheet music I've seen have key signatures for trumpet parts.
Comment: The "no key signatures for trumpets" convention only holds for orchestral music.  Wind band & brass band trumpet parts generally have key signatures (as you note).  See Gould's *Behind Bars*, pp. 263, 539, and 546 for orchestra, wind band, & brass band respectively.
Comment: [The trumpet part from the Boosey & Hawkes edition of "Pomp & Circumstance"](https://ks4.imslp.info/files/imglnks/usimg/a/a3/IMSLP50144-PMLP23738-Elgar-PompCirc1.Trumpet.pdf) also has no key signature, using accidentals instead.
Comment: As an example, see [the trumpet part for Tchaikovsky's Fourth Symphony](https://ks.imslp.info/files/imglnks/usimg/2/23/IMSLP724031-PMLP02735-2190-14.tpt1.pdf).  The first movement starts in concert F minor and modulates to B major & F major before returning to F minor, but there's not a key signature to be seen in the trumpet part — just a lot of accidentals.
Comment: @Michael Seifert - Unusual - the trumpets behave just like horns for that score. My claim that the Pomp and Circumstance trumpet parts have key signatures is mainly based on Marches No. [3](https://ks4.imslp.info/files/imglnks/usimg/c/c2/IMSLP24400-PMLP23738-Elgar_-_Pomp_and_Circumstance,_Op._39,_No._3.pdf) and [4](https://ks4.imslp.info/files/imglnks/usimg/e/e5/IMSLP24401-PMLP23738-Elgar_-_Pomp_and_Circumstance,_Op._39,_No._4.pdf).
Answer: Yes, historically valveless horns and trumpets were built (or adapted with interchangeable slides) in different keys, but always written 'in C'.
A modern orchestral horn player will still get given parts for 'Horn in D', 'Horn in Eb' etc etc. and will transpose them on the fly for his modern 'Horn in F'.   Which will probably be a 'Double horn in F/Bb'.   Unless they follow the increasing modern practice of using replicas of the original instruments...   Have I made the point that a modern hornist's life involves a LOT of transposition?   Trumpet players also use instruments in Bb, C, D, Eb (and more) to play parts in various keys.
Do these facts excuse a seemingly perverse insistence on no key signatures?   Perhaps.  Or maybe they just enjoy being special!   Anyway, it's only a symphony thing.  Horns and trumpets cope with key signatures perfectly well in band, commercial and theatre music.
There's a similar thing with harp players.   In traditional technique, harp is played with four fingers of each hand.  No thumbs. {Whoops!  Correction  - no 5th finger.  But the point stands.)  But while today's players of every other instrument delight in 'alternative' techniques, ask a harpist to pluck a string with their thumb and you'll hit a brick wall.
Comment: it's the pinkie finger that harp players don't use
Comment: I'm sure I've seen harpists use their thumbs.
Comment: See for example https://youtu.be/A0cyHGMsJBM?t=485
Comment: @ElementsinSpace it must be opposite day.
Comment: "The fifth finger is not used." - Walter Piston, *Orchestration*

Horn & Trumpet and Key Signatures


chaining methods and selectors using jquery inside of a loop

Question: Is it possible to generate a chain of selectors and methods inside of a loop?
For example, I have an array of elements:
array[0] = '.type1value1, .type1value2, .type1value3';
array[1] = '.type2value1, .type2value2, .type2value3';
array[2] = '.type3value1, .type3value2, .type3value3';

I somehow need to build a chain of methods using the array elements as selectors (by looping or any other possible means!) so that I would end up with the following:-
$('.type1value1, .type1value2, .type1value3').filter('.type2value1, .type2.value2, .type2value3').filter('.type3value1, .type3value2, .type3value3');

Answer: If I understand you correctly, you don't even need to do a loop:
var firstSelector = array.shift(); //returns first item in the array and removes it from the original array
var filterSelector = array.join(',');

$(firstSelector).filter(filterSelector);

Answer: Why can't you just do something like:
var $test = $(array[0]);

for (var i = 1; i < array.length; i++) {
   $test =  $test.filter(array[i]);
}

Looking at your example, the value of each array element is exactly the value you want to pass as the selector parameter to .filter()
Answer: use the following function to pass it an array of selectors...
function getSet(arrSet){
    var elements = $(arrSet[0]);
    for (var i = 1; i < arrSet.length; i++) {
        elements = $(elements).filter(arrSet[i]);
    }
}

Comment: `elements` is already a wrapped JQuery set so you don't need to `$()` wrap it to invoke `.filter`


not finishing activity when passing picture of byte array taken by camera

Question: i am using a main activity which is calling a cameraActivity and using picture taken by camera. i am finish camera activity on pictureTaken and passing byte array to parent activity
<code>  protected PictureCallback jpegCallback=new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {

               //Finishing Camera activity
           Bundle bundle=new Bundle();
       bundle.putByteArray("imageToPreview", data);
       mPreview.imageBundle=bundle;
               Intent it=new Intent;
               it.putExtras(bundle);
               CameraActivity.this.setResult(Activity.RESULT_OK,it);
       CameraActivity.this.finish();

        }

      }
    };
</code>
so passing image byte array creating problem and result in not finish of activity.
if i pass simply
<code>CameraActivity.this.setResult(Activity.RESULT_OK);
CameraActivity.this.finish();
</code>
it working properly
plz help i have to use this image in parent activity
Answer: i got the solution of my problem
actually we should not pass large amount of data through intent
as mentioned here
Answer: Hey sunil, same problem appeared wen i tried to work on image processing.
i was extracting image's pixels in bytearray and performing activity on array.
The problem was it was takin time to extract all bytes and so my program was becoming a big fussss.
But then i found in api that there were functions to stop performing next activity untill extraction is completed. also i was able to set max allowable time for extraction. check out in ur api such supportive methods and fields.


Why position of racers in this track not in order?

Question: I am referring to Athletics - Round 1 - Heat 3 of Women's 200m Olympics 2021:

Why position of racers in this track not in order ?
Comment: Because listing runners by finishing order rather than the lane they ran in seems more useful? Honestly not sure what you're expecting here.
Comment: Agreed - this looks like a misunderstanding of the information being presented, and when the misunderstanding is cleared up there's no question left.
Comment: Most likely, but that still seems like a valid question, just reposed - no?
Answer: "Lane" refers to which lane they raced in (there are 8 lanes on a track).  The racers start on a staggered start, as the inner lanes are shorter distances otherwise.  In the 200m race the racers will not switch lanes - they'll stay in the same lane the entire time.  See the rules here.
Beyond being informative as to which lane they raced in, that column is not useful - it is not related to the rank they finished in - and so it is not used to sort.
Comment: Although sightly oddly, the lanes for the Olympic sprint finals are numbered 2-9.
Comment: Maybe that's because it's "bad" to be on the outside or inside lane, and so they don't give anyone that number (1)?  (I.e., as superstition, not like the number 1 vs 2 matters...)
Comment: After a quick bit of digging: 9 lanes is good because it gives a "spare" lane which can be used if someone is re-instated from a semi-final or similar due to an infringement by another athlete, but if they have only 8 athletes they'll use lanes 2-9 because it avoids the inner lane with the tightest curve. (Doesn't _quite_ explain why they use 2-9 in the 100m, but at that point it may just be easier to do it that way).


How can I give advantage playing padel and have a fair game?

Question: A friend and me have started to play padel.
The problem is that we have different level and physical condition (without being any of us an expert), and due this the games can be quite boring.
How can I give some advantage and make these matches more interesting for both?
Obviously I'm not talking about playing bad on purpose. For example, when this happens in racing videogames, we have the rule that the more expert player have to use a slower car, but still drive as fast as he can.
Comment: I've don't have enought reputation to create the padel tag, so I've used tennis tag instead
Comment: The more experienced player should learn to play with his/her other hand (I have never heard of this sport, not sure if it's even a one-handed held racquet...).
Comment: @NicholasV. It's very similar to Tennis but with a little boundaries http://en.wikipedia.org/wiki/Padel_(sport)
Answer: A few options that can be used in lawn tennis, which may also work in padel:

only allow one serve for the stronger player, rather than two
the weaker player can play to the doubles' lines, but the stronger must play to the singles'
the weaker player can start each game with a point advantage
Comment: The first and last would work, but not the middle one since there are no doubles' lines in padel. Padel is almost always played as doubles.


How to determine "trendiness" of a time series

Question: I'd like to be able to compare two timeseries as to their level of "trendiness" to determine which trends better.
For example, assume two stocks, Google and IBM. Would like to understand approaches to determining which of the two trends better.
I realize that the concept of trend is a bit vague.
If one were to look at charts of two stocks (GOOG and IBM for example) one may visually exhibit smooth trends where it goes up for 20 days with little interruption and then goes down for 30 days with little interruption whereas the other may be very noisy in its movement.
Someone looking at the charts may say the first stock trends better. My question is how to mathematically/statistically determine this.
One approach might be to mark highs and lows that represent at least an N% (say 15) change in prices on both stocks and the one with the fewest N% changes therefore trends better.
Any other ideas? Is there a commonly accepted approach to this in the timeseries community?
Comment: There is already massive focus on trend determination in time series. However, it seems that your "trendiness" is to do with how well the trend captures all of the variability, and so high trendiness is low variability around the trend, and _vice versa_. If so, the recipe is: determine the trend and then quantify the variability around it. Neither is trivial but there is no shortage on advice on either in any time series text.
Comment: It's not really a matter of tests. It's a matter of finding the right estimation method for your purpose. That might be as simple as moving averages. You might need something else. What you should do can't be specified in a comment!
Comment: Perhaps this may help. I'd say that the main idea here was an echo of a standard idea in time series analysis, namely to think of the data as a combination data  $=$ trend $+$ residual. In this case the definition of trend is very generous, as whatever shows pattern. What is not trivial is precisely how to determine trend, as most of time series analysis is about different ideas on that. But once you determine trend, then you seem to be talking about measuring the variability of the residuals; again how you do it depends on your precise aims.
Comment: As near as I can tell, "trendiness" is a concept that might be captured by *temporal correlation of residuals* (relative to some underlying model). In the simplest case the model asserts the values fluctuate around some constant (such as zero). Long upwards or downwards sequences indicate large positive correlation, while rapid fluctuations above and below the average indicate large negative correlation. I very strongly doubt that statistical theory has neglected to recognize and evaluate "trendiness": the issue here is that the idea is only vaguely expressed in the post. (cc @NickCox)
Comment: Nick, thanks for the information. Will have to to some reading on the subject. When you say "determine the trend" what is it I'm seeking to do here and what will my answer look like? What tests should be run?
Answer: Nick Cox is correct that "trends" are the subject of a plethora of metrics by technically oriented financial analysts. While these technical trend metrics may be quite intensive methodologically, they tend to be weak or lacking in statistical rigor and motivation otherwise. In other words, they are pretty simple minded heuristics. What they do confirm is that your question is more about qualitative measures of "trendiness." On this topic there are no shortage of opinions.
My preference in trend analysis is to, first, answer the question of the growth rate and whether or not this growth is exponential or greater than exponential. The really interesting trends are the ones showing growth faster than exponential as these imply "bubbles" of some type. Then, over and against the growth rate, the slope or the rate of change in the predictors relative to Y, there is the acceleration in the slope or the rate of change in the rate of change. This is typically based on the slope of the second difference of Y wrt itself. Acceleration is also known as the Hessian and is considered one of the "greeks" in quantitative finance. Ron Gallant, in his 1986 Nonlinear Modeling book described as a good measure for the presence of nonlinearity in a time series. It has also been described as a measure of "success" or environmental fitness. I like it because acceleration gives you a quantification of the strength or magnitude of the force behind the first derivative or slope.
Comment: The remarks about acceleration, Hessian, greeks, and the exponential are somewhat telegraphic. No matter how I try to interpret and apply them to this context, they don't seem to match my experience with them. I suspect you may be referring to several mathematically related concepts that share a name but have quite different meanings than suggested here. For instance, exactly which of the greeks are you identifying with "acceleration"? Indeed, how does your definition of acceleration relate at all to sensitivities in the prices of financial derivatives?
Comment: Mathematically, acceleration and gamma are second derivatives--but there all connection with the context of this thread ends. Gamma is the second derivative of the value of a *derivative* on an asset with respect to its price. (Those are distinct uses of "derivative," btw.)  Acceleration is the second derivative of a function with respect to time. I believe you might privately be understanding these terms correctly, but that is not at all apparent in this post because it is just too terse: it lends itself to too many misinterpretations. I'm "fishing" for clarification and explanation.
Comment: @whuber  "Telegraphic?" I've been using these terms interchangeably for a long time and you're the first person to bridle at them. This doesn't mean you're wrong and, therefore, I'm right. But in terms of my own, personal "crowdsourcing," I find your persistent challenges a tad off -- I think you're fishing around for something. Acceleration or momentum, the rate of change in the rate of change, has embedded in it many other attributes within a time series – e.g., mass/force - which can be translated into many disciplines. Among the greeks, it corresponds to gamma. Hessian is Gallant's term.
Comment: Thanks for everyone's comments. I believe that what I'm seeking to quantify is not something that is a well know calculation in statistics circles. I thought maybe it was but I guess not.
Comment: @bobl  I will confess to still being a bit confused as to your original question. Quite honestly and in spite of all of the divagating opinions expressed on this thread, I am an expert at trends analysis. Please review this document and see if there isn't something that resonates with what you're trying to estimate. If your specific concerns still aren't addressed, I would like to propose taking this offline. I'm sure I can help answer your query, just not within the confines of this site  http://nymetro.chapter.informs.org/prac_cor_pubs/04-2015%20Thomas%20Ball_In%20Medias%20Res.pdf
Comment: Hi Mike, the goal of my original question was to learn the proper way to answer the question "does time series A trend better than time series B" where I used the time series of stocks Google and IBM as an example. From an investment standpoint it would likely be better to trade instruments which trend better than others. My definition of a better trend is one where there are more long periods of up or down movement in one time series versus another hence my idea of counting changes in direction of a certain % and the one with fewest changes over time therefore trends better. Thanks.


Two's complement and a number without a representation in a computer

Question: For the sake of the example, suppose we are working in a $4$ bit numbers. Then, addition is done modulo  $2^{n}.$ In a computer numbers from $0$ to $7$ will be our positives, and $8$ to $15$ the negatives. Hence, to find the additive inverse of a number $x$, we calculate $2^{n} - x$. Every positive number has an inverse in this system, but the number $-8,$ which is $8$ modulo $2^{4}$ has no additive inverse representation in this system, since $2^{4} - 8  = 8 \equiv -8.$
So, how would a program to compute $$-8 + x = 0$$ work on such a $4$ bit computer?
Comment: Computers (unless you are using a computer algebra system) do not solve equations, they perform computations.  You can't ask it to solve $-8+x=0$.  You can ask it to compute  $-8+0$ and store the result in $x$.  You can ask it to loop through all the numbers, add them to $-8$ and alert you if it finds $0$ for a sum.  In fact, $(-8)+(-8)=0$ (with an overflow).
Answer: The number representation you are describing is called 4-bit 2s complement. It can only represent the integers $-8, -7, \ldots 0, 1, \ldots 7$. So if you use this number representation, you cannot give the solution to $-8 + x = 0$ (namely $x = 8$). So a program that was restricted to 4-bit 2s complement numbers would have to use two 4-bit numbers to represent the solution to this problem. See https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic.


Parse error: syntax error, unexpected ' ' (T_STRING)

Question: <code>    <?php
 // Array com os dias da semana
 $diasemana = array('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabado');

 // Aqui podemos usar a data atual ou qualquer outra data no formato Ano-mês-dia (2014-02-28)
 $data = date('Y-m-d');

 // Varivel que recebe o dia da semana (0 = Domingo, 1 = Segunda ...)
 $diasemana_numero = date('w', strtotime($data));

 // Exibe o dia da semana com o Array
 echo $diasemana[$diasemana_numero];
?>
</code>
Answer: Você tem caracteres (quase) invisíveis no seu código (em space), no início de cada linha. Remova os espaços que estão no início de cada linha. Isso com certeza foi causado por ter copiado e colado esse código de algum lugar...
Comment: Que, por sinal, é o caractere [` `](http://www.codetable.net/decimal/8195)
Comment: Exatamente, esse mesmo :)


Easy code I copied straight off a tutorial not working, Javascript Notepad++

Question: This is my code:

Thanks in advance, I am not too sure how to fix it and I don't think theres anything wrong with the CODE itself, and when i passed it through an online IDE i got this error: Support for the experimental syntax 'jsx' isn't currently enabled.
Opened it in Brave browser to find there was no text, just blank
Comment: so, you've created this file in notepad++ ... great ... what did you do with this file? did you open it in a *web browser*?
Comment: Did you set the file extension to be `.html`?
Comment: NP++ is irrelevant. The browser doesn't care how the text got into the file it runs. Your "online IDE" (it's good to say which one, specifically) is probably running NodeJS. This is HTML code here, with JS embedded in a script tag, so you need to run it in a browser.
Comment: This is an html file, not a javascript file. Your online ide thought you were giving it jsx which is a html-like markup syntax for javascript. Also it's `textContent` not `textContext`
Comment: *"when i passed it through an online IDE"* - Can you elaborate on what specifically you mean by that?
Comment: @lejlun yes, is that why?
Comment: @mintymoes If you used the `.html` extension you have nothing to worry about. The syntax error mentioned in the post below is likely what's causing your error.
Answer: There is no JavaScript property called textContext. If you want to add text inside your h1 element using JavaScript, you can either use the textContent property or the innerText property like this:


App is crashing silently during custom camera (Swift)

Question: The app is crashing at random points in this function. I believe I need to scale it down but I am not sure. The only requirements I have for the image is that it remains a square and it remains decently sized because I need it to be big enough to take the entire screens width.
Here is an error that sometimes comes along with the crash:

warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.

<code>@IBAction func didPressTakePhoto(sender: UIButton) {
    self.previewLayer?.connection.enabled = false
    if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
            if (sampleBuffer != nil) {
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider = CGDataProviderCreateWithCFData(imageData)
                let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)
                var image = UIImage()

                if UIDevice.currentDevice().orientation == .Portrait{
                    image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
                }else if UIDevice.currentDevice().orientation == .LandscapeLeft{
                    image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Up)
                }else if UIDevice.currentDevice().orientation == .LandscapeRight{
                    image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Down)
                }

                //Crop the image to a square
                let imageSize: CGSize = image.size
                let width: CGFloat = imageSize.width
                let height: CGFloat = imageSize.height
                if width != height {
                    let newDimension: CGFloat = min(width, height)
                    let widthOffset: CGFloat = (width - newDimension) / 2
                    let heightOffset: CGFloat = (height - newDimension) / 2
                    UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), false, 0.0)
                    image.drawAtPoint(CGPointMake(-widthOffset, -heightOffset), blendMode: .Copy, alpha: 1.0)
                    image = UIGraphicsGetImageFromCurrentImageContext()
                    let imageData: NSData = UIImageJPEGRepresentation(image, 0.1)!
                    UIGraphicsEndImageContext()
                    self.captImage = UIImage(data: imageData)!
                }

            }
            self.performSegueWithIdentifier("fromCustomCamera", sender: self)
        })

    }

}
</code>
This code is running in my viewDidAppear and stillImageOutput is returning nil when I take a photo.
<code>if self.isRunning == false{
        captureSession = AVCaptureSession()
        captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

        let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

        var error: NSError?

        do {
            input = try AVCaptureDeviceInput(device: backCamera)
        } catch let error1 as NSError {
            error = error1
            print(error)
            input = nil
        }

        if error == nil && captureSession!.canAddInput(input) {
            captureSession!.addInput(input)
            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
            if captureSession!.canAddOutput(stillImageOutput) {
                captureSession!.addOutput(stillImageOutput)
                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
                previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
                previewView.layer.addSublayer(previewLayer!)

                captureSession!.startRunning()
                self.isRunning = true

            }
        }

    }
</code>
Comment: Crash even during debugging? Xcode must show something useful, including backtrace, and the type of crash, e.g. EXC_BAD_ACCESS...
Comment: I forgot to add. I get this error ...warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.
Comment: This is a well-known misleading warning. It could mean anything, including recursive loops (which apparently not your case), and cached libraries (which clean & rebuild will solve the case)
Comment: So there is no way to figure out why mine is crashing because cleaning it did not work.. It still crashes sadly
Comment: Try **Product > Clean** and Build & Run first. Make sure you removed the installed copy in your device
Comment: I did that and it is still crashing
Comment: Next, to debug your codes, you should comment out the codes line by line, to locate where the problem is. I know this sounds stupid, but it's very practical.
Comment: I honestly have put break points on all the lines and the app crashes at different places every time. I believe it is something to do with this : stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
Comment: It seems to crash at let imageSize: CGSize = image.size. I think this is due to the image being to big for memory
Comment: I printed out the error and it is finding nil when unwrapping an optional
Answer: Fixed it. The reason it was crashing was actually due to my images being way too big. I had to compress them.


AjaxControlToolKit is not working in any of the element of website

Question: A very weirdproblem in my asp.net website. There are UpdatePanel, UpdateProgress & ModalpopupExtender in my page. All were working fine. Suddenly all of them stopped working. e.g. ModalPopupExtender not showing popup. UpdatePanel reloads entire page, UpdateProgress not showing. All this were working but suddenly stopped.
In my Bin folder I have deleted all files & added again & Rebuilded projects but still didn't worked..
UpdatePanel & UpdateProgress
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
        <ProgressTemplate>

        </ProgressTemplate>
    </asp:UpdateProgress>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
           'content here
       </ContentTemplate>
</asp:UpdatePanel>

ModalPopupExender
<asp:HyperLink ID="quteRequest" runat="server" CssClass="quote-request" ClientIDMode="Static">Request A Quote</asp:HyperLink>

<asp:ModalPopupExtender ID="mpInquiry" runat="server" BackgroundCssClass="inquiry-form-container" PopupControlID="inquiryInner" TargetControlID="quteRequest" CancelControlID="closeEditPost"></asp:ModalPopupExtender>

<asp:Panel ID="inquiryInner" runat="server" CssClass="inquiry-form-inner" style="display:none">
<asp:HyperLink ID="closeEditPost" CssClass="cross-close" runat="server" style="margin-right:10px"></asp:HyperLink>
</asp:Panel>

Comment: Is your browser version recently updated? Please try in different browser. And check if there are any Javascript error in browser console log .
Comment: @Prasanjit Thing is I checked the version which I downloaded & that is working fine. It was working in my website as well but suddenly stopped working.
Comment: @stuartd in my browser console I can see this error ''Uncaught Error: ASP.NET Ajax client-side framework failed to load."
Comment: @Prasanjit in my browser console I can see this error ''Uncaught Error: ASP.NET Ajax client-side framework failed to load."
Comment: There coluld be multiple reasons for this error  like .Net Framework version and browser version.http://stackoverflow.com/questions/11288796/asp-net-ajax-client-side-framework-failed-to-load-when-put-the-scriptmanager-on
Answer: <asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true">

this solved my problem.. For more please refer this link


Estimating expected values for correlated data using random effects models

Question: Statement of the problem: in a study, continuous and dichotomous variables were measured for both eyes for 60 individuals. The researchers needs estimates of expected values (means and proportions) for those measurements for all 60 subjects across bot eyes. In order to do this, the 120 eyes from the 60 subjects must be used to provide a pooled estimate.
The proposed random effects models to achieve this are as follows:
$E(y_{ij})=\mu+\alpha_j+\epsilon_{ij}$
and
$Logit(p_{ij})=\gamma+\omega_j$
Where $\mu$ is the overall mean for a continuous variable $y_{ij}$, $\gamma$ is the overall log odds of the probability for the dichotomous variables, $\alpha_j, \omega_j, \epsilon _{ij}$ are uncorrelated random effects with normal distributions ($\alpha_j \sim N(0,\sigma_{\gamma}), \;\omega_j \sim N(0,\sigma_{\omega}), \; \epsilon_{ij} \sim N(0,\sigma_{\epsilon}), Cov(\alpha_j,\epsilon_{ij})=0$). Index $j$ stands for subject and index $i$ stands for eye nested in the subject.
A more complex nested random effects model could be appropriate, however, for the sake of simplicity will be ignored.
I have made a github project with the data and code in R to do this (https://github.com/nmolanog/glmer_question).
Now I present the main issue of this post: for  dichotomous variables I am observing huge differences in estimates ignoring correlation of eyes nested in subjects vs estimates provided by the random effect models. Those differences are so important, that researchers are questioning and mistrusting the approach and its results. For continuous variables the differences in estimates are almost none existent and (as expected) the main differences are found in confidence intervals, where random effects models provides wider CI's (see figure).

See for example variables M and N, the differences between approaches are huge. In the github repo I explored a nested random effects models for variable K obtaining very similar results to those provided by the simpler random effects model.
How those differences could be explained? Is there any problem with the approach?
Update-Sample code:
###estimate proportion for variable K using glm
mk_glm<-glm(K~1,data = ldf, family = binomial(link = "logit"))
mk_glm_ci<-inv.logit(confint(mk_glm))

##arrange result from glm model
(res_df<-data.frame(method="glm",estimate=inv.logit(mk_glm$coefficients),LCI=mk_glm_ci[1],UCI=mk_glm_ci[2]))

#compare to  raw estimate:
ldf$K%>%table()%>%{.[2]/sum(.)}

###estimate proportion for variable K using glmer model 1
mk_glmer<-glmer(K~1+(1|Id),data = ldf, family = binomial(link = "logit"),control=glmerControl(optimizer = "bobyqa"),nAGQ = 20)
mk_glmer_ci<-confint(mk_glmer)
#add result to res_df
(res_df<-rbind(res_df,data.frame(method="glmer",estimate=inv.logit(fixef(mk_glmer)),LCI=inv.logit(mk_glmer_ci[2,1]),UCI=inv.logit(mk_glmer_ci[2,2]))))

###estimate proportion for variable K using glmer model 2, nested random effects
mk_glmer_2<-glmer(K~1+(1|Id/eye),data = ldf, family = binomial(link = "logit"),control=glmerControl(optimizer = "bobyqa"))
mk_glmer_2_ci<-confint(mk_glmer_2)
(res_df<-rbind(res_df,data.frame(method="glmer2",estimate=inv.logit(fixef(mk_glmer_2)),LCI=inv.logit(mk_glmer_2_ci[3,1]),UCI=inv.logit(mk_glmer_2_ci[3,2]))))

Outuput
             method  estimate       LCI       UCI
(Intercept)     glm 0.7083333 0.6231951 0.7846716
(Intercept)1  glmer 0.9230166 0.7399146 0.9990011
(Intercept)2 glmer2 0.9999539 0.9991883 0.9999995

The dataset and code can be found in https://github.com/nmolanog/glmer_question
Answer: The largest variation in the width of your confidence intervals occurs in the estimates for the dichotomous outcome variables, so I will focus mostly on that part of the model.  I will speak to the models for the continuous outcome variables at the end.  The phenomenon you are observing is fairly easy to explain in the present case; it arises from the "externalising" effect that adding a random effect has in a GLM.

Models for dichotomous outcome variables: You fit one model that is a standard GLM and another that is a random effects model that includes a random effect on the subject index:$^\dagger$
$$\begin{matrix}
\text{GLM}   & & & \text{Logit}(p_{ij}) = \gamma_* \quad \quad \\[6pt]
\text{GLMER} & & & \text{Logit}(p_{ij}) = \gamma + \omega_j \\[6pt]
\end{matrix}$$
This leads you to the following estimates for the intercept terms $\gamma_*$ (in red) and $\gamma$ (in blue).

When you fit the initial GLM, the parameter $\gamma_*$ is an estimate of the location of the true probability $p_{ij}$ for the dichotomous outcome, taking into account both the variation over eyes and also the variation across subjects.  Since this is using a lot of information, it gives quite a tight estimate for the parameter, as shown by the relatively narrow confidence interval.  Contrarily, when you add a random effects term across subjects in the latter model, the variation of the outcome across subjects is "externalised" into the random effects term, so now the new parameter $\gamma$ is an estimate of the location of the true probability $p_{ij}$ taking into account only the variation over eyes.  Since this is very little information, it gives a very poor estimate for the parameter, as shown by the extremely wide confidence intervals.
This result is really quite unsurprising --- if you add a random effects term across subject then you are "externalising" the variation across subjects so it no longer affects the intercept parameter.  The particular reason that you get very wide confidence intervals in this case is that, presumably, the eye variable is only weakly associated with the dichotomous outcome variables.  If there is low association between these variables then the former gives little information on the latter, and so the range of estimates of the relevant coefficient parameter is large.  (It is also useful to note that the relationship is mediated through the logit function, so it is not the linear association that is germane here.)  If you look "under the hood" at the likelihood functions for each model, you will see that the intercept parameter in the second model is relatively insensitive to changes across subjects (in terms of derivatives, etc.) and this manifests in major differences in the estimated standard error of the intercept parameters in the two models.
As you can see from the above, the issue here is that you are using two very different models to estimate "the same" underlying parameter.  One model incorporates variation across subjects into the estimator, and therefore estimates relatively accurately.  The other model intentionally excludes this information (by externalising it into random effects terms) and therefore gives an estimate using much less information.  It is unsurprising that the results of the two exercises are very different.  Although they are estimating "the same" parameter, they are effectively using two very different sets of information.

Models for continuous outcome variables: In these cases you can see that the same phenomenon is occurring to some extent ---i.e., the confidence intervals under the random effects model are wider than under the corresponding models without those random effects.  The size of the effect is substantially smaller in this case, and as you can see, the difference in the width of the confidence intervals is much smaller.  Presumably this occurs because the eye variable is giving more information about the continuous outcome variables than the dichotomous outcome variables, and so the "remaining information" is larger in the continuous case.  It is also worth bearing in mind that this model posits a linear association between the variables, so the coefficient is more sensitive to outcome in the extremes of the range, and this may lead to the eye variable being more "informative" in the continuous case.

$^\dagger$ Note that I have used $\gamma_*$ instead of $\gamma$ for the GLM, in order to differentiate the parameters of different models.
Comment: But why those differences are not present in the case of continuous outcome? I cannot find anything in your reasoning which explains this. In fact your reasoning could apply as well to the continuous outcome case, however in that case there is almost no difference with exception of the confidence intervals which are a little wider.
Comment: That is a reasonable observation, and so I have updated the answer to discuss the continuous case.  In summary, yes, it does also apply to the continuous case (as you can see from the fact the intervals are wider with the random effect included), but the extent of the phenomenon is different in this case.  Presumably this occurs because the remaining variable (eye variable) is more informative about the continuous outcomes than the dichotomous outcomes.  If the eye variable is sufficiently informative about the continuous variables then the difference in CI width could be very small.
Comment: your comment about information in one or another case is indeed correct since it is a reflection on the spread of CI. However, no mention of behavior for variables C and K is present. Also, none of your affirmation are relaying in any statistics, indices or measures from the data. I think that there is more to be said in this problem.
Comment: I'm afraid you have lost me now.  I don't see any variables C or K in the question.
Answer: In the model for the continuous outcome $y$,
$$E(y_{ij})=\mu+\alpha_j+\epsilon_{ij}$$
$\alpha_j$ is measured in units of whatever your outcome variable is.
In the model for the binary outcome $p$,
$$Logit(p_{ij})=\gamma+\alpha_j$$
$\alpha_j$ is measured in units of the log odds.
This is clearly a problem!
I think this could be addressed by adding a scaling parameter to the first model,
$$E(y_{ij})=\mu+\beta\alpha_j+\epsilon_{ij}$$
where $\beta$ captures the mapping between the random effects in the binary model, measured in log-odds, and those in the continuous model, measured in units of $y$.
Comment: I updated the notation in the question to avoid any confusion. There is no relation between random effects in the first and second equations. The main objective is to estimate expected values in a dependent data context. The issue appears when comparing estimations by means of random effect models vs classical approach (maximum likelihood, assuming independent data) when outcome is dichotomous.
Answer: You are not supposed to compare models that have different assumptions. The classical GLM assumes independent data which you stated that this assumption is violated! So, you can't trust the output of such model.
The other point about GLMM (glmer) models, you have to come out with the best fit for the models first, for example compare the two models that have different structures of random effects using the
-2 * logLik(fit1) + 2 * logLik(fit2)
then decide which fit is better.
You can also use model diagnostics such as in "DHARMa" package to be more sure about the fit and the assumptions.
Note:
The number of random effects units should be at least 5-6, but you have only two ~(eyes) and this could pose a problem in the CIs, check out : http://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#inference-and-confidence-intervals
"Clark and Linzer (2015)... One point of particular relevance to 'modern' mixed model estimation (rather than 'classical' method-of-moments estimation) is that, for practical purposes, there must be a reasonable number of random-effects levels (e.g. blocks) – more than 5 or 6 at a minimum"
Comment: Thanks for your interest in the post. First and most important there are not just two groups for the random effects component. Here there are 60 groups, they are patients which have two eyes, so the random effect is associated to the patient and not to the eye. I suggest to check the github repo with all the data and code for analysis. Second, the main issue here is why there exist huge differences in estimation procedures (glm vs glmer) in the case of dichotomous outcome, whereas in the case for the continuous outcome (lm vs lmer) the differences are almost none existent.
Answer: First thing to note about the dichotomous variables with important differences between glm estimation and glmer estimation is that the glm estimation (which coincide to the raw proportion) is near 0,5. This is important since in a Bernoulli distribution (and also in the binomial case) this proportion is associated with the maximum variance. It is a "coincidence" that the variables D, L,M and N which have the widest CI for the random effects model are also those with raw proportion near 0,5.
An other very important part of the random effects model is the random effects an its behavior. Here I present the predictions of those random effects for each variable.
#######################
###load packages
#######################

options(max.print=999999)
library(pacman)
p_load(here)
p_load(tidyverse)
p_load(lme4)
p_load(reshape2)
p_load(performance) #to get ICC
p_load(boot) # to get inv.logit
p_load(gridExtra)
p_load(lattice)
path_RData<-"../data"

#######################
###load data
#######################
list.files(path = path_RData)%>%str_subset(".RData")
#> [1] "problem_data.RData"
load(paste0(path_RData,"/", "problem_data",".RData"))

###fitting models
vars_to_reg<-colnames(ldf)[-c(1:2,15)]
dic_vars<-c("C","D","K","L","M","N")
univar_mer<-list()
univar_glm<-list()

for(i in vars_to_reg){
  if(is.numeric(ldf[,i])){
    univar_glm[[i]]<-lm(formula(paste0(i,"~1")),data = ldf)
    univar_mer[[i]]<-lmer(formula(paste0(i,"~1+(1|Id)")),data = ldf)
  }else{
    univar_glm[[i]]<-glm(formula(paste0(i,"~1")),data = ldf, family = binomial(link = "logit"))
    univar_mer[[i]]<-glmer(formula(paste0(i,"~1+(1|Id)")),data = ldf, family = binomial(link = "logit"),control=glmerControl(optimizer = "bobyqa"),nAGQ = 20)
  }
}

###random effects
ranef_ls<-list()
for(i in vars_to_reg){
  ranef_ls[[i]]<-univar_mer[[i]]%>%ranef()%>%as.data.frame()%>%{cbind(.,var=i)}
}
ranef_df<-ranef_ls%>%reduce(rbind)

ranef_df[ranef_df$var %in% dic_vars,]%>%ggplot( aes(y=grp,x=condval)) +
  geom_point() + facet_wrap(~var,scales="free_x") +
  geom_errorbarh(aes(xmin=condval -2*condsd,
                     xmax=condval +2*condsd), height=0)

Created on 2020-08-06 by the reprex package (v0.3.0)
There is clearly a problem, they cannot be considered as normal distributed. Lets check the estimate of the standard deviation for those random effects and intraclass correlation coefficients.

###get sd of random effects
dic_vars%>%map_df(~data.frame(var=.,sd=VarCorr(univar_mer[[.]])%>%unlist))
#>        var        sd
#> Id...1   C 186.10495
#> Id...2   D 339.75926
#> Id...3   K  17.33202
#> Id...4   L  40.69868
#> Id...5   M 287.55684
#> Id...6   N 308.23320
###get sd of random effects
dic_vars%>%map_df(~data.frame(var=.,icc=performance::icc(univar_mer[[.]])$ICC_adjusted))
#>   var       icc
#> 1   C 0.9826296
#> 2   D 0.9904099
#> 3   K 0.8404672
#> 4   L 0.9252108
#> 5   M 0.9886887
#> 6   N 0.9894394

Created on 2020-08-06 by the reprex package (v0.3.0)
sd for random effects are pretty high.
Finally I want to compare with other data set:
#######################
###load packages
#######################
options(max.print=999999)
library(pacman)
p_load(here)
p_load(tidyverse)
p_load(lme4)
p_load(reshape2)
p_load(performance) #to get ICC
p_load(boot) # to get inv.logit
p_load(gridExtra)
p_load(lattice)

###lung cancer
### see https://stats.idre.ucla.edu/r/dae/mixed-effects-logistic-regression/
hdp <- read.csv("https://stats.idre.ucla.edu/stat/data/hdp.csv")
hdp <- within(hdp, {
  Married <- factor(Married, levels = 0:1, labels = c("no", "yes"))
  DID <- factor(DID)
  HID <- factor(HID)
  CancerStage <- factor(CancerStage)
})

###estiamtions
m0 <- glmer(remission ~ 1+(1 | DID),
            data = hdp, family = binomial, control = glmerControl(optimizer = "bobyqa"),
           nAGQ = 10)
mk_glmer_ci<-confint(m0)
#> Computing profile confidence intervals ...

m1 <- glm(remission ~ 1,
            data = hdp, family = binomial)
mk_glm_ci<-inv.logit(confint(m1))
#> Waiting for profiling to be done...

###summarizing
res_df<-rbind(data.frame(method=class(m0),estimate=inv.logit(fixef(m0)),LCI=inv.logit(mk_glmer_ci[2,1]),UCI=inv.logit(mk_glmer_ci[2,2])),
      data.frame(method=class(m1)[1],estimate=inv.logit(m1$coefficients),LCI=mk_glm_ci[1],UCI=mk_glm_ci[2]))

pd<-position_dodge(0.5)
res_df%>%ggplot(aes(x=method, y=estimate,colour=method))+
  geom_errorbar(aes(ymin=LCI, ymax=UCI), width=.5,position=pd)+
  geom_point(position=pd)+theme_bw()+ggtitle("dichotomous variables")+
  ylim(0, 0.5)

###ranef
dotplot(m0%>%ranef)
#> $DID

###ranef sd estimate
m0%>%VarCorr()
#>  Groups Name        Std.Dev.
#>  DID    (Intercept) 1.9511

###ICC
performance::icc(m0)$ICC_adjusted
#> [1] 0.5364152

###check number of measures by group
hdp$DID%>%table%>%unique
#>  [1] 28 32  6 30 18 34 27 23 22  2 20 29 35 19 11  4  5 14 17 37 13 12 31 36 15
#> [26] 39  9  7 33 25 40 26 10 38 21  8 24  3 16

Created on 2020-08-06 by the reprex package (v0.3.0)
From this example there are some things to note: first, here the estimate of the standard deviation of the random effect is very small. Second, the number of measures in the grouping factor used for random effects specification is much greater than 2 (as in my data set, since there are two eyes per subject). Also, the random effects prediction has a much better distribution.
In summary: The possible factors that are behind the "strange" behavior of estimations and wide confidence intervals in my dichotomous variables when using the glmer are:

raw proportions near 0,5

random effects not normally distributed

very high estimates of standard deviation of random effects

just 2 measures per group associated to random effects

To do next: I "feel" that points 2 and 3 are caused by point 4. This could be assessed by means of simulations and mathematical analysis.
Note: code can be found in this github repo, files ranef_assess.R and for_comparison.R were used for this answer.


convert any string or a character in php to unicode code points

Question: How to convert any string or a character in php to "unicode code points"
for example : unicode code points of letter अ is 0905
and A is 0041
I need a continuous string if i pass Aअ which will give me a output as 00410905
Comment: possible duplicate of [Unicode character in PHP string](http://stackoverflow.com/questions/6058394/unicode-character-in-php-string)
Answer: Use this function
function Unicode_decode($text) {
     return implode(unpack('H*', iconv("UTF-8", "UCS-4BE", $text)));
 }

If you want to have U+0000 use this :
for ($i=0; $i < strlen($word); $i++)
{
    $wordConvert = Unicode_decode($word[$i]);
    $result .= "U+" . substr($wordConvert, -4, 4) . "
";

}

echo $result;

Comment: No , Actually I want continuous string like .. 00410042 like this ..

so i , utilized the function you have given me with that .. i have divided that string by 8 characters each to make it array using "str_split"

then using for loop made that long string.

Thanks a lot Hearner.. your answer was very helpful to me.
Comment: Hi Hearner ,

Thanks a lot its working. one more request.

if i want to make it as "U+0041" for "A" what changes can be done in this any help can be appreciated...
Comment: Its not working for multiple characters ... :)

Thanks a lot for your efforts :)
Comment: You want, for example, "AB" to be `U+0041  U+0042` ?
Comment: No problem, I tried to make the simplest code I could :) If you need anything you can ask.


ObjectDisposedException

Question: Tenho o seguinte trecho de código:
var nivel = 1;
List<meuObjeto> meusObjetos = new List<meuObjeto>();

using(var objectContext = ((IObjectContextAdapter)db).ObjectContext)
{
   var cmd = string.Format(@"SELECT *
                             FROM meuObjeto
                             WHERE meuObjetoNivel = {0}", nivel);

   meusObjetos.AddRange(objectContext.ExecuteStoreQuery<meuObjeto>(cmd).ToList());
}

O problema é que ao tentar acessar qualquer objeto da lista meusObjetos fora do contexto do using recebo a exception com a seguinte descrição:

ObjectDisposedException
A instância de ObjectContext foi descartada e não pode mais ser usada
  para operações que exijam uma conexão.

Até consigo aceitar que por ObjectContext implementar a interface IDisposable ao sair do contexto do using os dados dele não estejam mais acessíveis, mas como então posso fazer com que meus objetos fiquem 'independentes" do ObjectContext e permaneçam existindo mesmo após o Dispose() dele, mantendo assim o using?
Comment: O problema é que você está adicionando uma referência aos dados em `objectContext` e não fazendo uma cópia deles.
Comment: Legal isso, hein? :) Acho pouco provável que ajude mas tentou jogar em uma variável, mesmo que seja só para testar, e só depois jogar na lista? Faça o teste tentando acessa a variável fora do `using`. Se der, aí tenta a lista.
Comment: exato, mas existe alguma forma de fazer a cópia deles de forma prática?
Comment: @bigown não consegui entender direito o que você quis dizer...
Answer: Aparentemente, a lista não foi materializada no .ToList(), então teremos que ser mais assertivos com o contexto para obtermos uma lista materializada de fato:
using(var objectContext = ((IObjectContextAdapter)db).ObjectContext)
{
   var cmd = string.Format(@"SELECT *
                             FROM meuObjeto
                             WHERE meuObjetoNivel = {0}", nivel);

   var objetosMaterializados = objectContext.ExecuteStoreQuery<meuObjeto>(cmd).ToList();
   meusObjetos.AddRange(objetosMaterializados);
}

Comment: pois é grande @CiganoMorrisonMendez o .ToList() já era pra ter materializado correto?
Comment: Depende, sobretudo porque essa abordagem só materializa a lista no último momento possível.

ObjectDisposedException


UISlider Thumbnail position offset

Question: I'm trying to implement a standard UISlider with a custom image.
Currently it looks like so

But I need it to look like this

How do I offset the thumbnail up so only the tip barely touches the line?
Comment: have you found any solution for it?
Comment: @mohsin nope :( I finally ended up abandoning the whole slider idea and moved on implementing it otherwise. But it would still be useful to know how to do it in the future..
Answer: If you want to change the offset of the thumb image you have to override thumbRectForBounds:trackRect:value: in a custom UISlider subclass.
class CustomSlider: UISlider {
    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
        let originalRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
        let yOffset: CGFloat = 16 // any value you want
        let newY = originalRect.origin.y - yOffset

        return CGRect(x: originalRect.origin.x, y: newY, width: originalRect.width, height: originalRect.height)
    }
}

Answer: When the value of slideBar changed, you can get the thumb position by following codes.
    let slideBounds = self.slideBar.bounds
    let trackRt = self.slideBar.trackRect(forBounds: slideBounds)

    // thumbRt is in slideBar coordination.
    let thumbRt = self.slideBar.thumbRect(forBounds: slideBounds, trackRect: trackRt, value: slideBar.value)

    // Get center point of slideBar with coordination of `self`.
    let centerPt = self.convert(CGPoint(x: thumbRt.midX, y: thumbRt.midY), from: self.slideBar)

    // Let a UILabel moving with thumb image of slideBar.
    var origPt = self.lblValue.center
    origPt.x = centerPt.x
    self.lblValue.center = origPt

UISlider Thumbnail position offset


Instruments reporting memory leak whenever AVSpeechSynthesizer is used to read text

Question: Everytime I use AVSpeechSynthesizer to speak text Instruments reports a memory leak in the AXSpeechImplementation library. Here's the code I'm using to make the call:
AVSpeechUtterance *speak = [AVSpeechUtterance speechUtteranceWithString:text];
speak.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
speak.rate = AVSpeechUtteranceMaximumSpeechRate * .2;
[m_speechSynth speakUtterance:speak];

Here's the link to the Instruments screenshot
http://imageshack.com/a/img690/7993/b9w5.png
Comment: "Is anyone else leaking memory" is not a specific, answerable question here. (Possible answers are "Yes, someone else is", "No, no one else is", or "Somewhere, someone probably is", none of which are useful to you or any future readers of this site.) Please read the [SO question checklist](http://meta.stackexchange.com/q/156810/172661), and then edit your question to make it more clear and specific about the problem you're asking us to help you solve.
Comment: You've still not asked a specific question, I'm afraid. :) It's better, but there still has to be a question. Visit the link I posted.
Comment: Ditto on getting this error. Anyone file a bug report?
Answer: For what it is worth - yes, I see exactly the same 16byte leak on every utterance from the speech synthesizer. So either it is a leak in Apple's code or we are both making the same error somewhere!
Ali
Comment: I second that. I'm also seeing the same 16 byte memory leak as well.
Comment: are you releasing the AVSpeechUtterance?  When are you allowed to do that... on the stop?
Answer: I solved this by declaring the AVSpeechSynthesizer as a global variable
static let synth = AVSpeechSynthesizer()


can't debug wince app

Question: Firstly,my environment is VS2005, and I want to debug app in the wince6.0 device.
I use Mfc.
I can deploy fine (I have linked vs2005 with the device successfully) and run the forms application through network.
Problem: Debugging wont start. It locks up VS2005. It seems to deploy the app fine, then hangs. Eventually it has no response, and vs 2005 is dead.
A little help for me is very important. Thank you!
Answer: If a thread gets in a tight loop and starves the RNDIS session, you will lose your activesync connection. VS2005 may very well lock up in this case.
Things you could try:

Does your app run okay when it's not on the debugger?
Can you debug application on the emulator?
Can you debug a trivial app on your device? (just a main function and a printf, for example)
Re-install VS2005 and your SDK
Upgrade to VS2008
Comment: Thank you very much, PaulH. VS2005 in pc connects with wince device without activesyync. Until now, the problem is not sloved. Then, I veritified your advice as listed.
Comment: I am sorry for uncompleted answer because of interruption of power supply.
I have verified your advice as listed .
1 My app runs very well in device, and vs2005 can deploy app to the device successfully through net.
2 I can debug app on the emulator.
3 I can't debug any app even though the app is very simple.
4 I don't reinstall vs05 and sdk, but I make a try on another computer, which is failed.

can't debug wince app


block.super returns NoReverseMatch

Question: I'm learning Django and I have problems with templates.
I'm trying to add content to extended template.
Structure of my code:
base.html
category
     -- category_detail.html
     -- list_content.html

category_detail.html
{% extends 'base.html' %}
{% block title %}
    {{ category_name  }}
{% endblock %}

{% block description %}
    {{ category_description }}
{% endblock %}

{% block content %}

    Error list

{% endblock %}

Simple subpage with button. Button should redirect to another template, hovewer it gives me NoReverseMatch.
list_content.html (which is category_error_list defined in view)
{% extends 'category/category_detail.html' %}

{% block content %}
   {{ block.super }}

 Some string

{% endblock %}

What I'm trying to achieve is displaying "Some string" under button. (I know it should be done better with AJAX for example, but I want to learn the basics).
urls.py
urlpatterns = [
    url(r'^category/$', views.categories_list, name='categories'),
    url(r'^category/(?P<category_name>\w+)/$', views.category_detail, name='category_detail'),
    url(r'^category/(?P<category_name>\w+)/list/$', views.category_error_list, name='category_error_list'),
]

views.py
# ${url}/category/${category}
def category_detail(request, category_name):
    cat_detail = Category.objects.get(name=category_name)
    return render(request, 'charts/category/category_detail.html',
                 {'category_name': cat_detail.name,
                 'category_description': cat_detail.description})

#${url}/category/${category}/list
def category_error_list(request, category_name):
    category_with_errors = Category.objects.filter(name=category_name)
    error_list = Error.objects.get(category=category_with_errors)
    return render(request, 'charts/category/list_content.html',
                 {'errors_list': error_list})

Problems seems to be related with urls.py, but I can't find what is wrong.
Stacktrace:
Template error:
In template
/usr/src/app/analizer/charts/templates/charts/category/list_content.html, error at line 0
Reverse for 'category_error_list' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['category/(?P<category_name>\\w+)/list/$']
1 : {% extends 'category/category_detail.html' %}
2 :
3 : {% block content %}
4 :    {{ block.super }}
5 :
 Cos tam

6 : {% endblock %}
7 :
8 :

If I will remove block.super tag it is working, but I'm overriding content on parent template. What I'm doing wrong?
I'm using Django-1.9.4.
Answer: I have found the solution - which is nonintuitive for me - but it is working.
View category_error_list was missing category_name variable, so I have fixed it but this:
def category_error_list(request, category_name):
    category_with_errors = Category.objects.get(name=category_name)
    error_list = Error.objects.get(category=category_with_errors)
    return render(request, 'charts/category/list_content.html',
                 {'category_name': category_with_errors.name,
                  'errors_list': error_list})

block.super returns NoReverseMatch


Lilypond - two voices, with overlapping beams

Question: I have the following in my measure:

What would I have to write, to have those <c e>'s connected with beam instead of 1/8 rests, and those in second voice bellow also?
Edit
upper voice : <c' e>8[ r8 <c e>] r8 |
lower voice : r8 g[ r8 g] | ,did connect them:

however, I am not shure if those rests should still be there in between?
Comment: Just to clarify - do you want a beam between the c/e as they are, with the rest still in between? So the actual music isn't changing - just adding a beam?
Comment: I'm not sure myself, sorry!
Comment: see my edit please..
Comment: I'm still confused by what your question is I'm afraid! Your edit is perfectly valid music - if that's what you mean?
Comment: Ok, now please tell me do I have to do this always like this manually, or is there some kind of override which would apply this kind of style for a few measures?
Comment: @branquito yes, you should enter in beams like this manually every time you need it that way since there is no way to automatically beam over rests... also it is proper for the rests should be there, but if you want to hide them it is also OK. You can use `\hideNotes`
Answer: The Auto_beam_engraver does not beam over rests, bar lines, manual beams or breathing signs.
The Notation Reference is quite explicit regarding the beaming across rests: "Beams must be entered manually if beams are to be extended over rests."
Comment: So you are suggesting I should do it manually every time I need it like that?
Comment: @branquito Yes.


Should you always wear socks with roller skates/blades?

Question: This does not relate to rental equipment.
I have inline skates, because I noticed I was getting better and better at skating and wanted something I know would be comfortable and fitting. I notice they have a lot of padding inside, I'm assuming so you can make it very tight and snug and still have circulation. My question is, should it be okay to go 'foot commando' as it were, or would that be too rough on my skin and cause lots of blisters, or some other problem?
Comment: While this kind of question *may attract* more opinion-based answers than usual, people with experience in roller skating and/or expertise in skincare w.r.t. active sports would be able to give an answer which is at least as valid as a majority of answers elsewhere on Sports.SE. **However**, they should ideally refer to credible independent sources wherever possible and appropriate.
Answer: Generically speaking (rather than regarding you specifically), socks are optional.  Barefoot skating is a pretty common question in skating specific forums like https://www.fsuniverse.net/ or https://skatingforums.com or http://www.skatelogforum.com.  Skaters say they can feel the surface better and the grip is better especially with custom fitted boots.  There is the same risk for infections as there would be for other sporting gear and shoes that touch sweaty skin.  There is discussion that one's skates stink more if one skates barefoot, but I skate with socks (albeit real thin ones) and my skates stink pretty bad.
Answer: For myself, no socks mean blisters will happen. This is true for any sport where the shoe itself is subjected to sudden stops, twists, turns, and long-term use.
Answer: I wear two pair of really thick high socks to have a better feel with my skates by strapping them extra tight at the same time. I like my skates really reactive and after some time I forget I have them on.
I wouldn't advice wearing none. Too much space around your feet and less overall feel with your boots in general. Blisters assured.


Sugar ORM doesnt store data

Question: I am using Sugar ORM 1.3.1 and i am trying to save the following objects
   public class Article extends SugarRecord
 implements Serializable {
    @JsonProperty("Categories")
    private List<Category> categories = new ArrayList<Category>();
    @JsonProperty("Contents")
    private List<Content> contents = new ArrayList<Content>();
    @JsonProperty("Country")
    private CountryRelated country;
    @JsonProperty("Description")
    private String description;
    @JsonProperty("ExpiryDate")
    private String expiryDate;
    @JsonProperty("ExtraFields")
    private List<ExtraField> extraFields = new ArrayList<ExtraField>();
    @JsonProperty("Identifier")
    private int identifier;
    @JsonProperty("ImageURL")
    private String imageURL;
    @JsonProperty("Name")
    private String name;
    @JsonProperty("PortalID")
    private int portalID;
    @JsonProperty("PublishDate")
    private String publishDate;
    @JsonProperty("Region")
    private Region region;
    @JsonProperty("Related")
    private List<Related> related = new ArrayList<Related>();
    @JsonProperty("Newsbite")
    private boolean newsbite;
    @JsonProperty("ShareURL")
    private String shareURL;
    @JsonProperty("Tags")
    private List<Tag> tags = new ArrayList<Tag>();
    @JsonProperty("Type")
    private int type;
    public Article() {
    }

    public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
        this.categories = categories;
        this.contents = contents;
        this.extraFields = extraFields;
        this.country = country;
        this.description = description;
        this.expiryDate = expiryDate;
        this.identifier = identifier;
        this.imageURL = imageURL;
        this.name = name;
        this.newsbite = newsbite;
        this.portalID = portalID;
        this.publishDate = publishDate;
        this.region = region;
        this.related = related;
        this.shareURL = shareURL;
        this.tags = tags;
        this.type = type;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public List<Content> getContents() {
        return contents;
    }

    public void setContents(List<Content> contents) {
        this.contents = contents;
    }

    public List<ExtraField> getExtraFields() {
        return extraFields;
    }

    public void setExtraFields(List<ExtraField> extraFields) {
        this.extraFields = extraFields;
    }

    public CountryRelated getCountry() {
        return country;
    }

    public void setCountry(CountryRelated country) {
        this.country = country;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getExpiryDate() {
        return expiryDate;
    }

    public void setExpiryDate(String expiryDate) {
        this.expiryDate = expiryDate;
    }

    public int getIdentifier() {
        return identifier;
    }

    public void setIdentifier(int identifier) {
        this.identifier = identifier;
    }

    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isNewsbite() {
        return newsbite;
    }

    public void setNewsbite(boolean newsbite) {
        this.newsbite = newsbite;
    }

    public int getPortalID() {
        return portalID;
    }

    public void setPortalID(int portalID) {
        this.portalID = portalID;
    }

    public String getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(String publishDate) {
        this.publishDate = publishDate;
    }

    public Region getRegion() {
        return region;
    }

    public void setRegion(Region region) {
        this.region = region;
    }

    public List<Related> getRelated() {
        return related;
    }

    public void setRelated(List<Related> related) {
        this.related = related;
    }

    public String getShareURL() {
        return shareURL;
    }

    public void setShareURL(String shareURL) {
        this.shareURL = shareURL;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}

Category.class
public class Category extends SugarRecord<Category> implements Serializable {
    @JsonProperty("Identifier")
    private int identifier;
    @JsonProperty("Name")
    private String name;
public constructor + getters and setters }

Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
Comment: Add an example of your record creation. You may have a typo, or be referencing the wrong object etc but we can't see. I would also include the full model (constructor and getters/setters).
Comment: just a minute and i will update full model
Comment: just added the full article model , List it doesnt store
Comment: Do you receive an kind of error in your logcat?
Comment: there is no error just when i select form db it gives me Article with List empty
Comment: Add the code of where you create and save your records, and where you select the list.
Comment: for save i use just Article article = new Article(with data); article.save();

for load saved articles Select.from(Article.class).list();
Answer: I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)

These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...

public Article() {
    this.name = "Default Value";
}

Hope this helps you finish troublshooting!

Sugar ORM doesnt store data


Do I need an amp for my guitar if I have an audio interface?

Question: I've been playing the bass for a few years now and want to start recording some of my songs. I've also just moved cities and am trying to save on space/money/number of belongings, so I'm a bit unsure as how to proceed here.
Do I need an amp if I'm going to be just practicing / recording what I play? I have a set of headphones with quarter inch plugs already, and I most likely won't be trying to play any gigs while I'm in this city. Would the interface give me all the capabilities I need for those two things?
Thanks!
Answer: If you are talking bass guitar only, I'd say that would work fine.
An audio interface has outputs for both headphones and your computer (USB for example). So you can record and/or hear yourself play.
For guitar (and possibly bass) you'll most likely want some effects (amp simulation, distortion, reverb, ...). In that case you'll either need to put a pedal between the guitar and the interface, or use a pedal unit that has interface capabilities (such as the Line6 HD500X). (Alternatively, you can create these effects digitally in your DAW, but that might give too much delay when listening to the processed signal).
Comment: Luckily, the *basic workflow setup* is virtually free using open source and free software, so the OP can test the waters without any investment. Further reading: "vst host amp sim asio asio4all". If it works, then the OP can start looking for the important bits to upgrade.
Comment: Thanks! Just bought a Focusrite Scarlett interface. I have a distortion pedal - will the effect work well when piped through the interface?
Comment: @king_geedorah Nothing for it but plugging in and trying! However, the distortion might sound raw because there's no amp behind it. You can always try to put a Cabinet IR plugin in your DAW, these can be excellent cabinet simulators to make your "head/pedal tone" sound amazing.


heartbeat doesn't work on virtual interface

Question: I try to use vertual interface as broadcast for heartbeat(bcast in ha.cf).
When I try it I see this message in syslog:
May 23 12:17:26 Ubuntu2 heartbeat: [1107]: ERROR: glib: Error setting socket option SO_BINDTODEVICE: No such device
May 23 12:17:26 Ubuntu2 heartbeat: [1107]: ERROR: make_io_childpair: cannot open bcast eth1:0

But when I try use physic interface it work.
My ifconfig:
eth1      Link encap:Ethernet  HWaddr 08:00:27:6c:46:05
          inet addr:192.168.1.162  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe6c:4605/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1092 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1061 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:69886 (69.8 KB)  TX bytes:67058 (67.0 KB)

eth1:0    Link encap:Ethernet  HWaddr 08:00:27:6c:46:05
          inet addr:192.168.1.62  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1323 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1323 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:120776 (120.7 KB)  TX bytes:120776 (120.7 KB)

Servers are pingable from each other from all interfaces.
How I should setup my heartbeat to use this virtual interface?
Answer: You... don't.  Heartbeat needs a physical interface to bind against.  If you're specifying a virtual interface because you want to use that interface's IP as the source address for your broadcasts, I believe you're out of luck -- there's no indication of a source address config option in the ha.cf docs.