Mob model tree algorithm

Question: I am trying to figure out the inner workings of the mob function in the party package. I can't figure out how the splitting variable is selected when it is a categorical variable.
In the publications by the authors, they say that it is done by a chisquare test of association between the residual deviances and the categorical variable. I can't see how this works.
In the toy example below, the mob function works fine. The variable X is the splitting variable.
b <- (1:1000) / 100 - 5
a <- c(b,-b)
b <- c(b, b)
X <- as.factor(c(rep(FALSE, 1000), rep(TRUE, 1000)))
mob(a ~ b |  X)

However, if I fit a linear model without splitting, there is (by construction) no association between the residuals and the values of the splitting variable:
res <- sign(residuals(lm(a ~ b)))
table(res, X)

The resulting table is:
X
res  FALSE TRUE
-1   499  500
1    501  500

This table does not show that the X variable is important, still the algorithm can figure it out. How is that done?
Answer: The parameter stability tests in mob() are based not only on residuals but the entire score (aka gradient aka estimating function). For a linear regression model with an intercept, the residual is the first component of the score but there are additional components for each regressor (= residual * regressor). In your example, the second score has the information because only the slope but not the intercept is affected by the change:
library("sandwich")
res <- sign(estfun(lm(a ~ b))[,2])
table(res, X)

which yields
    X
res  FALSE TRUE
  -1     0  999
  0      1    1
  1    999    0

Two further comments: (1) The test not only uses the sign of the score, though, but a full chi-squared statistics. (2) A more flexible and improved reimplementation of mob() is available in package partykit which also provides dedicated functions lmtree() and glmtree().

Mob model tree algorithm


Game characters stop moving

Question: I'm creating my first Unity game and I have an enemy character, that travels from left corner to the right perfectly fine, but then I have a prefab (copy of that character) that suddenly stops moving, but when I pick him up with the Location tool the character starts moving again and then stops again. I am using Unity 5.2.3f1 version.
Here is the code that I'm using
<code>public class EnemyPatrol : MonoBehaviour {

    public float moveSpeed;
    public bool moveRight;

    public float wallCheckRadius;
    public Transform wallCheck;
    public LayerMask whatIsWall;
    private bool hittingWall;

    private bool notAtEdge;
    public Transform edgeCheck;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //GetComponent<Rigidbody2D> ().velocity=new Vector2(3,0);
        //Debug.Log("Premikam se desno   "+GetComponent<Rigidbody2D> ().velocity);

        //hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
        wallCheckRadius = 0.6f;
        notAtEdge = Physics2D.OverlapCircle (edgeCheck.position, wallCheckRadius, whatIsWall);

        hittingWall = false;
        //notAtEdge = true;
        if (hittingWall || !notAtEdge) {
            moveRight = !moveRight;
            Debug.Log ("Zadene steno " + hittingWall + "  Ni na robu  " + notAtEdge);
        }
        // Prepreci krozenje igralca ( zabavna zadeva )
        GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;

        if (moveRight) {
            transform.localScale = new Vector3 (1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity=new Vector2(3,0);
            Debug.Log("Premikam se desno   "+GetComponent<Rigidbody2D> ().velocity);
        } else {
            transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity=new Vector2(-3,0);
            Debug.Log("Premikam se levo"+GetComponent<Rigidbody2D> ().velocity);
        }
    }
}
</code>
And here is a picture of how it looks in game.

