Stopwatch error, help!! - java.lang.NumberFormatException: Invalid int: "0:00"

Question: When I run this I'm getting this number format error. It only seems to happen when I comment out the lines in the OnLocationChanged method to test if the views will display and calculate the right speed or not, any help would be much appreciated :)
package com.nathan.trackrun;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import android.content.pm.ActivityInfo;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 *
 */

public class FragmentStats extends Fragment implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

    public FragmentStats() {
        // Required empty public constructor
    }

    LocationManager statsManager;
    TextView speedView;
    TextView speedUnit;
    TextView unitView;
    TextView timerView;
    TextView distanceView;
    TextView distanceUnit;
    ToggleButton buttonStart;
    Button buttonSave;
    Button buttonReset;
    ToggleButton buttonSpeedUnit;
    String mySpeedString;
    String kmhString = "Km/h";
    boolean checkSpeedUnit;
    private LocationRequest statsLocationRequest;
    private LocationClient statsLocationClient;
    FragmentMap fMap;
    Chronometer stopwatch;
    String chronoText;
    boolean reset;

    public static boolean startStop;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        View viewStats = inflater.inflate(R.layout.fragment_stats, container,
                false);

        // Reference buttons from XML into Java
        buttonStart = (ToggleButton) viewStats
                .findViewById(R.id.stats_start_button);
        buttonSave = (Button) viewStats.findViewById(R.id.save_button);
        buttonReset = (Button) viewStats.findViewById(R.id.reset_button);
        buttonSpeedUnit = (ToggleButton) viewStats
                .findViewById(R.id.speed_unit_button);
        speedView = (TextView) viewStats.findViewById(R.id.speed_int);
        speedUnit = (TextView) viewStats.findViewById(R.id.speed_unit);
        stopwatch = (Chronometer) viewStats.findViewById(R.id.stopwatchView);
        distanceUnit = (TextView) viewStats.findViewById(R.id.disctance_unit);
        distanceView = (TextView) viewStats.findViewById(R.id.distance_int);

        /*
         * buttonReset.setOnClickListener(new View.OnClickListener() {
         *
         * @Override public void onClick(View v) { // TODO Auto-generated method
         * stub
         *
         * pausedMilliseconds = 0;
         *
         * stopwatch.setBase(SystemClock.elapsedRealtime()); reset = true;
         *
         * } });
         */

        buttonStart
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        // TODO Auto-generated method stub

                        reset = false;
                        if (isChecked) {

                            int pausedMilliseconds;
                            pausedMilliseconds = 0;
                            String chronoText = stopwatch.getText().toString();
                            String chronoArray[] = chronoText.split(":");

                            if (chronoArray.length == 2) {

                                pausedMilliseconds = Integer
                                        .parseInt(chronoArray[0])
                                        * 60
                                        * 1000
                                        + Integer.parseInt(chronoArray[1])
                                        * 1000;

                            } else if (chronoArray.length == 3) {

                                pausedMilliseconds = Integer
                                        .parseInt(chronoArray[0])
                                        * 60
                                        * 60
                                        * 1000
                                        + Integer.parseInt(chronoArray[1])
                                        * 60
                                        * 1000
                                        + Integer.parseInt(chronoArray[2])
                                        * 1000;
                            }

                            stopwatch.setBase(SystemClock.elapsedRealtime()
                                    - pausedMilliseconds);
                            stopwatch.start();

                        }

                        else {

                            stopwatch.stop();
                        }

                    }
                });

        buttonSpeedUnit
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        // TODO Auto-generated method stub

                        if (isChecked == true) {
                            checkSpeedUnit = true;
                            speedUnit.setText("Km/h");
                            distanceUnit.setText("KM");

                        } else {
                            checkSpeedUnit = false;
                            speedUnit.setText("Mph");
                            distanceUnit.setText("Miles");
                        }

                    }
                });

        buttonSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

        return viewStats;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        statsLocationRequest = LocationRequest.create();
        statsLocationRequest
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
        statsLocationRequest.setInterval(5000);
        // Set the fastest update interval to 1 second
        statsLocationRequest.setFastestInterval(1000);
        statsLocationClient = new LocationClient(this.getActivity()
                .getApplicationContext(), this, this);
        statsLocationClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        //Below line commented out and replaced with mySpeed dummy value to see if it works
        // if (location.hasSpeed()) {
        float mySpeed = location.getSpeed();
        mySpeed = (float) 5.5;
        float distanceUpdater = Integer.parseInt((String) stopwatch.getText())
                * mySpeed;
        float distance = 0;
        String distanceString;
        distance = distance + distanceUpdater;

        if (checkSpeedUnit == true) {

            mySpeed = (float) (mySpeed * 3.6);
            distance = (float) (distance / 1000);
            distanceString = Float.toString(distance);
            mySpeed = 1;
            distanceView.setText(distanceString);
            mySpeedString = Float.toString(mySpeed);
            speedView.setText(mySpeedString);
        }

        if (checkSpeedUnit == false) {

            mySpeed = (float) (mySpeed * 2.237);
            distance = (float) (distance * 0.000621371192);
            distanceString = Float.toString(distance);
            mySpeed = 1;
            distanceView.setText(distanceString);
            mySpeedString = Float.toString(mySpeed);
            speedView.setText(mySpeedString);

        }

    }

    // }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        // TODO Auto-generated method stub
        statsLocationClient.requestLocationUpdates(statsLocationRequest, this);

    }

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

    }

}

Logcat:
12-01 20:59:19.715: D/ActivityThread(29203): handleBindApplication:com.nathan.trackrun
12-01 20:59:19.715: D/ActivityThread(29203): setTargetHeapUtilization:0.75
12-01 20:59:19.715: D/ActivityThread(29203): setTargetHeapMinFree:2097152
12-01 20:59:19.875: I/u(29203): Making Creator dynamically
12-01 20:59:19.925: I/Google Maps Android API(29203): Google Play services client version: 4452000
12-01 20:59:19.925: I/Google Maps Android API(29203): Google Play services package version: 6587038
12-01 20:59:20.505: W/ActivityThread(29203): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
12-01 20:59:20.685: I/Adreno-EGL(29203): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LNX.LA.18.104.22.168_RB1.04.04.04.087.028_msm8974_LNX.LA.18.104.22.168_RB1__release_AU ()
12-01 20:59:20.685: I/Adreno-EGL(29203): OpenGL ES Shader Compiler Version: E031.24.00.15
12-01 20:59:20.685: I/Adreno-EGL(29203): Build Date: 07/31/14 Thu
12-01 20:59:20.685: I/Adreno-EGL(29203): Local Branch:
12-01 20:59:20.685: I/Adreno-EGL(29203): Remote Branch: quic/LNX.LA.126.96.36.199_rb1
12-01 20:59:20.685: I/Adreno-EGL(29203): Local Patches: NONE
12-01 20:59:20.685: I/Adreno-EGL(29203): Reconstruct Branch: AU_LINUX_ANDROID_LNX.LA.126.96.36.199_RB1.04.04.04.087.028 +  NOTHING
12-01 20:59:20.705: D/OpenGLRenderer(29203): Enabling debug mode 0
12-01 20:59:20.915: I/Timeline(29203): Timeline: Activity_idle id: android.os.BinderProxy@418b7b90 time:109078101
12-01 20:59:26.185: D/AndroidRuntime(29203): Shutting down VM
12-01 20:59:26.185: W/dalvikvm(29203): threadid=1: thread exiting with uncaught exception (group=0x415ffdb8)
12-01 20:59:26.195: E/AndroidRuntime(29203): FATAL EXCEPTION: main
12-01 20:59:26.195: E/AndroidRuntime(29203): Process: com.nathan.trackrun, PID: 29203
12-01 20:59:26.195: E/AndroidRuntime(29203): java.lang.NumberFormatException: Invalid int: "0:00"
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.Integer.invalidInt(Integer.java:137)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.Integer.parse(Integer.java:374)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.Integer.parseInt(Integer.java:365)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.Integer.parseInt(Integer.java:331)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at com.nathan.trackrun.FragmentStats.onLocationChanged(FragmentStats.java:205)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at com.google.android.gms.internal.hb$a.handleMessage(Unknown Source)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at android.os.Looper.loop(Looper.java:136)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at android.app.ActivityThread.main(ActivityThread.java:5146)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.reflect.Method.invokeNative(Native Method)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at java.lang.reflect.Method.invoke(Method.java:515)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
12-01 20:59:26.195: E/AndroidRuntime(29203):    at dalvik.system.NativeStart.main(Native Method)

Answer: Well, your code here
float distanceUpdater = Integer.parseInt((String) stopwatch.getText()) * mySpeed;

