Regress IV on DV, or DV on IV?

Question: This is a question about statistical language. Do you regress the IV on the DV, or do you regress the DV on the IV? Which is the correct way of saying this?
Answer: Traditionally speaking, one regresses the dependent variable (the Y, the outcome) on the independent variable (the X, the input). However, this is such an egregious abuse of statistical language, many disciplines have abandoned such verbiage altogether. The mistake is that "dependence" (in the proper statistical sense) is commutative. If A depends on B, then B depends on A. We only call the "X" (input variable) "independent" because it is considered fixed or given as part of an experimental design, or is representative of a population of interest.
Regression models estimate the conditional mean of the outcome as a function of one or more predictors. To this end, the mean of one variable conditional on another may be a flat response although the variables are indeed dependent (suppose the error of the Y varies according to X). To belabor this point, one nice way of writing what a regression model estimates is the following:
$$E[Y|X] = \beta_0 + \beta_1 X$$
Better options would be calling the "dependent" variable (Y): an outcome, a response, an output, and calling the "independent" variable (X): an input, a predictor, a regressor, a covariate, or an exposure.
Comment: You mean that the words dependent and independent are the abuse of language, not which one you regress on which one?
Comment: Just to add another set of names very common in machine learning circles: $X$ is often also called a feature vector, an example, or a data point, and $Y$ is sometimes called a target or occasionally a label (though that is mostly used for discrete outputs).
Comment: @histelheim yes, avoid using these words to describe regression analyses. Use my suggested ones or whichever words are more prevalent in your discipline. If A depends on B, B depends on A. It's actually impossible for one variable to be "independent" and another to be dependent on it.
Answer: The question prejudges another question, good terminology for the variables concerned. Let's take that first.
DV is common, but not universal, shorthand for dependent variable. It's probably old-fashioned to remind that DV has often been used to mean Deo volente, God willing, but those who know that and also some statistics seem unlikely to confuse or conflate those two meanings.
IV is common, but not universal, shorthand for independent variable. It's not at all old-fashioned to point out that among many economists, and some other social scientists, IV is now more likely to mean instrumental variable. This isn't much of a problem either: by the time people have learned about instrumental variables, they should be able to distinguish the two usages, at least in context.
Let's take it for the moment that at least in many situations, a dependent variable can be identified on substantive grounds as whatever is the outcome, response or effect which we are in practice interested in explaining or predicting in some way. The independent variable is then the cause or factor used to predict the response. Most introductory courses and texts seem to use notation $y$ for dependent variable and $x$ for independent variable; whenever there are many such independent variables, they can be distinguished by subscripts and/or denoted collectively as a matrix.  That said, there are many examples in which predictive interest runs either way: if rainfall is a predictor of the response corn yield, so also we might use abundance of some taxon in reverse to predict temperature, rainfall or salinity of past environments. Yet again, and very much to the point, there are many problems in regression in which variables are on the same footing: properties of partners or siblings, two methods of measurement of ostensibly the same property, rainfall or temperature over time at two gauges or stations, and so on and so forth. The problem here has more symmetry and distinction between two kinds of variables is likely to be arbitrary if not meaningless.
As far as terminology is concerned, we note that many would prefer some other term rather than DV or dependent variable. This preference goes back at least some decades: John Wilder Tukey often used the term response in writings in the 1960s and 1970s. but teachers, writers and researchers often seem reluctant to abandon the terminology of dependent and independent. Grounds for objection include (a) many students and even researchers confuse the two words, which apparently seem so similar; (b) the words have other meanings, even in probability and statistics; (c) why use dull words when evocative alternatives are available?
Similarly, many find terms such as predictor, covariate, explanatory variable more congenial for independent variable. There are many such terms, and some, particularly the first two, have other meanings in statistical science. (For example, covariate had a very specific meaning in analysis of covariance for some decades, but somehow has morphed into also acquiring a more general meaning as any kind of predictor. I conjecture that writings of John Nelder had some influence there.) Yet again, some have favoured terms invented for the purpose, such as regressand and regressor: to me, these are so unattractive that it is slightly distressing even to think about them.
All this is lengthy preamble to the question given here (which to me is less interesting). In short,  the usual or standard regression is that of $y$ on $x$ (or $X$), but at least in the case of single predictors it can also make sense to talk about the regression of $x$ on  $y$, with different assumptions on error structure. There can be equal interest in both regressions when variables are on the same footing (and also in other models for the joint relationship, which are left to another story).
Comment: Nice explanation.  It is probably older-fashioned to mention that DV and IV were once used to represent 505 and 4, respectively :)
Comment: Interestingly, at least to me, I gather that smaller numeral before larger numeral meaning subtraction (e.g. IV meaning  V (5) - I (1) = 4) is a late medieval innovation and not Roman at all!

Regress IV on DV, or DV on IV?


Using arrays in java with methods, returning arrays

Question: Prompt: http://puu.sh/lvdIG/404ebfba03.png
I am so close to being done. I need to fix three errors I have: on the treeReport+= line, I get error: "cannot find symbol" for minSeeds, totalSeeds, and totalTrees. I cannot declare them as a member of the class, and I can't use static before them. I also can only use one class.
import javax.swing.JOptionPane;

public class TreeCalc {

    public static void main(String[] args) {
        String[] treeTypes = new String[] {"Fir", "Pine", "Spruce"};
        int[] desiredYield = new int[treeTypes.length];
        double[] decayRate = new double[] {0.07, 0.12, 0.08};
        desiredYield = getYield(decayRate, desiredYield, treeTypes);
        getCalculate(decayRate, desiredYield, treeTypes);
        printMessage(decayRate, desiredYield, treeTypes);
    }

    //Asks user to input # of trees for each tree type
    public static int[] getYield(double[] decayRate, int[] desiredYield, String[] treeTypes) {
        int index = 0;
        for (int i = 0; i < treeTypes.length; i++) {
            try {
                desiredYield[index] = Integer.parseInt(JOptionPane.showInputDialog("Please enter your desired yield for: " + treeTypes[i]));
            } catch (NumberFormatException e) {
                desiredYield[index] = 0;
                JOptionPane.showMessageDialog(null, "Error: Please enter your desired yield for " + treeTypes[i]);
            }
            if (desiredYield[index] <= 0) {
                JOptionPane.showMessageDialog(null, "Error: Please enter your desired yield for " + treeTypes[i]);
            } else {
                index++;
            }
        }
        return desiredYield;
    }

    //Calculates totals and minimums
    public static int[] getCalculate(double[] decayRate, int[] desiredYield, String[] treeTypes) {
        int totalSeeds = 0;
        int totalTrees = 0;
        int minSeeds = 0;
        int index = 0;
        for (int i = 0; i < treeTypes.length; i++) {
            minSeeds += (desiredYield[index] * (decayRate[index] * 7)) + desiredYield[index];
            totalSeeds += minSeeds;
            totalTrees += desiredYield[index];
        }
        return desiredYield;
    }

    public static void printMessage(double[] decayRate, int[] desiredYield, String[] treeTypes) {
        getCalculate(decayRate, desiredYield, treeTypes);
        String treeReport = "Tree Type | Minimum Seeds | Total Seeds | Total Trees ";
        for (int i = 0; i < treeTypes.length; i++) {
            treeReport += "\n" + treeTypes[i] + " " + minSeeds + " " + totalSeeds + " " + totalTrees;
        }
        JOptionPane.showMessageDialog(null, treeReport);
    }
}

Comment: What is your issue, please mention it clearly.
Comment: You would have less problems if you would move the `printMessage` call into the `getCalculate` method, but I guess this is too obvious.
Answer: Instead of returning desiredYield int array from getCalculate(), which you are not at all using in your printMessage(), you can prepare and return a more meaningful int array i.e. the results having your minSeeds, totalSeeds and totalTrees. And then use it in your printMessage().
With this you need not to declare those variables as class level or static. And this is what is your requirement.
I have commented the updated code with //Updated code... in my answer code snippet for your easy reference.
With int array you need to have index based approach to access the array, in case you want to have more readable approach then an alternative could be preparing and returning a HashMap.
   public static int[] getCalculate(double[]decayRate, int[]desiredYield, String[]treeTypes){
  int totalSeeds =0;
  int totalTrees=0;
  int minSeeds=0;
  int index=0;
  int[] finalResult = new int[3];  //Updated code...
  for(int i=0; i<treeTypes.length;i++){
      minSeeds+=(desiredYield[index] * (decayRate[index]*7))+desiredYield[index];
      totalSeeds+=minSeeds;
      totalTrees+=desiredYield[index];

      }
     finalResult[0] = minSeeds; //Updated code...
     finalResult[1] = totalSeeds; //Updated code...
     finalResult[2] = totalTrees; //Updated code...
   return finalResult; //Updated code...
}

   public static void printMessage(double[]decayRate, int[]desiredYield, String[]treeTypes){
   finalResult = getCalculate(decayRate, desiredYield, treeTypes); //Updated code...

   String treeReport = "Tree Type | Minimum Seeds | Total Seeds | Total Trees ";
   for(int i=0; i<treeTypes.length; i++){
    treeReport += "\n"+treeTypes[i] + " " + finalResult[0] + " " + finalResult[1] + " " + finalResult[2]; //Updated code...
   }
   JOptionPane.showMessageDialog(null, treeReport);
  }

Answer: You declare totalSeeds, totalTrees and minSeeds in getCalculate so of course it can not find these variables. Does getCalculate change at all desiredYield? If not instead of returning this, you should create a list where you put totalSeeds, totalTrees and minSeeds and return this so you can use it later.
Comment: Your answer maybe correct but can use improvement. please read How to improve your answer
http://meta.stackoverflow.com/q/253804/3664960


Divide DataFrame by its lag Error in FUN(left, right) : non-numeric argument to binary operator

Question: I have a dataframe with some asset prices. I would like to get the returns by dividing each column by its lag.
I have the following code:
df=structure(list(A = structure(c(19060, 19061, 19062, 19065, 19066,
                                  19067, 19068, 19069, 19072, 19073), class = "Date"), B = list(
                                    8359.87382308, 8361.93190783, 8364.50494403, 8368.10699178,
                                    8372.3097342, 8376.12364242, 8380.18626964, 8384.41865593,
                                    8387.38878791, 8390.92762529), C = list(48216.51809143, 48205.4923213,
                                                                            48141.39976957, 48018.63247926, 48051.45532043, 48091.22412151,
                                                                            48331.57538464, 48445.10388053, 48469.49369979, 48416.3347324),
                  D = list(17.34859405, 17.34882281, 17.34760762, 17.35130834,
                           17.36756919, 17.37318196, 17.39286354, 17.40391027, 17.40949275,
                           17.41696558), E = list(43.16646812, 43.17551867, 43.16216113,
                                                  43.17305155, 43.25924615, 43.33736433, 43.40667531, 43.45909204,
                                                  43.55074062, 43.60648949), F = list(25.83271054, 25.84295702,
                                                                                25.83724976, 25.85374492, 25.94544031, 26.02025781, 26.07185775,
                                                                                26.1007222, 26.18709194, 26.23574844), G = list(28.510282,
                                                                                28.525803, 28.539868, 28.55125, 28.563602, 28.576996,
                                                                                28.596242, 28.613565, 28.629501, 28.646878), H = list(
                                                                                11.88687581, 11.89326214, 11.89119058, 11.88914284, 11.8977977,
                                                                                11.90032756, 11.90797575, 11.91538244, 11.91918169, 11.92787376),
                  I = list(29.45064815, 29.46287037, 29.47530093, 29.4877662,
                           29.49959491, 29.5124632, 29.526301, 29.5401692, 29.5535557,
                           29.5686575), J = list(15.61856767, 15.62738944, 15.63486662,
                                                 15.61386311, 15.64214889, 15.64560406, 15.69008278, 15.73562823,
                                                 15.7482602, 15.78539406)), row.names = c(NA, -10L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))