-Circle Collider shows the collider range of the "kill zone", if the player touches it he dies.
-Box Collider checks if he is on the ground
-Green ball checks if he gets to the corner
-Yellow ball checks if he hits a wall (which I don't really use here but have it just in case if I need it)
Answer: You cannot do physics in Update.
...well, you can, but this breaks Unity. All sorts of weird stuff will happen. Everywhere in the docs they're explicit about "don't do that".
For anything involving Physics, you use FixedUpdate instead.

Also, you should be attaching scripts to the detector things themselves. You should be implementing them as triggers, and using OnTriggerEntered etc.
Let Unity physics do the work for you - that's what it's there for.
e.g. read about: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html

Game characters stop moving


Knowing the number of arguments passed to a method in java

Question: Lets say that I have a java method:
public void setStuff(String... stuff)

Is there a easy way for me to know the number of strings passed, without using a loop to test for it?
I basically want to know how many Strings are passed, so I can simply make an array of that size out of it.
Comment: `stuff` is an array. Use `stuff.length`.
Answer: stuff is simply an array. So calling stuff.length should give the length
Comment: Thanks for the help, I didn't know that it was simply an array.


MATLAB determining elementary matrices for LU decomposition

Question: I am confused by this question I am studying for MATLAB practice.
Comment: What exactly is confusing you?
Comment: Can matlab find the individual elementary matricies to solve or do I have to do it by hand?
Comment: I did it by hand, but it didn't seem like a very quick way of doing it
Comment: I presume you are meant to do it by hand for learning purposes?
Comment: This is a matlab assignment, I am assuming we use matlab. We haven't done this stuff by hand for months.
Comment: I mean use Matlab to do the computation (multiplying the matrices), you figure out the entries...
Comment: I thought that maybe one could make use of the fact that $A=LU$, $E_3E_2E_1A=U$ so, $E=L^{-1}$ where, $E=E_3E_2E_1$ but was not successful.
Answer: I thought this an interesting excercise so, I fired up Octave (poor man's Matlab) and gave it a try. Like I said in my comment, I tried to use Matlab to calculate the elementary matrices using the fact that $E = E_3E_2E_1 = L^{-1}$ but was uncessful. So then I thought that I'd just do row operations and construct the $E_i$ directly. Here is a transcript...
octave:1> A= [1, -2, 3; 2, -6, 5; -1, -4, 0]
A =
$
\begin{matrix}
   1 & -2  & 3 \\
   2 & -6  & 5 \\
  -1 & -4  & 0 \\
\end{matrix}$
octave:2> E1 = [1, 0, 0; -2, 1, 0; 1, 0, 1]
E1 =
$\begin{matrix}
   1 &  0 &  0 \\
  -2 &  1 &  0\\
   1 &  0  & 1\\
\end{matrix}$
octave:3> E1*A
ans =
$\begin{matrix}
   1 & -2 &  3\\
   0 & -2 & -1\\
   0 & -6 &  3\\
\end{matrix}$
octave:4> E2 = [1, 0, 0; 0, 1, 0; 0, -3, 1]
E2 =
$\begin{matrix}
   1 &  0 &  0 \\
   0 &  1 &  0 \\
   0 & -3 &  1 \\
\end{matrix}$
octave:5> E2* (E1*A)
ans =
$\begin{matrix}
   1 & -2 &  3 \\
   0 & -2 & -1 \\
   0 &  0 &  6
\end{matrix}$
octave:6>


Difference of amount of two virtual column

Question: I want to get the difference between two-column, here is my current query :
select customer_id as customers_id, sum(amount) as manual_amount,
       (select amount from customers where id = customers_id) as current_wallet_amount
FROM wallet_transactions
where customer_id = 14438
group by wallet_transactions.customer_id

The result that I am getting is attached below:

What I need is the difference of manual amount and current_wallet_amount. Any help would be highly appreciable
Comment: Are you using MySQL or MS SQL Server?
Comment: @Akina, I know, but OP needs tag properly anyway.
Comment: @jarlh MySQL is specified in Subject. Version is not specified...
Answer: You can try below -
With cte as
(
    select customer_id as customers_id, sum(amount) as manual_amount,
    (select amount from customers where id = customers_id) as current_wallet_amount,
    FROM wallet_transactions
    where customer_id = 14438
    group by wallet_transactions.customer_id
)

select  customers_id,manual_amount,current_wallet_amount,
manual_amount-current_wallet_amount as difference
from cte

Answer: SELECT
  wt.customer_id AS customers_id,
  SUM(wt.amount) AS manual_amount,
  ANY_VALUE(customers.amount) AS current_wallet_amount,
  (SUM(wt.amount) - ANY_VALUE(customers.amount)) AS diff_amount
FROM wallet_transactions AS wt
JOIN customers ON customers.id = wt.customer_id
WHERE customer_id = 14438
GROUP BY wt.customer_id

Answer: SELECT cu.id AS customers_id,
       SUM(wt.amount) AS manual_amount,
       cu.amount AS current_wallet_amount,
       SUM(wt.amount) - cu.amount AS difference
FROM wallet_transactions AS wt
JOIN customers cu ON cu.id = wt.customer_id
WHERE cu.id = 14438
GROUP BY cu.id, cu.amount


Why are locally compact groups Weil complete?

Question: Why are locally compact groups Weil complete?
Note: A topological group $G$ is Weil complete if every left Cauchy net in $G$ is convergent.
Thank you, and sorry if I have bad writing.
Answer: Take a left Cauchy net $(u_i)$. Choose $V$ a compact neighborhood of $1$. Using the Cauchy property, you should be able to show that for some $j$, for all $i>j$, $u_i$ lies in a translation of $V$, hence in a compact space. so you can extract a converging subset from $u_i$. and when you can extract a converging subnet from a Cauchy net it has to converge to the limit of the extraction. (direct consequence of the Cauchy property)
Comment: :How can conclude from subnet Convergence ,Convergence net?please more explain it.
Comment: Exactly as you would do with a sequence on a metric space : You have $(u_i)$ a cauchy net and $(u_j)$ a subnet converging to $u$. Take $V$ a neighborhood of $u$, and $V'$ a neighborhood of $0$ such that if $(u-x)$ and $(x-a)$ are in $V'$ then $a$ is in $V$.
write the cauchy propertie for $V'$, then write that there is therm of $(u_j)$ which is $V'$ close to $u$ for $j$ big enough to be converne bu the previous cauchy propertie you wrote, you can deduce from those two thing, that for any $i$ concerne bu the cauchy properties, $u_i$ is in $V$.
Comment: (I wrote as if the group was commutative, but that doesn't change anything if it is not, this will work in an arbitrary uniform space)


How can you be sure your teacher-to-be is an accomplished musician?

Question: If I plan to take some lessons, I would like to be sure my teacher is of sufficient level, for what I have to pay for.
Is there any way to be sure of that without being seemingly rude and take the risk to impair your maybe useful future relationship ?
Is it rude to ask the teacher at your first course to play some Chopin or Paganini etudes (piano or violin teacher) ?
EDIT: As many pointed out, there are many excellent teachers for all levels. For my sake, I would like to get to professional level (Im an advanced amateur (Chopin sonata 3 mv4 on my board right now)), and I am a bit afraid of non capable individuals for my level (without being pejorative), hence my question: how do I know it makes the fit ?
Comment: Instead of looking at the teacher, perhaps look more towards the teacher's existing students.
Comment: To answer the actual question, if you want to know if someone is an accomplished **musican**, ask them to list some of their accomplishments. Go see them at a gig. Ask them for recordings. Ask them for references. If you want to know if someone is a good music **teacher**, then take a lesson with them or ask their former or current students. Ask for references.
Comment: Usain Bolt's coach wasn't a good enough sprinter to go professional, fwiw
Comment: And after all that, how do you know he'll be an effective teacher for YOU?  How long has he been teaching?  How do his students' exam results look?  Is he adaptable enough to cope with you, or does he have one method? Question after question, all far more important than 'can he play well?'
Comment: @Tim I cannot endorse this enough. I've been fired by a piano teacher before, with the main issue being that we clashed over her teaching method. She was an incredible pianist, but that was irrelevant in the end.
Comment: "Is it rude to ask the teacher ... to play some ... etudes?" Think about what do *really* want. Are you paying somebody to give you a private piano recital once a week, or do you want to actually learn to play yourself? There's nothing "wrong" about wanting either of those things, but they are not the same.
Comment: @ToddWilcox - that comment pretty well answers the question(s).
Comment: I would imagine this is something that you could determine after a few lessons if you're not able to figure it out beforehand.  Ultimately, most teachers are able to recognize when they are not going to be useful for a student's progress and will either refer them to another teacher or just tell them they don't have anything further to offer them.  Unless you are a highly skilled player already, most teachers will have something to offer you, or they wouldn't be able to maintain a teaching career.
Comment: I would also recommended asking a music shop for recommendations on teachers.  A good music shop should have a long list of teachers they can recommend and potentially be able to differentiate between those that are best for beginners and those that are best for more experienced players.
Comment: I agree Tod, Ask the teacher if you could sit in on a lesson. You can learn much about him just observing.
Comment: @NeilMeyer - it's a nice idea. Some teachers, and probably their students, may find this daunting. A complete stranger sitting in on a private lesson can be an imposition to some. Others may relish the opportunity to impress.
Comment: Don't sweat all this. Ask around about good teachers, then pick one. If you find that you're learning and improving, continue with him/her. If not, find another.
Comment: Give them some sight reading!
Answer: Possibly putting the cat amongst the pigeons here. An expert (at anything, be it sport, art, science, etc.) is often not a good teacher. A good teacher knows the subject, of course, but maybe hasn't the propensity to perform as well as an expert.
Often, when someone is naturally good at something, they will lack the empathy to understand why the students find it more difficult than they do.
A good teacher has ways in which to explain and help a student understand what is going on.
Imagine a brilliant player/teacher with arthritis. Suddenly they must be seen as a not so good teacher due to their ailment?
Most coaches, particularly sports, are not as good as their proteges, but that doesn't make them less valuable as coaches.
Being able to play Paganini doesn't mean being able to teach it. All this is borne out with respect to uni. degrees. Available in 'performance' and 'teaching'. So the two aspects, whilst somewhat related, don't have a great deal of bearing on each other.
Rant over!
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/42493/discussion-on-answer-by-tim-how-can-you-be-sure-your-teacher-to-be-is-an-accompl).
Answer: Don't ask for it. Others have already pointed that the teacher's mechanical abilities have almost nothing to do with his pedagogical abilities.
One more point that I would like to add - if you can't play the instrument, can you judge the musicians abilities? I don't know about you, but most people can't. I am a guitar player and can play a bit of keyboards or drums. But when I'm listening or seeing someone playing saxophone, I have zero understanding if the musician is doing something incredibly challenging or as simple as it gets. If I hear no flaws in audial output, it just seems fine...
As a guitar player I have received far more praise and awe for playing stuff that is not actually that hard. Play something fast. Play something squeeky with whammy bar. If I do something flashy like use fretting hand from above the neck I seem like a virtuoso. Some people are even amazed by simple licks from famous pieces thinking that a song that sounds good and is famous must also be hard to play :)
And when actually playing something that is really challenging... Especially if the piece ain't that fast but there is some really demanding fingerings or rhytmic patterns - noone but guitarists can appreciate that accomplishment.
Also, if you don't play any instrument yet, someone might play a piece that is above their abilities by cheating on rhytm, tempo, skipping something or just simplifying/playing something dirty and you might not notice that the person can't actually play that piece...
Answer: If it  is possible, go to own of his/hers concerts. Most musicians (despite their musical style) play concerts. So, try to find out if the teacher you are interested in is playing a gig any day now and go and watch for yourself.
Try to find others students of his, and ask them. This is more important to me, because a good musician doesn't equal a good teacher.Jaco Pastorius (bassist extraordinaire) couldn't teach anyone. Bill Milkwoski (who wrote his biography) interviewed some of his students and all of them said that he was the worst teacher ever.
So, for me it would be more important to find 3-4 students and ask them about his teaching.
Lastly, I wouldn't say it's bad to ask for a demonstration. I mean you are there to invest your money, so you want to see if he/she is worth it. So, if you cannot find other students of his and/or see him in concert, ask for him to perform a bit.
Comment: I've never had a teacher who ever played a concert (at least during the time I knew them). My best teacher could barely play at all, after having a stroke that left her partly paralysed. But she could still *teach*.
Comment: @Blue_Elephant you can assume anything you like. You seem to have already decided that you want to make an assessment of your teacher's *playing* ability. Go right ahead if you want, but you are going to pay the teacher to *teach* you, not to give you private music recitals.
Comment: An example for "try to find his students". Here is a music teacher's channel: https://www.youtube.com/user/coltrane78/videos  Check out some videos of his pupils. If you see that he can teach this, do you care at all how well he plays the instruments himself? Just check out students and judge if their level is where you aim ;)
Comment: @alephzero So I can assume your teacher played concerts _before_ teaching ? In this case one would have no need for demonstration
Comment: @alephzero What I was trying to say was that your example was not adequate to the situation I describe, that's to say you don't know the person teaching abilities.
Comment: I know also know of one of the most respected violin teachers my country has produced in the last 50 years had the policy of almost never playing before his students, that did not in any way take away from the students he produced. The really good teachers will not feel the need to prove their skills to anyone
Answer: Accomplished musician does not always make an accomplished teacher. Pavarotti was a great singer, but I would not have brought my child within a mile radius of him. Domingo on the other hand, he would be a great teacher of children.
There is more to a good teacher than just the mere mastery of the subject matter, (That is important, though.) to me the natural born teacher can achieve more with people than virtuosos whose egos are so huge that they can barely share a room with a beginner, never mind teach one.
In the end teaching is a selfless act. You are making a sacrifice in time and money to teach young people. There has to be a certain amount of emotional maturity to be a teacher, something which some great musicians simply do not have.
Many times as teacher you have to think further than just what I want out of the situation and think what does the pupil need. This you cannot do if you think the whole world revolves around you.
There is also a great deal of social graces you need as the teacher. Working with children is not easy. You need the negotiating skills of an Ambassador to get them right.
So in closing what I would say is more important is does this teacher speak with authority? If he is a man how does he strike you? If he makes you uncomfortable then that should be a warning sign.
What are his qualifications, what results has he achieved with his pupils? Most importantly of all, how does he work with children and adults?
Answer: You do not want to ask the teacher to perform for you at your lesson. As a teacher my answer to that request is "if you would like to hear me perform I would be happy to let you know of upcoming performances in which I will be playing!" I send out a newsletter so students have plenty of opportunity to hear me play if they desire to do that.
While I agree with those who have said that performing ability does not equal pedagogical ability, how your teacher plays should be a part of your decision. However, you don't need to get lessons from the concert master of the local symphony in order to find a good instructor. Someone else in the orchestra, who may not be as good a player, might be a better teacher. Notice that they are still a professional player. I would say that is important.
I would suggest going to places you can hear the STUDENTS of the teacher perform. Do you like what  you hear? Do they look like they know what they are doing? You of course don't have all the information to be able to judge things, but in general good teachers will produce competent students and it will show.
Also, ask around in your area. Ask the local music teachers who they would recommend and why. Contact the personnel manager of the local symphony and see who they would recommend. Ask people you know have kids in lessons, etc. You will start seeing the same names come up over and over again as good teachers.
Once  you have narrowed down your search take a trial lesson with a teacher or ask if you can observe some of the lessons the teacher gives. Observe their style of teaching, the results they get from the student, and whether or not  you feel comfortable with them.
Answer: If you want to go to one of their concerts that's probably a good idea. Most musicians have a youtube channel or soundcloud or something, so this really shouldn't be that hard. If I were asked by a potential student to play for them so that I could "prove my worth", honestly I'd probably be pretty offended. I would do it, but I would find it to be tremendously disrespectful. One thing you may want to consider - have you been asked to play for them? A good teacher will teach anyone but a great teacher usually has a waiting list. And they won't just take you - they'll want to hear you play. Even when I was still in grad school earning my 3rd music degree (btw I had already gotten to carnegie hall at 15 - am I an expert or an amateur with my 2 masters degrees in your eyes?) I had a waiting list.
As far as the concern over "what you have to pay for"... standard rates for music lessons are $50/hr. Better teachers cost more. I've had a few lessons from some top tier musicians that have cost $175 an hour. Just want to make sure you're informed about pricing here. Being a musician is expensive as hell. And music teachers deserve to get paid that much.
I am a little bit bothered about your question conceptually. If you're asking this it sounds like you haven't actually taken lessons before. Which means that you could probably get a teacher at a local/community college to teach you and that would be more than sufficient. Hell, you could find a middle school band director that could do the job. Just so you know, I started teaching when I was 14 years old.
Comment: You'd really find it offensive if a potential student asked you to play for him? He is going to invest a lot of money in your lessons. Doesn't he have the right to see if (he believes) it is worth it?
Comment: I don't think the questioner was interested in the rates, and it may not be appropriate here as we don't even know what country he or she is in. You are right to mention what level the questioner is at though; I think an ambitious and experienced player might be concerned to learn more from a major performer, but a total beginner just needs much more basic instruction initially.
Comment: ... for a 1 hour lesson when it requires the teacher to drive 15-30 minutes each way. There are a lot of hidden costs for private teachers and music teachers in general and it simply is not fair to pay them below minimum wage because you don't think it's worth it.
Comment: @Shevliaskovic - with your comment we're back to is it a teacher or performer we're looking at.
Comment: @shevliaskovic yes he has the right to find out if the teacher is worth it, but to me asking in this way is akin to the "parlour trick" mentality that a lot of people have towards musicians in general. You wouldn't ask someone applying to be a doctor or a paralegal to come in and work for you for free - why would you do that to a musician? He seems concerned about spending money on a teacher that isn't worth it, which is why I explained the rates. I have run into a ton of people who have no idea about the rates and get sticker shock, but it seems unreasonable to me to pay a teacher  $20...
Answer: Don't equate their ability level with their teaching ability.  Obviously they should have a basic level of musicianship, and be able to demonstrate what the student should be able to do.  Beyond that it's all about how well they teach and the relationship between student and teacher.  I can imagine that a student could learn a tremendous amount from a gifted teacher who knows nothing about the student's instrument but knows how to motivate musicians and teach them to be expressive.  And I can imagine that a virtuoso on their instrument might be a rotten teacher or just a poor match for their personality.
The most important thing I've learned as a teacher is that I can't be better than all my students at everything (I teach chorus, general music, band, and orchestra - among other things - at a public school).  I am absolutely up-front with them, especially those who play an instrument that is NOT my primary focus as a musician, that I will tell them when they have exceeded my own ability level.  At that point I encourage them to seek a more specialized teacher to take them where they want to go.  But they still come to lessons with me.  Partly because they're free, and partly because even though I can play helpless little on viola (e.g.) I can help them with rhythm, I can help them be a part of an ensemble, etc.
I think they relate well to me as a fellow human when I'm honest and not trying to be master of all trades.  If they ask about my primary focus, I direct them to a page featuring my compositions.


Regression with MI of missing values: estimating residuals

Question: Imagine I want to regress y on x1, ..., xk. I have missing values in the dependent variable, as well as in some of the independent variables, and have used multiple imputation to create D imputed datasets.
So I run the regression using each of the datasets, combine the estimated parameters and standard errors using Rubin's rules, etc. I can also obtain predicted values of y.
My question is: can I obtain predicted residuals? I would have thought that since I can predict yhat, it would be acceptable to use yhat to predict residuals ... particularly for observations without missing values of y, but also when there D imputed values of y, just by averaging them first.
However, the Stata manual states that this is not appropriate:
"The MI predictions should be treated as a final result; they should not be used as intermediate results in computations. For example, MI estimates of the linear predictor cannot be used to compute residuals as is done in non-MI analysis. Instead, completed-data residuals should be calculated for each imputed dataset ... "
Is there any reason why I should not calculate residuals in the way I described, or by predicting separate residuals for each imputed dataset, and then averaging those? Thanks.
http://www.stata.com/manuals13/mimipredict.pdf
Answer: I'm not exactly sure why Stata says this. However, one thing to consider is that most properly, each predicted yhat is an estimate - it's the mean yhat from each imputation. Moreover, you have some cases with missing y - what is your residual in this case? It's not clear. I suspect that may be the main problem. Any interpretation about the residuals you make in that case may be biased, because you're excluding the people with missing Ys.
If you're trying to perform regression diagnostics, some guidance I've seen is that you want to examine plots for a few of your imputed datasets.
As an aside, if you have some observations with a missing dependent variable, why are you using those observations at all? In my field (outcomes research in healthcare, e.g. randomized trials of drugs), the advice we get is usually to drop them. If they are missing on the DV, then nothing can help you. The guys who set up the experiment or data collection needed to minimize missing data in the first place. One exception is when your DV is a multi-item scale, and some people have one or missing items in the scale; here, it's often quite reasonable to impute the missing items, then calculate the scale (but if you have a lot of people missing the entire scale, or many people miss the same item, or many people miss a number of items, then you have to ask what happened).


Disable converting WebVTT-content into lowercase (video.js)

Question: I'm using video.js for subtitles and chapters but in the player the labels are converted into lowercase while in the .vtt-files and html-tags it's written different.
For example in the track-element I wrote
<code><track src="vtt/1Startseite.vtt" kind="subtitles" srclang="de" label="Deutsch" default>
</code>
but in the player the label is written "deutsch".
(same for the whole chapter labels)
How can I prevent video.js from doing this?
Thanks in advance,
Marco.
Answer: Fixed it,
it's in the video-js.css:
<code>.vjs-default-skin .vjs-menu-button ul li { ... text-transform: lowercase;}
</code>
so just setting in to
<code>.vjs-default-skin .vjs-menu-button ul li { ... text-transform: none;}
</code>
will fix it, same for chapter titles.
Got an answer on Github, where it's called a "just a style thing", see here: https://github.com/videojs/video.js/issues/1636


Induction Proof and real analysis

Question: Can someone please solve the following. I'm not good at proofs by induction. I know the base case but I don't know how to solve it after that for $(N+1)$
Let $a_1, a_2, · · · , a_n ∈ R,,$ where n is a positive integer greater than or equal to 2. Use
induction to prove that
$|a_1 + a_2 + · · · + a_n| ≤ |a_1| + |a_2| + · · · + |a_n|$.
Comment: Does this answer your question? [General Proof for the triangle inequality](https://math.stackexchange.com/questions/195582/general-proof-for-the-triangle-inequality)
Comment: https://math.stackexchange.com/questions/3825060/prove-that-for-every-n-in-mathbbn-and-for-all-real-numbers-x-1-x-2-x-n
Answer: Step $1$:
You can prove step $1$
for $n=2$
$|a_1 + a_2| ≤ |a_1| + |a_2|$.
Step $2$:
Assume that it is true for $n=k$
$|a_1 + a_2 + · · · + a_k| ≤ |a_1| + |a_2| + · · · + |a_k|$.
for $n=k+1$
$|a_1 + a_2 + · · · + a_k+a_{k+1}| ≤ |a_1 + a_2 + · · · + a_k|+|a_{k+1}| ≤  |a_1| + |a_2| + · · · + |a_k|+|a_{k+1}|$.

Induction Proof and real analysis


When I plot 2 columns one over the other, a different graph is plotted

Question: I have 2 columns from 2 np.arrays of the same size. When I plot the only the one I get this result:
plt.figure(figsize=(70,10))

for i,h in enumerate(clean_head):

    plt.subplot(1,6,i+1)
    #plt.hist(non_fire[:,i],alpha=.3)
    plt.hist(fire[:,i],alpha=.3)
    plt.title(clean_head[i])

   # plt.tight_layout()

When I plot both I get this:
plt.figure(figsize=(70,10))

for i,h in enumerate(clean_head):

    plt.subplot(1,6,i+1)
    plt.hist(non_fire[:,i],alpha=.3)
    plt.hist(fire[:,i],alpha=.3)
    plt.title(clean_head[i])

   # plt.tight_layout()

Where no one of the two histograms is the same with the initial. I dont understand which is the pink and which is the lightblue graph.
I have 16 more plots like that and I have the same problem with all of them.
Answer: in the second set of plots the blue histogram is for the "non-fire"-case and the orange one is for the "fire"-case. If you would plot a third histogram, it would be green. In general you can change the color of a given histogram using the parameter color.
The reason why your histograms change is that your arrays have different value ranges. You can fix this by explicitly giving bins the the function:
import matplotlib.pyplot as plt
import numpy as np

a = np.random.rand(100)
b = np.random.rand(100)*2

bins = np.linspace(min(np.min(a), np.min(b)), max(np.max(a), np.max(b)), 10)

plt.figure(figsize=(7,5))
plt.hist(a,alpha=.3, bins=bins)
#plt.hist(b,alpha=.3, bins=bins) #toggle this to see the effect

Also note that histogram function returns the list of bins that it uses.
Hope that helps.
Comment: this is really helpful thank you very much. trying to implement the bins assignment to my case I write:      bins = np.linspace(min(np.min(non_fire[:,i]), np.min(fire[:,i])), max(np.max(non_fire[:,i]), np.max(fire[:,i])), 10) but iget this error: TypeError: cannot perform reduce with flexible type
Comment: What structures are your fire and non-fire objects (e.g. numpy array) and which datatype to the values have?


Pass PHP variable with GET to another PHP page

Question: There's probably something pretty easy here that I'm missing but I can't seem to figure it out.
I'm trying to pass a PHP variable "$session" from one PHP page to another PHP page using GET. The GET shows in the new URL but the value is not passed to the page so that I can retrieve it. Below is the relevant code.
On the main Index.php page.

       <?php echo "Click here for full size Google Earth	"; ?>

The "$session" variable is passed to 3D-Earth.php using GET and the correct value shows in the URL. However, when I try to retrieve the variable with:
<?php
  $session = $_GET["session"];
?>

and then try to create a javascript variable:

that I will use to concatenate the below string:
var href = 'http://localhost/satellites/' + session + '/master.kml';

nothing is being passed.
I appreciate any help anyone can provide. Thanks in advance.
Additionally, I've inserted the below code at the bottom of my 3D-Earth.php page to verify that the GET is being passed.

Hello " <?php echo $session; ?> " world!

The result is an empty string that shows: Hello " " World! Anyone know what I might be doing wrong?
Comment: Why on earth people need to be down-voting this question. People might have different knowledge, please
Answer: Try like this:
var session = '<?php echo $session; ?>';

Comment: I tried that and hopefully it will work when I eventually get the "$session" variable to recognize on the page. Right now it's still not working because my GET is wrong somewhere. Thanks for the help.
Answer: I suggest stop using names like 'session' that might conflict with php reserved words. Maybe that's not the issue here, but avoids many other problems and confusions.
Also in javascript put the echo in quotes:
    var session = '<?php echo $session; ?>';

Comment: Yeah, I thought of that and actually changed the name but when it didn't work I changed it back. I'll fix it just for clarity. Thanks.
Comment: also instead of trying to debug in the javascript, do this in PHP. do an echo there to make sure that the variable is ok and then see why js is not working.
Comment: Yeah, I added some additional code above to show what I'm trying to do to verify that the variable is passed. So far, no luck.
Comment: can you show the complete URL of the second php file?
Comment: Sorry about the delay but I haven't been on in a couple of days. Here is the URL that shows when I select the Google Earth page. http://localhost/satellites/web_access/3D-Earth.php?session=19572  The 5 digit number is generated randomly to hold the session data and matches the folder that it creates when I generate the KML.
Comment: your URL seems correct and should work with $_GET. maybe you have some redirects on the webserver that changes it?
Comment: Do you have any idea how I could change that? What configuration file?
Comment: in the root of the localhost there is usually an .htaccess file. If you have one, maybe thats the problem. you can try to remove it and see what happens.
Comment: No luck. I found a number of .htaccess files in the phpmyadmin folder as well as the apache folder but removing them didn't seem to do anything.
Comment: well, put them back in now :) so I don't know what's wrong. if you can put a live version on the web, I may be able to assist.
Answer: You should put a single quotes around your variable like this
var session = '<?php echo $session; ?>';

Answer: As above answers say, you have to have single quotes around a php statement when you want to use it in javascript. So var session = 'php statement'; is the right way to go.
Answer: have you tried to put this code

under this code ??
 <?php
  $session = $_GET["session"];
 ?>

Comment: Yeah, that's the way I have it with the CSS style section inbetween.


Attempt to invoke virtual method 'void com.facebook.marketing.ViewIndexer.unschedule()' on a null object reference

Question: I am getting this kind of error since I am using Facebook Account Kit I don't know how to deal with it Please help me, guys.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: in.co.ashclan.thunder, PID: 29664
                  java.lang.RuntimeException: Unable to pause activity {in.co.ashclan.thunder/in.co.ashclan.thunder.ActivitySplash}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.marketing.ViewIndexer.unschedule()' on a null object reference
                      at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3830)
                      at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3796)
                      at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3770)
                      at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3741)
                      at android.app.ActivityThread.-wrap16(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1538)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:163)
                      at android.app.ActivityThread.main(ActivityThread.java:6239)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.marketing.ViewIndexer.unschedule()' on a null object reference
                      at com.facebook.marketing.CodelessActivityLifecycleTracker$1.onActivityPaused(CodelessActivityLifecycleTracker.java:129)
                      at android.app.Application.dispatchActivityPaused(Application.java:229)
                      at android.app.Activity.onPause(Activity.java:1654)
                      at android.support.v4.app.FragmentActivity.onPause(FragmentActivity.java:441)
                      at android.app.Activity.performPause(Activity.java:7024)
                      at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
                      at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3819)
                      at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3796)
                      at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3770)
                      at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3741)
                      at android.app.ActivityThread.-wrap16(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1538)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:163)
                      at android.app.ActivityThread.main(ActivityThread.java:6239)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