is going to be string data with a : character.  You would have to parse the data that you are working with.
String[] parsedMinutesAndSeconds = stopWatch.getText().split(":");
String minutes = parsedMinutesAndSeconds[0];
String seconds = parsedMinutesAndSeconds[1];

And then you can parse the integers of these two fields and work with them.  Worth doing checks on whether or not there are 2 or three fields for hours as well or no minutes available depending on how the clock works.
Comment: oh damn yeahhh!! cheers dude i see that now, thanks XD been working on this app solidly, guess i let that slip through the net ;)


What chord is formed by the notes B, G, B?

Question: What chord is formed by the notes B, G, B? My guess it is an augmented chord where the 3rd is omitted. thank you
Comment: Other comments are correct, but I would add that it depends on what the bassist is doing!
Comment: Correct.  This is a dyad, not a chord.
Comment: Relevant: https://music.stackexchange.com/questions/51396/a-chord-is-three-notes-what-do-you-call-just-two-notes
Comment: Is there something else to your example that you haven't mentioned? Implying an augmented triad seems doubtful.
Comment: Whatever it is, it's almost surely not an augmented chord. I agree with Michael that it's most likely G major (and by default it sounds like it). But it still depends on the context, which you didn't provide, because it is possible for it to be E minor.
Comment: Huh, my first guess was an inverted major chord with the 5th omitted. ...Of course, some will make the argument here that a "chord" with only 2 pitch classes is not a chord at all.
Answer: More context about where this is found will make the case clearer, but as is we can still make a plausible claim.
Regarding comments about chords and 2 tones, 3 tones, etc.

Chords are abstract conceptions, you must analyze to identify chords
Theorists differ on their definitions of "chord." When the context is triad and triadic harmony, the definition is three tones, stacked in thirds. When the context is not specifically triadic any number of simultaneous tones - including only two - can constitute a chord.

Don't be distracted by the conversation about "dyads." You can use a polyadic term if you want, but the only commonly used one is "triad." The same folks that like to call an incomplete chord a "dyad" do not call seventh chord "tetrads" or ninth chords "pentads."
A chord is simply the main element of harmonic function regardless of how many tones are used.
Case in point: you could make a harmonic analysis, which is the identification of chords, of Bach's Two-Part Inventions. That the analysis would be based on dyads, incomplete chords, is beside the point.
Your item is tones B G B.
In tertian harmony, which for all practical purposes is all tonal harmony, makes chords of thirds "stacked" above a root.
For analysis purposes, just reverse that process. Take your collection of tone and re-arrange them in ascending thirds, the root of the chord is then the bottom tone...

G B B

...the root of your chord is G and the B above forms a major third, so the basic chord quality is major. If the chord were a complete triad, then it would need a D, but there is not one, so you can call the chord incomplete.
You have an incomplete G major chord.
As I mentioned before, it would be better to see this in harmonic context to make a claim about a chord. Other analysis is possible depending on the context. For example, if the Bs were held while the G descending to F#, it could make sense to say B G B is not your chord, the G is a non-chord tone resolving to the chord tone F#, and the chord is some kind of incomplete B chord.
A harmonic context where your chord might appear and be understood clearly as a G major chord could be something like...

...your chord in the red box, and incomplete chords marked with *. Incomplete triads and seventh chord like than are completely ordinary, and present no problem being identified as chords.
Comment: @Tim, I'm using "incomplete chord" for convenience to cover both "incomplete triad", "incomplete seventh chord", etc. Comparison to units of measure are bad, they are specific and discrete, not abstractions.
Comment: @Tim "I'd really like to be convinced 2 notes constitute a chord, but have failed so far." Could you do a Roman numeral analysis of Bach's first two part invention? Yes or no?
Comment: So a dyad is an incomplete chord. That makes it not a chord. If I run an incomplete mile, I've not run that mile. Ask for a kilo of spuds, don't expect to get an incomplete kilo! The bigger problem is what one calls any dyad. Since it's an interval, there's its name.G>B is M3, B>G is m6. I'd really like to be convinced 2 notes constitute a chord, but have failed so far. Impossibility of  naming doesn't help. If that's pedantic, so be it.
Comment: @JasonPSallinger, unfortunately the question needs to be answer in terms of what it could be, because the given chord is not shown in a real harmonic context. Instead of making analogies to chemistry, post an answer that shows how harmony is _actually_ analyzed.
Comment: It's just prefixes https://en.wikipedia.org/wiki/Unit_prefix and a suffix https://en.wiktionary.org/wiki/-ad#English, I supposed you could use "quartad", but it's not commonly used. That's part of my point about "dyad." "It's not a chord it's a dyad" is pedantic. The important thing to explain about common theory terminology and concepts is "incomplete chord."
Comment: Defining something by what it could be instead of what it is misleads the true nature of that thing.  Water - two parts hydrogen, one part oxygen - is not called "incomplete organic matter".  It is completely inorganic.  There is no mistaking what water is.  It can only be defined by what it contains, not what it could become if it only had another element.
Comment: Weird, I thought I read someone mention a "tetrad" (somehow never a "quartad") for a 4-note chord.
Answer: Most of us (I hope!) agree that with only two notes, it's very difficult to name it as a chord. Having 3 different notes makes it so much easier.
A chord to be named will need a root note - otherwise we can't even start to give it a name, surely. Most, but not all, will have a 3rd - be it M3 or m3.
BGB could be construed as G major - the 5 (D) often sounding as a harmonic of the G. or - it could be construed as B+ - except there's no 3, so it's unlikely.
It could be - and is - part of a chord - Cmaj7, Em, come to mind, and with enough knowledge of what harmony surrounds it, a name could be invented. But a lot of us won't consider it to be any more than the dyad it is.


Should degrees of freedom corrections be used for inference on GLM parameters?

Question: This question is inspired by Martijn's answer here.
Suppose we fit a GLM for a one parameter family like a binomial or Poisson model and that it is a full likelihood procedure (as opposed to say, quasipoisson). Then, the variance is a function of the mean. With binomial: $\text{var}[X] = E[X]E[1-X]$ and with Poisson $\text{var}[X] = E[X]$.
Unlike linear regression when the residuals are normally distributed, the finite, exact sampling distribution of these coefficients is not known, it is a possibly complicated combination of the outcomes and covariates. Also, using the GLM's estimate of the mean, that be used as a plugin estimate for the variance of the outcome.
Like linear regression, however, the coefficients have an asymptotic normal distribution, and so in finite sample inference we can approximate their sampling distribution with the normal curve.
My question is: do we gain anything by using the T-distribution approximation to the sampling distribution of the coefficients in finite samples? On one hand, we know the variance yet we don't know the exact distribution, so a T approximation seems like the wrong choice when a bootstrap or jackknife estimator could properly account for these discrepancies. On the other hand, perhaps the slight conservatism of the T-distribution is simply preferred in practice.
Comment: good question. You might want to look at *Bartlett corrections*.
Comment: I think this question is ill posed, when using MLE or QMLE you only have asymptotically justified estimation and inference. asking if assumption A or B is better in finite settings cannot be answered, it will always boil to the mundane "depends on the data and the which assumptions you are willing to make". Personally I like bootstrapping, and use it whenever I can, but it is no more wrong that using standard z or t based test - it does not allow you to escape the small data problem, and so you are still making assumptions (just different ones)
Answer: Short answer: Not a full answer yet, but you might be interested in the following distributions related to the linked question: It compares z-test (as also used by glm) and t-test
<code>    layout(matrix(1:2,1,byrow=TRUE))

    # trying all 100 possible outcomes if the true value is p=0.7
    px <- dbinom(0:100,100,0.7)
    p_model = rep(0,101)
    p_model2 = rep(0,101)
    for (i in 0:100) {
      xi = c(rep(1,i),rep(0,100-i))
      model = glm(xi ~ 1, offset=rep(qlogis(0.7),100), family="binomial")
      p_model[i+1] = 1-summary(model)$coefficients[4]
      model2 <- glm(xi ~ 1, family = "binomial")
      coef <- summary(model2)$coefficients
      p_model2[i+1] = 1-2*pt(-abs((qlogis(0.7)-coef[1])/coef[2]),99,ncp=0)
    }

    # plotting cumulative distribution of outcomes z-test
    outcomes <- p_model[order(p_model)]
    cdf <- cumsum(px[order(p_model)])
    plot(1-outcomes,1-cdf,
         ylab="cumulative probability",
         xlab= "calculated glm p-value",
         xlim=c(10^-4,1),ylim=c(10^-4,1),col=2,cex=0.5,log="xy")
    lines(c(0.00001,1),c(0.00001,1))
    for (i in 1:100) {
      lines(1-c(outcomes[i],outcomes[i+1]),1-c(cdf[i+1],cdf[i+1]),col=2)
    #  lines(1-c(outcomes[i],outcomes[i]),1-c(cdf[i],cdf[i+1]),col=2)
    }

    title("probability for rejection with z-test \n as function of set alpha level")

    # plotting cumulative distribution of outcomes t-test
    outcomes <- p_model2[order(p_model2)]
    cdf <- cumsum(px[order(p_model2)])
    plot(1-outcomes,1-cdf,
         ylab="cumulative probability",
         xlab= "calculated glm p-value",
         xlim=c(10^-4,1),ylim=c(10^-4,1),col=2,cex=0.5,log="xy")
    lines(c(0.00001,1),c(0.00001,1))
    for (i in 1:100) {
      lines(1-c(outcomes[i],outcomes[i+1]),1-c(cdf[i+1],cdf[i+1]),col=2)
      #  lines(1-c(outcomes[i],outcomes[i]),1-c(cdf[i],cdf[i+1]),col=2)
    }

    title("probability for rejection with t-test \n as function of set alpha level")
    [![p-test vs t-test][1]][1]