df2=mutate(df[,c(2:ncol(df))]/lag(df[,c(2:ncol(df))]))

However I get the error: Error in FUN(left, right) : non-numeric argument to binary operator
I have no idea why this is giving me an issue.
Answer: The columns in the dput are all list columns.  We can unnest them first and loop over the numeric columns (across) and divide by the lag.
library(dplyr)
library(tidyr)
df2 <- df %>%
    unnest(where(is.list)) %>%
    mutate(across(where(is.numeric), ~ .x/lag(.x)))

-output
df2
# A tibble: 10 × 10
   A              B      C     D     E     F     G     H     I      J
   <date>     <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
 1 2022-03-09 NA    NA     NA    NA    NA    NA    NA    NA    NA
 2 2022-03-10  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
 3 2022-03-11  1.00  0.999  1.00  1.00  1.00  1.00  1.00  1.00  1.00
 4 2022-03-14  1.00  0.997  1.00  1.00  1.00  1.00  1.00  1.00  0.999
 5 2022-03-15  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
 6 2022-03-16  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
 7 2022-03-17  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
 8 2022-03-18  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
 9 2022-03-21  1.00  1.00   1.00  1.00  1.00  1.00  1.00  1.00  1.00
10 2022-03-22  1.00  0.999  1.00  1.00  1.00  1.00  1.00  1.00  1.00

It is possible to divide the data with more than one column at once with lag, but then we don't need mutate i.e
df2 <- unnest(df, where(is.list))
df2[-1] <- df2[-1]/lag(df2[-1])


How can $\mathbb{R} \subset \mathbb{C}$?

Question: My book defines $\mathbb{C}$ as $\{(x, y) : x,y \in \mathbb{R} \}$. So even when the imaginary part is zero, the elements of $\mathbb{C}$ are ordered pairs, while the reals are not.
I'm not sure if I should make a different question for this, but my book says that the reals are embedded in $\mathbb{C}$. Does this simply mean that the reals are a subset? Orthat we have an injective function from $\mathbb{R} \to \mathbb{C}$?
Comment: Not _exactly_ a duplicate, but the answers to [What is an advantage as defining $\mathbb C$ as a set containing $\mathbb R$?](https://math.stackexchange.com/questions/876195/what-is-an-advatage-of-defining-mathbbc-as-a-set-containing-mathbbr) have useful discussion of these matters.
Comment: How did you introduce the rational numbers? Is $\mathbb{N} \subseteq \mathbb{Q}$?
Comment: @user159517 Yes that's another issue I had.
Answer: This is one of the quirks that comes up when you formally define the number systems. Usually, it happens none of the number systems $\mathbb{N}, \mathbb{Z}, \mathbb{Q}, \mathbb{R}, \mathbb{C}$ is literally a subset of the next, if you look at the formal constructions.
But each one embeds in an obvious way into the next one, and so there is no real harm in pretending that each is already a subset of the next.  Most of the time, mathematicians will talk as if the number systems are already embedded in each other, except when we are specifically looking at the formal constructions of the number systems.
For example, the map that takes $x \in \mathbb{R}$ and sends it to $x + 0i$ in $\mathbb{C}$ is an embedding. In particular, it is a field isomorphism, so any field property of the reals will also hold for the set $\{x + 0i : x \in \mathbb{R}\}$.
Answer: When people write $\mathbb{R}\subset \mathbb{C}$, they really mean that that there is a ring isomorphism between $\mathbb{R}$ and $\mathbb{R}^\prime = \{(x,0):x\in\mathbb{R}\}$, and that $\mathbb{R}^\prime \subset \mathbb{C}$.
Comment: I don't know any algebra, but I did a quick google search and I think I got the general idea. Isthis synonimous with embedding?
Comment: @Ovi: that's correct
Answer: Adding to that a little bit to the other answers:
The topology of $\; \mathbb{C}$ is often identified with the topology of $\mathbb{R}^2$. We consider the isomorphism:
$$ \pi:\mathbb{R}^2\to\mathbb{C}, (x,y)\to x+iy
$$
where our norms of choice is often $||z||_\mathbb{C}^2=Re(z)^2+Im(z)^2$ and $||(x,y)||_\mathbb{R^2}^2=x^2+y^2$. And from that, you get that $\mathbb{R} \subset \mathbb{C}$, since $\mathbb{R}=\pi(\big\{(x,0)|x\in\mathbb{R} \big\}) \subset \mathbb{C}$.
By using this isomorphism, you can proof a lot of things in $\mathbb{C}$ while "being in $\mathbb{R}^2$". That why your textbook "defines" $\mathbb{C}$ that way. However, note that those are different spaces after all!


HorizontalScrollView: auto-scroll to end when new Views are added?

Question: I have a HorizontalScrollView containing a LinearLayout.  On screen I have a Button that will add new Views to the LinearLayout at runtime, and I'd like the scroll view to scroll to the end of the list when a new View is added.
I almost have it working - except that it always scrolls one view short of the last view.  It seems like it's scrolling without first calculating the inclusion of the new view.
In my app I am using a custom View object, but I made a small test application that uses ImageView and has the same symptom.  I tried various things like requestLayout() on both the Layout and ScrollView, I tried scrollTo(Integer.MAX_VALUE) and it scrolled into the netherverse :)  Am I violating a UI thread issue or something?

Rick

======
    public class Main extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

             Button b = (Button) findViewById(R.id.addButton);
             b.setOnClickListener(new AddListener());

             add();
        }

        private void add() {
             LinearLayout l = (LinearLayout) findViewById(R.id.list);
             HorizontalScrollView s =
                 (HorizontalScrollView) findViewById(R.id.scroller);

             ImageView i = new ImageView(getApplicationContext());
             i.setImageResource(android.R.drawable.btn_star_big_on);
             l.addView(i);

             s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
        }

        private class AddListener implements View.OnClickListener {
             @Override
             public void onClick(View v) {
                 add();
             }
        }
    }

Layout XML:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <HorizontalScrollView
            android:id="@+id/scroller"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scrollbarSize="50px">
            <LinearLayout
                android:id="@+id/list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4px"/>
        </HorizontalScrollView>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center">
            <Button
                android:id="@+id/addButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingLeft="80px"
                android:paddingRight="80px"
                android:paddingTop="40px"
                android:paddingBottom="40px"
                android:text="Add"/>
        </LinearLayout>

    </LinearLayout>

Answer: I think there's a timing issue. Layout isn't done when a view is added. It is requested and done a short time later. When you call fullScroll immediately after adding the view, the width of the linearlayout hasn't had a chance to expand.
Try replacing:
s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);

with:
s.postDelayed(new Runnable() {
    public void run() {
        s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
    }
}, 100L);

The short delay should give the system enough time to settle.
P.S. It might be sufficient to simply delay the scrolling until after the current iteration of the UI loop. I have not tested this theory, but if it's right, it would be sufficient to do the following:
s.post(new Runnable() {
    public void run() {
        s.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
    }
});

I like this better because introducing an arbitrary delay seems hacky to me (even though it was my suggestion).
Comment: That did it exactly Ted, thanks very much, that's been bugging me for days! :)
Comment: @PratikButani - That works, but it would be more efficient to allocate a `Handler` once as a field and use that, rather than creating one on the fly each time. However, since we have the view reference `s` already available, it's best to just use `s.postDelayed(...)`, which nicely sidesteps the need for a `Handler` of our own.
Comment: Hi Ted....when I am trying to use above code then it showing error can not resolve method 'postDelayed(java.lang.runnable, long)'...
please help me....
Comment: @VinitVikash - That's a method in the `View` class. You may need to do `s.postDelayed(...)`. Alternatively, create a `Handler` and use it's `postDelayed()` method.
Comment: `new Handler().postDelayed()` if you don't know how to use `postDelayed()`
Answer: I agree with @monxalo and @granko87 that the better approach is with a listener instead of making an assumption that the layout will be complete if we let some arbitrary amount of time pass.
In case, like me, you don't need to use a custom HorizontalScrollView subclass you can just add an OnLayoutChangeListener to keep things simple:
mTagsScroller.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        mTagsScroller.removeOnLayoutChangeListener(this);
        mTagsScroller.fullScroll(View.FOCUS_RIGHT);
    }
});

Comment: This is the solution I came up with too. Less code, did the work.
Comment: This is by far the correct answer to the problem.
Waiting any random time is nonsense.
Waiting for the layout engine to do its job is the proper one.
Answer: Just another sugestion, since this question helped me a lot :).
You can put a listener when the view has finished its layout phase, and right after do the fullScroll althought you'll need to extend the class for that.
I only did this because i wanted to scroll to a section right after onCreate() to avoid that flickering from starting point to scroll point.
Something like:
public class PagerView extends HorizontalScrollView {

    private OnLayoutListener mListener;
    ///...
    private interface OnLayoutListener {
        void onLayout();
    }

    public void fullScrollOnLayout(final int direction) {
        mListener = new OnLayoutListener() {
            @Override
            public void onLayout() {
                 fullScroll(direction)
                 mListener = null;
            }
        };
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if(mListener != null)
             mListener.onLayout();
    }
}

Answer: Use the View method smoothScrollTo
postDelayed(new Runnable() {
    public void run() {
       scrollView.smoothScrollTo(newView.getLeft(), newView.getTop());
 }
 }, 100L);

You need to put in a runnable so you give time to the layout process to position the new View
Comment: Not working for me. View#getTop() returns position relative to parent, thus this will not work in more nested layouts
Answer: Use below code for horizontal scrollview {Scroll to right}
view.post(new Runnable() {
                @Override
                public void run() {
                    ((HorizontalScrollView) Iview
                            .findViewById(R.id.hr_scroll))
                            .fullScroll(HorizontalScrollView.FOCUS_RIGHT);
                }
            });

Answer: This is what I did.
//Observe for a layout change
ViewTreeObserver viewTreeObserver = yourLayout.getViewTreeObserver();
   if (viewTreeObserver.isAlive()) {
     viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                yourHorizontalScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
            }
     });
   }

Answer: I think the best approach is the one posted by monxalo because you can not know how much time will it take until the layout is done. I tried it and it works perfectly. The only difference is, that I added only one row to my custom horizontal scroll view:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    this.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
}

Comment: I don't think that the amount of time is relevant. The issue is that the scrolling should not happen on the current iteration of the UI thread loop. Once the current iteration is finished, the view hierarchy should be up to date and laid out.
Answer: The child View may not be immediately added in a ViewGroup. So it is required to post a Runnable which will run after other pending tasks are completed.
So after adding View, use:
horizontalScrollView.post(new Runnable() {
    @Override
    public void run() {
        horizontalScrollView.fullScroll(View.FOCUS_RIGHT);
    }
});

Answer: This is my way for 3 ImageViews in kotlin:
var p1 = true; var p2 = false; var p3 = false
val x = -55
val handler = Handler()
handler.postDelayed(object : Runnable {
    override fun run() {

        if (p1){
            mainView.picsScrollViewID.smoothScrollTo(mainView.bigPic1ID.x.toInt() + x, 0)
            p1 = false
            p2 = true
            p3 = false
        }
        else if(p2){
            mainView.picsScrollViewID.smoothScrollTo(mainView.bigPic2ID.x.toInt() + x, 0)
            p1 = false
            p2 = false
            p3 = true
        }
        else if(p3){
            mainView.picsScrollViewID.smoothScrollTo(mainView.bigPic3ID.x.toInt() + x, 0)
            p1 = true
            p2 = false
            p3 = false
        }
        handler.postDelayed(this, 2000)
    }
}, 1400)