V/FA: Activity paused, time: 966233817
Here is my code
<code>public class ParticipantsLogin extends AppCompatActivity implements View.OnClickListener{

FButton btn_facebook,btn_Gmail,btn_submit;
FirebaseDatabase database;
DatabaseReference table_participant ;
FirebaseStorage storage;
Context mContext;
DatabaseReference table_user;

//Get GMail Data from login Account
public String personName,personFirstName,personLastName,personEmail,personId;
Uri personPhoto ;

//Root Layout
LinearLayout linearLayout;

//Participant Pojo
ParticipantModel participantModel;

//FireBase to Facebook
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "GoogleSignIn";

//FireBase to Google
private FirebaseAuth mAuth;
GoogleSignInClient mGoogleSignInClient;
public static final int REQUEST_CODE = 7171;

MaterialEditText edtUserName,edtPassword;
String phone,pass;

//Alert Dialog View
MaterialEditText edtMobileNo;
RadioButton rd_male,rd_female;

//Upload Images
Uri saveuri;
StorageReference storageReference ;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    FacebookSdk.sdkInitialize(getApplicationContext());
    AccountKit.initialize(this);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_participants_login);
    mInit();
    btn_Gmail.setOnClickListener(this);
    btn_facebook.setOnClickListener(this);
    btn_submit.setOnClickListener(this);

    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}