</code>
And there is only a small difference. And also the z-test is actually better (but this might be because both the t-test and z-test are "wrong" and possibly the error of the z-test compensates this error).

Long Answer: ...
Comment: What happened to the long answer?


Modifying only one field with a twig template

Question: I have a content type that has multiple fields.   I'm fine with the generic display view for all but one of those fields.   Is it possible to use a twig template to modify only one of those fields?
For example:
Content type: Stuff and Things
with Fields:
Body,
URL,
Notes,
Status,
Peer Review
I want to modify the URL field and leave the rest alone... is this doable, or do I have to render each field in the twig template?
Comment: you should get familiar with [overriding Twig templates](https://www.drupal.org/docs/theming-drupal/twig-in-drupal/working-with-twig-templates). Make sure you have debugger on to know what you will be calling your overriding file name.
Answer: Target the field template instead of node. Enable twig debugger and then inspect element with browser to see all the template files available to use/override.
You'll see you can use field--[field-name].html.twig or field--node--[field-name]--[content-type].html.twig if you want to be more specific.


Highlight table view cell programmatically

Question: I have a cell in a static table view which I want selected (highlighted blue) when the view appears. Does anyone know of a way to do this?
I have tried using cell.selected = YES;. This will make the cell selected for a very short time (it goes blue, then white just after).
Answer: I found the solution. I used cell.selected = YES; in viewDidLoad. Doing it in viewDidAppear will work.
Answer: I think you can write cell.selected = true in didSelectRowAtIndexPath also.


Non-Ambiguous Description of PASTA Property

Question: I find the word "see" as in PASTA (Poisson Arrivals See Time Averages) to be a bit ambiguous and thus wanted some clarification in what it means (see http://pages.cs.wisc.edu/~dsmyers/cs547/lecture_11_pasta.pdf).
Basically the above says the probability of an arrival coming in some period of length $b$, say $[c,d]: c,d \in [0,t], t \in \mathbb{R^{+}}$ and $c<d$ such that $d-c=b$ given that an arrival occurs in the time up until now, being time $t$, is merely $\frac{b}{t}$.
That is, P(arrival in period $b$| there is an arrival before time $t$)=$b/t$. This implies that the probability of a system being in some state A of the state space of this system before the time of an arrival is stationary.
Now, I am wondering if the above is merely saying that the system conforms to a stationary distribution or if there is more specificity with regard to "before the time of arrival" (e.g., the system turns stationary given that an arrival is to occur, which seems to make more sense but is never explicitly stated - could this be the explicit definition of "seeing"?).
Answer: Let $\{t_1, t_2, t_3, ...\}$ be arrival times of a Poisson process of rate $\lambda>0$. Let $X(t)$ be a real-valued random process that possibly depends (causally) on the Poisson process.  Assume that $\overline{X}$ is a real number such that:
$$ \lim_{T\rightarrow\infty} \frac{1}{T}\int_0^T X(t)dt = \overline{X} \quad (\mbox{ with prob 1}) $$
The PASTA result says that under "mild" conditions we have:
\begin{align}
&(a) \quad \lim_{k\rightarrow\infty} \frac{1}{k}\sum_{i=1}^k X(t_i^-) = \overline{X} \quad (\mbox{ with prob 1}) \\
&(b) \quad \lim_{k\rightarrow\infty} \frac{1}{k}\sum_{i=1}^k E[X(t_i^-)] = \overline{X}
\end{align}
where $X(t_i^-)$ is the value of the random process sampled "just before" the $i$th Poisson arrival (so it is the value "seen" by this $i$th arrival). Since $\overline{X}$ is the "time average" of $X(t)$, we have that the average of the sequence of samples that are "seen" by arrivals is the same as the full time average (integrated over all time). This can be interpreted to mean that Poisson Arrivals See Time Averages (PASTA).

Example: Consider an M/G/1 queue $Q(t)$ and define
$$ X(t) = 1_{\{Q(t)>0\}}=  \left\{ \begin{array}{ll}
1 &\mbox{ if the queue is nonempty at time $t$} \\
0  & \mbox{ if the queue is empty at time $t$}
\end{array}
\right.$$
Then:
$$ \lim_{k\rightarrow\infty} \frac{1}{k}\sum_{i=1}^k X(t_i^-) = \lim_{T\rightarrow\infty} \frac{1}{T}\int_{0}^T 1_{\{Q(t)>0\}}dt = \rho$$
so the fraction of Poisson arrivals that see a non-empty system is the same as the fraction of time the system is non-empty.
This is not necessarily true if the arrivals are not Poisson.  For example if arrivals are periodic with period $2$ and service times are $1$, then $\rho=1/2$ but all arrivals see an empty system, so
$$ \lim_{k\rightarrow\infty} \frac{1}{k}\sum_{i=1}^k X(t_i^-)=0 \neq 1/2 = \lim_{T\rightarrow\infty} \frac{1}{T}\int_0^TX(t)dt$$
Other examples:

Fix $m \in \{0, 1, 2, ...\}$. Defining $X(t) = 1_{\{Q(t)=m\}}$ shows that the fraction of Poisson arrivals that see $m$ jobs in the system (not including the arrival itself) is the same as the fraction of time there are $m$ jobs in the system. For ergodic Markov chains with steady state distributions (stationary distributions), this is the same as the steady state probability there are $m$ jobs in the system.
Defining $X(t) = Q(t)$ shows that the average number of jobs in the system as seen by a Poisson arrival is the same as the time average number of jobs in the system.
Comment: Thank you so much! This is probably the most in-depth description of this property I have seen online!


Design and Error handling in windows service

Question: I have to design windows service and I have some question:

Proper error handling, if there is an error what happens to the
service? Does he continue to be up and logging in? Error recording
in event viewer? Is he falling?
What happens to a long run? How do you know for sure that everything
is running as required,     and he is not stuck?
How to handle high memory consumption, out of memory, or other error
that wasn't been write to the log?
Handle users - what happened if create log to user A and changed to
user B? Rewrite or continue from same point?
How to handle times? - Is the service automatically up?

Thank you.
Comment: In which programming language are you writing the service? C#?
Comment: @GeoSn0w - yes.
Answer:
For error handling, the best I can recommend is taking advantage of try / catch cases. This way you ensure that you handle the cases where something unexpected happens and you can either try to correct it or bring the service down cleanly. Keep in mind that exceptions are not propagated outside the scope of a thread so you need to handle them in each thread.

To be able to tell if the service is doing fine, you can periodically log into the Event Log what the service does. If you do proper try / catch for each thread, it should go smoothly. In C# you can use log4net and the EventLogAppender to log crucial / error info in the Event Log.

If your service causes high memory usage for no apparent reason, it is likely a memory leak. Microsoft has a free tool called ".Net CLR profiler" that allows you to properly profile your service and see what exactly is causing the leak.

Unless you are dealing with user-protected files (in which case you need to consult the Log On tab of your service to give it the appropriate credentials), your service shouldn't depend on any logged-in user. Services run independently of the users on the computer.

A service can be set to start automatically, to start only on-demand, or to simply be disabled completely.


geodesic distance

Question: Let $G(V,E)$ be a graph , suppose that $\vert N_{i,r} \vert $ be number of vertices whose geodesic distance from vertex $i$ is exactly $r$ edges.if $d_i$ the degree of  vertex $i$ and $d_{max} := \max_n {d_n}$, how can resulted that
$$\vert N_{i,r} \vert \leq d_i (d_{\max} -1)^{r-1} ?$$
Comment: What is $d_{max}$? Also, can you give some context? I take it (from the tags) that this is a question about graphs, and I'm guessing that it's about graphs where every node has finite degree, but are there any other hypotheses we should know about, like that the graph is planar, etc.?
Comment: @JohnHughes yes,Edited. $d_{max} := \max_{n} {{d_n}}$.
Answer: HINT:
The short answer is that this follows by induction on $r$; it's clearly correct for $r = 1$, because the number of vertices whose distance from $i$ is no more than $1$ is certainly bounded by the degree, $d_i$, of vertex $i$. (And if you only allow one edge between any two vertices, then it's not only bounded but equal to $d_i$).
Now you just need to work out the inductive step. When you do so, you can show your progress by clicking on the "edit" link below your question. And if you get stuck, we can help you from there.
Comment: Many thanks for your adequate and clear explanation. I understood  the answer.

geodesic distance


How to compare conversion rates in an AB test?

Question: Please help me decide how to proceed in the following situation:

Suppose we have an AB test with 2 groups.
The target metric is the conversion from one web page to another.
Suppose also, that whenever a user enters the website, we are able to identify his ID correctly.
Every user can go through the "flow" arbitrary number of times (i.e. he can do the target action 3 out of 7 times).

So here is my question:
Should I:

Calculate the overall conversion rate for both groups and compare it via a simple z-test?
Calculate the overall conversion rate for each user and then compare the average values across groups via a t-test?

Intuitively, users with a larger number of actions are given more weight in the first option, while in the latter everyone carries equal weight.
Finally, which option do I choose?
Comment: I would estimate the proportion of times users convert and then do the t test.  In my experience, real world data can have weird pathologies (like people who visit the site frequently and would convert no matter what group they are in).  That can bias your effect estimate if you were to take the first approach, but *should* be ok under the second approach.  Not to mention, the first approach violates the assumption of iid observations.
Comment: @DemetriPananos thanks! by the way, I think the first approach violates the assumption of iid observations only if we assume that people have **unequal** probability to convert
Comment: If you have several people in each group who are observed multiple times, then de facto you have correlated observations.  The assumption of equal probability of conversion doesn't affect this.  That's ok though, like I said if you average observations for each user (conversions/visits) then you should be fine to do something like a t test).  You could, if you are up to it, to a hierarchical binomial model instead.  Maybe I will post an answer on how to handle all three approaches.
Comment: @DemetriPananos thank you. Would be great if you could post describe the approaches in a full answer :)
Answer: I am going to cook up an admittedly  extreme answer to demonstrate my point.  Let's say you run an AB test on your platform to examine conversion.  Whatever you are measuring can be accessed several times, and so you see the same customer pop up in your data more than once.
We randomize 10 users to versions A or B, and then perform a hypothesis test.  Here is some data I simulated
# A tibble: 2 x 3
  group     z     n
  <chr> <int> <int>