Answer: mainView.horizontalScrollImgs.postDelayed(Runnable { kotlin.run { mainView.horizontalScrollImgs.fullScroll(HorizontalScrollView.FOCUS_RIGHT) } },500)

Comment: Stack Overflow recommends against posting just code. Please provide explanation of what your code does and why. Also formatting your code would make it easier to read.
Comment: sure i'll do it


Android OpenGL Circle Texture Doubled

Question: I am trying to draw Circle with texture on it which should be stretched on all vertices.
The problem is that the result i get looks like this:
http://s14.postimg.org/3wyb74469/image.png
I have tried to draw triangle fan as it need to be , first coordinates at 0,0,0
And rest as needed:
http://escience.anu.edu.au/lecture/cg/surfaceModeling/image/surfaceModeling015.png
Also here is the same question and I couldn't get answer for my problem from it :
OpenGL ES, add texture to circle
Loading circle vertices coordinates function:
private final int mVerticesDataSize = 3;
private final int mNumberOfVertices = 180;
private final int mBytesPerFloat = 4;
private float[] vertices;
private  FloatBuffer mVerticesBuff;

public void loadCircleVerticesBuff(Context mActivityContext){

       mVerticesBuff = ByteBuffer.allocateDirect(mNumberOfVertices * mVerticesDataSize * mBytesPerFloat).order(ByteOrder.nativeOrder()).asFloatBuffer();
       vertices = new float[mNumberOfVertices * mVerticesDataSize];
       float theta = 0;

       for (int i = 0; i < (mNumberOfVertices * mVerticesDataSize); i += 3) {
       vertices[i] = (float) (((float) 5*Math.cos(theta)));
       vertices[i + 1] = (float) ((float) 5*Math.sin(theta));
       vertices[i + 2] = 0;
       theta += Math.PI / 90;
       }

       mVerticesBuff.put(vertices);
       mVerticesBuff.position(0);
}

Loading circle texture coordinates function:
private final int mTextureCoordinateDataSize = 3;
public void loadCircleTextureBuff(){
    mCircleTextureCoordinatesBuff = ByteBuffer.allocateDirect(mNumberOfVertices * mTextureCoordinateDataSize * mBytesPerFloat).order(ByteOrder.nativeOrder()).asFloatBuffer();
    mCircleTextureCoordinatesBuff.put(vertices);
    mCircleTextureCoordinatesBuff.position(0);
}

The opengl function used to draw is  :
 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, mNumberOfVertices);