//Initialisation
private void mInit()
{
    mContext = ParticipantsLogin.this;
    btn_facebook = (FButton)findViewById(R.id.btn_facebook);
    btn_Gmail = (FButton)findViewById(R.id.btn_Gmail);

    //InIt FireBase
    database = FirebaseDatabase.getInstance();
    table_participant = database.getReference("Participant"); //Linked to Participant table
    mAuth = FirebaseAuth.getInstance();
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();

    //Init ROOT LAYOUT
    linearLayout = (LinearLayout)findViewById(R.id.root_layout);
    participantModel = new ParticipantModel();

    //Submit Button
    btn_submit = (FButton)findViewById(R.id.btn_submit);
    edtUserName = (MaterialEditText)findViewById(R.id.edt_User_id);
    edtPassword = (MaterialEditText)findViewById(R.id.edt_User_password);
}
//OnclickListner
@Override
public void onClick(View view)
{
    switch (view.getId())
    {
        case R.id.btn_facebook:
            startFacebookLogin();
            break;
        case R.id.btn_Gmail:
            startGmailLogin();
            break;
        case R.id.btn_submit:
                    //Save username and password
                        phone = edtUserName.getText().toString();
                        pass = edtPassword.getText().toString();

                        if(edtUserName.getText().length()==0)
                        {
                            edtUserName.setError("Please Enter Your Mobile No");
                        } else if (edtPassword.getText().length()==0) {
                            edtPassword.setError("Please enter correct password");
                        }else {
                            login(phone, pass);
                        }
               break;
            }
    }