1 A        23    50
2 B       159   230

Here, the sum of the $n$ column is larger than 10 because I see experimental units more than once (as in your first approach).  If I did a test of proportions on this data, then I would reject the null with a p value of about 0.003.  Wow, there is less than a 3 in 1000 chance we get this result assuming there is no difference.  We should ship this change!
Or should we?  Let's see how many times each subject was observed.
  users     n
   <fct> <int>
 1 1        10
 2 2        10
 3 3        10
 4 4        10
 5 5        10
 6 6        10
 7 7        10
 8 8        10
 9 9       100
10 10      100

We saw 8 of the 10 experimental units a total of 10 times, but we saw the last two units 100 times!  If these users were more likely to convert anyway regardless of experimental arm, then our results are biased!  And that is exactly what happened.
# A tibble: 10 x 4
   group users     z     n
   <chr> <fct> <int> <int>
 1 A     1         4    10
 2 A     2         4    10
 3 A     3         5    10
 4 A     4         4    10
 5 A     5         6    10
 6 B     6         7    10
 7 B     7         6    10
 8 B     8         3    10
 9 B     9        74   100
10 B     10       69   100

These users were just more likely to convert even before the experiment.  This happens in real life.  If you buy a lot of stuff on Amazon, for example, you probably are not going to be affected by experimental arm, which can lead to stuff like this happening.
How can we get around this?  Previously, the more we saw an experimental unit, the more weight they had.  To weight everyone accordingly we can estimate each person's probability of conversion and then do a t test.  When we do that, we correctly fail to reject the null (when I generated this data, I made sure there was no difference between groups but that experimental units had their own unique probability of conversion).
Answer: Let's refine the design of the experiment: in a typical ab test, the
experiment is randomized by user, this means that the group to which the user belongs does not change during the overall experiment. Randomize by visit is possible, but not commonly used: this means giving the same user inconsistent treatment, and may violate the Stable Unit Treatment Value Assumption (SUTVA). The following discussion will be based on the first design.
Here is a toy data:
  user_cnt <- 100

  ## each user can go through the "flow" many number of times
  visit_oer_user <- rpois(user_cnt, 10)

  ## each each have unequal probability to convert
  user_conversion_rate <- runif(user_cnt, 0.0, 0.1)
  visit_cnt <- sum(visit_oer_user)

  ## multiple visit of a user have equal probability to convert
  visit_conversion_rate <- rep(user_conversion_rate, visit_oer_user)
  visit_id <- seq(1, visit_cnt)
  user_id <- rep(1:user_cnt, visit_oer_user)

  ## randomized by user, not visit
  user_group <- sample(0:1, user_cnt, replace = TRUE)
  visit_group <- rep(user_group, visit_oer_user)

  y <- rbinom(visit_cnt, 1, visit_conversion_rate)

  df <- tibble(
    visit_id,
    user_id,
    trt = visit_group,
    y
  )
  df

Both options are common used but represent different meanings: conversion-by-visit vs conversion-by-user. If you choose the first option(conversion-by-visit), you need to use more nuanced analyses methods such as bootstrap, delta method or cluster robust standard errors, for violates the assumption of iid. An example in R would like this:
library(sandwich)
library(lmtest)

ols_mod <- lm(y ~ trt, df)
cluster_mod <- coeftest(ols_mod, vcov = vcovCL, cluster = ~user_id)
cluster_mod

t test of coefficients:

             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.097561   0.034858  2.7988 0.005631 **
trt         -0.047561   0.039602 -1.2010 0.231182
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

by the second option(conversion-by-user) is easier: aggregate data to user level, apply t test or linear regression.
df_user <- df %>%
  group_by(user_id, trt) %>%
  summarise(
    y = max(y),
    .groups = 'drop'
  )
ols <- lm(y ~ trt, df)
summary(ols)

Call:
lm(formula = y ~ trt, data = df)

Residuals:
     Min       1Q   Median       3Q      Max
-0.09756 -0.09756 -0.05000 -0.05000  0.95000

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.09756    0.02807   3.476 0.000624 ***
trt         -0.04756    0.03642  -1.306 0.193031
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2542 on 200 degrees of freedom
Multiple R-squared:  0.008457,  Adjusted R-squared:  0.003499
F-statistic: 1.706 on 1 and 200 DF,  p-value: 0.193

references:
Deng, A., Lu, J., & Qin, W. (2021). The equivalence of the Delta method and the cluster-robust variance estimator for the analysis of clustered randomized experiments. arXiv preprint arXiv:2105.14705.
Deng, A., Lu, J., & Litz, J. (2017, February). Trustworthy analysis of online a/b tests: Pitfalls, challenges and solutions. In Proceedings of the Tenth ACM International Conference on Web Search and Data Mining (pp. 641-649).


window.onload !=

Question: This is rather interesting, I think. Consider following code, both the window.onload and body onload="" call the same function. However, the results are different. It appears to me that window.onload has a problem with collections. Here's the code:

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Untitled Document</title>

     test

As you can see, both report that the collection exists, however window.onload reports that it has no members. Any ideas?
Answer: You're setting the function wrong:
window.onload = getSpanElements();

should be
window.onload = getSpanElements;

You're setting the onload handler to the return value of getSpanElements() at the moment.
Answer: window.onload = getSpanElements();

should be
window.onload = getSpanElements;

The code you have calls the getSpanElements function and assigns its return value as the onload event handler.
Answer: You're wrongly doing this:
window.onload = getSpanElements();

which sets the window.onload to the result of the call to the function getSpanElements (undefined).
You should do this instead:
window.onload = getSpanElements;

Comment: actually, the function returns `undefined`, not `null`
Answer: You might want to move your window.onload assignment below the getSpanElements declaration:

        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>

         test

At the point in your code where you're assigning the window.onload event handler, getSpanElements() has not yet been defined. Also, the line should be
window.onload=getSpanElements;

not
window.onload=getSpanElements();

The function name without parentheses is a reference to the function. With parentheses, it executes the function and the return value is assigned to window.onload.
Comment: Since getSpanElements is defined with the function statement rather than the function expression, it is subject to hoisting — so it doesn't need appear before the assignment in the code order.
Answer: You have to assign a reference to the function getSpanElements to window.onload - currently, the function doesn't get executed onload, but immediately after parsing.
What you actually assign is the undefined return value.
In short: drop the ().
Answer: I think the window object is created before any actual elements are parsed.
Comment: i would assume so as well, however it is well aware that the collection exists, that is what confuses me.