Comment: I've never used OpenGL directly, but in my experience with SFML it looks like your texture isn't being "stretched". Your sprite is smaller than the surface you're painting to, and so it's painted in a repeating pattern (default behavior). Is there a way to set your texture/sprite to zoom/stretch?
Comment: Hi ^^ Normally yeah this is the solution...but unfortenetly not in this case, this is not the texture image size ): but maybe yeah i forgot to use some stretch flag but idk which one it is . please look at the third link i gave its same problem " OpenGL ES, add texture to circle"
Comment: The question you link has an answer. While it's short, I think it explains the solution clearly. You can't use the same values for the vertex positions and texture coordinates to get the desired result. Either define a separate vertex attribute with the correct texture coordinates, or shift/scale the values in your vertex shader.
Answer: So solution found (: 1 very very importent thing i missed up / or openGL missed up.
Texture coordinates can be only in range of 0 to 1 .
So here is the trick/solution :
//Build vertices :
vertices[i] = (float) (((float) raduis*Math.cos(theta)))+raduis;
vertices[i + 1] = (float) ((float) raduis*Math.sin(theta))+raduis;

// Build texture :
 for (int i = 0; i < (mNumberOfVertices * mVerticesDataSize); i += 3) {
           vertices[i] = (vertices[i])/(raduis*2);
           vertices[i + 1] = (vertices[i+1])/(raduis*2);
           vertices[i + 2] = 0;
  }

And here is the res :
http://s2.postimg.org/tno4jr4y1/image.png
Dont forget to flip texture vertices as i forgot (:

Android OpenGL Circle Texture Doubled


Fill A Graphic With Text Using RectangleF and DrawString

Question: I've been asked to generate placeholder graphics for some items in a database but with one caveat - the font size needs to be dynamic so that the text fills the entire graphic.
The first iteration of the code works just fine, but the client wants to the font to be bigger so that the graphics are easier to read. Here's a snippet of the part which generates the text:
using (Graphics Graphic = Graphics.FromImage(Img))
{
   // Add Some Padding
   Width = Width - 20;
   Height = Height - 20;

   // Generate The Text
   Font GraphicFont = new Font("Arial", 26, FontStyle.Bold);
   RectangleF RectF = new RectangleF(10, 10, (float)Width, (float)Height);
   StringFormat sf = new StringFormat();
   sf.Alignment = StringAlignment.Near;
   sf.LineAlignment = StringAlignment.Near;
   Graphic.DrawString(Title, GraphicFont, Brushes.Black, RectF, sf);
}

Is there I can detect text overflow in my RectangleF, or can I detect the size of my DrawString before I apply it to the graphic, or is there some other magic I can do to get the text to fill the graphic?
I would like the text to wordwrap and the font to be the same size for all the words, so it doesn't necessarily need to fill the graphic entirely - hope this all makes sense.
Comment: You'll need to test several preselected font sizes and pick one that fits the rectangle.  Go from, say, 8 points to 24 points in increments of 2.  Do avoid using binary search, it isn't stable.  And use TextRenderer when output goes to the screen instead of a printer.
Comment: Thanks for the advise; if I did it your suggested way, how would I know if the text was overflowing the specified rectangle?
Comment: Start with a rectangle that has the desired width and a very large height.  It doesn't fit when the rectangle you get back has too large a height.
Answer: Use Graphics.MeasureString (documentation: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx)
If you want to size text to fill a region, you can do binary search on different sizes to determine the largest size that still fits in your target region, then use that size to actually draw the string.
Comment: Be nice to get some sample code that the OP was likely to have used after accepting this answer


Como selecionar "1" ou "2" dependendo do valor da coluna, em PL/SQL?

Question: Tenho uma coluna na minha tabela TIPOCLIENTE. Nela aparecem CPF para Pessoa Física e CNPJ para Pessoa Jurídica.
Eu gostaria que no momento do SELECT viessem "1" para CPF e "2" para CNPJ. Como posso fazer isso?
Comment: Porque você não utiliza a condicional no código mesmo, pois assim você pode criar uma função para fazer isso e chama-la quando precisar. Espero ter ajudado.
Answer: Use a condicional CASE.
SELECT lista_de_campos,
    CASE tipocliente
        WHEN 'CPF' THEN 1
        ELSE 2
    END AS novo_tipo_cliente
FROM sua_tabela;

Comment: No lugar da coluna original você coloca a expressão  CASE.
Comment: Mas neste caso ele cria uma nova coluna tipo cliente.

Teria como sair na mesma?
Answer: select c.cpf_cnpj,
       case
          when length(c.cpf_cnpj) > 11 then
           2
          else
           1
       end case
  from (
        select '12345655551' cpf_cnpj
          from dual
        union
        select '01234567000115' cpf_cnpj
          from dual) c

Answer: Select decode(tipo,1,cpf,2,cnpj,null) campo
From tabela

Uma solução com o DECODE.
Ajudou!?
Answer: Seria isso:
Select decode(TIPOCLIENTE,'CPF',1,'CNPJ',2,0) TIPOCLIENTE
  From tabela

No caso, o valor '0' zero, vai retornar caso o valor seja diferente de CPF ou CNPJ. Também daria para tratar para caso não encontre traga a própria coluna, mas aí tem que verificar o tipo de dado, pois como é uma string deve retornar string.


lifecycle delphi datasnap qual usar?

Question: Saudações a todos.
Desenvolvi um app para android usando a tecnologia datasnap reflection REST com JSON delphi usando no server mecanismo de conecxao de dados firedac.
Esse app tem basicamente a função de consulta de dados.
A minha dúvida é qual tipo de lifecycle seria o ideal a ser usado.
Answer: A propriedade LifeCycle tem basicamente três opções:

Server: O servidor mantém uma única instância da classe no server, todos os clientes ao solicitar essa classe receberão sempre a mesma instância (Singleton).
Session:  O servidor mantém uma instância da classe por sessão do DataSnap, cada cliente recebe uma instância diferente da classe.
Invocation: A cada invocação de um cliente uma instância da classe será criada e logo depois destruída (Stateless).

A documentação cita que para clientes REST, se o ciclo de vida escolhido for Session em DSServerClass, Session se comportará como sendo Invocation. Se não tiver maiores problemas, a primeira opção, Server, pode ser apropriada.
Comment: Estou usando Session e ele está se comportando como Session, tanto é que depois de um tempo de inatividade ele perde a sessão e tenho que reconectar. Na verdade eu queria saber que prejuízo eu tenho em usar invocation no meu caso.
Comment: @edmjunio Basicamente ao usar *invocation* você cria uma nova instância para cada invocação do cliente.
Comment: Ok isso eu tenho ciência mas teria algum ônus essa modalidade?  Pelo que eu andei lendo a tecnologia REST é por padrão statless ou seja invocation. Eu uso autenticação no processo de acesso será que usando invocation terei que refazer a autenticação a cada solicitação ao server ?
Comment: @edmjunio Acredito que em teoria sim.
Comment: Vou testar e reporto
Answer: Modifiquei o lifecycle no server para invocation. No cliente, modifiquei a propriedade PreserveSessionID do componente DRestConection para false pois não tenho a necessidade de gerenciar ou criar sessões. Desta forma caso ocorra indisponibilidade do server ou do link de internet assim que a interrupção for sanada o app conseguirá refazer a conexão.
A rotina de segurança que eu uso, é aplicada em dois momentos, no momento da criação do mainform onde os menus são montados e durante a conexão do componente DRestConection onde são passadas o login e senha para acesso aos métodos do servidor.
A principio funcionou estou fazendo mais testes para chegar a uma conclusão final.
Obrigado a todos pela ajuda.
Comment: Se isso funcionou para você, marque a sua resposta como aceita. Veja mais detalhes [aqui](http://meta.pt.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079).
Answer: Se vc estiver utilizando REST e sem sessão o q é session naturalmente fica invocation nao precisa nem mudar. Pela caracteristica do protocolo mesmo. Conecta processa e desconecta.

lifecycle delphi datasnap qual usar?


Rails Devise NON HTML email

Question: I've following setting in my Application.rb file
Devise::Mailer.layout "Mailer Layout Name"

I'm sending both HTML and NON-HTML(text) emails. I want to ignore the "Devise::Mailer.layout" for Non-HTML(text) email. Is there anyway to get this done in Devise and Rails.
I'm using Rails 4.2.4 & devise (3.5.1)
Answer: This is standard ActionMailer functionality, not related to Devise.
class UserMailer < ActionMailer::Base
  layout :layout

  private

  def layout
    'my-layout' if content_type == 'text/html'
  end
end

Rails Devise NON HTML email


How to switch from Fixed-do solfège to Movable-do?

Question: I was born in a country where Fixed-do solfége is the standard. I was taught to use it from a very early age. It's deeply engraved in my brain.
However, I plan to leave the country and study music in Austria, where movable-do is the norm. I've tried many times, but I simply cannot do movable-do. Fixed was hammered into my brain from the age of 8. I don't know how to not do it. I suspect others probably face similar challenges when studying music abroad.
Any recommendations on how to switch?
Comment: @nuggethead Wouldn't it be better to learn the letters A to G instead?
Comment: What about starting to learn it using the numbers 1-7 instead of do-re-mi?
Comment: Actually @SimonB I think numbers are better.  Assign 1 to the first scale degree in any key and practice learning the relationships that way.  Using the letters A through G isn't much different than fixed do.
Comment: Once the numbers are learned, the OP might have the flexibility to sing do for 1, re for 2, and so on.
Comment: @nuggethead but musicians in Austria use the letters (A through H in fact) to denote absolute pitches.  It's surely better to learn the system that everyone else is using.
Comment: @phoog I guess the question is what the OP wants.   According to the title, op wants to learn movable do.  If not, I agree that letter names would be more helpful
Answer: First of all (though off topic to the question but important for the situation): In Austria we use movable-do solfeggio pretty much exclusively in basic music education, such as in teaching melodies, scale degrees, ear training and such. Primarily we use note names (C-D-E-F-G-A-B/H) for notes and numbers for scale degrees or functions.
You do not need to be proficient in movable-do solfeggio to be able to study music in Austria!
Now, on how to change: Usually when we employ solfeggio this does often not include actual written notes, but rather it is used in pedagogics to teach melodies or scales without notes. So unless you have perfect pitch it is just a matter of taking everything as C major.
I know this is not a good answer to the actual question, but it is a bit too long for a comment, so I'm putting this down as answer.
Point is: If you want to study music in Austria do not worry too much about solfeggio (unless you want to go into music pedagogics). You should try to have a good grasp of the German language and of the C-D-E-F-G-A-B/H note names (optimally to the point where you can understand these names directly as notes without having to translate them to solfeggio first). Because you want to understand as much as you can. If you have problems with movable-do solfeggio, teachers will understand. But if you unstand only 80% of what is said it will be much harder for you to understand what is going on.
Comment: How wonderful to hear from an Austrian on this!

I want to study composition, so I'm not super concerned about solfeggio with regard to pedagogics haha. I'm mainly concerned about it because entrance exams in Austria seem to always require good sight-singing skills. They even require atonal sight singing, which I'm rather scared about lol, do you think it would be a big problem if I did these exams without using movable-do solfege?
Comment: @John05 You do not need solfeggio to sight-sing a piece. If they bring something like this they most like want to assess if you are able to understand a melody from looking at the notes without having to play them. If you feel uncomfortable about this it is wiser to spend your time training this instead of forcing yourself to do it in movable-do solfeggio. I'm quite sure they's accept you singing on *la-la* or something. Do you have a specific place in mind? Vienna? Salzburg? Linz? Klagenfurt? Graz? You might just want to write a mail and directly ask if movable-do solfeggio is required.
Comment: that's a wise suggestion! My 1rst choice would be the "Universität für Musik und darstellende Kunst Wien," which you are probably familiar with. However, their entrance exam is spectacularly difficult, so obviously I would be open to other options. If you don't mind me asking though, have you had any experience with music entrance exams in Austria? I would appreciate any tips/wisdom on that front!
Answer:
As a first step, learn an entirely different system. It could be numbers (0 = C; 1 = C#; 2 = D; ...), scale degrees, or note names, for example, but what you're looking for is anything that disrupts your connection to fixed do. A couple of other possibilities: Indian classical music has a solfege system called sargam that can be adapted to operate like do-based systems. Or create your own system (say, T for tonic; U for supertonic; M for mediant; etc....)

(Optional) Once you're comfortable (enough) with the new system — meaning, you can use it without getting unduly distracted by do-based thinking — convert the new system to a movable system. Let's say, for example, the "new" system was numbering the notes 0 to 11 — that's a "fixed" system, but it can be converted to a moveable system by shifting from 0 = C to 0 = Tonic.

Once you have a moveable non-do solfege system, convert back to do, but now in moveable form.
Comment: I agree,  mostly.  Yes to disrupting the fixed do system.  But I don't see the value in giving each pitch a number, such as c=0, c#=1 etc.  For movable do to work, the syllable do (or the number 1) isn't assigned to a specific note, but to the tonic.
Comment: @nuggethead Agreed. That's why an interim stem might be needed to shift a new fixed system to a new movable system. If the "new" system is already moveable, then step (2) isn't needed.
Answer: Working with French musos, having been steeped in movable do, I appreciate your problem from the opposite side!
Chances are, you will by now have developed a pretty good 'absolute pitch', where do has always been C.
It's going to be (as you've already found) a hard job to change. However, a way round might be to get used to the idea that there's a change of key for every piece - which is in fact true!
So, instead of regarding a piece in key D having the D as re, ignore your instinct, and pretend the key is actually C, so that D now becomes do. Which is exactly what movable do is all about. This will be difficult while looking at the dots, but easier when playing them on an instrument.
In other words, accept it for what it is, and don't try to translate from fixed to moveable, just gently take the time to learn the new system, and regard it as that.
Otherwise, try using diatonic numbers - as in ^1 for tonic, ^5 for dominant, etc., without referring any of that back to fixed do (unless the piece is actually in key C!). Sharps and flats (accidentals, not key sig.) will be needed - but they are in both systems anyway. Best of luck - it'll take time, and effort.


Binding a usercontrol to SQL datatable

Question: I have a user control that is supposed to view some data from a SQL datatable. My database class is called DBManager it has a property called ResTable which is of type Datatable. It has data that is relevant to what is in my user control. Upon retrieval of the Table i want to instantiate a number of controls as the number of rows in the Datatable and bind each field with the corresponding one in the table. I know how to bind comboboxes but not usercontrols.
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Menupedia"
mc:Ignorable="d"
x:Class="Menupedia.RestaurantViewer"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Width="330" Height="150">
<Grid x:Name="LayoutRoot" Width="330">

    <Image x:Name="image_Logo" HorizontalAlignment="Left" Margin="16,13,0,37" Width="100"/>

    <ComboBox x:Name="combobox_Branch" Height="30" Margin="0,21,29,0" Style="{DynamicResource MPComboBox}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="135"/>
    <Image Margin="126,55,0,59" Source="Images/Phone.png" Stretch="Fill" HorizontalAlignment="Left" Width="36"/>
    <Image Margin="120,13,164,0" Source="Images/Branch.png" Stretch="Fill" Height="46" VerticalAlignment="Top"/>

</Grid>

The corresponding object of this usercontrol has no properties. I though have a class called Restaurant that have the same format as that of the Datatable i am using but i don't know how to fill it either.
Answer: You can make constructor of the user control take in parameters. You can then bind the controls of user controls to the passed parameters. Example:
 public partial class TestControl : UserControl
 {
    public TestControl()
    {
        InitializeComponent();
    }

    public TestControl(string name)
    {
        lblName.Content = name;
        InitializeComponent();
    }
 }

Use it as:
TestControl tc = new TestControl("Austin");

Binding a usercontrol to SQL datatable


Questions on Inverting Laplace transforms and Probability

Question: From Williams' Probability w/ Martingales:

Are we allowed to switch derivative and integral as follows:

$$\frac{\partial}{\partial \lambda} \int_{0}^{\infty} e^{-\lambda x} f(x) = \int_{0}^{\infty} \frac{\partial}{\partial \lambda} e^{-\lambda x} f(x) $$
?
Why/Why not?

Assuming the $E[f(S_n)]$ equation is true, how does one prove the $f(y)$ equation?

That is, consider $E[f(S_n)]$ as a function of $\lambda$:
$$E[f(S_n)] = E[f(S_n)](\lambda) = \frac{(-1)^n (\lambda)^n L^{n-1}(\lambda)}{(n-1)!}$$
If $\lambda = \frac{n}{y}$, then
$$E[f(S_n)](\frac{n}{y}) = \frac{(-1)^n (\frac{n}{y})^n L^{n-1}(\frac{n}{y})}{(n-1)!}$$
How does one prove that
$$\lim_{n \to \infty} E[f(S_n)](\frac{n}{y}) \left(= \lim_{n \to \infty} \frac{(-1)^n (\frac{n}{y})^n L^{n-1}(\frac{n}{y})}{(n-1)!} \right) = f(y)?$$
Answer: I also worked on this problem several days before. My point of view:
(1) Yes we are allowed to. Because $\partial_{\lambda}^{n-1}(e^{-\lambda x}f(x))$ exists and it is continuous.
(2) By weak law
$$\frac{S_n}{n}\to \mathbb{E}(X_1)=\frac{1}{\lambda}~~\text{in probability.}$$
In other words,
$$S_n \to \frac{n}{\lambda}=:y~~\text{in probability.}$$
Composition with a continuous function $f$ preserves convergence, so
$$f(S_n)\to f(y)~~\text{in probability.}$$
Now apply bounded convergence theorem, and replace $\lambda$ with $\frac{n}{y}$,
$$f(y)=\mathbb{E}(f(y))=\lim\limits_{n\rightarrow\infty}\mathbb{E}\left[f(S_n)\right]$$
Comment: Thanks zed! I guess I understand convergence in probability, but it wasn't discussed at that point in the book. I thought of something else based on what you commented. Editing now
Comment: Posted an answer
Answer: Define $B_n(y) := E[f(S_n)](n/y)$, $Y_n := |f(S_n) - f(y)|$ and $Z_n := |S_n - y|$
Since f is bounded and continuous on $[0,\infty)$, it is bounded and continuous on $[0,M] \ \forall M > 0$ and hence uniformly continuous in $[0,M]$.
$\to \forall \epsilon > 0, \exists \delta > 0 \forall x, y \in [0,M]$ s.t.
$$Z_n \le \delta \to Y_n < \epsilon/2$$
Let us try to show that $\forall \epsilon > 0, \exists N > 0$ s.t. $n > N \ \to \ |B_n(y) - f(y)| < \epsilon$:
$$|B_n(y) - f(y)|$$
$$ = |E[f(S_n)](n/y) - f(y)|$$
$$ = |E[f(S_n)](\lambda)|_{\lambda = n/y} - f(y)|$$
$$ = |(E[f(S_n)] - f(y))(\lambda)|_{\lambda = n/y}|$$
$$ = |(E[f(S_n) - f(y)])(\lambda)|_{\lambda = n/y}|$$
$$ = (|E[f(S_n) - f(y)]|)(\lambda)|_{\lambda = n/y}$$
By Jensen's Inequality,
$$ \le (E[|f(S_n) - f(y)|])(\lambda)|_{\lambda = n/y}$$
Omitting $\lambda$ for now
$$ = E[|f(S_n) - f(y)|]$$
$$ = E[Y_n]$$
$$ = E[Y_n 1_{Z_n \le \delta} + Y_n 1_{Z_n > \delta}]$$
$$ = E[Y_n 1_{Z_n \le \delta}] + E[Y_n 1_{Z_n > \delta}]$$
$$ < E[\epsilon/2 1_{Z_n \le \delta}] + E[Y_n 1_{Z_n > \delta}]$$
$$ = \epsilon/2 E[1_{Z_n \le \delta}] + E[Y_n 1_{Z_n > \delta}]$$
$$ = \epsilon/2 P(Z_n \le \delta) + E[Y_n 1_{Z_n > \delta}]$$
$$ = \epsilon/2 (1) + E[Y_n 1_{Z_n > \delta}]$$
$$ = \epsilon/2 + E[Y_n 1_{Z_n > \delta}]$$
$$ \le \epsilon/2 + E[2K 1_{Z_n > \delta}]$$

Note: $\exists K > 0$ s.t. $|f(x)| \le K \forall x \in [0, M]$
$\to \ Y_n = |f(S_n) - f(y)| \le |f(S_n)| + |f(y)| \le K + K = 2K$

$$ = \epsilon/2 + 2K E[ 1_{Z_n > \delta}]$$
$$ = \epsilon/2 + 2K P(Z_n > \delta)$$

By Chebyshev's Inequality, $\forall \delta > 0, P(Z_n > \delta) = P(|S_n -
 \frac{n}{\lambda}| > \delta) = P(|S_n - \frac{n}{\lambda}| > n\delta)$
$= P(|\frac{S_n}{n} - \frac{1}{\lambda}| > \delta) \le \frac{1}{n
 \lambda^2 \delta^2}$

$$ \le \epsilon/2 + 2K \frac{1}{n \lambda^2 \delta^2}$$
$$\le \epsilon/2 + \epsilon/2 = \epsilon$$
if we choose $\color{red}{N}$ as such:
$$2K \frac{1}{n \lambda^2 \delta^2} < \epsilon/2$$
$$\frac{1}{n \lambda^2 \delta^2} < \frac{\epsilon}{4K}$$
$$\frac{1}{n} < \frac{\lambda^2 \delta^2 \epsilon}{4K}$$
$$n > \frac{4K}{\lambda^2 \delta^2 \epsilon} \color{red}{= N}$$
Not sure what to do about the $\lambda$, but it seems that $\forall \epsilon > 0$,
$$n > \frac{4K}{\lambda^2 \delta^2 \epsilon} \to Y_n < \epsilon/2$$
$$\to |B_n(y) - f(y)| < \epsilon \ QED$$
$$\therefore \ \lim_{n \to \infty} B_n(y) = f(y)$$


What are good resources to learn about GLM?

Question: Generalized linear models (GLM's) are apparently widely used, but I'm having some trouble to find comprehensive but still simple resources to explain it to someone who is not a statistician but has a basic background on statistics.
Currently I have found the following references:

Wikipedia GLM article
This book (I didn't have access to it yet):MCCULLAGH, Patrick; NELDER, John A. Generalized linear models. 2nd ed. London: Chapman & Hall/CRC, 1995. 511 p.
This paper (very hermetical): McCullagh, Peter. "Generalized linear models." European Journal of Operational Research 16.3 (1984): 285-292.

Looking for websites, books or research papers.
Comment: This post might be helpful http://stats.stackexchange.com/questions/94371/reference-request-generalized-linear-models
Comment: For non-statisticians I would start with the Gelman-Hill reference from the above comment.
Comment: I've found this good. Not knowing much about soil science is not a barrier to finding it useful.  Lane, P. W. 2002.
Generalized linear models in soil science. _European Journal of Soil Science_ 53: 241-251 DO  - 10.1046/j.1365-2389.2002.00440.x
Comment: [This](http://www.sagepub.com/upm-data/21121_Chapter_15.pdf) borrows heavily from McCullagh and Nelder and I've found it to be a convenient reference. Also Faraway's book on GLMs is popular (if you google it I believe you can find a free pdf).
Comment: In the duplicate post check in particular the Dobson book & Rodriguez lecture notes (which I just added) for introductory accounts.
Answer: To the references of the above comment, I would like to add "Introduction to Categorical Data Analysis" by Alan Agresti.
The book is precisely intended for non-statisticians and I believe it is commonly used as a first couse in the theory of GLM. Its main focus is logistic regression but you also see the Poisson, Negative Binomial and Gamma models in worked out examples. The book uses SAS but not to worry. There is an R-manual that also accompanies it]2, one important difference between SAS and R being of course that the latter is freely available.
I believe there is a free pdf version available somewhere on the internet, so take a look. If you are finding it too easy, you might also want to try its twin, which is intended for more advanced students.


Allow a user to restart a service

Question: I am trying to restart a service without being root. Here is the code snippet where the command being used
template {
  source      = "{{vault_template_dir}}/agent.crt.tpl"
  destination = "{{vault_tls_dir}}/agent.crt"
  command     = "/usr/bin/systemctl restart vault.service"
}

after researching and reading similar issues, I've tried to give a limited sudo command for the group I an using (user=vault, group=vault) by editing the /etc/sudoers file and adding the following line:
%vault ALL=(root) NOPASSWD: /usr/bin/systemctl restart vault.service

However, I am still getting an error when I try and run the command. error log file:
Apr  4 23:27:41 xxxxxx vault[133973]: Failed to restart vault.service: Interactive authentication required.

vault.service
[Unit]
After=network.service hostname.service consul-init.service consul.service
Description="Hashicorp Vault - A tool for managing secrets"
Documentation=https://www.vaultproject.io/docs/
StartLimitInterval=200
StartLimitBurst=5

[Service]
User=vault
Group=vault
ExecStart=/usr/bin/vault server -config="{{vault_server_config_file}}"
ExecReload=/usr/bin/kill -HUP $MAINIP
CapabilityBoundingSet=CAP_SYSLOG CAP_IPC_LOCK
LimitNOFILE=65536
LimitMEMLOCK=infinity
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target

can someone please help me with this issue?
Comment: Exactly what command did you execute as the vault user? What happens when you restart the service as root?
Comment: @pmdba it is another service `vault-agent.service` looks almost identical to `vault.service` except the `ExecStart=/usr/bin/vault server..` part has `agent` as an argument instead of `server`
Answer: You need to use sudo to execute command, so your template needs to look like this:
template {
  source      = "{{vault_template_dir}}/agent.crt.tpl"
  destination = "{{vault_tls_dir}}/agent.crt"
  command     = "sudo /usr/bin/systemctl restart vault.service"
}

For future, make sure to edit sudoers file with visudo program. If you directly edit /etc/sudoers, a mistake can lock you out of the system.
Comment: Yes, thanks for the hint. I am doing it with Ansible which has the visudo as a validation option.

Allow a user to restart a service


Very basic question about task

Question: As a machine learning super beginner I decided to play around with some programs that can perform action recognition task. I decided to give this one a try:
x
1) I don't really understand why accuracy number for each iteration is so high. I decided to print out the values of TN, TP, FN and FP for diving action and here's what I got:
TP =  9
FP =  4
FN =  1
TN =  109
Why is there such a disparity between these numbers? I have to admit that I don't now much about programming in Python and can't fully grasp how the program exactly works.
Answer: Because most examples in your training set are not of the diving action. This leads to class imbalance, and accuracy is a mostly meaningless metric in the presence of significant class imbalance. Here is your confusion matrix:
<code>                      P |   N | Total
------------------------+-----+------
Prediction Positive   9 |   4 |   13
Prediction Negative   1 | 109 |  110
------------------------+-----+------
              Total  10 | 113 |  123
</code>
Note that 113/123 of your actions are not diving, while only 10 are. That means that even if I just guessed "not diving" every time, I would be right 92% of the time! That means that 92% accuracy is the "floor" for any non-trivial model. A model would have to be truly broken to get less than that! Sure, your model gets 96% accuracy, but it's really only edging out the constant model by 4%. The moral of the story is that accuracy is basically the wrong metric to look at in the presence of class imbalance, not only because it will be inflated, but also because it will be inflated by a different amount depending on prevalence, making it very difficult to compare performance across difference classes (actions in your case.)
AUC ROC is a widely used metric in these cases, and one of the reasons is that it is insensitive to changes in class prevalence. Another metric (less commonly used but closer in spirit to accuracy) is Matthews correlation coefficient. The $F_\beta$ score (for a suitable choice of $\beta$ that incorporates your own priorities) is also a good choice. Any of these should be more useful and easier to interpret than accuracy for your case.
Comment: Most of the criticisms at [Why is accuracy not the best measure for assessing classification models?](https://stats.stackexchange.com/q/312780/1352) also apply to AUROC and to $F_\beta$.

Very basic question about task


Drupal Installation running without settings.php (multisite)

Question: What we intended to achieve was setup drupal.abcd.com as main installation of multisite setup, and abcd.com, xyz.com, pqrs.com as sub-sites of the multisite setup.
The main installation (drupal.abcd.com) should contain the default Drupal installation (with the Bartik theme), and abcd.com should have the ABCD theme with content.
drupal.abcd.com is automatically taking the settings.php file from abcd.com. So, when I make change in abcd.com (e.g. setting a different database) the same change is done for drupal.abcd.com.
I also tried deleting drupal.abcd.com/sites/default/settings.php, but I can visit drupal.abcd.com with same settings as abcd.com.
The installation and creation of folders were done by the customer; I don't know what mistake he did.
Could anyone please suggest me where things might have gone wrong, or what can be done to avoid this behavior, and run everything as normal?
Comment: `Drupal Installation running without settings.php` This is totally misleading its like `My Car is running without gas`
Answer: Have a look at sites.php in your sites folder.
<code> $sites = array(
   'devexample.com' => 'example.com',
   'localhost.example' => 'example.com',
 );
</code>

The above array will cause Drupal to look for a directory named
  "example.com" in the sites directory whenever a request comes from
  "example.com", "devexample.com", or "localhost/example".

So in your case you should have <code>'drupal.abcd.com' => 'default'</code>
The reason why its picking up settings file from abcd.com is because when a request comes for drupal.abcd.com it looks for folder drupal.abcd.com since that folder is not there it will look for next match like abcd.com and it picks it up from there.
I am not sure about Drupal 7 site set up but playing around with sites.php should fix it.
Comment: Thank you Kantu for the quick response. But I can not see sites.php in sites folder. And in example.sites.php everything is commented. So is there any other possibility that could be causing this to happen? Thank you.
Answer: With kantu's help the problem is fixed now.
What I did was copying examples.sites.php, and creating the sites.php file.
Then, I uncommented the last two lines of sites.php, and re-wrote them as:
<code> $sites['drupal.abcd.com'] = 'default';
 $sites['abcd.com'] = 'abcd.com';
</code>


Criar efeito de botão apertado

Question: Tenho o seguinte componente no React:
import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: parseInt(this.props.value)
    };

    this.inc = this.inc.bind(this);
    this.dec = this.dec.bind(this);
  }

  inc() {
    this.setState({ count: this.state.count + 1 });
  }

  dec() {
    this.setState({ count: this.state.count - 1 });
  }

  render() {
    return (

          O valor inicial é: {this.props.value}.

          O valor atual é: {this.state.count}.

          <button onClick={this.inc}>Incrementar</button>
          <button onClick={this.dec}>Decrementar</button>

    );
  }
}

module.exports = Counter;

Ele basicamente tem um número, que, ao pressionar um botão, é incrementado em um. Desse modo, a cada clique, o valor aumenta um.
Como faço para que, ao manter esse botão pressionado (mantendo o botão esquerdo do mouse pressionado), o valor continue a ser aumentado (até que eu pare de pressionar o botão esquerdo)?
Answer: Defina dentro do método construtor uma variável, exemplo:
this.interval = null;

Ela ira guardar o temporizador setInterval, agora crie um método para limpar o temporizador:
clear() {
    clearInterval(this.interval);
    this.interval = null;
}

No método construtor faça o bind do novo método:
this.clear = this.clear.bind(this);

Deve fazer a seguintes modificações nos métodos inc e dec:
inc() {
    if (this.interval === null) {
        this.interval = setInterval(this.inc, 100);
    }
    this.setState({ count: this.state.count + 1 });
}

dec() {
    if (this.interval === null) {
        this.interval = setInterval(this.dec, 100);
    }
    if (this.state.count > 0) {
        this.setState({ count: this.state.count - 1 });
    }
}

Altere os eventos onClick para onMouseDown e adicione o evento onMouseUp o qual ira executar o método clear, ficando assim o código:
<button onMouseUp={this.clear} onMouseDown={this.inc}>Incrementar</button>
<button onMouseUp={this.clear} onMouseDown={this.dec}>Decrementar</button>

Exemplo funcionando

class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      count: parseInt(this.props.value)
    };
    this.interval = null;
    this.clear = this.clear.bind(this);
    this.inc = this.inc.bind(this);
    this.dec = this.dec.bind(this);
  }

  inc() {
    if (this.interval === null) {
      this.interval = setInterval(this.inc, 100);
    }
    this.setState({ count: this.state.count + 1 });
  }

  dec() {
    if (this.interval === null) {
      this.interval = setInterval(this.dec, 100);
    }
    if (this.state.count > 0) {
      this.setState({ count: this.state.count - 1 });
    }
  }

  clear() {
    clearInterval(this.interval);
    this.interval = null;
  }

  render() {
    return (

          O valor inicial é: {this.props.value}.

          O valor atual é: {this.state.count}.

          <button className="inc" onMouseUp={this.clear} onMouseDown={this.inc}>Incrementar</button>
          <button className="dec" onMouseUp={this.clear} onMouseDown={this.dec}>Decrementar</button>

    );
  }
}

