speed of convergence to infinity

Question: Lets take for example $\lim_{x\rightarrow\infty} \log(x)$, from a mathematical point of view this is $+\infty$, but from a logical point of view it's clear that $x$ converges to $+\infty$ much more quickly than $\log(x)$. Is there any kind of mathematics which take this into account?
Comment: You can say that the function $f(x)$ converges faster to infinity than the function $g(x)$ if $\lim_{x\rightarrow \infty }\frac{f(x)}{g(x)}=\infty $ or equivalently $\lim_{x\rightarrow \infty }\frac{g(x)}{f(x)}=0$.
Comment: Could you please clarify your question? Is there anything specific that is bothering you, or that you would like to have a second opinion on? The question "Is there any kind of mathematics which take this into account?" is rather vague as asked.
Comment: Let me just add that, from a strictly mathematical point of view (which I presume won't help to hint your intuition, but perhaps the answer is in line with your question), we have: the derivative of $\log(x)$ is $1/x$, while the second derivative is $-1/x^2$. It follows that while $\log(x)$ diverges to infinity, its "drive" to infinity is decelerating as a quadratic (i.e., it goes to infinity, so to speak, at ever decreasing speed with time, if you regard $x$ as time).
Comment: @WNY Well to clarify the question, I just wondered if there is any numerical analysis methods to compute the speed of convergence of a given function. And if it exists, I wondered if this notion of "speed of convergence" can be taken into account to compute F(+inf, with_a_convergence_speed) instead of "limit of F(x) when x-->+inf"
Answer: The big O notation (and its various siblings and cousins) used to classify the asymptotic growth rates of functions addresses this problem head on.
For your two examples $f(x)=x$ and $g(x)=\log x$, we say that $g(x)$ is $O(f(x))$ but $f(x)$ is not $O(g(x))$. The $O(\cdots)$ intuitively denotes "grows no quicker than" or "is eventually proportional to or smaller than". Formally $f(x)$ is $O(g(x))$ if there exists an $N$ and a constant $c>0$ such that $f(x)\le cg(x)$ for all $x>N$. This is equivalent to the limit-based comparison given by Américo Tavares in the comment about; the result is a partial order on the set of all functions from positive reals (or integers) to positive reals (or integers).
Such properties are intensively used, for example, in the study of algorithmic complexity, where the functions being compared are the running times (or resource usage) of computer programs as a function of the size of their input.
Incidentally, there's no good way to assign numbers to different asymptotic growth rates. A coarse first approximation would be to classify a function $f$ according to the infimum of the $b$'s such that it is $O(x^b)$. But it turns out that $x\mapsto x^b\log x$ has a growth rate strictly between $x^b$ and $x^{b+\varepsilon}$ for any $\varepsilon>0$ -- and there is an entire hierarchy of logarithmically differing growth rates in that gap, which would be lost if we reduced it all to being about the exponent $b$.
Comment: @user995434: First, no, the same $c$ must work for _all_ $x>nN$, and you can't do that for $x \le c\log x$. The big-O notation is more fine-grained than the "rate of convergence" vocabulary you link to -- when faced with a _finite_ limit $L$, one might speak about the asymptotic behavior of the function $x\mapsto f(x)-L$ -- only then _smaller_ values mean quicker convergence, so many details end up looking opposite of the $f(x)\to\infty$ case.
Comment: [typo alert: $nN$ above should have been just $N$] _(continued...)_ Yes, the partial order expressed by big-O is the same as the one Américo defines using limits (except for some often irrelevant caveats about what if one of the functions is $0$ infinitely often so the rations don't exist, etc). Finally, congratulations on rediscovering asymptotic analysis of algorithms! If you want to go deeper, there are lots of excellent textbooks about the matter, often with "algorithms" as the central keyword in their titles.
Comment: Is there any calculable convergence rate that accompanies this notion of big O for functions ? Like for sequences, the convergence rate is the speed at which a convergent sequence approaches its limit: http://en.wikipedia.org/wiki/Rate_of_convergence.

By the way, it always exists a constant c > 0 such that x <= c log(x) what ever is x > 1, that means according to the definition that x is O(log(x)), which is not correct since x grows quicker than log(x), or I missed something.

Coincidentally, I had this question when I was thinking about how to define a worst-case bounds for a program.
Comment: And formally can we also define the big O as: f(x) is O(g(x)) <==> limit of (g(x)/f(x)) is 0 when x-->+inf ? as @AméricoTavares said.
Comment: Thanks for the precision. I'm looking at the free book [The Design of Approximation Algorithms](http://www.designofapproxalgs.com/download.php), actually I'm a beginner in this area.

speed of convergence to infinity


Placing content in different regions using a controller

Question: I've defined a route to a custom controller, which returns a render array to define its content. By default, this content gets rendered entirely inside the main content region of the page: what I want is to have different parts of it rendered to different regions.
I've tried specifying the region (e.g. <code>'#region' => 'content_intro'</code>) in the relevant sub-arrays for different elements, but they are still output to my main content region.
I've also then tried adding the following to the base definition of the returned render array:
<code>$content = array(
  '#type' => 'page',
);
</code>
This does then allow me to successfully specify the region for placing individual elements. However, other standard elements placed in page regions - specifically, a navigation menu block - are then not output.
How would I best go about having my controller add its content to regions, while still retaining elements placed by other systems?
Answer: The normal way to do this is to provide the main content in a controller and the additional content in block plugins.
If you don't want to use blocks and the block layout for this task (what you really should do!), and want to solve this in code, you can use a preprocess hook to add content your module provides in a function (procedural or static, not a controller) to a region.
Comment: The block plugin approach has worked nicely - thanks for the guidance.


How to bind to AccessibilityService in Mono (Xamarin)

Question: I've tried and got OnServiceConnected event in ServiceConnection class. But casting IBinder to my class (it inherits Binder, that inherits IBinder) returns null if I try to do that as  "var myObject  = IBinderObject as myBinderClass;" or casting error if I try to do that as "var myObject = (myBinderClass) IBinderObject;".
Please, any working example...
MainActivity code:
namespace MyApp.Droid
{
    [Activity(Label = "MyApp", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        AccessibilityServiceBinder binder;
        AccessibilityServiceConnection accessibilityServiceConnection;
        bool isBound = false, isBoundAC = false, isConfigurationChange = false;
        protected Intent ServiceIntent;
        AccessibilityServiceClass ServiceClass;

        protected override void OnStart()
        {
            base.OnStart();
            if (!isBoundAC)
            {
              accessibilityServiceConnection = new AccessibilityServiceConnection(this);
              isBoundAC = BindService(ServiceIntent, accessibilityServiceConnection, Bind.AutoCreate);
              if (isBoundAC)
              {
                Toast.MakeText(this, "AccessibilityService is Bound", ToastLength.Long);
              }
            }
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            ServiceIntent = new Intent(this, typeof(AccessibilityServiceClass));
            ServiceIntent.SetPackage("android.accessibilityservice.AccessibilityService");
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
        public class AccessibilityServiceConnection : Java.Lang.Object, IServiceConnection
        {
            MainActivity activity;
            AccessibilityServiceBinder binder;
            public AccessibilityServiceBinder Binder
            {
              get
              {
                return (AccessibilityServiceBinder)binder;
              }
            }
            public AccessibilityServiceConnection(MainActivity activity)
            {
              this.activity = activity;
            }
            public void OnServiceConnected(ComponentName name, IBinder service)
            {
              var accessibilityServiceBinder = service as AccessibilityServiceBinder;
              //accessibilityServiceBinder is always null here
              if (accessibilityServiceBinder != null)
              {
                activity.binder = accessibilityServiceBinder;
                activity.isBound = true;
                this.binder = accessibilityServiceBinder;
              }
            }
            public void OnServiceDisconnected(ComponentName name)
            {
                activity.isBound = false;
            }
        }
        public override Java.Lang.Object OnRetainNonConfigurationInstance()
        {
            base.OnRetainNonConfigurationInstance();
            isConfigurationChange = true;
            return accessibilityServiceConnection;
        }
    }
}

Service code:
namespace MyApp.Droid
{
    [Service(Label = "MyApp", Permission = Manifest.Permission.BindAccessibilityService), IntentFilter(new[] { "android.accessibilityservice.AccessibilityService" }), MetaData("android.accessibility-service", Resource = "@xml/accessibilityserviceconfig")]
    public class AccessibilityServiceClass : Android.AccessibilityServices.AccessibilityService
    {
        public override void OnAccessibilityEvent(AccessibilityEvent e)
        {
            Toast.MakeText(this, "OnAccessibilityEvent", ToastLength.Short);
        }

        public override void OnInterrupt()
        {
            Toast.MakeText(this, "OnInterrupt", ToastLength.Short);
        }

        protected override void OnServiceConnected()
        {
            Toast.MakeText(this, "OnServiceConnected", ToastLength.Short);
        }
    }
    public class AccessibilityServiceBinder : Binder
    {
        AccessibilityServiceClass service;

        public AccessibilityServiceBinder(AccessibilityServiceClass service)
        {
            this.service = service;
        }

        public AccessibilityServiceClass GetAccessibilityService()
        {
            return service;
        }
    }
}

Comment: Add your service code
Comment: Done... Thank you.
Answer: You aren't overriding the OnBind event of your service, thus the binder is null as you haven't provided an instance.
Add this to your service:
AccessibilityServiceBinder binder;

public override IBinder OnBind (Intent intent)
{
    if(binder == null)
        binder = new AccessibilityServiceBinder (this);

    return binder;
}

For more info read the Xamarin docs on bound services, they're very well explained: https://developer.xamarin.com/guides/android/application_fundamentals/services/part_2_-_bound_services/
EDIT: Total wrong answer (I will delete it in some minutes). It seems it's not possible to bind to an Accessibility service. More info here: android bind to AccessibilityService
Comment: Thank you, but it said that OnBind is sealed and cannot be overriden...
Comment: AccessibilityServiceClass inherits Android.AccessibilityServices.AccessibilityService, not Android.App.Service
Comment: Yes, my fault, for what I see the internal implementation creates an IAccessibilityServiceClientWrapper (source here: https://sourcegraph.com/android.googlesource.com/platform/frameworks/base/-/info/JavaArtifact/AndroidSDK/-/android/accessibilityservice/AccessibilityService:type/onBind:android.content.Intent) so I suppose accesibility services aren't supposed to be binded, some other posts state this (http://stackoverflow.com/questions/9683927/android-bind-to-accessibilityservice)


Stochastic interpretation of Einstein equations

Question: Einstein's theory of gravitation, general relativity, is a purely geometric theory.
In a recent question I wanted to know what the relation of Brownian motion to the Helmholtz equation is and got a very thorough answer from George Lowther.
He pointed out that there is, roughly speaking, a very general relation of semi-elliptic second order differential operators of the form
$$Af = \frac12 a^{ij}f_{,ij} + b^i f_{,i} - cf = 0$$
to a "killed" Brownian motion. (I used some summation convention and $,i = \frac{\partial}{\partial x^i}$.)
Now, the Einstein field equations
$$R_{\mu\nu}-\frac12 g_{\mu\nu}R = \frac{8\pi G}{c^4}T_{\mu\nu}$$
are coupled hyperbolic-elliptic partial differential equations (I dropped the cosmological constant here). Can we somehow adopt the relation of a random process to this kind of equation, or

Is there a way to interprete the
  Einstein equations stochastically?
Comment: The evolutionary Einstein's equation: probably not. The hyperbolic part of the equation does have the same interpretation, especially since the equation is non-linear and there is no easy way to perform separation of variables (or "Fourier transform in time") to reduce to elliptic problem. (Also, no preferred time function etc.) For the constraint problem, which is purely elliptic, there maybe something you can say. There's some recent work by Blaine Lawson on fully non-linear elliptic systems arising in geometrical contexts, which formally has many parallels with the analytic half of ...
Comment: ... George's answer you linked to, so one may try to run the same argument and see if a random process pops out. I thought about it briefly in passing last year, but the situation seems rather complicated (to me) and I am not personally aware of anyone fully fleshing out the ideas just yet.
Comment: @Willie Wong: Thank you again for your nice comments! You have a lot of knowledge about the structure of general relativity and the underlying geometrical and functional concepts and I enjoy reading your thoughts. So, for this question, the situations seems to be arbitrarily complicated - even though there might exist a corresponding stochastic process we simply don't know it yet :) You may consider posting your comments as answer, I would be glad to accept. Sincerely
Answer: The link between Einstein equations and a stochastic process can be achieved through Ricci flow. I can state the question very easily for the 2d case while, for higher dimensions things may become quite involved. The idea is that a stochastic process satisfy a diffusion equation
$$\partial_tP=\Delta_2P$$
and one can write down the solution through a Wiener integral
$$P=\int[dx(t)]e^{-\frac{1}{2}\int_0^td\tau{\dot x}^2(\tau)}.$$
When one extend this to a generic two-dimensional manifold, the diffusion equation, when applied to the metric, is that of the Ricci flow as one has just the Laplacian replaced by the Beltrami operator applied to metric. Then, the fixed point of this Ricci flow is just Einstein equations for the two-dimensional manifold at hand. I have given some considerations about, well-founded on a theorem by Baer and Pfaeffle (see here).
The exciting idea behind this is that a Ricci flow could be always derived from a stochastic process underlying a manifold. I think that this is material to be studied yet.
Comment: Dear @Jon, thank you very much for your answer! Since I think the generalization to a four-dimensional Pseudo-Riemannian manifold is challenging, I appreciate your insightful two dimensional approach very much. Greets


How do I make a guitar string easier to bend?

Question: Basically, every string on my guitar is kinda easy to do a full bend on, except for the high e string, where if I bend it as much as I can, it still sounds flat. I was wondering what I should do, whether I should get a new E string, should I lower/raise the action etc. I'd rather not get a new string, because I have to replace it so often, and I'm gonna change the pegs next time I switch strings.
Comment: What guitar is it? What gauge strings are on it? Why do you have to replace it so often? All important points that will help find answers.
Comment: Be sure there are no sharp edges on your bridge or saddle that could be causing your string to break.
Answer: How hard a string is to bend depends on its tension. The only way to make the high E easier to bend is to use a lighter gauge. Raising or lowering the action will do nothing.
If you currently use a .010 try a 0.009. The downside is that it is more likely to snap and won't last as long.
The other option is just keep practicing, and your fingers will get stronger over time.
You did use one phrase which is puzzling, "bend it as much as I can, it still sounds flat." What does this mean? I typically can bend my E string up at least 3 semitones, so I can decide how sharp or flat I want it to be.
Comment: Seems reasonable. To keep going higher, just push through the B
Comment: Yep - it's tension that is the issue. Remember, you can push the E right through the B and beyond. You just need the strength to push 2 or even 3 strings
Comment: I've used .008 for top string for many years, and yes, they're much more bendable. Can't remember the last one that broke through bending, though. And they seem to last well enough.
Comment: That's pretty good. I tried 8's but went through them way too fast (one a month or so) Now I use 9's and 10's as they last a lot longer. I do a lot of bends though.
Comment: At that time, I was changing strings about every 6-8 gigs, so the sound was always fresh. So maybe it's not a fair comparison.
Comment: If I was to bend the E string so it's where the b string is supposed to be, it's almost one semitone, if I bend it as far as I can, it's 2 semitones, 3 is basically impossible. On every other string, if I bend them as far as I can go on every other string, it's 3 semitones. I think I'm using a .010, because the string always snapped, but whatever. If I can bend the strings without fearing something to break, then it's worth it.
Comment: Anyways, is the only way to make it more bendable by getting a lighter gauge string? Nothing to do with how you string the guitar or anything?
Answer: Adding to Dr Mayhem's answer, it's usually better to bend a string using more than one finger. Not always possible, but when you can, use the other fingers to help push or pull the string to be bent. On top string, it's going to be a push rather than a pull.
Answer: The only reason I could think of that could stop you from doing a full bend is improper technique, such as:

Using your fingers instead of your wrist to bend: Your wrist has a lot more power than your fingers - to bend you should "lock" your fingers on the string, put your thumb over the neck (this will make it easier, but everybody should be able to do it without the thumb) and rotate your wrist.
Not using enough fingers to bend: The more fingers you have on the string, the stronger the grip and the easier it will be to bend the string.
Answer: Hell I use a .007 Billy Gibsons custom strings, and I love them, I do a lot of bending in my leads.. standard e tuning is why I go to such small strings I used 9's when I was tuned a step down..


FTP Daemon for Windows?

Question: I need to replace an IIS FTP server that uses AD accounts for consultants to transfer files to an organization.  I would like to slowly migrate away from these AD accounts for security reasons.
Whats a good FTPd for Windows that supports:

Existing AD credentials (Including user@domain, domain\user forms)
As functional as IIS's ftpd (thats not saying much)
SCP/SFTP/FTP/HTTPS for FIle Transafers.
Perhaps a simple web interface (not critical).
Comment: In regard to point 3, it's either an FTP server or it isn't. You've listed protocols, most notably HTTPS, which are unrelated to FTP.
Answer: I'm not sure what 'security reasons' you're referencing that wouldn't be present in another Windows solution (that presumably would still rely on Windows security).  However, FreeNAS allows for just about every file transfer method imaginable and has an easy-to-configure active directory authentication connector.  We've had very good luck integrating FreeNAS boxes into our AD domain and it's easy to get up and running in only a few minutes with the web management interface.
Answer: I am also looking for a FTP server software and stumbled over CrushFTP 5 (http://www.crushftp.com/5.html) today. I havn´t tested it yet but it seams like it will fullfill you needs.
If someone have any experience of CrushFTP then I am listening...

FTP Daemon for Windows?


Is this a bound variable?

Question: If I write
$\left \{\begin{array}{llll}
    &   y = z \\
    &   z = x + 2
  \end{array} \right.$
could I make the argument that $z$ is a "bound" variable.  I've seen it referred to as a "dummy" variable.  Is it bound by the $\{$.  Thanks.
Answer: All the variables in the two equations are free. The bracket to the left groups the equations together, meaning both equations must hold. So the expression is two equations in three variables. You probably noticed that $z$ can be eliminated, transforming the expression into the single equation $y=x+2$. In other words, it is not true that $z$ is a bound variable, but it is true that it can be easily eliminated, giving a simpler expression.
If a variable is bound, it makes no sense to substitute a number for it. In the problem, you can substitute numbers for all three variables, sometimes making the equations simultaneously true and sometimes not.

Is this a bound variable?


Got this error when trying to run node server

Question: I am using Linux mint. My node version is 9.4 and nmp version is 5.6
See the error i got when run "node server"
/var/www/html/mean/firstapp/server.js:1
(function (exports, require, module, __filename, __dirname) { import mongoose from 'mongoose';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at new Script (vm.js:51:7)
    at createScript (vm.js:138:10)
    at Object.runInThisContext (vm.js:199:10)
    at Module._compile (module.js:624:28)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:193:16)

Generally i am getting this error from MongoDB
MongoDB shell version v3.6.2
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 3.6.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
Server has startup warnings:
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten]
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten]
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten]
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-01-31T11:15:50.975+0530 I CONTROL  [initandlisten]
2018-01-31T11:25:28.254+0530 E -        [main] Error loading history file: FileOpenFailed: Unable to fopen() file /home/ranjit/.dbshell: No such file or directory

Answer: Imports, also known as ES modules are not natively supported by node. Node uses CommonJS by default (require).
Node 9 does now support ES modules but it's behind a flag.[1]
To use your server.js with ES modules you need to rename it to server.mjs and launch it like this:
node --experimental-modules server.mjs
[1] https://nodejs.org/api/esm.html
Comment: It is still giving error as i tried this . I rename the server.js to server.mjs and run the command written above
Comment: what is the error
Answer: import is not supported syntax for CommonJS module system in node.
You either use require, or transpile your Node.js code with something like babel-node.
https://babeljs.io/docs/usage/cli/#babel-node
Comment: Should i change in all the files where it is written import ?
Comment: Yes you should, or use babel. Read the linked docs.


Quadrilateral in quarter circle

Question: My friend, who is an elementary school teacher, found this problem in one of their text books and asked me for help. Turns out I'm not much of a geometry buff.
You have a quarter section of a circle. Inside this section, there is a quadrilateral with one corner at the center, with two corners at the axes, and with the last corner on the circle such that it creates a right angle. You are given that the non-trivial diagonal is $8$. What is the radius of the circle?
I observed that it is a cyclic quadrilateral, and I tried to apply Ptolemy's theorem to show that the radius is uniquely determined, but I didn't succeed and now I'm not convinced that it is true. What do you think?
Answer:
You're correct the radius is not unique. Instead, it can be anything within a range of values. To see why, consider my diagram above. First, draw any line segment $AB$ of length $8$. Have $C$ be its midpoint. Consider the line segment $CD$ of length $4$. Note that for any circle circumscribing $\triangle ABD$ that $AB$ would its diameter, so $\measuredangle ADB = 90^{\circ}$. You can also see this because, by isosceles triangles, you have $\measuredangle CAD = \measuredangle CDA$ and $\measuredangle CDB = \measuredangle CBD$, so since the total sum of these angles is $180^{\circ}$, you have that $\measuredangle BDA$ is half of that, i.e., $90^{\circ}$. Regardless of how you determine it, note it meets your requirements.
However, $D$ can move around anywhere on that circumscribed circle, so the circle going through $D$, as shown, would have different radii depending on where that point is, such as point $E$ instead as shown above. Overall, the locus for valid positions for $D$ would form a semi-circle of radius $4$ with center $C$.
Answer: This question is very nice but you can determine the radius of the circle with only these informations. I give you two different situations which satisfie hypotesis but the two radius are different. Instead of $8$ I use $5$ (Using Pythagorean triple in computation)
Case 1: Take as quadrilater a square with edge's length equal to $\frac{5}{\sqrt{2}}$. Thanks to this fact you have that the two diagonal are equal and of the circle has radius equal to $5$.
Case 2: Take the quadrilater $ABCD$ with coordinates $A=(0,0)$, $B=(3,0)$, $C=(4,2)$, $D=(0,4)$. Thanks to Pythagorean theorem we have that $\overline{BD} = 5$ as we want. Moreover, the ipotetic radius $AC$ has length equal to $\sqrt{4^2 + 2^2} = 2\sqrt{5}\neq 5$. So, if we show that $\overline{CD}$ is orthogonal to $\overline{BC}$ we are done. The angular coefficient of the line passing through $\overline{CD}$ is $-\frac{1}{2}$ and the angular coefficient of the line passing through $\overline{BC}$ is $2$; so $\overline{CD}$ is perpendicular to $\overline{BC}$.

Quadrilateral in quarter circle


What does an arc mean above the notes in a piano sheet music? How do I play it?

Question:
See the picture above. Is there a website where these (perhaps not so basic) notations are collected?
UPDATE: I see Wikipedia has a nice collection of musical notations.
How do I play the slur on the piano? The slur example on Wikipedia is not to much help :(
Answer: As you've already discovered, it's a slur, and it means that you should play the notes that fall under it legato.

In musical notation the Italian word legato (literally meaning "tied together") indicates that musical notes are played or sung smoothly and connected. That is, in transitioning from note to note, there should be no intervening silence.

Essentially, you want one note to stop ringing the same instant that the next begins ringing.  This is obviously contrasted with staccato, where notes are played sharply and stop ringing well before the next is played.  Normal playing falls in between, though generally more towards the legato side.
This is just a matter of practice to get the feel and timing right.  Experiment!
Comment: One can use over-legato as well, depending on the circumstances and instrument. This means holding the preceding note slightly into the next one. The corollary to the use of legato, though, is that the last note under the slur is usually somewhat detached from the note that follows it (i.e., slightly shortened).
Answer: The puzzle connected with the legato slur is "fingering": use different fingers for each pairs of notes so that you could play them slightly overlapping.  Theoretically, the notes should be tied seamlessly.  But for many keyboard instruments it's more feasible to "hide" the key release action in the attack of the next note.  For a piano, the timing is not overly sensitive since the key release action is pretty silent and does not interact with the attack.
For an organ or harmonium or accordion, however, a slightly early release results in a slight buildup of pressure from the continued movement of the bellows giving the next note an onset accent inappropriate for legato but making leggiero play more poignant.
I am not overly versed with piano keyboards but would imagine that a fingering of 1-4 alternating with 2-3 would allow the kind of "parallel walk" allowing to play this phrase with a slight overlap.
Answer: The simplest way to play this legato on piano is to use all digits - 3 and 5 on the E and G;2 and 4 on D and F#; 1 and 3 on C# and E. Thumb on a black note is acceptable. This way, it plays smoothly, and there's no need to jump from any note .
Answer: OK, my old piano teacher would hit me with a ruler for saying this, but the "legato" is most idiomatically achieved here with the sustain pedal. Look at the left hand part:  it is simply arpeggiating a D-major chord. So you "catch" the low D with the pedal, and then sustain it as you jump the left hand up to catch the rest of the notes. The slur here is a pedal marking in disguise.
Comment: Pedalling could be part of the legato. But it would have to be lifted on each RH note. Pedalling over the whole phrase would give a most unpleasant smear of C#, D, E, F# and G all sounding at once!


Eager loading problem

Question: I've a problem with this linq to nhibernate query
var listeShopping = (from cart in session.Query<Cart>()
    .Fetch(cart => cart.ItemShopping)
    .ThenFetch(item => item.Manufacturer)
    select cart.ItemShopping).ToList<ItemShopping>();

When I launch it I've a strange error :
Query specified join fetching, but the owner of the fetched association was
not present in the select list [FromElement{explicit,not a collection join,
fetch join,fetch non-lazy properties,classAlias=_1,role=,tableName= (...)

I need the eager loading, how can I avoid that error ? If it can help, I'll mention that I use the cart table only like a inner join table. I just need to know the ItemShopping in the Cart.
Regards
Edit
I modified the code to make it readable in english. I corrected the error.
Edit 2
I found that method, it seems to work ... Can someone check it if I didn't make an error ?
        var list = (from item in session.Query<ItemShopping>()
                   .Fetch(item => item.Manufacturer)
                   from cart in item.Cart
                   select item).ToList<ItemShopping>();

Comment: where is the `pan` in the `select` defined ?
Comment: You are quering Cart's, selecting something from pan and trying to cast it to list of ItemShopping... Some details needed :)
Comment: I modified the code ... sorry !
Answer: I don't think it's possible to handle this scenario with Linq. But it is with HQL:
var listeShopping = session.CreateQuery(@"
    select item
    from Cart cart
    join cart.ItemShopping item
    join fetch item.Manufacturer
    ")
    .List<ItemShopping>();

Side note: eager fetching the Manufacturer this way is not necessarily the best performing approach. Consider using batch-size in the Manufacturer class instead.
Comment: Why should I use Batch-size instead of eager loading ? What are the pro and the cons ? I simplified by request, I have 10 Fetch and I don't have enough volume to have some production performance test.
Comment: @PhilippeSohm: 10 fetch? you should be using batch-size *and* caching, not fetch. Using batch size allows for small, efficient queries per entity type, while using multiple fetch statements creates huge joins that are much more costly.
Comment: Is caching efficient for a web application ? If I have a query like var items = (from item in session (...) select item) and then a foreach (var item in items) var data = item.Manufacturer.Name. Is batch-size efficient ?
Comment: @PhilippeSohm: yes. Considering your Manufacturers don't change every day, you're looking at huge query savings.

Eager loading problem


Como funciona pivot table no pandas?

Question: Sou novo em ciência de dados e estou tentando utilizar o DataFrame.pivot() do Pandas para criar um heatmap mas ele está me retornando este erro:

ValueError: Index contains duplicate entries, cannot reshape

Não estou conseguindo resolvê-lo, mas quando altero os parâmetros do pivot() funciona, porém, muitos valores retornam como NaN.
Pesquisei alguns tópicos sobre isso mas não consegui encontrar uma solução.
O formato do heatmap será com as colunas de ano e as linhas serão os meses.
Estrutura do DataFrame
data        usuarios    ano     mes      dia    ano-mes     mes-dia
2018-01-01  215         2018    01       01     2018-01     01-01
2018-01-02  167         2018    01       02     2018-01     01-02
2018-01-03  123         2018    01       03     2018-01     01-03
2018-01-04  193         2018    01       04     2018-01     01-04
2018-01-05  235         2018    01       05     2018-01     01-05
2018-01-06  241         2018    01       06     2018-01     01-06

Tipo das Series
data        datetime64[ns]
usuarios             int64
ano                 object
mes                 object
dia                 object
ano-mes             object
mes-dia             object

Tentativas
# Com esse trecho, está me retornando o erro que especifiquei acima
test = df.pivot("ano", "mes", "usuarios")

# Utilizando assim ele até funciona, mas todos os valores ficam NaN
test2 = df.pivot("data", "mes", "usuarios")

Valores após utilizar o pivot df.pivot("data", "mes", "usuarios") que funcionou
mes 01  02  03  04  05  06  07  08  09  10  11  12
data
2018-01-01  215.0   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2018-01-02  169.0   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

Por que os valores estão sendo setados como NaN e como eu poderia utilizar o pivot referenciando apenas o ano e o mês sem retornar o erro mencionado?
Comment: Editei a pergunta com as informações que você solicitou
Comment: Você poderia adicionar mais linhas ao banco para que a gente possa replicar o erro? Se não puder disponibilizar esses dados, faça um exemplo mínimo replicável. Veja instruções aqui: https://pt.stackoverflow.com/help/minimal-reproducible-example
Comment: Qual a sua unidade de cross-section?
Comment: se possível, procure deixar mais claro qual o output desejado. O seu heatmap vai ter que variáveis na linha e nas colunas?
Answer: Existem duas formas de pivot no pandas, o pivot e a pivot_table. Tanto o pivot quanto a pivot_table retornam um dataframe como output, a diferença entre elas  é que a primeira não aceita agregação, como pode ser visto na documentação.
Pivot
Voltando ao seu problema, ao menos para mim, não está claro se existe repetição da combinação ano-mês no seu banco. Se não existe repetição, você não precisa de agregação e seu problema pode ser resolvido com pivot. Veja um exemplo replicável:
import pandas as pd

df = pd.DataFrame({'ano': [2017,2018,2017,2018,2017,2018],
                       'mes': [1,1,2,2,3,3],
                       'usuarios': [215,167,123,193,235,241]})
print(df)

    ano mes usuarios
0   2017    1   215
1   2018    1   167
2   2017    2   123
3   2018    2   193
4   2017    3   235
5   2018    3   241

df.pivot(values = 'usuarios', index = 'mes', columns = 'ano')

Output:
ano 2017   2018
mes
1   215     167
2   123     193
3   235     241

Pivot Table
Por outro lado, se existe repetição no padrão ano-mês, então você terá que agregar o número de usuários de alguma forma e terá que usar pivot_table. Veja esse exemplo a seguir usando a soma como função de agregação:
df = pd.DataFrame({'ano': [2017,2018,2017,2018,2017,2018],
                       'mes': [1,2,2,2,3,3],
                       'usuarios': [215,167,123,193,235,241]})
df

    ano mes usuarios
0   2017    1   215
1   2018    2   167
2   2017    2   123
3   2018    2   193
4   2017    3   235
5   2018    3   241

df.pivot_table(values = 'usuarios', index = 'mes', columns = 'ano', aggfunc = 'sum')

Output:
ano 2017    2018
mes
1   215.0   NaN
2   123.0   360.0
3   235.0   241.0

Note que nesse caso, há uma NaN no mês 1 de 2018, isso ocorre porque não existe essa entrada no banco original.

Como funciona pivot table no pandas?


JavaScript not working in Firefox. Might be parseInt

Question: The following script is working perfectly in most browser but not at all in Firefox.
If anyone has any thoughts it would be a great help.
I have included jQuery
I am trying to make a sprite button.

AND the initial CSS:
#logo{
 background:url(circles2.jpg) 0px 0px no-repeat;
 height:40px;
 width:40px;
 display:block;
}

Comment: Can you be more specific than "not at all in Firefox"? Are you getting an error? Do you have one of the firefox developer add-ons (like webdeveloper) installed so you can see the specifics of the error?
Answer: Where you have var frame = $('#logo').css('background-position-x').split(' ');
I think you actually want var frame = $('#logo').css('background-position').split(' '); (remove the "-x").  That fixes it for me.
Comment: Yep.  There is no `background-position-x` CSS property in the spec.  Some browsers just sort of made it up.


How to Count - 3 balls in 3 boxes

Question: I've been spinning my wheels on this for an embarrassing amount of time. This is not for an assignment, I'm just studying.

Three balls are placed at random in
  three boxes. There is no restriction
  on the number of balls per box; list
  the 27 possible outcomes of this
  experiment.

I could only come up with 10 where order of placing the balls into the boxes doesn't matter.
{(0,0,3), (0,1,2), (0,2,1), (0,3,0), (1,0,2), (1,1,1), (1,2,0), (2,0,1), (2,1,0), (3,0,0)}
What am I doing wrong?
Comment: The problem wants you to treat the three balls as distinct.  (I realize this isn't obvious from the statement.  It's the only way to get 27 as the answer.)
Comment: Now I have the correct number; thank you. When I considered distinct I also included the order that balls are put into boxes, and the number for that was much larger than 27. However only considering distinctness without respect to order is perfect.
Answer: Using the stars-and-bars technique, for your interpretation of the problem, there are in fact ${3+3-1\choose 3}=10$ possible outcomes.
As Qiaochu Yuan said in his comment, 27 is the result when the three balls are distinguishable (and I agree with him that it is not clear in the problem statement)—for each of the 3 balls, there are 3 possible locations, so $3^3=27$ possible outcomes.

How to Count - 3 balls in 3 boxes


How to define array of arrays

Question: I am trying to fetch the Json data from Api which is in the following format
<code>     [
{
"id": "244",
"name": "PIZZAS",
"image": "",
"coupon": "1",
"icon": "",
"order": "1",
"aname": "",
"options": "2",
"subcategory": [
  {
    "id": "515",
    "name": "MARGARITA",
    "description": "Cheese and Tomato",
    "image": "",
    "icon": "",
    "coupon": "1",
    "order": "1",
    "aname": "",
    "options": "2",
    "item": [
      {
        "id": "1749",
        "name": "9 Inch Thin & Crispy Margarita",
        "description": "",
        "price": "3.40",
        "coupon": "1",
        "image": "",
        "options": "2",
        "order": "1",
        "addon": "495",
        "aname": "",
        "icon": ""
      },
      {
        "id": "1750",
        "name": "12 Inch Thin & Crispy Margarita",
        "description": "",
        "price": "5.20",
        "coupon": "1",
        "image": "",
        "options": "2",
        "order": "2",
        "addon": "496",
        "aname": "",
        "icon": ""
      }
      ]
  }
</code>
How can i fetch the "subcategory name" as well as " items name". Please help me out.I have written some codes and tried to fetch but not working.
<code>      var json: NSArray!
        do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSArray

        } catch {
            print(error)
        }

        self.AllData = json.valueForKey("subcategory") as! Array<String>
        print(self.AllData)
        print(self.AllData.count)
</code>
But its not fetching any value
Other way also I have tried but still no data fetching . only the data is coming in json1.
<code>    do {
            let json1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
           // print(json1)

            if let subcategory = json1["subcategory"] as? [[String: AnyObject]] {
                for subname in subcategory {
                    if let name = subname["name"] as? String {
                        print(name)
                    }
                    if let items = subname["item"] as? [[String: AnyObject]] {
                        for item in items {
                            if let itemName = item["name"] as? String {
                                print(itemName)
                            }
                        }
                    }
                }
            }
        } catch {
            print(error)
        }
</code>
Comment: Your error is that "subcategory" is not an array of Strings, it's an array of Dictionaries.
Comment: What exactly do you want in the category "SubCategory"?
Comment: i want to fetch the subcategory name and description as well in items , name and price
Comment: I am really stuck in it. please someone help me out
Comment: @pradip-kumar Please do not change the meaning of a question. Your edit removed the reason why OP was confused! Don't do this...
Comment: Ok thats good but I only change the question only because others can able to search the exact answer ,not again confused @eric
Answer: This may just be a problem when cutting and pasting into the question, but it looks like your JSON data isn't formatted correctly (the []s and {}s don't match up).  As the previous commentor said, you're dealing with an array of dictionaries not an array of strings.  Try something like this:
<code>do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

    if let subs = json[0]["subcategory"] as? [[String: AnyObject]] {
        for sub in subs {
            if let name = sub["name"] as? String {
                print(name)
            }
            if let items = sub["item"] as? [[String: AnyObject]] {
                for item in items {
                    if let itemName = item["name"] as? String {
                        print(itemName)
                    }
                }
            }
        }
    }
} catch {
    print(error)
}
</code>
Comment: I also have tried in the same way. but no data is coming. only response is coming.
Comment: the data is not coming in "subs" according to your code
Comment: Hey Pradip.  Have you tried the code I posted in your actual app, or just in a Playground?  When I run this code in an app it works fine, when I try it in a playground the second item name gets printed out twice... strange.  I think it must be a bug in playground.
Comment: Does your JSON actually start with a '[' as in the example you posted?  If so you may need to use: json[0]["subcategory"]
Comment: Did you try dereferencing the overall parsed JSON with json[0]["subcategory"].... instead of json["subcategory"]?
Answer: At first its an array of objects/Dictionary.And you are creating an array of string. Thats why for subcategory it will not work.You need to create an array of Dictionaries like this:
<code>        do {
            let json1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

            self.AllData = json1.valueForKey("name") as! Array<String>
            print(self.AllData)

            print("Number of menu = \(json1.count)")
            for var i in 0..<json1.count {
              print(" \n \(i+1) row menu \n")

                if let subs = json1[i]["subcategory"] as? [[String: AnyObject]] {
                    //print(subs)

                    for sub in subs {

                        if let name = sub["name"] as? String {
                            print("subcategory name= \t \(name)")
                            //print(name)
                        }

                        if let desc = sub["description"] as? String {
                            print("description= \t \(desc)")
                           // print(desc)
                        }

                }

                    print("Number of subcategory= \(subs.count)")
                    for var i in 0..<subs.count {

                     if let items = subs[i]["item"] as? [[String: AnyObject]] {
                     print("items = ")
                        print(items.count)
                       for item in items {
                            if let itemName = item["name"] as? String {
                                print(itemName)

                              }
                         }
                     }
                 }

                }

            }
                        }catch {
            print(error)
        }
</code>
Try this one it will work accoording to your json data
Comment: Maybe its better to use structs if you have always X with subcategories inside them and items inside subcategories. Its just cleaner.

How to define array of arrays


Audacity - Remove blank space on two track (3.1)

Question: How do I remove any selected blank space on a track in Audacity 3.1.3 ?
Before, I could just select it and click backspace/delete/cut and it would work.
Now it only works if a track is part of the selection.
Answer: Just left-click with your mouse on the top border of the adjacent clip. You get the hand symbol. Sometimes, it comes after pressing 'shift'. Drag the clip closer to the first clip. Similarly in all places where ypu have such dead blanks. Hope this helps.
Answer: I found this answer but it did not solve my problem, which was an entire track preceded by a gap that had no sound - just time at the top, and rounded edges what was now the second track. I ended up grabbing (with the mouse, holding the left button down) the entire track and moving it. A yellow line showed when I was flush with 0 seconds.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://music.stackexchange.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://music.stackexchange.com/help/whats-reputation), you can also [add a bounty](https://music.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/74910)
Comment: @Aaron I believe this does answer the question- "How do I remove any selected blank space" ... "it only works if a track is part of the selection."  I can't verify that it works, though, because I'm on a different version of Audacity.
Comment: @Edward "but it did not solve my problem."
Comment: I believe that is referring to the other answer posted by Ram, which he found before posting his own answer.


Wrong Intepretation of Kruskal Wallis Test in R

Question: I have some data (called egecNonmated) in R and I am trying to show that the distributions of a variable (MatchScore) are identical across three different Categories (Cat).  I am using a box plot to do this visually but it has been suggested (wisely) that I also show this quantitatively.  Below is the R code I am running to do the visual analysis:
allNm <- boxplot(MatchScore~Cat, data=egecNonmated)

Showing "allNm" produces the following graph:

Viewing the statistics associated with the boxplot via
allNm$stats

Produces the following:
          [,1]      [,2]      [,3]
[1,] 0.3988655 0.3982853 0.3988191
[2,] 0.4349543 0.4347747 0.4349721
[3,] 0.4478581 0.4478713 0.4479012
[4,] 0.4590152 0.4591016 0.4590747
[5,] 0.4951032 0.4953164 0.4952006

We can see that the median score [3,] for each of the categories is identical to three decimal places.  As are all the other statistics (lower whisker [1,], lower hinge [2,], upper hinge [4,] and upper whisker [5,].  So I would expect kruskal wallis to accept the null hypotheis that the three distributions are from identical populations.  However when  I run
kruskal.test(MatchScore ~ Cat, data=egecNonmated)

I get the following:
Kruskal-Wallis chi-squared = 15.5941, df = 2, p-value = 0.0004109

If I am interpreting this correctly tells me that at a p value of 0.01 I should reject the null hypothesis and therefore these distributions are NOT identical.  Am I using the wrong test?  Wrong interpretation?  Thanks in advance for the help
Comment: The third row is not the mean, but the median.
Comment: i might take a different tack than the answers below. Boxplots can hide significant differences in a variable when n is large. it is often worth - using domain knowledge - trying to think of different ways of presenting the data (tables or subgroup graphs)
Comment: @charles: Plotting the empirical distribution functions & kernel-smoothed density estimates can be useful.
Comment: You might also consider looking at measures of association
Comment: @Scortchi - Thank you for the recommendation. I've just started using kernal-smoothers and violin-plots. Still have a lot to learn before I have a good handle on them.
Answer: I don't think anything is amiss here.
The three distributions are very similar, but not identical (why would they be exactly the same, rather than different in very tiny ways?)
Your sample sizes are very large, so your hypothesis test can pick up extremely small differences, even trivial ones.
It's giving you information, but it's probably an answer to a question you don't actually care about very much (which suggests that you probably didn't actually want to test for identical distributions in the first place; it's likely you need a different tool for whatever your actual problem is).
Comment: Kruskal Wallis works *perfectly* on large $n$. Your problem isn't that the screwdriver doesn't work - it's great unless you try to hammer in nails with it. You need a different tool than null-hypothesis significance tests, but first you need to clearly identify the problem you want to solve. It might be best achieved by finding confidence intervals for location-shifts. It might be best achieved by some overall measure of effect size. It might be handled by equivalence tests. It might need something else ... which you might want depends on just what you're trying to achieve in the end.
Comment: @JHowIX I think it would be worthwhile for you to visit the question [Why does frequentist hypothesis testing become biased towards rejecting the null hypothesis with sufficiently large samples?](http://stats.stackexchange.com/questions/108911/why-does-frequentist-hypothesis-testing-become-biased-towards-rejecting-the-null/)
Comment: Hi Glen.  So I think "identical" was maybe a bit strong.  I just want to quantify the similarity in the distributions.  I thought kruskal wallis was the tool to do that but clearly not.  Do you know of a statistical method that is similar but will work on sets with large N?
Comment: @Alexis - Yes, this is exactly the explanation I needed.  Both yours an Glen_b's explanations have had me leaning toward using TOST (although my data isn't strictly normally distributed, but its close).  I am going to try that out this week instead of KW.  Thanks for the help.
Comment: @JHowIX You can apply TOST for nonparametric tests using *z* test approximations, it's a pretty straightforward translation of the approach from *t* to *z*.


Piecing together DRF, auth, and registration

Question: I want some advice on choosing right package in a REST Api django project

For authentication:Which one of below I should choose ?
django-oauth-toolkit: seems to be the most robust and recommended oauth library for DRF. This do not have account management. How can i implement account management with this package? If yes, can I get some guide.
django-rest-auth: API endpoints for authentication, and basic account management for DRF. But seems not as robust as django-oauth as django-oauth allows token expiery etc. or i am missing some feature of rest-auth

For authorisation: I will be going for  django-guardian  over django-role-permission. Later seems more like back end utility to control user roles.

My deep desire is to use oauth-toolkit but it does not have basic user management. On the contrary rest-auth has user management but lacks (seems to be) roubustness of oauth.
Please help me make a choice.
Comment: By basic user management I mean rest-auth has many api end points like user registration, pasaword change, confirmation on password chane.. Django-Outh Toolkit do not have those. So what to do? I need to write my own code for such functionality if I choose Django-autho.?
Comment: Dear ken4scholars, kindly go through my dilemma once again. Can you tell me how to implement user management in django-outh just like django-rest-auth? If no, then fine, if yes, any help is much much appreciated.
Comment: Yes as you said, oauth is the robust package you can use it for securing all you api's via token based authentication. Also What do you mean by basic user management ?
Comment: It sounds like you already know the pros and cons of each package, so why look up to others to make the choice for you? I doubt that is in line with the purpose of this site
Answer: I came to understand that DRF supports builtin support for OAuth2 and provides token utilising 'provider.oauth2'dependency hence django-oauth-toolkit could be avoided just in case.
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.OAuth2Authentication',
),
Thanks every one for your interest.
Answer: Django rest auth amounts to a small set of API views around django-allauth which is (according to github usage stats) much more used than oauth-toolkit.
allauth is pretty great and has a long list of available providers. Adding a new one is very easy and can nearly be completed 100% through the admin interface.
rest_auth essentially wraps django allauth to make it available via API. Where rest_auth falls short, it is fairly easy to implement what you need to work directly with allauth. If you need jwt support with rest_auth they recommend another 3rd party library.
The biggest problem with rest_auth we've run into is that the documentation is just OK and there are many open issues in the repo that should be closed with more clear resolution, there is a lot of misinformation in the issues.
Looking forward to resolving some of that confusion by inquiring as to the State of rest_auth
As far as your need for user management goes, django user management is robust as is.
Comment: Dear Mr. Wade, I ormally find allauth for social authorization. My Idea is to implement own authetication server using oauth rather than depending on social authentication. Problem is I am not able to find any api like send reset password mail etc in oauth-toolkit while  rest_auth has built in provision. So if I choose oauth-toolkit, i will not be able to send reset password mail etc as there is no api for this in oauth-toolkit. If you can guide me or suggest something for how to mange such kind of user related chores while using oauth-toolkit - Full marks, sir.


Game of pong ball is getting stuck at line in unity 3d 2020

Question: I am making a game called pong as we all no from this tutorial  https://www.youtube.com/watch?v=YHSanceczXY however my ball is getting stuck in the line that separates the two players I am using unity 2020 version 1.1.11f1 Personal DX 11

My Ball script is as follows
<code>public class Ball : MonoBehaviour
 {
  public float speed;
  public Rigidbody2D rb;
  // Start is called before the first frame update
  void Start()
  {
      Launch();
  }

  private void Launch()
  {
    float x = Random.Range(0, 2) == 0 ? -1 : 1;
    float y = Random.Range(0, 2) == 0 ? -1 : 1;
    rb.velocity = new Vector2(speed * x, speed * y);
  }
}
</code>
However speed of the ball is set to 5 as suggested in the tutorial

And the line object is setup as such

However i cannot figure out why my ball is getting stuck at the line. Do you guys be able to help thanks
Answer: Have you checked if the "Line" has a rigidbody/collider on it? this could be causing the collision system to get the ball stuck in it or on it.
just click on the line -> scroll down in the inspector -> check for a rigidbody or collider -> remove it if it is there.
//edit
i now see that you do have a box collider, if you need to check for collisions, set it to isTrigger else just remove it. that will probably fix the issue
Comment: thanks for the help some people can be so snobby
Comment: hahah, yeah i know. I hope it works! if it doesnt get back to me and ill do my best to get the right answer!


Passing data from outer preprocess to inner template

Question: I have two templates:
- a child that is printing each item in a list;
- and a parent that calls it
there is also an intermediate Field template that is not involved.
The parent has preprocess access to node field data that each child (node teaser) call needs to use. The child is printing items in a multivalue entity reference field.
How can the child get the data from the parent felds so it can print the right html?
Edit: Just in case it's not clear, the situation is:
<code>paragraph_entity        <== preprocess hook can see field_settingsN which change how "B" and "A" render (e.g. add/change attrs, class).
  -> field_settings_1
  -> field_settings_2
  -> field_references   <== have a defined template "B"
    -> 1.. entity refs to nodes
      -> node           <== have a defined (teaser) template "A"
</code>
Comment: 100% doable. Actually did this within the last week, answer coming right up.
Comment: I was hoping the parent can save some data in the environment of the child... is that possible?
Answer: Done this a couple times, but really got the caching better last time so that it works perfectly... I've put in some fairly verbose comments, but if anything is unclear just shout.
<code>/**
 * Implements HOOK_preprocess_paragraph().
 */
function HOOK_preprocess_paragraph(array &$vars) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $vars['paragraph'];
  // Change 'content_reference' to be your paragraph bundle's machine name.
  if ($paragraph->bundle() === 'content_reference') {
    // Instead of 10 set that to be the max number of references in the field.
    foreach (range(0, 10) as $i) {
      // Change all references to 'field_content_reference' to use your field's
      // machine name.
      if (!isset($vars["content"]["field_content_reference"][$i])) {
        break;
      }
      /** @var \Drupal\node\Entity\Node $node */
      $node = $vars["content"]["field_content_reference"][$i]["#node"];

      // Example change to the Node.
      $node->field_parent_paragraph = $paragraph;
      $changed = TRUE;

      if (isset($changed)) {
        // If we've changed the node, give a new cache id.
        // THIS IS IMPORTANT!
        $vars["content"]["field_content_reference"][$i]['#cache']['tags'][] = "paragraph:{$paragraph->id()}";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = "paragraph";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = $paragraph->id();
      }
    }
  }
}
</code>
Follow that up with something like:
<code>/**
 * Implements HOOK_preprocess_node().
 */
function HOOK_preprocess_node(array &$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $vars['node'];
  if (isset($node->field_parent_paragraph)) {
    $paragraph = $node->field_parent_paragraph;
    $vars['content']['#attributes']['class'][] = $paragraph->field_settings_1->value;
  }
}
</code>
Comment: That's great..For the sake of other readers, I presume in the second part the field_paragraph should be field_parent_paragraph?
Comment: Thanks, Nick. If I understand, you're setting a value on just the in-memory copy of referenced nodes, so when they are rendered they can look up their parent and determine the needed settings?
Comment: I don't want to risk saving such local changes, because a given referenced node may well be referenced from more than one place.
Comment: Pretty much. In that example I didn't actually set any parent reference - instead I set the title on the node to match an imaginary title field on the paragraph. I'll do a slight change actually to match your example need a bit better.
Comment: As long as you don't call $node->save() it won't save the changes anywhere.
Comment: @rivimey updates saved, showing how to access the whole paragraph from the node preprocess which can give you more flexibility.
Comment: ahem... yes that'd be a typo. fixed, thanks.


I've "lost my voice." What physically happened to my vocal physiology?

Question: I've been suffering from a mix of allergies and a cold over the past few days, and woke up this morning to find that overnight, my normal singing range of about F2 to G4 had been reduced and lowered to about Db2 to Ab2. I can breathe in and out through my nose, but I have a fair bit of sinus congestion elsewhere.
From the perspective of singing technique, mechanics, and physiology, what has happened to have this drastic of an effect on my range?
Answer: Inflammation.
What inflammation is is the engorgement of tissue with blood in response to that issue releasing a signaling chemical (histamine) that dilates blood vessels.  That is why inflamed tissue is redder than usual.  Theory is that the body has this response to rush additional white blood cells to the site of a lesion.  (An allergic reaction is one where the tissue releases histamines in confused response to something innocuous.)
Tissue that is full of blood is thicker, heavier, and stiffer.  Since vocal sound production is actuated by vibrating tissue (the vocal cords), when that tissue is inflamed, the vibrating  apparatus is thicker, heavier, and stiffer.  In the same way a thicker, heavier, stiffer guitar string sounds lower than a thinner, lighter, more flexible one, vocal cords which are afflicted with inflammation will sound lower than they otherwise do.
P.S.  Singing on inflamed vocal cords will make the inflammation worse, by irritating them further.
Comment: Agreed with Codeswitcher here - drink lots of water and rest, and don't sing. Singing with inflamed vocal cords can damage them (even though it is awesome to sing the really low notes...).


how to disable the textbox in jquery?

Question: If i have to enter any value in that text box and press tab button. text box will remove and value should be display. like this way $('#txt').val();
Please help me how to do?
Answer:

<input type='text' id='txt'>

//If you don't require a tab push
$('#txt').live('blur'){
   var value = $(this).val();
   if(value){
      $(this).parent().html(value);
   }
}

//If you want tab only
$('#textbox').live('keydown', function(e) {
  var keyCode = e.keyCode || e.which;

  if (keyCode == 9) {
    e.preventDefault();
    var value = $(this).val();
    if(value){
        $(this).parent().html(value);
     }
  }
});

As others have stated, if you can't change your HTML markup to conform above...
$('#txt').blur(function(){
    $(this).hide().after($(this).val());
});

Comment: That's a dangerous one. If he has multiple form fields in the same container, they'll all be deleted by your solution :)
Comment: Hens why I showed the div structure...there should be a div wrapping it to make it that much easier....  Planning your HTML sometimes is just as important as your jQuery code.
Comment: Your solution forces the OP to abide by your DOM is all I'm saying. You have no idea what his form looks like, so you can't really assume he's able to change the entire structure.
Comment: True, but maybe he doesn't have an issue with it either...  I like your way too...but there's more than one way to fry a fish.  My brain went immediately to this method cause I have a few recent scripts that I can click to create a form element, then change, then blur and it saves automatically...  And thanks for the mark down...shows you have a good sense of community effort!  ;) Night.
Comment: HEHE, it's not stealing if I contribute it to the response of others (and you suggested it as a format change on my post)... And I probably should have referenced the other guys answer since it actually considers the tab key press... Anyways, I got better things to do than argue with you...  See you around..
Answer: Shooting from the hip here.  Is this what you are looking for?
$('input[type="text"]').blur(function() {
  $(this).hide().after($('').text($(this).val()));
});

$('input[type="text"]').keydown(function (e) {
  if (e.keyCode == 9) {
    $(this).hide().after($('').text($(this).val()));
  }
});

Answer: Try this:
$('#txt').blur(function(){
    $(this).hide().after($(this).val());
});

Working example: http://jsfiddle.net/AlienWebguy/Jdf5m/1/

how to disable the textbox in jquery?


QML StackView, how to navigate within the pushed item?

Question: My app has a stackview that has two QML files.
And I need to navigate from one QML file to another from inside that QML file itself where I won't have access to stackview to push or pop.
How should I design this?
Main.qml
Rectangle
{
   id: mainBkg
   color: "white"
   width: Screen.width
   height: Screen.height

    //Tickes every globalTimer.interval
    property int globalTick: 0

     Statusbar
     {
        width: Screen.width
        height: Screen.height*0.2
        id: statusBar
        Rectangle
        {
         width: parent.width
         height: parent.height*0.2
         anchors.fill: parent
         color: "green"

         Text {
            id: t
            text: qsTr("QMLfile1")

         }
       }
     }//end of statusbar

    StackView {
        id: stackView
        anchors.top: statusBar.bottom
        anchors.centerIn: parent

        //What should be here? So that stackView
        //will be available inside the loaded items.
        initialItem:
    }
}

Following are the two QML files:
QMLfile1.qml
Rectangle
{
    width: parent.width
    height: parent.height*0.2

    anchors.fill: parent
    color: "green"

    Text {
        id: t
        text: qsTr("QMLfile1")

    }
    MouseArea:{
      onClicked: //move to other QML file in stackview
    }
}

I have another QML file like the above one.
Comment: Please share some code to boost my imagination.
Comment: You should provide any source code describing your code. What does  you mean saying "I won't have access to stackview"?
Comment: sorry for that. I have updated with code. The reason why I didn't add code is because the sample StackView code's are like that.
Answer: You have tons of options.
One would be, to add a signal to the root-element of the QMLfile1.qml, and connect to it in the main.qml. The change will be performed there.
You can also add a property var callback to the root-element of the QMLfile1.qml where you inject the push-method of the StackView when instantiating it.
Finally you can just not shadow the id of the StackView and access it across file boundaries. I generally don't like that.
Comment: Hi thanks. Can you please provide me an example code?
Comment: Sorry, I have very little time right now. Could you outline your planed usecase a bit more? That would help me to know, which option suits you the best... If any at all. It might be very well, that a `StackLayout` or `SwipeView` might be more what you are looking for.
Comment: Thanks :) I figured it out how to do it. I created components of each QML file in the QML file where I have the StackView.


How to get name in php api in android

Question: In android how to get like,
<code> {
categories: [
{
id: "20",
name: "health",
created_at: "2016-07-15 10:17:51",
updated_at: "2016-07-15 10:17:51",
color: "#0d5a91",
parent_id: "0",
order: "0"
},
{
id: "21",
name: "fashion",
created_at: "2016-07-15 10:23:00",
updated_at: "2016-07-15 10:23:00",
color: "#c732bd",
parent_id: "0",
order: "0"
},
{
id: "22",
name: "people",
created_at: "2016-07-15 12:42:47",
updated_at: "2016-07-15 12:42:47",
color: "#c7323e",
parent_id: "0",
order: "0"
},
],
success: 1
}
</code>
Comment: First of all you need to solve to syntax problem of your api json
Comment: There are at least a billion tutorials around to fetch and parse data
Comment: what is syntax probllem buddy..? i know there is so billion tutorials around it but i need success tag and name tag...how it is possible there is not any tutorioal on internet..
Answer: First of all, the json format is wrong
<code>{
    "categories": [
        { "id": "20", "name": "health", "created_at": "2016-07-15 10:17:51", "updated_at": "2016-07-15 10:17:51", "color": "#0d5a91", "parent_id": "0", "order": "0" },
        { "id": "21", "name": "fashion", "created_at": "2016-07-15 10:23:00", "updated_at": "2016-07-15 10:23:00", "color": "#c732bd", "parent_id": "0", "order": "0" },
        { "id": "22","name": "people", "created_at": "2016-07-15 12:42:47", "updated_at": "2016-07-15 12:42:47", "color": "#c7323e", "parent_id": "0", "order": "0" }
    ],
    "success": 1
}
</code>
Next use
<code>JSONObject response = (JsonObject) someStringValueAsResponseFromAPICall;
JSONArray array = response.optString("categories");
JSONObject innerObject = array.optJSONObject(position);
String success = response.optString("success");
</code>
Note: Use "opt"JSONObject/JSONArray/String instead of "get"JSONObject/JSONArray/String, this will avoid errors but lookout for null pointer exceptions
Answer:
Your json should be like this

<code>{
"categories":[
{
"id":"20",
"name":"health",
"created_at":"2016-07-15 10:17:51",
"updated_at":"2016-07-15 10:17:51",
"color":"#0d5a91",
"parent_id":"0",
"order":"0"
},
{
"id":"21",
"name":"fashion",
"created_at":"2016-07-15 10:23:00",
"updated_at":"2016-07-15 10:23:00",
"color":"#c732bd",
"parent_id":"0",
"order":"0"
},
{
"id":"22",
"name":"people",
"created_at":"2016-07-15 12:42:47",
"updated_at":"2016-07-15 12:42:47",
"color":"#c7323e",
"parent_id":"0",
"order":"0"
}
],
"success":1
}
</code>

Try this to get name or others

<code> JSONObject jsonObject=new JSONObject(response);
    try {
    String success=String.valueOf(jsonObject.getString("success")) ;

    JSONArray jsonArray=jsonObject.getJSONArray("categories");

    for (int i=0; i<jsonArray.length();i++)
    {

            JSONObject jsonCategoryObject=jsonArray.getJSONObject(i);

        String name=jsonCategoryObject.getString("name");

        String id=jsonCategoryObject.getString("id");

        String created_at=jsonCategoryObject.getString("created_at");

        String updated_at=jsonCategoryObject.getString("updated_at");

        String color=jsonCategoryObject.getString("color");
        String order=jsonCategoryObject.getString("order");
        String parent_id=jsonCategoryObject.getString("parent_id");
        }
    }

    catch (JSONException e) {
        e.printStackTrace();
    }
</code>
Comment: public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String name="";
                JSONObject jsonObject=new JSONObject();
                try {
                    String success=jsonObject.getString("success");
                    JSONArray array=jsonObject.getJSONArray("categories");

                    for(int i=0;i<array.length();i++) {
                        JSONObject obj = array.getJSONObject(i);
                        name = obj.getString("name");
               }
Comment: You take the name outside the for loop check the code
Comment: Success here Integer value... take    String.valueOf(jsonObject.getString("success"))  ;
Comment: Other take 1 in double quato to response 1  "success": "1"
Comment: JSONObject jsonObject=new JSONObject(response) Aree You Pass the response in json

How to get name in php api in android


Inheritance - Creating a class Commission Employee from class Employee and testing

Question: Good Morning, I've been given the assignment to:
 rewrite the CommissionEmployee class as a subclass of Employee. CommissionEmployee should contain only the instance variables and methods that are not declared in superclass Employee. CommissionEmployee's constructor should invoke Employee's constructor and CommissionEmployee's toString method should invoke Employee's toString method.
Create a Driver class to test your new CommissionEmployee class. Prompt the user to input the first name, last name, social security number, gross sales, and commission rate and create a CommissionEmployee object, using the toString method to print its information.
The issue I seem to be having is class CommissionEmployeeTest will not output what I've placed in my toString method of class CommissionEmployee. I feel like like my superclass Employee is correct as well as me test class but my belief is the error lies somewhere in the method I've created to determine the earnings. The output I'm looking for is
Employees First Name Last Name
Social Security NUmber
Earnings
Earnings would be the total of gross sales + (commission rate * gross sales)
Here is what I have along with the error:
class Employee
public class Employee extends Object {

    protected final String firstName;
    protected final String lastName;
    protected final String socialSecurityNumber;

    public Employee(String firstName, String lastName, String socialSecurityNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.socialSecurityNumber = socialSecurityNumber;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getSocialSecurityNumber() {
        return socialSecurityNumber;
    }

    @Override

    public String toString() {
        return String.format(firstName, lastName, socialSecurityNumber);
    }
}

class CommissionEmployee
public class CommissionEmployee extends Employee {

    private double grossSales;
    private double commissionRate;
    private double earnings;

    public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales,
            double commissionRate, double earnings) {
        super(firstName, lastName, socialSecurityNumber);

        if (grossSales < 0.0)
            throw new IllegalArgumentException("Gross sales must be >= 0.0");

        if (commissionRate <= 0.0 || commissionRate >= 1.0)
            throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");

        this.grossSales = grossSales;
        this.commissionRate = commissionRate;
    }

    public void setGrossSales(double grossSales) {

        if (grossSales < 0.0)
            throw new IllegalArgumentException("Gross sales must be >= 0.0");
        this.grossSales = grossSales;
    }

    public double getGrossSales() {
        return grossSales;
    }

    public void setCommissionRate(double commissionRate) {

        if (commissionRate <= 0.0 || commissionRate >= 1.0)
            throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
        this.commissionRate = commissionRate;
    }

    public double getCommissionRate() {
        return commissionRate;
    }

    public Double earnings(double d) {
        return earnings(grossSales+ (commissionRate * grossSales));
    }

    public double getEarnings() {
        return earnings;
    }

    public void setEarnings(double earnings) {
        this.earnings = earnings;
    }
    @Override

    public String toString() {

        return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f%n%s: %.2f%n%s",
                "commission employee", firstName, lastName,
                "social security number", socialSecurityNumber,
                "Total earnings", earnings(earnings));
    }

    public void setFirstName(String firstName) {
    }

    public void setLastName(String lastName) {
    }

    public void setSocialSecurityNumber(String socialSecurityNumber) {
    }

    public void setGrossSales(String grossSales) {
    }

    public void setCommissionRate(String commissionRate) {
    }
}

class CommissionEmployeeTest
  //CommissionEmployee test program.
 import java.util.Scanner;

  public class CommissionEmployeeTest {
     public static void main(String[] args) { // instantiate CommissionEmployee object

        CommissionEmployee employee =
           new CommissionEmployee(null, null, null, 0, .1, 0);

        Scanner input = new Scanner(System.in);

       // get commission employee data
       System.out.printf(
          "Employee information obtained by get methods:%n");

       System.out.printf("Enter employee's First name:");
               String firstName = input.nextLine();
               employee.setFirstName(firstName);

       System.out.printf("Enter employee's last name:");
               String lastName = input.nextLine();
               employee.setLastName(lastName);

       System.out.printf("Enter employee's social security number:");
               String socialSecurityNumber = input.nextLine();
               employee.setSocialSecurityNumber(socialSecurityNumber);

       System.out.printf("Gross sales for employee:");
               String grossSales = input.nextLine();
               employee.setGrossSales(grossSales);

       System.out.printf("Commission rate for employee:");
               String commissionRate = input.nextLine();
               employee.setCommissionRate(commissionRate);

        System.out.printf("%n%s:%n%n%s%n",
            "Updated employee information obtained by toString",

          employee.toString());
    }
  }

Error
Employee information obtained by get methods:
Enter employee's First name:John
Enter employee's last name:Doe
Enter employee's social security number:123456789
Gross sales for employee:4000.00
Commission rate for employee:.1
Exception in thread "main" java.lang.StackOverflowError
    at CommissionEmployee.earnings(CommissionEmployee.java:45)
I've tried manipulating my toString method in CommissionEmployee as well as my method to determine earnings but I feel like I'm spinning my wheels.  I appreciate any help.  I have 1 week left in class and feel like I can contribute more information each week when I post a question then I did the last.  Thank you in advance.
Answer: I have resolved the issue. After reviewing and revising(several times) I have found my answer.   I needed revision on my toString method as well as my earnings method.  Cleaned up quite a bit of the code and resolved.
Comment: Don't have a method named the same as an instance variable.


Analysis: Composition of a regulated function and a continuous function

Question: What would be an example which proves that the composition of a regulated function $f: [-1, 1] \to \mathbb{R}$ and a continuous function $g: [-1, 1] \to [-1, 1]$, of the form $f \circ g$ may not necessarily be regulated? And how is it so?
Answer: Here is the example from http://users.math.cas.cz/~tvrdy/Cichon.pdf
"In contrast to the case of continuous functions the composition of regulated functions need not to be regulated.  The simplest example is a composition $(g \circ f)$ of functions $f, g: [0,1] \to \mathbb R: f(x) = x·sin(1/x)$ and $g(x) = sgn( x) $ ($f$ continuous and both  regulated), which has no one-side limits at 0.  Thus even a composition of a regulated and continuous functions need not to be regulated".
(the sign function has values $+1$ for $x > 1$; $0$ for $x = 0$ and $-1$ for $x < 1$)
How it is so ? is interesting.......
Suppose that $g$ is regulated and has left and right limits $g(a-)$ and $g(a+)$ at a point $a$, but the limits differ, and $f$ is continuous with some $x$ having $f(x) = a$. While $f$ is continuous at $x$, $f(x)$ can oscillate either side of $a$ as x is approached from the right (getting ever closer). But then $g(f(x))$ will oscillate between values ever closer to the left and right limits $g(a-)$ and $g(a+)$ which differ. So, $g(f(x))$ with not have a right limit as x is approached from the right.
This is what is happening in the example.
For interest, the opposite composition with a continuous function of a regulated function is regulated. See for example Composition of regulated functions on $[0,1]$}


update customerDomain returns 400 for Google Apps for work account when changing primary domain

Question: This is a Google Apps for Work account.
It has one primary domain, and one secondary.
It is not believed to have been a primary domain created via Google, but rather directly by GoDaddy and then added to google during the account creation.
Here is the result of the TryItNow call from the Google Developers Directory API page:
<code>PUT https://www.googleapis.com/admin/directory/v1/customers/my_customer?fields=customerDomain&key={YOUR_API_KEY}
{
 "customerDomain": "I PUT MY SECONDARY DOMAIN HERE"
}
</code>
Response:
<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid Input"
   }
  ],
  "code": 400,
  "message": "Invalid Input"
 }
}
</code>
Comment: I think in this method you should use your actual customerKey instead of "my_customer".
Comment: I will try... But I did use GET on the directory and used my_customer and it worked fine.
Answer: Questions,
1 - Are you a Google Apps reseller? Won't work if so
2 - Was your current primary domain bought through Google on sign up? Won't work if so :(
- https://support.google.com/a/answer/6301932
If these aren't the issue then I suspect you've added the domain as an alias rather than a secondary domain. Can you confirm it doesn't say 'Alias' next to the domain inside the 'Domains' tab of your Admin Console?
Comment: 1. No not an apps reseller, 2. No - the domain was not bought through Google ( which is a weird issue but oh well). I did originally add it as an alias, but I removed it and added it as a secondary. Perhaps all state not cleaned out ? I did wait several hours between the change just in case.
Answer: Please make sure you follow this steps,

Navigate to the Google Developers article at:
https://developers.google.com/admin-sdk/directory/v1/reference/customers/update.

Under "Try it!" select "Authorize requests using OAuth 2.0"
In the "Select OAuth 2.0 scopes" window, click "AUTHORIZE"
In the "customerKey" field, enter: "my_customer" (without quotes)
In the "Request body" field, click the "-- add a property --" drop down
Select "customerDomain"
Enter the secondary domain name that should be set as the primary domain
Click "EXECUTE"
If the primary domain has been renamed successfully, a "200 OK" message will displayed

This should work just fine if you are logged in with the right admin account, you are not a reseller and you don't have any Chrome devices on that domain.
Hope it helps,
Radu