//Methods
private void startFacebookLogin()
{
    Intent intent = new Intent(ParticipantsLogin.this, AccountKitActivity.class);
    AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
            new AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
                    AccountKitActivity.ResponseType.TOKEN);
    intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,configurationBuilder.build());
    startActivityForResult(intent,REQUEST_CODE);
}
private void startGmailLogin()
{
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    try{
        //Activity result set for facebook login
        if(requestCode==REQUEST_CODE)
        {
            AccountKitLoginResult result = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
            if(result.getError()!=null)
            {
                Toast.makeText(this, ""+result.getError().getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }else if(result.wasCancelled())
            {
                Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
                return;
            }
            else
            {
                if(result.getAccessToken() != null)
                {
                    //Show Dialog
                    final AlertDialog watingDialog = new SpotsDialog(this);
                    watingDialog.show();
                    watingDialog.setMessage("Please Wait");
                    watingDialog.setCancelable(false);
                    //get Current Phone
                    AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
                        @Override
                        public void onSuccess(Account account) {
                            String phone  = account.getPhoneNumber().toString();
                            final String userphone = phone.substring(3);
                            Log.e("fbno-->",userphone);

                            //Check if User Exist on Firebase if not then add it
                            table_participant.orderByKey().equalTo(userphone)
                                    .addListenerForSingleValueEvent(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {

                                            if(!dataSnapshot.child(userphone).exists())//if User not Exist
                                            {
                                                Intent intent = new Intent(ParticipantsLogin.this,RegistrationActivity.class);
                                                intent.putExtra("mobilno",userphone);
                                                startActivity(intent);
                                                watingDialog.dismiss();
                                                finish();

                                            }else //if User Exist
                                            {
                                                startActivity(new Intent(ParticipantsLogin.this, Activity_DashBoard2.class));
                                            }
                                        }
                                        @Override
                                        public void onCancelled(DatabaseError databaseError) {
                                        }
                                    });
                        }
                        @Override
                        public void onError(AccountKitError accountKitError) {
                            Toast.makeText(ParticipantsLogin.this, ""+accountKitError.getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }
    }catch (Exception e)
    {
        Log.e("-->FbError",e.toString());
    }

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);

    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // ...
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct)
{
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    //Show Dialog
    final AlertDialog watingDialog = new SpotsDialog(this);
    watingDialog.show();
    watingDialog.setMessage("Please Wait");
    watingDialog.setCancelable(false);

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        //showFireBaseDialog();
                        watingDialog.dismiss();
                        //If user is not registred then register it
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                       // Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                        updateUI(null);
                    }
                }
            });
}
//User Login
private void login(final String phone, final String pass)
{
    try
    {
        Log.d("-->",phone +" "+pass);

        if (util.isConnectedToInterNet(getBaseContext())) {

            final ProgressDialog mDialog = new ProgressDialog(ParticipantsLogin.this);
            mDialog.setMessage("Please Wait.....");
            mDialog.setCancelable(false);
            mDialog.show();

            table_participant.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Check if User doesnt exist in database
                    if (dataSnapshot.child(phone).exists()) {
                        //mDialog.dismiss();
                        //get User Values
                        Log.d("-->123",dataSnapshot.toString());
                        ParticipantModel user = dataSnapshot.child(phone).getValue(ParticipantModel.class);
                            user.setMobile(phone);
                            Log.d("PoJo-->",user.toString());
                            if (user.getFirstname().equals(pass)) {
                                Toast.makeText(getApplicationContext(),"Successful",Toast.LENGTH_LONG).show();

                                startActivity(new Intent(mContext,Activity_DashBoard2.class));
                                PreferenceUtil.setSignIn(mContext,true);
                                PreferenceUtil.setMobileNo(mContext,phone);
                                PreferenceUtil.setPass(mContext,pass);

                            mDialog.dismiss();
                            finish();
                        } else {
                            mDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "Wrong Password", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        mDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "User Doesnt Exist", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        } else {
            Toast.makeText(ParticipantsLogin.this, "Please Check Your Internet Connection!", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
    {
        Log.e("-->",e.toString());
        Toast.makeText(mContext, "Something went Wrong!", Toast.LENGTH_SHORT).show();
    }
}
private void updateUI(FirebaseUser user)
{
    if (user != null) {
        // User is signed in
        GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        if (acct != null) {
            personName = acct.getDisplayName();
            personFirstName = acct.getGivenName();
            personLastName = acct.getFamilyName();
            personEmail = acct.getEmail();
            personId = acct.getId();
            personPhoto = acct.getPhotoUrl();

       /*     Toast.makeText(ParticipantsLogin.this, "" + personName + "\n" +
                    personFirstName + "\n" +
                    personLastName + "\n" +
                    personEmail + "\n", Toast.LENGTH_LONG).show();*/
            PreferenceUtil.setSignIn(ParticipantsLogin.this,true);
        } else {
            // No user is signed in
        }
        //Show Dialog
        android.support.v7.app.AlertDialog.Builder alertDialog = new android.support.v7.app.AlertDialog.Builder(ParticipantsLogin.this);
        alertDialog.setTitle("One More Step... ");
        alertDialog.setMessage("Please Enter Your Registred Mobile");

        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.custom_mobileno_dialog, null);

        edtMobileNo = (MaterialEditText) view.findViewById(R.id.edt_gm_MobileNo);

        alertDialog.setView(view);
        alertDialog.setIcon(R.drawable.ic_person);

        //Set Buttons
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String phone = edtMobileNo.getText().toString();
                final AlertDialog watingDialog = new SpotsDialog(ParticipantsLogin.this);
                watingDialog.show();
                watingDialog.setMessage("Please Wait");
                watingDialog.setCancelable(false);

                //Check if User Exist on Firebase if not then add it
                table_participant.orderByKey().equalTo(phone)
                        .addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                if (!dataSnapshot.child(phone).exists())//if User not Exist
                                {
                                    Intent intent = new Intent(ParticipantsLogin.this, RegistrationActivity.class);
                                    intent.putExtra("email", personEmail);
                                    intent.putExtra("firstname", personFirstName);
                                    intent.putExtra("lastname", personLastName);
                                    intent.putExtra("mobilno", phone);

                                    PreferenceUtil.setMobileNo(mContext,phone);
                                    PreferenceUtil.setEmailid(mContext,personEmail);
                                    PreferenceUtil.setLastname(mContext,personLastName);
                                    PreferenceUtil.setFirstname(mContext,personFirstName);
                                    PreferenceUtil.setPass(mContext,personFirstName);

                                    startActivity(intent);
                                    watingDialog.dismiss();
                                    finish();

                                } else//if User Exist
                                {
                                    table_participant.child(phone)
                                            .addListenerForSingleValueEvent(new ValueEventListener() {
                                                @Override
                                                public void onDataChange(DataSnapshot dataSnapshot) {
                                                    ParticipantModel localUser = dataSnapshot.getValue(ParticipantModel.class);
                                                    startActivity(new Intent(ParticipantsLogin.this, Activity_DashBoard2.class));
                                                    util.currentParticipant = localUser;

                                                    PreferenceUtil.setMobileNo(mContext,phone);
                                                    PreferenceUtil.setEmailid(mContext,personEmail);
                                                    PreferenceUtil.setLastname(mContext,personLastName);
                                                    PreferenceUtil.setFirstname(mContext,personFirstName);
                                                    PreferenceUtil.setPass(mContext,personFirstName);

                                                    watingDialog.dismiss();
                                                    finish();
                                                }

                                                @Override
                                                public void onCancelled(DatabaseError databaseError) {
                                                }
                                            });
                                }
                            }
                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                            }
                        });
            }
        });
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alertDialog.show();
    }
}
//Check User VAlidataions
public boolean utilsCheck()
{
    boolean cancel = false;
    View focusView = null;
    if (TextUtils.isEmpty(edtUserName.getText())){
        edtUserName.setError("Please enter first Name");
        focusView=edtUserName;
        cancel=true;
    }
    if (TextUtils.isEmpty(edtPassword.getText())){
        edtPassword.setError("Please enter Password");
        focusView=edtPassword;
        cancel=true;
    }
    return cancel;
}
</code>
}
public class SplashScreen extends AppCompatActivity {
<code>Context mcontext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);

   try {
       if (PreferenceUtil.getSignIn(this)) {
           final Handler handler = new Handler();
           handler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   Intent intent = new Intent(SplashScreen.this, Activity_DashBoard2.class);
                   startActivity(intent);
                   finish();

               }
           }, 7000);
       } else {
           final Handler handler = new Handler();
           handler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   Intent intent = new Intent(SplashScreen.this, ParticipantsLogin.class);
                   startActivity(intent);
                   finish();
               }
           }, 7000);
       }

   }catch (Exception e)
   {
       Log.e("-->splashexp",e.toString());
   }
}