ReactDOM.render(<Counter value="0" />, document.getElementById('app'));
button {
  border: 0;
  color: #fff;
  cursor: pointer;
  font-family: 'Verdana', sans-serif;
  font-size: 1em;
  padding: 8px;
  text-transform: uppercase;
}

.inc {
  background: #388E3C;
  margin-right: 14px;
}
.dec {
  background: #E57373;
}

Se preferir você pode ver funcionando em codesandbox.io

Referência

setInterval
clearInterval
Comment: Obrigado pela ajuda.
Comment: Bem legal. É isso aí.

Criar efeito de botão apertado


Computing second point of intersection on Elliptic Curve.

Question: This is a problem from http://www.williamstein.org/ent/ent.pdf

Problem 6.2. One rational solution to the equation $y^2=x^3-2$ is $(3,5)$. Find a rational solution with $x$ not equal to $3$ by drawing
  the tangent line to $(3,5)$ and computing the second point of
  intersection.

My attempt: So I have drawn the graph, and have points $P_1=(3,5)$ and $P_2=(3,-5)$.
I used (with uncertainty) the Elliptic Curve group law such that $\lambda=(3x_1^2+a)/(2y_1)$, and got $27/10$ for my value.
I then used the equation $Q=(\lambda^2-x_1-x_2, -\lambda x_3-v), v = y_1 - \lambda x_1, x_3 = \lambda^2 - x_1 - x_2$.
From this, I got the following: $Q=(1.29,-5)$.
The answer in the book says that $(129/100, 383/1000)$ is the correct answer.
Could anybody help me figure this out with a solution?
Did I coincidentally get $1.29$ for my $x$-coordinate?
Comment: Did you use the tangent line? You picked two points instead.
Comment: Unfortunately I don't know how to. I'm stuck.
Comment: Is that not exactly what I did?
Comment: I did use the formula for P1=P2, and the answer I get is the one above.
Comment: Here's a [sagemath cell solution](https://sagecell.sagemath.org/?z=eJxNUMEOgjAMvS_ZPyw7AY7oWLyYeDJkFw9wRkgUSSQqEsSF_b3t0GmWdK_vvXbtikkKK0u2ZYUS65KSfmi7kfHC81x8MCX74_10PgIXqGiSVRIugySyMvRV3sDFDCmhZFJAzGmVsJhN0gVKDPAWk1mMkLNojr-EAtH47sY1Nn8zKmHVd0aHvQahGZ5NPbaPDpcDOf73YiL4oeM44admd2nq6waYFGzp7db2Y1vvXoNpgjwXxUrMJ07K38bpBhqm2ERjUQCf-BOzB17aPaopyQDohfYyYCdlbpA3LBlnVQ==⟨=sage) if you want to check the compuations.
Answer: There was a little mistake in the calculations. Point doubling requires $P_1=P_2=(3,5)$. Next find $\lambda=(3x_1^2+a)/(2y_1)=27/10.\;$ Now $\;x_3=\lambda^2-x_1-x_2=729/100-3-3=129/100\;$ and $\;y_3=\lambda(x_1-x_3)-y_1=27/10(3-129/100)-5=-383/1000.\;$ There is a sign difference because $P_3$ is the sum of $P_1$ and $P_2$. The second point of intersection is $(129/100,383/1000).$
You can easily check the point doubling using PARI/GP with the following code:
$$\texttt{E=ellinit([0,0,0,0,-2]); print(ellmul(E,[3,5],2))}$$
with the resulting output
$$\texttt{[129/100,-383/1000]}$$