window.onload !=


How to use an aliased content title for a Views contextual filter?

Question: I've set up a page view with a path of 'services/communication/%' the '%' being a contextual filter of 'Content: Title'.
The problem with this is that the url ends up looking something like 'services/communication/Best Practices'. In the contextual filter I have set the case to 'lower case' and checked the box to 'Transform spaces to dashes in URL', however, neither of these things are doing anything.
In most cases the link to some content works fine but if there is a dash in the content title (e.g. 'online-led reporting') the content won't display.
How can I use an aliased content title with the contextual filter?
Comment: the dash issue is one of those thorny ones in that views will, if asked, transform all spaces to dashes or all dashes to spaces. So, in your example, `online-led reporting` becomes `online-led-reporting` in one direction, but then becomes `online led reporting` in the other, and then, it can't be found because you're really looking for `online-led reporting`
Comment: @Jimajamma Ah yes if I uncheck that 'transform spaces' option it will display the content. However, it's still annoying to have spaces in the url. Is there any way of using an aliased content title with the contextual filter? Obviously pathauto will do this but how can I use the alias it creates in Views?
Answer: How I attacked the spaces/punctuation issue ( http://drupal.org/node/786612 ) in Drupal 6 was by creating a url_safe_title text field and putting it in any content type that needed to be looked at, searched for, etc by it, and then having nodeapi() "fill it in for me" like this:
function MODULE_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (isset($node->field_url_safe_title) && $op == 'presave') {
      module_load_include('inc', 'pathauto');
      $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }
}

You can get fancy and hide the field with permissions, css etc so your users don't see it when creating content. I use http://drupal.org/project/nodeformcols to hide it and hide it from $content on display, too.
So, what this does is change simple titles like Hello World into hello-world but also online-led reporting into online-led-reporting with the added/needed benefit of being able to get back to "online-led reporting" from it.  It also helped out with stuff like Kukla, Fran and Ollie that turned into kulka-fran-ollie :)
So now in Views I use this field instead of the node title when I needed to grab things.  Just have to be aware of uniqueness, but that's another story in of itself :)
Comment: Thanks for your response. I'll have to look into this more closely when I get a chance. I'm not so familiar with the Drupal API.


ERROR: Manifest merger failed with multiple errors, see logs | BUT NO ERRORS IN LOG

Question: I have the following error when I build my React Native app for Android (no problem on iOS).

ERROR: Manifest merger failed with multiple errors, see logs

This causes a real problem when I build in release mode (no problem with the app in debug) because it produces the following Manifest file for my release build:
AndroidManifest.xml (in app/src/release/)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myAppName"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission tools:node="remove" android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</manifest>

I know there are plenty of questions about this but they don't really help in my case, because if I follow what is said in this answer (https://stackoverflow.com/a/42023614/1432355) and go to Merged Manfiest tab on my AndroidManifest.xml file I don't see any errors:

Below are my manfiest and gradle files:
AndroidManifest.xml
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myApp">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>

<application
    tools:ignore="GoogleAppIndexingWarning"
    android:name=".MainApplication"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:allowBackup="false"
    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config">

        <provider
            tools:replace="android:authorities"
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                tools:replace="android:resource"
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

        <activity
            android:name=".SplashActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize|stateAlwaysHidden"
            android:exported="true">
        </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>

build.gradle (Project: MyAppName)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 19
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

wrapper {
    gradleVersion = '5.4'
    distributionUrl = distributionUrl.replace("bin", "all")
}

build.gradle (Module: app)
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: "com.android.application"

import com.android.build.OutputFile

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
        // OneSignal-Gradle-Plugin
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.2, 0.99.99]'
    }
}

project.ext.react = [
    entryFile: "index.js",
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.example.myApp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 18
        versionName "0.6.3"
//        ndk {
//            abiFilters.clear()
//        }
        ndk {
            abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
// ...
        }
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
//    splits {
//        abi {
//            enable true //enables the ABIs split mechanism
//            reset() //reset the list of ABIs to be included to an empty string
//            include 'arm64-v8a', 'armeabi-v7a', 'x86'
//            universalApk false
//        }
//    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
    buildToolsVersion '28.0.3'

    packagingOptions {
        pickFirst '**/libc++_shared.so'
        doNotStrip '*/mips/*.so'
        doNotStrip '*/mips64/*.so'
    }
}