private void login(final String phone, final String pass) {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference table_user = database.getReference("Participant");

    Log.d("-->",phone +" "+pass);

    if (util.isConnectedToInterNet(getBaseContext())) {

        final ProgressDialog mDialog = new ProgressDialog(mcontext);
        mDialog.setMessage("Please Wait.....");
        mDialog.show();

        table_user.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //Check if User doesnt exist in database
                if (dataSnapshot.child(phone).exists()) {
                    //mDialog.dismiss();
                    //get User Values
                    Log.d("-->123",dataSnapshot.toString());
                    ParticipantModel user = dataSnapshot.child(phone).getValue(ParticipantModel.class);
                    user.setMobile(phone);
                    Log.d("PoJo-->",user.toString());
                    if (user.getFirstname().equals(pass)) {
                        //Toast.makeText(getApplicationContext(),"Successful",Toast.LENGTH_LONG).show();
                        startActivity(new Intent(mcontext, DashBoard.class));
                        util.currentParticipant = user;
                        finish();
                    } else {
                        mDialog.dismiss();
                        Toast.makeText(getApplicationContext(), "Wrong Password", Toast.LENGTH_LONG).show();
                    }
                } else {
                    mDialog.dismiss();
                    Toast.makeText(getApplicationContext(), "User Doesnt Exist", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    } else {
        Toast.makeText(mcontext, "Please Check Your Internet Connection!", Toast.LENGTH_SHORT).show();
    }

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}
</code>
}
Comment: Post your code.
Comment: please give me solution as soon as possible
Comment: please provide some solution if you have any
Comment: I think the error is in Splash activity. Can u post the code for that too.
Answer: Upgrading <code>facebook-android-sdk</code> did the trick for me:
<code>implementation com.facebook.android:facebook-android:5.1.1
</code>
Also I discourage people from using wildcard format such as
<code>implementation com.facebook.android:facebook-android-sdk:[4:5)
</code>
despite facebook recommending it on their website, since it can lead to the unpredictable builds if the latest version of the library changes and breaks something.
Answer: I'd encountered the same problem on Splash,I was using latest fb sdk i.e.

implementation 'com.facebook.android:facebook-android-sdk:4.34.0'

I changed it to

implementation 'com.facebook.android:facebook-login:[4,5)'

This solved the problem in my case.
Answer: You must change marketing in fbsdk.
implementation <code>com.facebook.android:facebook-android-sdk:4.34.0</code>
change to:
implementation <code>com.facebook.android:facebook-android-sdk:[4:5)</code>
It will auto change <code>com.facebook.marketing</code>.


Is it possible to make apache print http parameters in access log?

Question: Apache prints the request to access log. The line will tell you which page is access, say test.php but is it possible to ask it to log the HTTP post parameters as well? Ideally, a specific parameter?
Answer: Yes, it's possible.  I found several references to various methods, depending on whether you want just a set of parameters or a full data dump of POSTed data.

Use mod_dumpio.  This can dump all input and output (separately, if desired) the server receives.  (The same post suggests mod_security but doesn't detail a configuration.)
Use mod_log_post (download).  Apparently it's a stripped-down cousin of mod_security.  See this somewhat related ServerFault question.
Don't; instead, log inputs from your script directly.  (This is due to security concerns -- a malicious attacker could flood your server with POST requests and fill up the logfile partition.)
Comment: + for last point.
Answer: Not by default not with the mod_log_config module as far as I know.
You might want to check these instructions using the mod_dumpio module.


Android Biometric Security API

Question: I have a great idea for a biometric security app and some secure transactions, but i have no idea how to use a biometric api, if it exists. Anyone knows anything about any biometric api? Any ideas how to develop one?
I would appreciate any kind of help or information. Thanks a lot.
Answer: What kind of biometrics? OpenCV can help you do this using the camera...
http://opencv.org/android
Comment: I want to use biometrics in my app like face recognition using the camera to make secure transactions.

Have you worked with OpenCV before? I'm new in this, and i have no much experience in Android.

Thanks for the reply, it was very helpful.
Comment: @brachialste: sorry, have not used OpenCV for biometrics, and never used it on Android either.
Answer: OpenCV is a good tool to make facial recognition. You can use it to communicate with embedded cameras, detect faces, and compare two faces. But if you need a better SDK you can use Neurotechnology or a free webservice supplied by SkyBiometrics
My advice is if you don`t have much time to work with OpenCV and improve it algorithms / study it to use correctly, you can use SkyBiometrics that have a free usage and could work fine with your application if you have internet access.
Answer: I personally don't have experience working with a biometric API for Android. From what I've read and heard from developers, OpenCV seems like something you should opt for, especially since you don't have experience of it either.
This information might be of help if you want to use the fingerprint ID feature of the phone:
Android fingerprint API launched with Android 6.0 will offer a bevy of useful features to integrate new authentication technology for app developers with the apps. To implement this API in your new Android app you need to get the Android SDK first. The SDK Manager then will allow you to download the SDK platform for Android 6.0 and introduce necessary steps. As part of the launching process, Android has also come up with new sample to demonstrate and guide the developers in integrating the API with the fingerprint readers in various devices.
Beating the so called security concerns over the use of fingerprint technology in mobile transaction Android has revealed how the new API offers protective measures for maintaining privacy. The new API as revealed will protect the critical fingerprint features by keeping them in the secure device hardware.
Android also expressed future plans to come with measures that can help identifying fingerprint of users just before allowing access to critical resources and data. These identification measures would help protecting against all malicious intrusions and tampered applications by ensuring cryptographic level security for all types of transactions and access to offline data and online interactions. This hardware level protection of critical data offers full proof protection against all malicious actions and security threats making it safe for the users to use their fingerprints.
Source:
Android Fingerprint API for App Developers
Comment: Hi, welcome to SO. You shouldn't base your answer on a link: if it changes or the site goes offline, your answer becomes useless. Instead, use the info on the site to build your answer and post the link as reference only. Thanks.

Android Biometric Security API


administer MSSQL databases from Drupal 6

Question: Can you advise on a way to manage my SQL Server databases from Drupal 6x. I am using SQL Server for PHP driver (i.e. sqlsrv_connect()) to connect to my databases. Is there any module I could use to administer my databases?
If any more information about my query is needed, please let me know.
Answer: There is no support for MSSQL Server in Drupal 6, so it is higly unlikely that a module that can help you to administer your MSSQL databases exists.
You could maybe write your own, see MSSql or SQL Server Wrapper for custom module? for a possible way to connect to your database while still being able to rely on some API's provided by Drupal.
Comment: Thank you Berdir for your quick response! I shall look into what you mentioned... Cheers
Answer: I am also connecting to sql server from drupal, and here is what I've learned on my blog http://www.barnettech.com/taxonomy/term/28  It describes what to install on the linux box to run queries and stored procs.  You need to create custom modules to make calls to sql server from within Drupal.  In my case I made my own services to add on to the services module.
Comment: Thank you for the advice user1246! I shall look into what you suggested


How to count the number of posts by a author?

Question: I have created a view with table settings. I would like to display the name of the author and the total number of posts that he has created. I have used relations to get the author name but I don't see any fields related to count the number of posts.
Any suggestions?
Comment: See very similar question (with answer that goes through Views aggregation steps) at [User list view showing total nodes created for each user](http://drupal.stackexchange.com/questions/34204/user-list-view-showing-total-nodes-created-for-each-user)
Answer: If you are using D7 I think you will have to enable aggregation for you view, and then set the group by for you field (Content:nid for example) to Count.
Comment: Thanks for your reply krister. May i know how to enable aggregation? the only thing i can see in my modules page is a aggregator.
Comment: Under /admin/structure/views/view/your_view you click the `Advanced` tab at the top-right and the you'll find `Use Aggregation` under `Others`.
Comment: thanks a lot!!! you have finally solved my 4 hrs battle:):) thank u so much.
Comment: FYI: [Count of nodes by type](http://drupal.stackexchange.com/a/15875/226) is a very similar question, and I posted a step-by-step instruction for Views with aggregation, as well as an export of such a view.
Comment: Wow amazing work marcvangend!!! thanks a lot for such a usefull explaination. Finally i got every thing working:)
Answer: Which version of Views/Drupal are you using?
The User Stats module may work for what you need.
Comment: I tried this module. But i don know how to use this in views.


Virtualmin and phpmyadmin - You don't have permission to access /phpmyadmin/ on this server

Question: I can`t reach phpmyadmin. I tried all ways what I found in google. Maybe someone can help me? Thanks for any answer.
Forbidden

You don't have permission to access /phpmyadmin on this server.

I use CentOS 5 with virtualmin.
phpMyAdmin.conf
# phpMyAdmin - Web based MySQL browser written in php
#
# Allows only localhost by default
#
# But allowing phpMyAdmin to anyone other than localhost should be considered
# dangerous unless properly secured by SSL

Alias /phpMyAdmin /usr/share/phpMyAdmin
Alias /phpmyadmin /usr/share/phpMyAdmin
<Directory /usr/share/phpMyAdmin/>
   #order deny,allow
   #deny from all
   allow from 127.0.0.1
   allow from ::1
</Directory>

# This directory does not require access over HTTP - taken from the original
# phpMyAdmin upstream tarball
#
<Directory /usr/share/phpMyAdmin/libraries>
    Order Deny,Allow
    Deny from All
    Allow from None
</Directory>

# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc.  This may break your mod_security implementation.
#
#<IfModule mod_security.c>
#    <Directory /usr/share/phpMyAdmin>
#        SecRuleInheritance Off
#    </Directory>
#</IfModule>

config.inc.php
...
$cfg['Servers'][$i]['auth_type']     = 'http';      // Authentication method (config, http or cookie based)
...

Answer: You are not accessing the phpmyadmin from the 127.0.0.1 or ::1 addresses.
You need to find out what address you are accessing phpmyadmin from and add it to the list of allowed addresses. This will most likely be the public ip address of your server.
e.g. if your public ip address is 192.168.1.54 then you would add it to your
 configuration
<Directory /usr/share/phpMyAdmin/>
   #order deny,allow
   #deny from all
   allow from 192.168.1.54
   allow from 127.0.0.1
   allow from ::1
</Directory>


How can filter a view by several NID's?

Question: I try to filter a node by the criteria of NID. Naturally I can filter by a single NID, but in this case I need to to filter by multiple NIDs.
I tried to wrote the following number values and non worked:
1, 20, 31
1+20+31
How should I write the number values so that it would work?
Thanks.
Answer: You will need to add contextual filters in the view.

Just go to advanced -> contextual filter -> add new 'content:nid'
field.
Check 'profile default value' option from list entitled 'WHEN THE FILTER VALUE IS NOT AVAILABLE' -> Choose 'Fixed value' option and add multiple nids seperating them via '+' e.g. 1+2+3
Then from 'more' fieldset check on 'allow multiple values' option.

This should do it. You can check also in sql query generated by view below it which should show something like this in where clause e.g. WHERE (( (node.nid IN('1', '2', '3') ) )
Comment: Ah! This was getting really annoying! Didnt see the hidden "multiple" option. Thanks!
Comment: Did you use Seven as your admin theme at the time @Collins ? I love this theme very much for admin but I think it has some small css probs regarding to this (and maybe some other dialogues) in Views... I hope In Drupal 8 these problems will be no longer; Given that Drupal 8 went through a Mobile-first responsivness process, I'm optimistic :)
Comment: Works great until you go past the maxlength of 128 characters - which is all the more easy when your NIDs are higher...

How can filter a view by several NID's?


Postgresql Index Only Scan Doesnt Properly Work On Group By

Question: I have a table like:
CREATE TABLE summary
(
    id serial NOT NULL,
    user_id bigint NOT NULL,
    country character varying(5),
    product_id bigint NOT NULL,
    category_id bigint NOT NULL,
    text_id bigint NOT NULL,
    text character varying(255),
    product_type integer NOT NULL,
    event_name character varying(255),
    report_date date NOT NULL,
    currency character varying(5),
    revenue double precision,
    last_event_time timestamp
);

My table size is 1786 MB (except index). In here, I've created index like below:
CREATE INDEX "idx_as_type_usr_productId_eventTime"
    ON summary USING btree
    (product_type, user_id, product_id, last_event_time)
    INCLUDE(event_name);

And my simple query looks like below:
select
   event_name,
   max(last_event_time)
from summary s
where s.user_id = ? and s.product_id = ? and s.product_type = ?
   and s.last_event_time > '2020-03-01' and s.last_event_time < '2020-03-25'
group by event_name;

When I explain it, it looks like;
HashAggregate  (cost=93.82..96.41 rows=259 width=25) (actual time=9187.533..9187.536 rows=10 loops=1)
  Group Key: event_name
  Buffers: shared hit=70898 read=10579 dirtied=22650
  I/O Timings: read=3876.367
  ->  Index Only Scan using "idx_as_type_usr_productId_eventTime" on summary s  (cost=0.56..92.36 rows=292 width=25) (actual time=0.485..9153.812 rows=87322 loops=1)
        Index Cond: ((product_type = 2) AND (product_id = ?) AND (product_id = ?) AND (last_event_time > '2020-03-01 00:00:00'::timestamp without time zone) AND (last_event_time < '2020-03-25 00:00:00'::timestamp without time zone))
        Heap Fetches: 35967
        Buffers: shared hit=70898 read=10579 dirtied=22650
        I/O Timings: read=3876.367
Planning Time: 0.452 ms
Execution Time: 9187.583 ms

In here, everything looks fine. But when I execute it, it takes more than 10 seconds, sometime it takes more than 30 seconds.

In here, if I execute it without Group By, it returns so quickly like less than 2 seconds. What can be the effect of Group By? The select part is so little (like a 500 rows).
This table has insert/update operations with 30/per second. Can this be related with this indexing problem?

Updated:
Query Without - GroupBy:
select
   event_name,
   last_event_time
from summary s
where s.user_id = ? and s.product_id = ? and s.product_type = ?
   and s.last_event_time > '2020-03-01' and s.last_event_time < '2020-03-25';

Explain Without - Group By:
Index Only Scan using "idx_as_type_usr_productId_eventTime" on summary s  (cost=0.56..92.36 rows=292 width=25) (actual time=0.023..79.138 rows=87305 loops=1)
  Index Cond: ((product_type = ?) AND (user_id = ?) AND (product_id = ?) AND (last_event_time > '2020-03-01 00:00:00'::timestamp without time zone) AND (last_event_time < '2020-03-25 00:00:00'::timestamp without time zone))
  Heap Fetches: 22949
  Buffers: shared hit=37780 read=12143 dirtied=15156
  I/O Timings: read=4418.930
Planning Time: 0.639 ms
Execution Time: 4625.213 ms

Comment: Please show the EXPLAIN (ANALYZE, BUFFERS), and in text format.  JSON format is nice for machines to read, but we are not machines.  And better yet, turn track_io_timing on first if it is not already.  And please do the same with the query without the GROUP BY, since you asked about that one too.
Comment: The query does not match the plan. `(last_event_time > '2020-03-01 00:00:00'::timestamp without time zone) AND (last_event_time < '2020-03-25 00:00:00'::timestamp without time zone))"` is not in the query. Please present a consistent question. Always start by disclosing your version of Postgres. And what Jeff said about text format.
Comment: @jjanes and Erwin; Question was edited like you said.
Comment: @a_horse_with_no_name fixed.
Answer: There are several problems:

PostgreSQL had to set hint bits, which dirty the pages and cause writes.
PostgreSQL has to fetch table rows from disk to fetch their visibility.
PostgreSQL has to scan 80000 pages to get 87000 rows, so the index must be totally bloated.

The first two can be taken care of by running
VACUUM summary;

which is always a good idea after a bulk load, and the bloat can be cured by
REINDEX INDEX "idx_as_type_usr_productId_eventTime";

Comment: That is the root cause of your problem. Tune autovacuum and use HOT updates. But that is material for another question.
Comment: Laurenz, thanks for your answer. I know that is related with DB-cache because I fetched them sequentially. Hence, I updated question again. At this time, I fetched them with time break 15 minutes between two queries.
Comment: And here my main question is not differences between group-by and non-group-by. My main question is; there are only 500 rows to scan and this scan is index-only-scan so why fetching time takes so long?
Comment: I have adapted the answer to the changed question.
Comment: But this table has at least 30 insert/update operations for per second. So should I do reindex it all time? Is it applicable solution?


Unrecognized VM option 'MaxPermSize=512m' when running Zeppelin

Question: When I try to run Zeppelin by either
bin/zeppelin.sh

or
bin/zeppelin-deamon.sh start

I was getting the following error message.
Unrecognized VM option 'MaxPermSize=512m'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Java 9 is installed on my system (Ubuntu 16.04).
$ java -version
openjdk version "9-internal"
OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)

Comment: You appear to have an ancient build of JDK 9 on your system. The JDK 9 GA build reports itself as "9", released September 2017. Your build seems to be from early 2016. In any case, the MaxPermSize option only make sense with JDK 7 and older releases. With JDK 8 and JDK 9 you will get a warning like this: "ignoring option MaxPermSize=128m; support was removed in 8.0". One final point - if zeppelin have an issue tracker then it would be good to submit a bug so that they know to update their scripts.
Comment: Yeah, it does look like an ancient version. `openjdk-9-jdk` series was installed on my system, and I removed them.
Comment: Does this answer your question? [Android Studio - Unrecognized VM option 'MaxPermSize=256m'](https://stackoverflow.com/questions/31411989/android-studio-unrecognized-vm-option-maxpermsize-256m)
Answer: If anyone still getting this renaming MaxPermSize to MaxMetaspaceSize fixed the issue on my part, migrated from gradle7.2 to gradle8 with jdk11 previously, now on jdk17
Comment: @Gorbles The old option was superceded. That does not mean that the new one is a drop-in replacement of it. I even mentioned why - someone setting MaxPermSize to *increase* it (which I believe was the most popular reason of setting it) has no need to set MaxMetaspaceSize.
Comment: @rjurney if you previously set MaxPermSize to increase it - delete it. If you set it before to decrease it - find someone who knows why, these days shaving off from 82MB default doesn't seem impactful, but maybe you have a specialized usecase. If you don't know - find out.
Comment: That should not be the accepted answer - PermGen and Metaspace are completely different beasts. Main difference for a person setting that parameter is that PermSize always had an upper bound and if unspecified it defaulted to 82MB, while Metaspace upper bound is not specified by default (so setting it actually introduces it). As such these are two completely separate properties with different meaning, and one should not recommend simply replacing one with the other. If anything general recommendation would be jsut to remove the argument alltogether and leave metaspace alone.
Comment: @Deltharis - the docs literally recommend the replacement: https://docs.oracle.com/en/java/javase/17/docs/specs/man/java.html#removed-java-options
Comment: @Deltharis what are we supposed to do when the build is broken? :)
Answer: It appears the MaxPermSize VM option is no longer supported in Java 9. Perhaps they changed the parameter name or something. Instead of digging into this issue further, as I had no particular reason to insist on using Java 9, I installed Java 8 as follows:
sudo apt install openjdk-8-jdk

And made it a default Java environment
sudo update-alternatives --config java

This fixed the issue.
Comment: `MaxPermSize` was already removed in Java 8. You should get the same warning with that version.
Comment: Downgrade because of "wrong" parameters always is the worst idea.
Comment: @DidierL is right. Zeppelin was spitting out a warning: `OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0`.
Comment: The concept worked for me. In my case the versions were different.
Answer: Starting OpenJDK17 these java options -XX:MaxPermSize=256m have been removed and using them results in an error. You need to remove -XX:MaxPermSize=512m in java option and replace with -XX:MaxMetaspaceSize=512m.
See: Removed Java Options Documentation
Answer: Check your gradle.properties
I had this line in it
org.gradle.jvmargs=-Xmx4g -XX:MaxPermSize=2g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

removed it and everything works like charm :)
Comment: What does removing this line do?
Answer: Maybe this could answer your question:
https://stackoverflow.com/a/12114284/3957538
You don't need to remove the full line as @Maulzey said.
Instead, just remove MaxPermSize or use it respective sustitution.


Obtaining wifi name in iOS

Question: I'm developing an app for Cydia. Is there a way to get the name of actual connected wifi network?
There seems to be a way with the Apple SDK, any ideas?
This is my action:
<code>-(IBAction)addCurrent:(id)sender {
if ([[objc_getClass("SBWiFiManager") sharedInstance] currentNetworkName] != @"") {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathFile];
        NSMutableArray *networks = [dict objectForKey:@"Networks"];
        [networks addObject:[[objc_getClass("SBWiFiManager") sharedInstance] currentNetworkName]];
        [dict setObject:networks forKey:@"Networks"];
        [dict writeToFile:pathFile atomically: YES];
        [dict release];
}
</code>
When I click the button connected to the action, does not add anything to the plist file
Answer: This will require a jailbroken device:
<code>[[objc_getClass("SBWiFiManager") sharedInstance] currentNetworkName]
</code>
Comment: SpringBoard is NOT a Cydia app. SpringBoard is basically "Finder" in iOS, where your icons / dock sit, etc.
Comment: Does anyone know what SB stands for?
Comment: Writing "NSString * networkName = [[objc_getClass (" SBWiFiManager ") sharedInstance] currentNetworkName]," it seems that the string is null.
Comment: I know, I will say it to JustSid. Like this:
JustSid SB stands for Springboard
WrightsCS yes, it's for a cydia app (Jailbroken devices).
Got it now?
Comment: ah, okay. So if you know how to hook into SpringBoard this will get you want you need. You will need the `SBWifiManager` classes imported. You should also look into Theos and how to make dylibs.
Comment: CHDeclareClass(SBWiFiManager);? Still return a null string
Comment: are you importing the headers? or making dummy classes for `SBWifiManager`?
Comment: I'm importing SpringBoard/SBWifiManager.h
Comment: where are you using the code, and maybe you can edit your question with the entire code you are using and a little more detail on how you are implementing it.
Comment: you will no be able to call this from an App. You would need to send an `NSNotification` to a dylib. The dylib is what works inside SpringBoard, not apps. You can then have your dylib send back a notification with the network name, or write it to a file that your app can read.
Comment: Can you write a little example?
Comment: There are quite a few examples on the internet. If you want to contact me outside of S.O. see my profile for contact information and maybe we can work something out.
Answer: You can use my 3rd party library for this, it uses only Public API:
https://github.com/Krivoblotsky/SSIDObserver

Obtaining wifi name in iOS


Learning Scales, should I initially focus on thirds and sixths as well?

Question: Background: Learning piano on my own using a method book (alfred's adult series) (88 hours of practice so far), since a month ago. Don't have access to a piano teacher for the moment but will definitely get one as soon as possible.
I'm currently going through a scales book ( Scales, Chords, Arpeggios and Cadences: Complete Book ) and for each key we have:

Parallel motion in octaves.
Contrary motion starting on the same note.
Parallel motion in thirds or tenths.
Parallel motion in sixths.
Triads
Cadences (3 positions)
Arpeggios (2 inversions + root )
Dominant Seventh Arpeggios (3 inversions + root)

For each key, I'm currently only concentrating on: scales (parallel and contrary motion),  cadences and the first Arpeggios (not the dominant 7th one)).
Question: Does it make sense (from a more traditional piano learning point of view) at this stage to also include the 3rds and 6ths or would it be better to come back them later?
Answer: From memory, and it's been decades, scales in thirds didn't come in until grade VI, which is normally taken after some five years of playing. And contrary motion scales started with C,and then E, as they are pretty well symmetrical. So, there's enough other stuff to be going on with, I'd have thought, for now! Suggest you look at piano grade requirements, ABRSM, Trinity, etc.,as they obviously put stuff in at what they feel is an appropriate level.
Comment: By going through several of the ABRSM syllabuses I now realise that I was focusing on too much stuff at once. I'm certainly reducing the scope a bit now. Thanks for the recommendation.


Loaded javascript function is undefined

Question: I am sure the answer to this is simple but I have researched possible answers for hours with no luck.
I am trying to call a JavaScript addToHomeScreen function from onClientLoad (Client Side script) which is loaded but I get the ReferenceError: addToHomeScreen is not defined.  The script loads from our script library and it does load.
My Custom Control source code:
<code>    <?xml version="1.0" encoding="UTF-8"?>
    <xp:view xmlns:xp="http://www.ibm.com/xsp/core">
        <xp:this.resources>

            <xp:script src="/addToHomeScreen.js" clientSide="true">
            </xp:script>

        </xp:this.resources>

        <xp:eventHandler event="onClientLoad" submit="false">
            <xp:this.script><![CDATA[addToHomeScreen()]]></xp:this.script>
        </xp:eventHandler>
    </xp:view>
</code>
return:
<code>    <script type="text/javascript" src="/web3/website.nsf/addToHomeScreen"></script>
....
....
<script type="text/javascript">
 function view__id1__id4__id5__id7_clientSide_onClientLoad(thisEvent) {
addToHomeScreen()}
</code>
Any ideas?  I have also tried to call it from afterPageLoad (server side)
Answer: It could be a timing issue. Try enclosing your method call in a XSP.addOnLoad() call:
<code>XSP.addOnLoad(function(){
    addToHomeScreen();
});
</code>
Comment: Great. Welcome to Stack Overflow. Please accept the answer as the correct answer.

Loaded javascript function is undefined


For two single irrational numbers "a" and "b" if (a+b) or (a-b) is rational , will it always be "0"?

Question: As per me the above statement should be true since if the sum of two irrational numbers is 0 , it implies that two irrational numbers must be like +k and
-k  where k is an irrational number . Also when diffrence of two irrational numbers is rational it is possible only when both the irrational numbers are same . From both the above cases we can conclude that if sum of two irrational numbers is rational  or difference of two irrational numbers is rational then it must be 0 . Please correct me if I am wrong . By "a" and "b" I mean single or individual irrational numbers for example only "pi" and not "pi +/- something" .
Comment: Your title talks about the sum *and* difference being rational, but the body talks about the sum *or* difference being rational.  These are very different.  The body is longer, so seems to be what you are asking about.  Please clarify.
Comment: $\pi -2$ is a single irrational number.  How do you distinguish between   $3.1415926535897932384626433832795....$ being a "single irrational number" but $\pi -2 = 1.1415926535897932384626433832795...$ is not?  Are you saying $1.1415926535897932384626433832795...$ doesn't count? Isn't really irrational?  Doesn't exist on its own?  What?  In any event $3.1415926535897932384626433832795...$ is irrational.  And $1.1415926535897932384626433832795...$ is irrational.  And $3.1415926535897932384626433832795...-1.1415926535897932384626433832795... = 2$
Comment: $\implies$ and $\Leftarrow$ are not the same thing.  If $x + k =0$ then $k=-y$ is $k$ irrational.  So if the some of an irrational and a number is $0$ the other number is irrational.  That's $\Leftarrow$.  That that WASN'T the question.  The question was if $x$ is irration and $y$ is irrational but $x + y=q$ is rational is $q$ equal to $0$.  That's $\implies$ and the answer is no.  Take $x = \pi$ and $y = 2-\pi$.  Both are irrational and $x + y = 2$ which is rational but not $0$.
Comment: "if the sum of two irrational numbers is 0" That was not the hypothesis so it is not relevent.  The hypothese was the sum of the two irrational number is *rational*.  There are other rational numbers than just $0$...."Also when diffrence of two irrational numbers is rational it is possible only when both the irrational numbers are same"  Nonsense!  If $x - y = 2$, then does that mean $x$ and $y$ must both be rational?  What if $x = \pi$?  Then $y = \pi-2$.   $\pi$ is irrational.  Does that mean $\pi-2$ must be rational?
Comment: @fleablood symbolically by "a" and "b" I mean single irrational number , that is , for example , only "pi" and not "pi - 2" . I do have sense just forgot to clarify what I mean
Comment: Note:  $x + y = k\iff x = k-y$.  So distinguishing between $x$ as an irrational number and $k-y$ as "not a single irrational number" doesn't really make any sense.
Comment: OK you win , i was wrong thanks for your valuable time and guidance.
Answer: If $a+b$ and $a-b$ are both rational, then so is $a$ since it is the average of those two quantities, and the average of two rational numbers is also rational. Thus also $b=(a+b)-a$ is rational.
Answer: Your statement in the body is not correct.  For example, both $\sqrt 2$ and $\sqrt 2 +1$ are irrational.  Their difference is $1$, which is rational.  If both the sum and difference of two numbers are rational, the two numbers must be rational, but that is not what your question says.
Comment: i have edited my question.
Answer: Don't overthink it.
If $x$ irrational then $q - x$ is irrational for every rational $q$.
So $x + (q-x) = q$ is the rational sum of two irrational numbers.  But $q$ can be any rational number and doesn't have to be $0$.
=====
This is one of those results that when you analyze it you realize it can't actually mean anything.
We think.  $rational + rational = rational$
And $rational + irrational = irrational$.
But what of $irrational + irrational$ can that be rational.
Well, $\sqrt 2 + (-\sqrt 2) = 0$ and $0$ is rational so it can be rational.
So we think... and we say... Yeah, but $\sqrt 2$ and $-\sqrt 2$ are related to each other, they are negatives of each other.  I bet if you have two independent irrationals the must add to a irrational.
So someone else says well if $x +y = k$ and $k$ is rational, then if $x$ is irrational then $y= k - x$ is irrational and $x + y = x+(k-x) = k$. so that is two irrationals that add to a rational.
So we say... but those are dependent to each other; I bet if you have two independent irrationals the must add to a irrational.
So the other person asks.  How exactly to you define if two irrationals are "dependent"?
And we say... well if $x$ is irrational and $y = \pm x + k$ for some rational $k$ they are dependent.  So I claim that if $x,y$ are independent than $x + y$ is not rational.
And then other person says.... so in other words, you are claiming that there is no rational number $k$ so that $y =\pm x + k$ then $y \mp x \ne k$ for any rational $k$ but if there is such a rational $k$ so that $y =\pm x + k$ then $y\mp x$ might be rational; is that what you are claiming?
And we say, yes, now how can I prove it?
And the other person says.  Um... you just said $x \mp y =k; k$ rational if and only if $x = \pm y +k$ for some rational $k$.  Do you really think that is meaningful?
And we say.... Ulp, I guess not.


Will isset() trigger __get and why?

Question: class a {
   function __get($property){...}
}

$obj = new a();
var_dump(isset($obj->newproperty));

Seems the answer is nope but why?
Answer: Because it checks __isset rather than retrieving it using __get.
It is a much better option to call __isset, as there is no standard on what is empty. Maybe in the context of the class null is an acceptable value. You could also have a class that if the member didn't exist, it returned a new empty object, which would break isset($myObj->item) as in that case it would always return true.
Answer: It just isn't; you can use __isset instead. This is laid out here.
Answer: No, __get should not be triggered when you're trying to determine whether a property is set : testing if a property is set is not the same thing as trying to get its value.
Using isset triggers the __isset magic method.
See :

isset
and Overloading
Comment: Seems I didn't define __isset in my example?
Comment: Seems you didn't, indeed -- but, if you had defined it, it should have been called ;; and defining it or not doesn't change anything about `__get` not being called when you're testing if a property is set.
Answer: The magic function __get is only called when you try to access a property that doesn't exist. Checking whether a property exists is not the same as retrieving it.
Answer: Class A{
   public function __get($key){
      ...
   }
   public function __set($key,$name){
      ...
   }
   public function __unset($key){
      ...
   }
   public function __isset($key){
      ...
   }
}
$obj = new A();
$get = $obj->newproperty;//$obj->__get("newproperty")
$obj->newproperty = "X";//$obj->__set("newproperty","X")
$bool = isset($obj->newproperty);//$obj->__isset("newproperty")
unset($obj->newproperty);//$obj->__unset("newproperty")

Will isset() trigger __get and why?