Attribute Error 'module' object has no attribute 'ascii_letters'

Question: Why do I receive the error message in the title from the code below?
Edit: Cause I didn't pay attention to how I wrote "ascii". Thanks everyone
The code below works fine on my Iphone IDE but not on my Windows 7 (w/Notepad++ and Command Prompt). I checked the directory to see if any string.py files existed which I did not see any. I ran a search on my desktop and found 4 files named that, two of which said they were complied. I deleted the compiled files and left the other two. I'm a noob.
import string
import random

x = string.acsii_letters
y = random.choice(x)

print y * 5

Comment: The error you'll get is `AttributeError: 'module' object has no attribute 'acsii_letters'` it's funny that you posted the correct "ascii" in the title tho
Comment: it is `ascii` not `acsii`
Comment: What version of python?
Comment: @ChadSimmons python 2.7 per title
Answer: It should be string.ascii_letters letters instead of string.acsii_letters. If that's a typo in code statement here only, then your guess must be right, there is another string module in your PYTHONPATH. Open python shell,
import string
print(string.__file__)

to ensure string is being imported from right path. If its not remove that path from PYTHONPATH.
Answer: In python 3 I found that using the string.ascii_letters works as string.letters results in an AttributeError.
Answer: You have a typo. It should be string.ascii_letters or string.letters. You can look at the attributes of the string module with dir(string) and see what you can access.
Answer: i  had the same issue the reason was that the name of the file is the same of the module name . so just rename your file the module will work well
Comment: This question has already been answered six years ago.


$m\mathbb{Z}= \bigsqcup_{s=0}^{n-1} ms + mn\mathbb{Z}$

Question:
Claim: $m\mathbb{Z}= \bigsqcup_{s=0}^{n-1} ms + mn\mathbb{Z}$

May I know if my proof is correct? Thank you.
If $m=0,$ the claim is obviously true.
Now, let $m \neq 0.$
Suppose $\exists s,s'(\neq s) \in \{0,1,...,n-1\}$ such that $(ms + mn\mathbb{Z}) \bigcap (ms' + mn\mathbb{Z}) \neq \emptyset.$
$x \in (ms + mn\mathbb{Z}) \bigcap (ms' + mn\mathbb{Z}).$
$ \implies ms + mnr = ms' +mnr',$for some $r,r' \in \mathbb{Z}.$
$\implies n| s-s'.$ (Contradiction)
Given $z\in m\mathbb{Z},$ there exists $y\in \mathbb{Z}$ such that $z=my.$ Also, $\exists q,r\in \mathbb{Z},$ with $0\leq r \leq n-1,$ such that $z= m(nq+r).$ Hence $z \in \bigsqcup_{s=0}^{n-1} ms + mn\mathbb{Z}.$ It is clear that $\bigsqcup_{s=0}^{n-1} ms + mn\mathbb{Z} \subseteq m\mathbb{Z}$
Comment: You should first do the case $m=0$ separately.
Comment: Thank you, I have made necessary amendments.
Answer: The proof is correct, under the unstated assumption that $n>0$.
Here's a refinement, because contradiction is not necessary in the first part.
The case $m=0$ is obvious, so we can assume $m\ne0$. Suppose $0\le s<n$ and $0\le s'<n$ and that $z\in(ms+mn\mathbb{Z})\cap(ms'+mn\mathbb{Z})$. We can assume $s\ge s'$ without loss of generality; in particular $s-s'<n$. Then
$$
z=ms+mnr=ms'+mnr'
$$
for some $r,r'\in\mathbb{Z}$. Therefore $n\mid(s-s')$ with an obvious simplification, so $s=s'$. Thus the sets
$$
ms+mn\mathbb{Z}\quad(s=0,1,\dots,n-1)
$$
are pairwise disjoint. It is also clear that their union is a subset of $m\mathbb{Z}$.
If $mr\in\mathbb{Z}$, then $r=nq+s$, for some $q$ and $s$, with $0\le s<n$, so $mr=ms+mnq\in (ms+mn\mathbb{Z})$. Therefore $m\mathbb{Z}$ is contained in the union of those sets.

A different proof. It is well known that $\mathbb{Z}=\bigsqcup_{s=0}^{n-1}(s+n\mathbb{Z})$, because this is the partition relative to the congruence modulo $n$. Since the map $f\colon r\mapsto mr$ from $\mathbb{Z}$ to $m\mathbb{Z}$ is bijective (for $m\ne0$), we immediately get that
$$
m\mathbb{Z}=f(\mathbb{Z})=\bigsqcup_{s=0}^{n-1}f(s+n\mathbb{Z})
=\bigsqcup_{s=0}^{n-1}(ms+mn\mathbb{Z})
$$


Filtering a R datatable subtable

Question: I have a shiny app with a dataframe displayed as a datatable. Filtering is enabled and working fine. However, some of the data are tags, and every object has several tags, resulting in a very large table with a lot of redundant data. What I would like to do is to aggregate the tags in a subtable (or another way) but still be able to filter for every tag.
My data is similar to this:
df <- data.frame(name=c(1,1,1,2,3,3), color=("blue","blue","blue","red","green","green"), tags=c("fine","awesome","cute","sweet","cute","fine"))

output$myTable <- DT::renderDataTable ({
datatable(df, filter = 'top')
})

My datatable looks currently like this:

name
color
tags

1
blue
fine

1
blue
awesome

1
blue
cute

2
red
sweet

3
green
cute

3
green
fine

What I would like it to look like is something similar to this:

name
color
tags

1
blue
fine, awesome, cute

2
red
sweet

3
green
cute, fine

I can get this by using aggregate:
df <- aggregate(tags ~., df, toString)

however, I then cannot filter the tags seperately anymore, e.g. filter for everything tagged "fine" and "cute". Is there any other way to make the tags filterable while not having to have a row for every tag? Alternately, is there any way to affect the filtering?
Additionally, is there any way to change the default filter from AND ("blue" AND "green") to OR ("blue" OR "green")?
Thank you very much in advance!
Answer: I got the desired table like this
df <- data.frame(name=c(1,1,1,2,3,3), color=c("blue","blue","blue","red","green","green"), tags=c("fine","awesome","cute","sweet","cute","fine"))

library(dplyr)
df1 <- df %>%
    group_by(name, color) %>%
    summarise_all(funs(trimws(paste(., collapse = ','))))

output <- DT::renderDataTable({datatable(df1, filter = 'top')})

Comment: Thank you for taking the time to answer me! I have since realized my problem is more with how DataTable filters content and have included a workaround using selectInput.

Filtering a R datatable subtable


Is there a way to check condition while streaming a list

Question: I have a Persons entity and it has a field contactType.
Now according to contact type I want to map List to different resource file ie WorkContactResource or HomeContactResource.I will be using java 8.
workContact=personList.stream().filter(p->p.getPhoneType == PhoneType.WORK).map(WorkResource::new).collect(Collectors.toList());

homeContact=personList.stream().filter(p->p.getPhoneType == PhoneType.HOME).map(HomeResource::new).collect(Collectors.toList());

workContact.addAll(homeContact);
I made to two different List.
But what I want is while streaming personsList I would be checking if contactType is home or work and there only map to specific resource.
How to achieve this.
Comment: With Java you cannot have more than one return value, so I suggest you forget using `stream()` and write a simple `for`-each instead. Although it's asymptotic complexity would stay the same which is `O(n)`
Comment: Can you be more specific about your desired outcome? Do you want a single `List` of both `WorkResource` and `HomeResource`, which each `Person` filtered to its respective entity based on phone type?
Comment: yes I want a single List
Comment: What is the type of the List for workContact?
Answer: I believe it should be something like this
abstract class Resource {
}