dependencies {
    implementation project(':react-native-reanimated')
    implementation project(':react-native-image-resizer')
    implementation project(':react-native-pdf')
    implementation project(':react-native-vector-icons')
    implementation project(':react-native-gesture-handler')
    implementation project(':rn-fetch-blob')
    implementation project(':react-native-image-picker')
    implementation project(':react-native-onesignal')
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation "com.facebook.react:react-native:0.59.9" // From node_modules
    implementation('org.conscrypt:conscrypt-android:2.0.0')
////    implementation fileTree(dir: "libs", include: ["*.jar"])
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

UPDATE 1
Comment: @Moucheg sorry man, I am out of ideas. I had same issue after updating Android Studio to new version, but had to make a crucial fix so temporarily solved by using older version of Studio to make a build which worked great. Ofc I am planning to resolve that so will keep an eye on this question and report back if I find anything. Good luck!
Comment: do you have other module in your app?
Comment: @PrachiSingh See update 1
Comment: make sure same dependencies have same versions in all modules gradle
Comment: @PrachiSingh The only difference is that I have `implementation "com.facebook.react:react-native:0.59.9"` and the modules `implementation "com.facebook.react:react-native:+"`. Setting them to the same version didn't change anything unfortunately
Comment: @Moucheg I am using similar libraries and was having a conflict with rn-fetch-blob and image-picker.
Have you tried with provider's meta-data tag like this?
``
Comment: @ZassX Yes I've tried it but I have the same error. If I comment the rn-fetch-blob and image-picker dependencies I get this error in Merged Manifest tab: `Merging Errors: Warning provider#android.support.v4.content.FileProvider@android:authorities was tagged at AndroidManifest.xml:29 to replace other declarations but no other declaration present app main manifest (this file), line 28 Warning meta-data#android.support.FILE_PROVIDER_PATHS@android:resource was tagged at AndroidManifest.xml:35 to replace other declarations but no other declaration present app main manifest (this file), line 34`
Comment: @Moucheg just to test: leave dependencies commented and insert the meta-data tools:replace property. Still same error?
Comment: @ZassX Same error when commenting all dependencies
Comment: @ZassX I've found what was causing this error, see my answer below
Answer: My problem wasn't really related to my code or gradle settings but to Android Studio itself.
I found out (with a lot of help) that in the Preferences (cmd + ,) there is a section called Experimental and in there there is an option called Only sync the active variant that was checked. Once I unchecked it there error went away.
I've filled an issue for this on b.android.com
Comment: @sam did you try to invalidate cache, clean project, restart AS ? What kind of errors do you have ?
Comment: error was same but I solve it  by updating all Gradle dependency


Predicting time series value given a threshold weight

Question: I have 2 datasets.  One is time series data of sale of homes by region by type:
Region    Type    SaleMonth   Sales
NE        SF      201601      100
NE        SF      201602      100
NE        SF      201603      150
NE        SF      201604      100
NE        SF      201605      150

These data were manually entered by realtors and given to us by a data feed.
We also get another data set of registered homes from the county. However there is a 2-month lag for this data set. It is structured as follows:
Region    Type    SaleMonth   Sales
NE        SF      201601      130
NE        SF      201602      130
NE        SF      201603      160
NE        SF      201604
NE        SF      201605

The weight is calculated as: Retail Transactions/Registered values.
So, assuming the weight is correct, I have to predict the Registered values for 201604 and 201605. I have tried regression, time series analysis, etc., but I wasn't able to get to the threshold weight.
Is this a candidate for neural net time series? Is there anything else I can do assuming the weight is correct.
Assuming it is incorrect, what is the best approach to determine what sliding window of values to use from the transactions to accurately predict the registered values?
Comment: Can you clarify the "weight"? I don't see "Retail Transactions" or "Registered values" in either dataset. What do you mean that you weren't "able to get to the threshold weight"?
Comment: Thank you gung for your response. The first table is Retail Transactions and the second table is Registered Values. Weight is defined as: Retail sales/registered sales.
Comment: So you want to determine if the ratio of the sales variables in the two tables is roughly constant? What do you mean that you weren't "able to get to the threshold weight"?
Answer: Your data set is too small. So It is very hard to estimate and forecast the values with such a small data set by using methods as auto regressions and others. Either way, you may use simple linear regression on Retail Transactions/Registered values, But It will hard to say about the accuracy of prediction. The data set should be large enough for forecasting.


how to delete all facebook app request in rails?

Question: I have a simple problem. I want to delete all app request sent via my Facebook application. Facebook documentation gives following code to do that:
DELETE https://graph.facebook.com/[<request_id>_<user_id>]?access_token=[USER or APP ACCESS TOKEN]

My problem is how to make HTTP DELETE request in my rails application?
I am using following code to make HTTP GET request:
client = HTTPClient.new
@data = client.get_content(URI.parse(
  URI.encode("https://graph.facebook.com/RequestID?access_token=AccessToken")
))

Answer: Have a look at HTTPClient#delete method. I believe that's all you need. That should be smth like
client = HTTPClient.new
url = "https://graph.facebook.com/#{request_id}?access_token=#{access_token}"
data = client.delete url

Btw, why do you need that URI.parse and URI.encode stuff in you example?
And as you're dealing with Facebook I'd suggest looking at rest-graph gem. It's a pretty good tool for dealing with Facebook Graph API.
Answer: If the above doesn't work you can also GET the url, but specify the method as delete:
"https://graph.facebook.com/[<req id>]?access_token=[<access_token>]&method=delete"

This works for GET, POST, and DELETE.


Time.parse .. the hour is not what is expected

Question: Why does this say 13 instead of 14?
Time.parse('2014-01-08 14:01:00 +0300').hour
# => 13

Answer: The time is parsed correctly, but displayed in your local time zone.
This happens in my console:
Time.parse('2014-01-08 14:01:00 +0300')
=> 2014-01-08 12:01:00 +0100

Note the +0100.
Answer: http://apidock.com/rails/Time/use_zone/class
should help you to get time in correct time zone

Time.use_zone(zone name) accepts block. Inside this block application uses time zone you've provided in zone name

use_zone(time_zone) public

  Allows override of Time.zone locally inside supplied block; resets Time.zone to existing value when done.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.


Replace all observations except for the first with 0 in each ID

Question: I have a dataset that looks something like this.
    ID    date   price   day
    a     2005/5   100    16
    a     2005/6   110    1
    a     2005/7   90     1
    b     2005/5   90     20
    b     2005/6   100    1
    b     2005/7   90     1
    c     2005/5   90     3
    c     2005/6   95     1
    c     2005/7   100    1

And for the day column, I want to replace every row EXCEPT the first row into 0.
So my desired result is as below.
    ID    date   price   day
    a     2005/5   100    16
    a     2005/6   110    0
    a     2005/7   90     0
    b     2005/5   90     20
    b     2005/6   100    0
    b     2005/7   90     0
    c     2005/5   90     3
    c     2005/6   95     0
    c     2005/7   100    0

I have tried using command such as
    rbonds1 <- as.data.table(rbonds1)
    setkey(rbonds1,ID,date)
    rbonds1[rbonds1[-1, 21]==0,by=ID]

But it does not work.
Answer: You can do this by replacing day with 0 whenever ID is duplicated:
rbonds1$day[duplicated(rbonds1$ID)] <- 0
rbonds1
#   ID   date price day
# 1  a 2005/5   100  16
# 2  a 2005/6   110   0
# 3  a 2005/7    90   0
# 4  b 2005/5    90  20
# 5  b 2005/6   100   0
# 6  b 2005/7    90   0
# 7  c 2005/5    90   3
# 8  c 2005/6    95   0
# 9  c 2005/7   100   0

Comment: @josliber I have a quick another question. Can I do `rbonds1$day[duplicated(rbonds1$ID)] <- rbonds1$day[!duplicated(rbonds1$ID)]` if I want to replace all the other variables as the value in the first row in each ID?
Comment: @hk824 So you want to replace all the values in day by first value of day from each group ID ?
Comment: @hk824 You could try: `library(dplyr); rbonds1 %>% group_by(ID) %>% mutate(day = first(day))`
Answer: An option using data.table (as the OP showed some attempts in data.table).  Convert the 'data.frame' to 'data.table' (setDT(df1)), grouped by 'ID', we get the row index (.I) where the sequence is not 1, extract that column ('V1') and assign (:=) the 'day' to 0 for those rows.
library(data.table)
setDT(df1)[df1[,.I[1:.N!=1] , by = ID]$V1, day:=0][]
#   ID   date price day
#1:  a 2005/5   100  16
#2:  a 2005/6   110   0
#3:  a 2005/7    90   0
#4:  b 2005/5    90  20
#5:  b 2005/6   100   0
#6:  b 2005/7    90   0
#7:  c 2005/5    90   3
#8:  c 2005/6    95   0
#9:  c 2005/7   100   0


SimpleSAMLphp installation in Windows Apache

Question: I want to install SimpleSAMLphp in windows Apache/Xampp. Let me tell you what did so far:
1. I have downloaded latest stable version from https://simplesamlphp.org/download and placed the unzipped file in Apache folder, i.e. C:\Apache24\simplesamlphp directory contains composer.json. I have downloaded dependencies as well.
2. Now when I am going to setup the vhost as shows in the site 6. Configuring Apache section as
<VirtualHost *:80>
        ServerName localhost
        DocumentRoot C:/Apache24/htdocs
</VirtualHost>

<VirtualHost *:80>
        ServerName service.example.com
        DocumentRoot C:/Apache24/service.example.com

        Alias /simplesaml C:/Apache24/simplesamlphp/www
</VirtualHost>

Changed the config file.

Now the problem:
I am unable to open the Alias in browser. And running httpd.exe in browser shows error about the example.com does not exist.
Need help if anyone have setup SimpleSAMLphp in Windows, please share your steps and vhosting configurations. It would help I think lot of peoples.
Thanks in advance.
Comment: What are those errors exactly?
Comment: Waning: Directory service.example.com does not exist
Comment: I have Xampp setup with *:80 as localhost, so what should be the vhsot conf for simplesamlphp?
Comment: Hi "ogondza", kindly verify my answer. I will be oblized. Also if there is any other configuration possible, please let me know. Thanks.
Answer: I am sorry, that I was doing some mistake...
I am going to add one vhost, rather in Windows Xampp, there is one file /xampp/apache/conf/extra/httpd-xampp.conf. Need to add one Alias below /phpmyadmin statement:
Alias /simplesaml "C:/xampp/simplesamlphp/www"
<Directory "C:/xampp/simplesamlphp/www">
        AllowOverride AuthConfig
        Require all granted
</Directory>

Now restart server and hit http://localhost/simplesaml/ and all you go...
All windows xampp users if faced configure simplesaml...might be helped.
Answer: For anyone else who is trying to set up SimpleSAMLphp on a Window's version of xampp, here are the steps I took to get it running.

Install xampp. For this example, I've installed to: "c:\xampp"
Download and unzip SimpleSAMLphp to htdocs folder ("c:\xampp\htdocs\simplesamlphp"). It will probably extract with version numbers appended to the end, so I've renamed the folder to 'simplesamlphp' in this example.
Add the alias and directory from the answer above into the httpd-xampp.conf file, but change both "C:/xampp/simplesamlphp/www" to "C:/xampp/htdocs/simplesamlphp/www".
Start Apache server and in your browser, go to: "localhost/simplesaml"
This assumes that there are no exotic entries in your hosts file.

You should now see the SimpleSAMLphp Installation Page.


My Date in Twig is ignoring format

Question: I have a twig file with the following code in my Drupal 8.4.4 site:

{{ node.field_date.value }}

And in my content type, manage display option, I have it formatted like this:

But on the website, it shows the date as
2019-01-16T23:00:00
What am I missing?
Answer: You are printing the node value directly, which is bypassing the field formatter and other things (since you are not using the render array).
Do this instead:
{{ content.field_date }}
This will render normally and ensure field formatter settings are respected.
Comment: This is much better than my answer!
Answer: Try piping the value to twig's date function:
https://twig.symfony.com/doc/2.x/filters/date.html
That approach might give you something like this:

{{ node.field_date.value | date("D M j G:i T") }}

Comment: Funny enough this didn't work, I was trying this before until someone else pointed me to the fact that the formatting should work above. Thanks for posting!
Comment: I guess technically this would work, but you lose the ability to change the format on the fly from the admin. It would also print the div out, regardless of if there is a value in the field or not.

My Date in Twig is ignoring format


Regression vs. Classification: Is there a clear, generally accepted definition?

Question: As a mathematician/economist, I am not trained to think in classification and regression tasks. This is why I wonder: is there a clear, widely accepted definition of regression and classification problems?
E.g., this paper says that When $Y$ has a finite number of states we
refer to the task as classification. Otherwise we refer
to the task as regression.
Does this mean that count data with many counts are a classification problem (e.g., Poisson regression). Or if we model life expectancy, is this generally supposed to be a classification task?
Is this definition generally accepted?
Comment: @seanv507 I don't think that is really true, there are plenty of statisticians that seem happy to talk of classification (or equivalently pattern recognition), e.g. Brian Ripley or Geoff McLachlan.  Also Vladimir Vapnik is a statistician.
Comment: The question "Is there a generally accepted definition of concept X in science?" always seems a bit of fruitless to me. (Usually the answer is "no, so what?") And for distinction between classification and regression, variations of this question have been asked on CV before, incl. [1](https://stats.stackexchange.com/q/249010/237901), [2](https://stats.stackexchange.com/q/526361/237901), [3](https://stats.stackexchange.com/q/526361/237901). I find this thread most interesting: [Why not approach classification through regression?](https://stats.stackexchange.com/q/22381/237901).
Comment: Classification is (also) what people do with language (that's a cat; that' policy is reprehensible) and was a really big deal in much of science (e.g. biology) long before machine learning was ever a thing.
Comment: classification is really an ML name, with the historical view of assigning labels to a data point (ignoring class probabilities - unlike this paper). for a statistician everything is really regression estimating E(y|x).
Answer: Classification denotes an action.  It's what you do with the result of an analysis in which there is one or more outcome variables and one or more input (predictor; covariate) variables.  If there is a single outcome variable, the discreteness of the variable does not matter.  For example, binary logistic regression is for binary Y and is a direct (continuous) probability model that was not intended to be used for classification.  The action of classification involves making choices and use of decision rules.  In most cases it represents a premature decision made by an analyst who is not blessed with knowledge about the consequence of the decision (i.e., does not possess the utility/loss/cost function needed to make a good decision).
One can use any predictive method to do classification even if that was not the intent of the method.   For example one can use arbitrary thresholds on predicted values to do classification from ordinary regression for continuous Y, or ordinal or binary regression for ordered or binary Y.
Many in machine learning think of classification as a good default mode; it is not, as detailed in my blog post.  Among other things, classification hides close calls and lulls users into making decisions at the boundaries (e.g., when a predicted probability is 0.5001) when a better approach would be "get more data first".
Most of the time when you see classifier used in a sentence the correct term is prediction when the output is considered to be continuous.
Comment: That would make sense were practitioners to do what you mentioned (create a "we don't know" category).  But they almost always forget to do this.
Comment: Sometimes decisions must be made under constraints which prevent deep analysis. Take tumour segmentation on a 1 Mpixel image: Do you want to perform 1 million statistical analyses? While knowing that the independence assumption is extremely violated? And the linearity of the odds, at best, a pious hope? Or, think about stock trading: By the time you have made your analytical decision, the conditions for it will have become obsolete a thousand times. The choice is not between classification and statistical analysis; it is between classification and doing nothing.
Comment: @IgorF. It's certainly possible to code the nuances of probabilistic predictions into whatever algorithm you put into production to operate autonomously.
Comment: @IgorF. there are many statistical modeling approaches that do not assume independence or linearity.
Comment: Please consider making it clearer that the provided reference is not a usual one, but something written solely by you.
Comment: Also, I think this answer is helpful in general but it doesn't start very well. "Classification denotes an action" looks like a noisy statement - regression is also a sort of "action". The problem as I see it is they are significantly different actions, and that's the thing that needs an explanation for this question :-) And one other thing is that "fitting a model" or "prediction" or similar are much better terms than the outdated and confusing "regression".
Comment: @Dave I think one point here is that estimating the probability of class membership and then thresholding does not necessarily give the optimal classifications.  So if the misclassification costs etc. are fixed and known a-priori, then when an autonomous decision must be made, discrete classifiers (such as the SVM) may give better performance.  Having said which, I am a big fan of [multinomial][kernel] logistic regression, for many applications it is the right approach for the reasons given by Prof. Harrell.  Best to have both sets of tools in the toolbox and use the right tool for the job.
Comment: The point of classification is not to make decisions when it is a close call (in fact, we can always place those low-confidence regression outcomes in a separate category). The point is to make the alignment better and to regularize the model so it doesn't spit out nonsense under a significant covariate shift. To that end, statements about whether it is a good default seem heavily field-dependent: if yours happens to be the one where humans don't doubt their annotations for a moment, there - ideally, at least - should not be any close calls to begin with.
Comment: @Lodinn "if yours happens to be the one where humans don't doubt their annotations for a moment" this sounds like label noise, which is well studied in both probabilistic and discrete classifiers.  There are situations where "we don't know" *is* taking a decision, e.g.  a camera that knows when you are smiling in order to take the picture, there "don't know" is basically equivalent to "not smiling" as you don't take the picture.  Horses for courses, there is no one true approach to anything non-trivial (IMHO).
Answer: No, I don't think that definition is generally accepted.  I would not regard Poisson regression as classification as the thing you are generally interested is the conditional values of a Poisson distribution that describes the distribution of the target variable for those values of the attributes.  Those parameters are generally continuous.  You might then use that to work out the most likely count, but that would be discretising the predictive distribution given by the model.
Likewise some here (e.g. Frank Harrell - see his answer to this question +1) view logistic regression purely as a probabilistic model, used to estimate a conditional probability, and not as a classification model (which is what you get by applying a threshold and discretising the continuous output of the model).  I have a lot of sympathy with this view, except that in practical applications where you need to perform that discretisation, that still impacts on the design and evaluation of the model and shouldn't be ignored.  The optimal classification is not always obtained by estimating the probability of class membership and thresholding, sometimes it is better to classify the data directly.  If that were not the case, [kernel] logistic regression would not perform worse than the Support Vector Machine, but on some applications it clearly does.
I'd probably say that a classifier is a problem where the target distribution is categorical, and the aim to to place each object into a category.
Answer: A reasonable standard definition of classification would be that the $Y$ value is of nominal scale level, i.e., that order and numerical differences are not meaningful (or at least not of interest). Models with count or ordinal responses are widely referred to as regression, e.g., Poisson regression, ordinal regression.
Note that the comment by Dikran Marsupial is correct that some models with nominal scaled outcome are also referred to as regression ((multinomial) logistic regression). My interpretation of this would be that the term regression is also used to refer to a class of models that grew out of historically quantitative regression models. I think it makes still sense (and would probably be standard handling of the term) to also refer to these as classification methods, and certainly to the problems solved by them as classification problems. This handling of terms would have regression and classification as not necessarily mutually exclusive. Probably regression is more ambiguous than classification, as it can be used for methods for quantitative or at least ordinal responses (and insofar be distinct from classification), but also for certain model classes that may also have versions for classification problems.
Comment: @DikranMarsupial Fair enough. To some extent regression and classification can be seen as overlapping. I add something to the answer.
Comment: +1, but a [multinomial] logistic regression model would have a Y value that is nominal, but some would still reasonably view it as a regression problem.
Answer: To muddy the waters further, classification can mean

trying to find distinct classes in a dataset from scratch, which has attracted many different names, including mathematical or numerical taxonomy, but cluster analysis seems the most durable and popular

assigning observations to classes already defined, which has other names too including identification and discrimination.
Comment: These are rather routinely referred to as unsupervised vs. supervised classification, although of course the other terms exist as well.
Comment: Sure, but only routinely over the last decade or so, I think. The terminology I mention goes back much further.
Comment: Trivially, but crucially in practice, terminology that is familiar comes to seem obvious, even though you know that wasn't true when you first learned it and isn't true for many other people still. Thus I have no difficulty in distinguishing _independent_ and _dependent_ variables, but think that poor terminology given that the terms are often confused. Conversely, which is  _unsupervised_ and which is _supervised_ I find quite hard to remember, that could mean stupidity, or arise because I don't mix with machine learners or read much in their literature.
Answer: Definitions are overrated. They are just words which someone claims are synonymous to other words. They may be useful in special situations, e.g. to help a novice get a grasp of a concept, or to ensure that experts, when communicating with each other, know precisely what they are talking about. But, standing alone, who cares?
That said, I believe all machine learners and a good deal of statisticians wouldn't object and would understand what you mean if you say "classification" for a task where your dependent variable is nominal (synonym: categorical) in Stevens' typology. Most machine learners will associate regression with numerical dependent variables, but some statisticians would say that "everything is regression", and classification a step---obviously outside of "everything"---you apply after performing some kind of regression (e.g. logistic regression) for the purpose of decision-making.
For dependent variables which don't fit these two categories, the things get murky. Ordinal regression lies somewhere between classical (numerical) regression and classification. Predicting counts is, in my opinion, clearly a regression (Poisson, binomial etc.), and not classification.
Comment: Nominal isn't a synonym of categorical to just about any statistical person looking at texts or courses on categorical data analysis, as there usually categorical includes ordinal. Now you can agree or disagree with that, like or dislike that, but the point is that even if you don't use or like a definition it may be what other people are using. I agree that fussing about terminology or word use can seem trivial or pointless, but it is needed whenever people can't communicate easily or effectively because they are using different definitions.
Comment: Your take on the usefulness of definitions seems very strange to me. We use words so that we can communicate efficiently but clearly it only works so long as we mostly agree about definitions. Definitions only "stand alone" for people who don't have to communicate in that field.
Comment: @einar I don't think natural languages work that way (which is one reason maths is so useful).  We often have to use reasoning to disambiguate meanings and also the meanings tend to evolve differently in different communities, c.f. "two great [sic] nations divided by a common language" - attributed to George Bernard Shaw.  Definitions are useful, but they don't define what words mean so much as tell you generally accepted usages (but there may also be other usages that don't fit the definition).  ML is a good example of this, due to the diversity in educational backgrounds of practitioners.
Comment: @DikranMarsupial no you're probably right and I'm not even sure I expressed myself clearly in that comment just to underline your point.
Answer: You need to search more about these terms. Resources may contain 'Linear Algebra', 'Signal & Control', 'Data Mining', 'Predictive Models',... vice versa. I explain some of them briefly here:
Interpolation: Some times we need to predict value of some data points based on another ones, that is generalizing the order we found on some observations (sampled data points) , to another one. Observed data points might be sampled points. We describe this order as mathematical functions (named basis function). This function may be a linear function; in this case we call it Linear Regression. If interpolation is based on current observed values, and aims to predict upcoming observations (assumes that current trend of data points continues on future) we call the method 'Extrapolation'.
Regression: Is the process of finding the best values for  parameters of a regression function (for example parameters of a line) in-order to fir into data points. Regression about  doesn't have any scenes about trend, it just tries to optimize the parameters of a linear function and find their best values, which fit best to data points. A polynomial regression tries to fit the best polynomial function to data points.
Classification: Some times you want to assign a category to data points. Classes are finite and are pre-known. It is like a process of mapping data points from a infinite space, into some points in a finite space. In Regression, you was trying to search for best values for a basis functions parameters, but in classification you are trying to find best values for a Mapping function. A mapping function could also be a line, a polynomial, or each function which was applicable in interpolation (and regression). The only difference is the way we use it. We use mapping function for separating data points from each other, while use basis functions in regression for finding out the order which describes them the best. Neural Networks (which are used vastly in classifications) contain several mapping matrices which maps input data described in finite properties to output finite classes.
Prediction: Could be prediction value of future data points or their class. That is a general term which can contain both Regression, and Classification. Predication can employ any mathematical approach with the assumption that the current order of events, will continue in future, or any changes will follow an order which could be known or estimated.
Modeling: Is another general term (more general one) which is the way we describe a system by a mathematical (or any thing) abstract model. The output of this process is a tool for predicting, interpolation, describing, and analyzing a system. Regression is a kind of modeling which describes the system as a linear function and could be used for prediction and describing.
Comment: I can't see that this really complements exists fine answers helpfully, and some of its details are disputable. The insistence that regression is about fitting a linear function doesn't capture many important variants such as logit regression.
Comment: I wanted to show questioner that there are many related or similar terms. I tried to clarify the purpose of different methods, to make him understand why we can use methods in any problem (using classification instead of regression).  And Yes! these are disputable because can't claim that i am an expert. @NickCox
Answer: I think people are overcomplicating this. Simply put, in classification problems the target variable is nominal (eg "dog" vs "cat"), whereas in regression problems the target is numeric.
Comment: What to do with ordinal target variables?
Comment: Your comment like your post is all of a circle with your terminology without recognizing fully that terminology is not consistent across statistical science.  Naturally if you define the two as disjoint any other usage is at odds with that.  I too prefer the terminology I use. But here it goes. Regression can in essence forecast probabilities and a decision to classify can follow. But it's not my point; it's quite standard and already very well developed by @Frank Harrell in his answer.
Comment: This misses the major difficulty, which is more than that you and people close by have a terminology you think is good, clear and consistent. The problem is twofold at least (a) all the meanings other people have (b) where to draw the line. For example, it's not (in my view) perverse to regard classification as a limiting case of regression.
Comment: @RichardHardy I think you need to interpret the answer as an exercise in classification, while the problem in the question is actually one of regression
Comment: @RichardHardy Well "ordinal" means the order matters, so this is a regression problem to me.
Comment: @NickCox I'm curious how you consider classification as a limiting case of regression. In regression the order of the target variable matters but in classification it does not. I can reverse the labels and it is still the same problem. What we call the target is irrelevant. That is not true for regression problems where the *actual* target is important to keep track of.


Calcular o tempo que um carro esteve estacionado

Question: Estou a ler um ficheiro parque.txt que contém as horas que um carro esteve num parque de estacionamento, do tipo "9h00 10h30", isto em cada linha.
Estava a tentar obter essas horas em cada bloco de char, neste caso teria hora_i="9", min_i="00", hora_f="10", min_f="30", o problema é que no printf final ele mostra hora_i="9", min_i="009", hora_f="10009", min_f="3010009".
Já experimentei a fazer fflush(stdin), mas não resultou...
void calcula_estacionamento()
{
    FILE *f;
    int n=0,i=0;
    char linha[MAX],hora_i[2]="",min_i[2]="",hora_f[2]="",min_f[2]="";
    f=fopen("parque.txt","r");
    while(fgets(linha,MAX,f)!=NULL)
    {
        while(linha[n]!='h')
        {
            hora_i[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!=' ')
        {
            min_i[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!='h')
        {
            hora_f[i]=linha[n];
            n++;
            i++;
        }
        i=0;
        n++;
        while(linha[n]!='\0')
        {
            min_f[i]=linha[n];
            n++;
            i++;
        }
        printf("\n%s %s %s %s",hora_i,min_i,hora_f,min_f);
        n=0;
        i=0;
    }
}

Answer: Faltaram os caracteres nulos (\0) em cada uma das suas strings. Ou seja, cada um dos seus vetores deve possuir até 3 caracteres:
char linha[MAX], hora_i[3] = "", min_i[3] = "", hora_f[3] = "", min_f[3] = "";

É importante que você termine todas as string corretamente durante a leitura do seu código
hora_i[i] = '\0';
i=0;
// ...
min_i[i] = '\0';
i=0;
// ...
hora_f[i]= '\0';
i=0;
// ...
min_f[i]= '\0';

Finalmente, se você realmente for ler múltiplas linhas de um arquivo, é importante prever tanto o fim do arquivo quanto o fim de uma linha:
while(linha[n]!='\0' && linha[n]!='\n')
{
    // ...

Exemplo funcional no Ideone

Pontos importantes que eu não pude incluir no exemplo
Faltou o tratamento de erros na hora de abrir o arquivo:
f=fopen("parque.txt","r");
if(f == NULL) {
    perror("Erro abrindo o arquivo");
    return(-1);
}

Bem como o tratamento para fechá-lo:
fclose(f);

Comment: obrigado, agora resolveu o erro, não me lembrei desse pormenor do '\0' para finalizar a string... eu quando faço apenas read de ficheiros não costumo fazer fclose(), não sei se é boa política, mas eu faço assim
Comment: Sem problemas Miguel, fico feliz em ter ajudado. Sobre arquivos (e ponteiros em geral), minha dica é: sempre que alocar algo já digite o código para fechar :). Se a resposta resolveu o seu problema não se esqueça de aceitá-la.


Inserir registro em uma tabela e usar ID recém gerado para inserir registro em tabela relacionada

Question: Tenho um insert em que eu salvo um registro, e preciso utilizar o resultado do valor salvo em outro insert.
Empresa emp = new Empresa();
emp.setId(1);
emp.setNome("Nome da empresa");

repository1.saveAndFlush(emp);

RelacaoEmp relEmp = new RelacaoEmp();
relEmp.setId(100);
relEmp.setIdEmp(1); //O mesmo Id Cadastrado na empresa
relEmp.setTpEmp(10);

repository2.save(relEmp);

Quando efetivo essa operação ele fala que a empresa 1 não existe.
Existe alguma forma para eu efetivar o registro do repository1 antes de executar o repository2 para não dar este problema?
Comment: isso está dentro de uma transaction?
Comment: Veja se isso ajuda: https://stackoverflow.com/q/45491551/8133067
Answer: Empresa emp = new Empresa();
Empresa empSalva = new Empresa();

emp.setId(1);
emp.setNome("Nome da empresa");

empSalva = repository1.saveAndFlush(emp);

RelacaoEmp relEmp = new RelacaoEmp();
relEmp.setId(100);
relEmp.setIdEmp(empSalva.getId()); //O mesmo Id Cadastrado na empresa
relEmp.setTpEmp(10);

repository2.save(relEmp);

Comment: Já resolveu o problema? Isso é a solucao?