class WorkResource extends Resource {
    public WorkResource(Person person) {
        ***********
    }
}

class HomeResource extends Resource {
    public HomeResource(Person person) {
        ***********
    }
}

Map<PhoneType, List<Resource>> contacts = personList.stream().collect(Collectors.groupingBy(p->p.getPhoneType, Collectors.mapping(Resource::new)));

And then iterate through a map by the type
Answer: Given that you want a single list as an output, the most neat would be probably to create a method that does that and refer to it: .map(this::asResource)
public Resource asResource(Person person) {
    if (person.getPhoneType() == PhoneType.WORK) {
        return new WorkResource(person);
    } else {
        return new HomeResource(person);
    }
}

That would make your code look like this:
personList.stream()
        .map(this::asResource)
        .collect(toList());

You can also declare that method in another class, as static so that the usage looks e.g. like this PersonConverter::asResource.


What is noise-tolerant learning?

Question: I was reading this Development and validation of phenotype classifiers across multiple sites in the observational health data sciences and informatics network and came across the below paragraph. Can you please help me understand what does the highlighted term <code>noise-tolerant learning or </code>noisy-labeled training data` mean with a simple example and how is it useful when we don't have labels in our dataset etc? I am learning ML and your inputs would be helpful.

To address the scarcity of labeled training data, Chen et al used
active learning to intelligently select training samples for labeling,
demonstrating that classifier performance could be preserved with
fewer samples.16 Another trend is the use of "silver standard training
sets," a semisupervised approach where training samples are labeled
using an imperfect heuristic rather than by manual review.17–22 The
intuition is that noise-tolerant classifiers trained on imperfectly
labeled data will abstract higher order properties of the phenotype
beyond the original labeling heuristic (so-called "noise-tolerant
learning"23).
Comment: [google gives many hits](https://www.google.com/search?q=noise-tolerant+learning&oq=noise-tolerant+learning&aqs=chrome..69i57j69i60.9313j0j7&client=ubuntu&sourceid=chrome&ie=UTF-8)
Comment: I guess this is different from what is used in the paper.
Comment: The number 23 after "noise tolerant learning" is presumably a citation. Reading the citation will probably provide context and elaboration on the sentence.
Answer: The paper is clear enough, noise-tolerant learning, in this case, is about label noise. In this case the labels are medical diagnosis, in part decided automatically by some algorithm. Such decisions can be noisy so the labels will be noisy.
So this is about learning algorithms which is robust against possible label noise. To give some context, the first part of the abstract of that paper is

Objective
Accurate electronic phenotyping is essential to support collaborative
observational research. Supervised machine learning methods can be
used to train phenotype classifiers in a high-throughput manner using
imperfectly labeled data. We developed 10 phenotype classifiers using
this approach and evaluated performance across multiple sites within
the Observational Health Data Sciences and Informatics (OHDSI)
network.

And the paper 23 from the references is General Bounds on the Number of Examples
Needed for Learning Probabilistic Concepts, which indeed contains theorems about classification noise (the term used in that paper.)
Comment: Hi, Thanks for the response. Upvoted. Yes, I already read the paper. But I couldn't understand the equation component. Hence, I was trying to know whether there could be  any other simple explanantion
Comment: Thanks for your help

What is noise-tolerant learning?


Kernel and Image of a linear transformation $L:P_n \rightarrow P_n$

Question: Given a linear transformation
$L: P_n \rightarrow P_n$, where $(Lf)(x) = f(x+1) - f(x)$, find $KerL$ and $ImL$
I have managed to prove that $$KerL = \{f\in P_n : f(x) = a, a \in \mathbb{R}\}.$$
Following that we have that the image of given linear transformation will be the span of
$$ \{ L(x^2), \dots, L(x^n)\},$$
that is
$$ \{ (x+1)-x, (x+1)^2 - x^2,\dots, (x+1)^n-x^n\}.$$
Obviously we have that
$$ImL = P_{n-1},$$
but I am struggling to prove that. How would one go about it ?
Answer: Hint: It is clear that $Im L \subseteq P_{n-1}$. Use  a dimension argument to see that equality must hold. These two spaces both have dimension $n$ since the kernel of $L$ has dimension $1$.
Comment: So by showing that the dimension of ImL is n we show that the vectors, the span of which creates the Image, are actually a basis, which would in turn mean that the span of that is actually P_{n-1} itself, is that correct ?


No route matches [GET] "/subjects/list"

Question: I'm stuck with this error when I try to access the list.html.erb page. Is there something wrong with the code?
Error: No route matches [GET] "/subjects/list"
subjects_controller.rb
class SubjectsController < ApplicationController

    def list
        @subjects = Subject.order("subjects.position ASC")

    end

end

routes.rb
 Rails.application.routes.draw do

      get 'demo/index'
end

list.html.erb

Subjects

      Subject
      Visible
      Pages
      Actions

    <% @subjects.each do |subject| %>

      <%= subject.position %>
      <%= subject.name %>
      <%= subject.visible ? 'Yes' : 'No' %>
      <%= subject.pages.size %>

        <%= link_to("Show", {:action => 'show', :id => subject.id}, :class => 'action show') %>
        <%= link_to("Edit", '#', :class => 'action edit') %>
        <%= link_to("Delete", '#', :class => 'action delete') %>

    <% end %>

Any help on this would be much appreciated.
Answer:
Is there something wrong with the code?

The route is not declared properly as Ilya has pointed out. But there is a far better way of doing this using the Rails conventions.
The "list" action in rails is known as index. And the index action for subjects should be [GET] "/subjects".
routes.rb:
Rails.application.routes.draw do
  resources :subjects, only: [:index]
end

app/controllers/subjects_controller.rb:
class SubjectsController
  # GET /subjects
  def index
    @subjects = Subject.order(position: :asc)
  end
end

You want to mode/rename your list.html.erb to app/views/subjects/index.html.erb.
Then when you want to add more routes to show, create, update etc. You can simply remove the only option:
Rails.application.routes.draw do
  resources :subjects
end

http://guides.rubyonrails.org/getting_started.html
http://guides.rubyonrails.org/routing.html

No route matches [GET] "/subjects/list"


Logarithm of a matrix: inequalities

Question: Let A, B, C, D be positive semi-definite matrices and $\alpha$ a real number between zero and one.
It is fulfilled:
$Tr(A \log(B)) \geq Tr(A \log(C))$,
where $Tr$ is a trace. Does from this follow:
a) $Tr(A \log(B+D)) \geq Tr(A \log(C+D))$
b)$Tr(A \log(\alpha B)) \geq Tr(A \log(\alpha C))$
c) $Tr(A \log(B+A)) \geq Tr(A \log(C+A))$
?
I would be also grateful for naming me some literature which can me help with these problems. "Topics in matrix analysis" wasn't helpful (or I have missed something).
Answer: Ok, I have found an answer for part b): Yes.
The proof:
We use the following property of the matrix logarithm:
$\log(GF)=\log(G)+\log(F)$,
where $G$ and $F$ commute. Accordingly, where $F$ will be in our case $\alpha 1$ (where 1 is identity matrix, so it commutes with everything)
$Tr(A\log(B)) \geq Tr(A\log(C)) \Rightarrow$
$Tr(A\log(B)) + Tr(A\log(\alpha 1))  \geq Tr(A\log(C)) + Tr(A\log(\alpha 1)) \Rightarrow$
$Tr(A\log(\alpha B)) \geq Tr(A\log(\alpha C)).$
According a) and c): No, as the matrices
$
a=\left(
\begin{array}{cc}
 0.584421 & 0.295001\, +0.310138 i \\
 0.295001\, -0.310138 i & 0.415579 \\
\end{array}
\right)$,
$b=\left(
\begin{array}{cc}
 0.385804 & 0.286079\, -0.213992 i \\
 0.286079\, +0.213992 i & 0.614196 \\
\end{array}
\right),$
$c=\left(
\begin{array}{cc}
 0.688838 & 0.37651\, -0.227299 i \\
 0.37651\, +0.227299 i & 0.311162 \\
\end{array}
\right)$
does not satisfy c).

Logarithm of a matrix: inequalities


Wrong result SoapVar

Question: I am trying to post my SoapHeader with the function 'SoapVar'. When I print the information of the variable I can see that the data that is posted is not correct:
SoapHeader Object
(
    [namespace] => http://www.example.com/
    [name] => Header
    [data] => SoapVar Object
        (
            [enc_type] => 147
            [enc_value] => xxx
        )

    [mustUnderstand] =>
)

The [data] that has type SoapVar Object. The [data] has also the objects [enc_type] => 147 and [enc_value] => xxx. I dont know what these objects mean, but the result I get is: "the access token is missing".
I get this result when I use the following script:
$headerVar = new SoapVar('<AccessToken>xxx</AccessToken>', XSD_ANYXML);
$header = new SoapHeader('http://www.example.com/', 'Header', $headerVar);

When I try to work with a array, instead of a XML call I get the following SoapHeader:
SoapHeader Object
(
    [namespace] => http://www.example.com/
    [name] => Header
    [data] => Array
        (
            [AccessToken] => xxx
        )

    [mustUnderstand] =>
)

The script that I use for this result is:
$header = new SoapHeader('http://www.example.com/', 'Header', array('AccessToken' =>'xxx'));

Does someone know what I need to change to get the script with SoapVar working?
Here is my full script:
$cluster = $result->cluster;
$qq = new domDocument();
$qq->loadXML($session->__getLastResponse());
$newurl = $cluster.'/services/process.asmx?wsdl';
try
{
    $client = new SoapClient($newurl);

    $headerVar = new SoapVar('<AccessToken>xxx</AccessToken>', XSD_ANYXML);
    $header = new SoapHeader('http://www.example.com/', 'Header', $headerVar);
    $client->__setSoapHeaders($header);
    echo 'Header:
';
    echo '
';
    print_r($header);
    echo '
';
}
catch (SoapFault $e)
{
    echo $e->getMessage();
}
try
{
    echo '

XML Result:

';
    $xml = "";
    $result = $client->__soapCall('ProcessXmlString', array(array('xmlRequest'=>$xml)), null, $header);
    echo '<xmp>';
    print_r($result->ProcessXmlStringResult);
    echo '</xmp>';
}
catch (SoapFault $e)
{
    echo $e->getMessage();
}

Comment: Are you really passing `xxx` as the token or did you do that just to protect you real token
Comment: Should there really be 2 of these `` at the front of your SoapVar?
Comment: I did it to protect my real token. The  `` are necessary for the script. I also tried it with 1x `` and without ``. The result is the same.
Comment: Have you tried creating your `$headerVar` using an alternate call to `SoapVar`? For example: `$headerVar = new SoapVar('xxx', XSD_STRING, null, null, 'AccessToken' );`
Answer: The problem with your current code is that you are not setting the node name.
That is the reason why your data (enc_value) is present but your node name (enc_name) is missing
$headerVar = new SoapVar('<AccessToken>xxx</AccessToken>', XSD_ANYXML, null, null, 'AccessToken');
$header = new SoapHeader('http://www.example.com/', 'Header', $headerVar);

this would output:
SoapHeader Object
(
    [namespace] => http://www.example.com/
    [name] => Header
    [data] => SoapVar Object
        (
            [enc_type] => 147
            [enc_value] =>
xxx
            [enc_name] => AccessToken
         )
    [mustUnderstand] =>
)

Please be aware that although you only see the 'xxx' value, the rest of your XML data is present. If I do a var_dump I can see that the 'enc_value' == string(64)
I don't know what your endpoint is expecting so that part might need some tweaking.

Wrong result SoapVar


Looping when using node js require()?

Question: Currently i have define require file as below.
constantPath = './config/file/'

fileAA = require(path.resolve(constantPath + 'A-A')),
fileBB = require(path.resolve(constantPath + 'B-B')),
fileCC = require(path.resolve(constantPath + 'C-C')),
....
....

It is notice that all the path is of same path and the require variable is of the similar of file name.
I would not like to repeat this procedure x number of times as it violates the DRY principle
Is it possible to have foreach loop here. Eg: Read all file in the folder dynamically and use require to assign it?
Answer: Similar to the answer by BradyCartmell, but a bit neater;
var fs = require('fs');

var constantPath = './config/file/';
var files = { };

fs.readdir(constantPath, function(err, modules) {
  if (err) {
    throw err;
  }

  modules
    .filter(function (module) {
      return module.slice(module.length - 3) === '.js';
    })
    .forEach(function (module) {
      files[module] = require(constantPath + module);
    });
});

Noted differences;

I don't think you have to trim the ".js" when calling require
Store in a files object, rather than globally... that is gross

Note: Please be aware this is asynchronous, and so please write the rest of your code appropriately (i.e. trigger it running from inside the fs.readdir callback.
For completeness, if you'd like a synchronous version to avoid bothering with that;
var fs = require('fs');

var constantPath = './config/file/';
var files = { };

fs.readdirSync(constantPath)
  .filter(function (module) {
    return module.slice(module.length - 3) === '.js';
  })
  .forEach(function (module) {
    files[module] = require(constantPath + module);
  });

Comment: Yes, storing it on global feels gross, but it creates the same result as the code in the original question and that of typical require usage.  Good call on using the sync version and dropping the .js slice.
Comment: @BradyCartmell technically, you're right. But I imagine the OP just left out `var` declarations, which make it slightly different to `global`. ;)
Answer: If every file of that folder is meant to be required as a script, you probably want something that explicitly requires all files.
It's possible with the node module require-all.
NodeJS:
require('require-all')(__dirname + '/config/file/');

You can also use module require-dir.
NodeJS:
require('require-dir')('./config/file');

Hope this helps.
Comment: let say i use `var a = require('require-all');` How could i specific which file i am using in the code?
Comment: Hi, you can use it with `filter`, you can refer to examples of usage: https://www.npmjs.com/package/require-all
Comment: I think i did not elaborate clearly. Assume that `var a = require('require-all')(__dirname + '/config/file/');` will have all the json file be required. Now suppose that i would like to use the json of the file with name "country.json" in a, how could it be done?
Comment: @vincentsty The `filter` option allows you to use a regular expression. That means you can use generic patterns and specific file names as well into it with "ORs" in the expression. However, for those specific files, it can be more readable to reach them in specific file queries. Does it make sense?
Comment: I am getting confused. Suppose that var a now includes file1.json, file2.json and file3.json after require-all. How can i access file2.json specifically in my code?
Comment: Please read the documentation on `require-all`, where it says: "an object with references to all modules matching the filter"
Answer: const fs = require('fs');

var modsDir = './mods/dir';
fs.readdir(modsDir, (err, fileNames) => {
  if (err) throw err;
  fileNames.forEach((fileName) => {
    if (fileName.slice(fileName.length-3) === '.js') {
      fileName = fileName.slice(0, fileName.length-3);

      // This feels dirty
      global[fileName] = require(modsDir+fileName);

    }
  });
});

Should probably be encapsulated to isolate modsDir, but this shows the gist of it anyway.

Looping when using node js require()?


Is $\mathbb Q$ definable in $\bar {\mathbb Q}$ ?

Question: Let $L$ be a first-order language and $M$ be an $L$-structure. Let $D \subseteq M^n$ . Let us say $D$ is definable in $M$ if for some finite set (possibly empty) $A=\{a_1,...,a_m\} \subseteq M$  and some formula $\psi[x_1,...,x_n,y_1,...,y_m]$ , $D=\{(b_1,...,b_n)\in M^n : M\vDash \psi[b_1,...,b_n,a_1,...,a_m]  \}$.
(i.e. $D$ is definable by a finite set of parameters according to this definition
https://en.wikipedia.org/wiki/Definable_set )
Now consider the first-order theory of fields. Let $\bar {\mathbb Q}$ be the algebraic closure of $\mathbb Q$ in $\mathbb C$. Take $M=\bar {\mathbb Q}$.
My question is : Is $\mathbb Q$ definable in $\bar {\mathbb Q}$ ?
Answer: No. The most basic way to see this is to use the fact that ACF$_0$ (the theory of algebraically closed fields of characteristic $0$, of which $\overline{\mathbb{Q}}$ is a model) has quantifier elimination. So every formula $\varphi(x,\overline{a})$ (with parameters $\overline{a}$, in one free variable $x$) is equivalent to a quantifier-free formula. But any quantifier-free formula is equivalent to a boolean combination of polynomial equalities of the form $p(x) = 0$, where $p\in \mathbb{Q}[\overline{a}]$. Since a polynomial has at most finitely many solutions, such a formula defines a finite or cofinite set. And $\mathbb{Q}$ is infinite and coinfinite in $\overline{\mathbb{Q}}$.
At a higher level: What we've really shown above is that ACF$_0$ is strongly minimal (every definable set in one variable is finite or cofinite), from which it follows that it is uncountably categorical, in particular $\omega$-stable, i.e. the tamest of the tame kind of theory. On the other hand, any theory which interprets $\mathbb{Q}$ (as a field) is the wildest of the wild kind of the theory: it can define arithmetic and all recursively enumerable sets and do Gödelian tricks, and it's definitely definitely not $\omega$-stable, much less strongly minimal.
So this is stronger: not only is the "standard" copy of $\mathbb{Q}$ not definable in a model of ACF$_0$, but ACF$_0$ doesn't interpret $\text{Th}(\mathbb{Q})$, by which I mean  there is no definable subset $Q\subseteq (\overline{\mathbb{Q}})^n$ and definable functions $\hat{+}\colon Q^2\to Q$ and $\hat{*}\colon Q^2\to Q$ such that $(Q,\hat{+},\hat{*})\models \text{Th}(\mathbb{Q},+,*)$.
Comment: @Noah: I copied Robinson's definition in my answer here https://math.stackexchange.com/a/2644566/630 - it is not so bad.
Comment: +1. Note for the OP: the fact that $\mathbb{Q}$ (as a field) is "wild" - in particular, $\mathbb{Z}$ is definable - is very surprising, and as far as I know all definitions of $\mathbb{Z}$ in $\mathbb{Q}$ are quite complicated.
Comment: Thanks for your answer ... I will have to study about the fact that $ACF_0$ has quantifier elimination ( I am new to these things )
Comment: @CarlMummert Ah, right - I was thinking of definitions shooting for optimal quantifier complexity (like [this one](https://math.mit.edu/~poonen/papers/ae.pdf)).
Comment: @Noah yes, much worse!


Having trouble writing data to csv file in python

Question: I want to output some of my data to a csv file so I can open it in excel. However, I can't even get my simple example to work. This is what I have:
import csv

with open('test.csv','wb') as csvfile:
    writer = csv.writer(csvfile, delimiter='\t')
    writer.writerow(['hi'] + ['how'] + ['goes'] + ['it'])

I want my words to be separated with tabs so that when I open the file in excel, each word becomes a new column.
Comment: Last but not least, are you using Python 2 or 3? If Python 3, then you need to open the file object slightly differently: `with open('test.csv', 'w', newline='') as csvfile:`
Comment: @RDoolabh: In that case just omit the whole `delimiter` argument; commas are the default.
Comment: Your code certainly writes the row `hi\thow\tgoes\tit\r\n`, but could be made simpler with `writer.writerow(['hi', 'how', 'goes', 'it'])` What problems are you having, specifically?
Comment: Note that the *default* dialect is already the Excel CSV dialect. Are you certain you want to use tabs as the delimiter here? You could also use `dialect='excel-tab'` to get the pre-configured tab-delimited Excel dialect.
Comment: And what's wrong with your solution? By the way, excel default separator is not a tab, but semicolon. It is possible to load table separated data, but somewhat tricky.
Comment: cool, I changed the delimiter to commas and that worked. thanks
Comment: and I'm using Python 2 so my example worked
Answer: Are you on Python 3 and getting TypeError: 'str' does not support the buffer interface?
This thread answers that problem.
Python3: writing csv files
Commas work for my excel if you're on 2 and that isn't the problem:
import csv

with open('test.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['hi', 'how', 'goes', 'it'])

Hmmm Martijn posted the same thing but earlier. Upvote him, don't accept this.


Hot reloading does not update changes

Question: I have a react native app, right now when I make changes to it hot-reloading is triggered but the changes do not show up in the app. E.g. changing a background color from green to white in a stylesheet causes app to say "Hot Reloading" but then the color stays white. Fully reloading the app will then show the green background.
Things I have tried:
Setting root component to a class.
Removing yarn.lock
Reinstalling watchman
Trying to set MAX_WAIT_TIME (did not work due to solution being outdated)
Installing Babel Functional HMR
Running simulator via Xcode and react-native run-ios.
Running with only hot-reload, both hot-reload and live-reload, only live-reload. With and without remote-debugging.
System:
MacOS: 10.13.2
React-Native: 0.51.0
React-Native-Cli: 2.0.1
Xcode (for running the simulator): 9.2
What is going wrong here? How can I get hot-reloading to work?
EDIT:
Looks like this is an bug. Keeping this question open incase someone has a workaround.
Answer: Downgrading to react-native 0.48.4 solved the problem. Still not an optimal solution, so I won't mark this as the answer.
Answer: _#    ###SOLUTION
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
OUTPUT will be :
c:\Users\lenger\Desktop\webrowser>react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Scanning folders for symlinks in c:\Users\lenger\Desktop\webrowser\node_modules (43ms)
Scanning folders for symlinks in c:\Users\lenger\Desktop\webrowser\node_modules (38ms)
Loading dependency graph, done.
bundle: start
bundle: finish
bundle: Writing bundle output to: android/app/src/main/assets/index.android.bundle
bundle: Done writing bundle output
and after
Run react-native run-android again, you will find your modification work.
Thanks to :
[https://lengerrong.blogspot.am/2018/01/react-native-run-android-do-not.html][1]
Answer: Try,
rm -rf /usr/local/var/run/watchman && npm uninstall watchman && npm install watchman

or
rm -rf /usr/local/var/run/watchman && brew uninstall watchman && brew install watchman

Then
react-native run-android

Comment: what are your arguments for posting that answer ?

Hot reloading does not update changes


Write a maximum as integral of indicator function (clarification)

Question: It is known that a random variable $X$ can be written in terms of positive and negative parts $X=X^+-X^-$.
Also, $X^+=\max(0,X)=\int_0^\infty I(X>x)dx$. I don't know how to show it.
Say that $a\in\mathbb{R}$. I can see that $\max(0,a)=aI(a>0)$, and that $a=\int_0^adx$. It indicates me that $\max(0,a)=\int_0^{aI(a>0)}dx$, but I can't relate this with $\max(0,a)=\int_0^\infty I(a>x)dx$.
Can you help me with it?
Answer: As you noticed, a real number $x\ge 0$ can be written as $\int_0^x 1\,dz$. Thus,
$$
X\vee 0=\int_0^{\infty} 1\{X\vee 0>z\}\,dz=\int_0^{\infty} 1\{X>z\}\,dz.
$$