问:
pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
I have two fragments where inside both of these fragments, it will execute codes that utilize sqlbrite. While the app won't crash in normal usage, but the problem is, if I load these 2 fragments back-and-forth multiple times in a short period, the app will crash with this error.

```<code>E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
W/System.err:     at    at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:438)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:431)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err: android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:438)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:431)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err: android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err: rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err: rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
</code>```

One of the fragment has about 50 Observable which are then combined using Observable.combineLatest. Here's the code snippet for the fragment (the other fragment have a similar code). Below is basically the simplified version of my code.

```<code>public class MenuSummary extends Fragment{

private DbHelper dbHelper;
private Observable<?> incomeFromParentJar, getIncomeNecessities, getIncomeSavings, getIncomeEntertainment, getIncomeInvestment, getIncomeEducation, getIncomeCharity;
private Observable<?> getExpensesNecessities, getExpensesSavings, getExpensesEntertainment, getExpensesInvestment, getExpensesEducation, getExpensesCharity;
private Observable<?> getTotalUnpaidMonthlyRecurringExpensesNecessities, getTotalUnpaidMonthlyRecurringExpensesSavings;
private Observable imin;
private Subscription s;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper = new DbHelper(getContext());
}

@Override
public void onPause(){
    super.onPause();
    dbHelper.close();
    s.unsubscribe();
}

@Override
public void onResume(){
    super.onResume();
    displaySummary(selectedYear,selectedMonth);
}

@Override
public void onStop() {
    super.onStop();
}

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
}

private void displaySummary(final int selectedYear, final int selectedMonth){

    incomeFromParentJar = dbHelper.getParentJarIncomeUpTo(selectedYear,selectedMonth);
    getIncomeNecessities = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_NECESSITIES);
    getIncomeSavings = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_SAVINGS);
    getIncomeEntertainment = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_ENTERTAINMENT);
    getIncomeInvestment = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_INVESTMENT);
    getIncomeEducation = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_EDUCATION);
    getIncomeCharity = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_CHARITY);

    getExpensesNecessities = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_NECESSITIES);
    getExpensesSavings = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_SAVINGS);
    getExpensesEntertainment = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_ENTERTAINMENT);
    getExpensesInvestment = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_INVESTMENT);
    getExpensesEducation = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_EDUCATION);
    getExpensesCharity = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_CHARITY);

    List<Observable<?>> myObservables = Arrays.asList(incomeFromParentJar,getIncomeNecessities,getIncomeSavings,getIncomeEntertainment, getIncomeInvestment,getIncomeEducation,getIncomeCharity,getExpensesNecessities,getExpensesSavings,getExpensesEntertainment,getExpensesInvestment, getExpensesEducation,getExpensesCharity);
    imin = Observable.combineLatest(myObservables, new FuncN<List<BigDecimal>>() {
        @Override
        public List<BigDecimal> call(Object... args) {
            BigDecimal incomeTotal, incomeNecessities, incomeSavings, incomeEntertainment;
            BigDecimal incomeInvestment, incomeEducation, incomeCharity;
            List<BigDecimal> incomeFromParentJar = (List<BigDecimal>) args[0];
            List<BigDecimal> expensesAndBalance = new ArrayList<BigDecimal>();

            incomeTotal = incomeFromParentJar.get(0);
            incomeNecessities = incomeFromParentJar.get(1);
            incomeSavings = incomeFromParentJar.get(2);
            incomeEntertainment = incomeFromParentJar.get(3);
            incomeInvestment = incomeFromParentJar.get(4);
            incomeEducation = incomeFromParentJar.get(5);
            incomeCharity = incomeFromParentJar.get(6);

            incomeNecessities = incomeNecessities.add((BigDecimal) args[1]);
            .....
            .....
            .....
        }
    }
).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
s = imin.subscribe(new Action1<List<BigDecimal>>() {
@Override
public void call(List<BigDecimal> expensesAndBalance) {
    //do plenty of view.settext here
}});
}
</code>```

And here's how the DbHelper class looks like. Take note that I only display the code for one of the called function.. the other function is pretty much the same (except for the query of course)..

Can anyone pinpoint where did I went wrong?

```<code>   public class DbHelper {

        private MySQLiteHelper mySQLiteHelper;
        SqlBrite sqlBrite = new SqlBrite.Builder().build();
        BriteDatabase briteDb;
        Subscription subscription;

        private static DbHelper instance;
        public DbHelper(Context context) {
            mySQLiteHelper = new MySQLiteHelper(context);
            sqlBrite = new SqlBrite.Builder().build();
        }

        public Observable<BigDecimal> getIndividualJarIncomeUpTo(final int endYear, final int endMonth, final int moneyJar){
            briteDb = sqlBrite.wrapDatabaseHelper(mySQLiteHelper,Schedulers.io());
        final String[] args = new String[]{moneyJar + "", endYear + "", endMonth + "", endYear + "", };
        Observable<BigDecimal> myObservable;
        myObservable = briteDb.createQuery(MySQLiteHelper.TABLE_INCOME, "SELECT total FROM " + MySQLiteHelper.TABLE_INCOME +
                " WHERE moneyJar = ? AND ((year = ? AND month <= ?) OR (year < ?)) and isDeleted = 0", args)
                .map(new Func1<SqlBrite.Query, BigDecimal>() {
                    @Override
                    public BigDecimal call(SqlBrite.Query query) {
                        Cursor cursor = query.run();
                        BigDecimal income, incomeTotal = new BigDecimal(0);
                        if (cursor != null) {
                            try {
                                if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                                    do {
                                        income = new BigDecimal(cursor.getString(cursor.getColumnIndex("total")));
                                        incomeTotal = incomeTotal.add(income);
                                    } while (cursor.moveToNext());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                cursor.close();
                            }
                            if (moneyJar == 1) {
                                Log.v(FILE_NAME, "imini " + endYear + " " + endMonth + " incomeTotal: " + incomeTotal);
                            }
                        }
                        return incomeTotal;
                    }
                });
        return myObservable;
    }

    public void close(){
        if (briteDb != null) {
            briteDb.close();
        }
    }
}
</code>```

答: I restructured my codes and sql query and lessen the number of observables to only 12 instead of the original 60, and the problem is gone. So basically this issue was caused by bad design on my part.</p>

Body:
I have two fragments where inside both of these fragments, it will execute codes that utilize sqlbrite. While the app won't crash in normal usage, but the problem is, if I load these 2 fragments back-and-forth multiple times in a short period, the app will crash with this error.

E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/CursorWindow: Could not allocate CursorWindow '/data/data/com.imincode.meniti/databases/meniti' of size 2097152 due to error -12.
W/System.err: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
W/System.err:     at    at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at    at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at android.database.CursorWindow.<init>(CursorWindow.java:108)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:438)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:431)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err: android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)
W/System.err:     at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:438)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at com.imincode.meniti.db.DbHelper$6.call(DbHelper.java:431)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err: android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:139)
W/System.err:     at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:368)
W/System.err:     at com.imincode.meniti.db.DbHelper$4.call(DbHelper.java:361)
W/System.err:     at rx.internal.operators.OnSubscribeMap$MapSubscriber.onNext(OnSubscribeMap.java:69)
W/System.err:     at rx.observers.Subscribers$5.onNext(Subscribers.java:235)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.emit(OperatorOnBackpressureLatest.java:165)
W/System.err: rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestEmitter.onNext(OperatorOnBackpressureLatest.java:131)
W/System.err:     at rx.internal.operators.OperatorOnBackpressureLatest$LatestSubscriber.onNext(OperatorOnBackpressureLatest.java:211)
W/System.err:     at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:224)
W/System.err:     at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err: rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:230)
W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"
W/libc: pthread_create failed: couldn't allocate 1064960-byte stack: Out of memory
E/art: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again"

One of the fragment has about 50 Observable which are then combined using Observable.combineLatest. Here's the code snippet for the fragment (the other fragment have a similar code). Below is basically the simplified version of my code.

public class MenuSummary extends Fragment{

private DbHelper dbHelper;
private Observable<?> incomeFromParentJar, getIncomeNecessities, getIncomeSavings, getIncomeEntertainment, getIncomeInvestment, getIncomeEducation, getIncomeCharity;
private Observable<?> getExpensesNecessities, getExpensesSavings, getExpensesEntertainment, getExpensesInvestment, getExpensesEducation, getExpensesCharity;
private Observable<?> getTotalUnpaidMonthlyRecurringExpensesNecessities, getTotalUnpaidMonthlyRecurringExpensesSavings;
private Observable imin;
private Subscription s;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper = new DbHelper(getContext());
}

@Override
public void onPause(){
    super.onPause();
    dbHelper.close();
    s.unsubscribe();
}

@Override
public void onResume(){
    super.onResume();
    displaySummary(selectedYear,selectedMonth);
}

@Override
public void onStop() {
    super.onStop();
}

@Override
public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
}

private void displaySummary(final int selectedYear, final int selectedMonth){

    incomeFromParentJar = dbHelper.getParentJarIncomeUpTo(selectedYear,selectedMonth);
    getIncomeNecessities = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_NECESSITIES);
    getIncomeSavings = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_SAVINGS);
    getIncomeEntertainment = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_ENTERTAINMENT);
    getIncomeInvestment = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_INVESTMENT);
    getIncomeEducation = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_EDUCATION);
    getIncomeCharity = dbHelper.getIndividualJarIncomeUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_CHARITY);

    getExpensesNecessities = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_NECESSITIES);
    getExpensesSavings = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_SAVINGS);
    getExpensesEntertainment = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_ENTERTAINMENT);
    getExpensesInvestment = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_INVESTMENT);
    getExpensesEducation = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_EDUCATION);
    getExpensesCharity = dbHelper.getJarExpensesUpTo(selectedYear,selectedMonth,MySQLiteHelper.JAR_CHARITY);

    List<Observable<?>> myObservables = Arrays.asList(incomeFromParentJar,getIncomeNecessities,getIncomeSavings,getIncomeEntertainment, getIncomeInvestment,getIncomeEducation,getIncomeCharity,getExpensesNecessities,getExpensesSavings,getExpensesEntertainment,getExpensesInvestment, getExpensesEducation,getExpensesCharity);
    imin = Observable.combineLatest(myObservables, new FuncN<List<BigDecimal>>() {
        @Override
        public List<BigDecimal> call(Object... args) {
            BigDecimal incomeTotal, incomeNecessities, incomeSavings, incomeEntertainment;
            BigDecimal incomeInvestment, incomeEducation, incomeCharity;
            List<BigDecimal> incomeFromParentJar = (List<BigDecimal>) args[0];
            List<BigDecimal> expensesAndBalance = new ArrayList<BigDecimal>();

            incomeTotal = incomeFromParentJar.get(0);
            incomeNecessities = incomeFromParentJar.get(1);
            incomeSavings = incomeFromParentJar.get(2);
            incomeEntertainment = incomeFromParentJar.get(3);
            incomeInvestment = incomeFromParentJar.get(4);
            incomeEducation = incomeFromParentJar.get(5);
            incomeCharity = incomeFromParentJar.get(6);

            incomeNecessities = incomeNecessities.add((BigDecimal) args[1]);
            .....
            .....
            .....
        }
    }
).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
s = imin.subscribe(new Action1<List<BigDecimal>>() {
@Override
public void call(List<BigDecimal> expensesAndBalance) {
    //do plenty of view.settext here
}});
}

And here's how the DbHelper class looks like. Take note that I only display the code for one of the called function.. the other function is pretty much the same (except for the query of course)..

Can anyone pinpoint where did I went wrong?

   public class DbHelper {

        private MySQLiteHelper mySQLiteHelper;
        SqlBrite sqlBrite = new SqlBrite.Builder().build();
        BriteDatabase briteDb;
        Subscription subscription;

        private static DbHelper instance;
        public DbHelper(Context context) {
            mySQLiteHelper = new MySQLiteHelper(context);
            sqlBrite = new SqlBrite.Builder().build();
        }

        public Observable<BigDecimal> getIndividualJarIncomeUpTo(final int endYear, final int endMonth, final int moneyJar){
            briteDb = sqlBrite.wrapDatabaseHelper(mySQLiteHelper,Schedulers.io());
        final String[] args = new String[]{moneyJar + "", endYear + "", endMonth + "", endYear + "", };
        Observable<BigDecimal> myObservable;
        myObservable = briteDb.createQuery(MySQLiteHelper.TABLE_INCOME, "SELECT total FROM " + MySQLiteHelper.TABLE_INCOME +
                " WHERE moneyJar = ? AND ((year = ? AND month <= ?) OR (year < ?)) and isDeleted = 0", args)
                .map(new Func1<SqlBrite.Query, BigDecimal>() {
                    @Override
                    public BigDecimal call(SqlBrite.Query query) {
                        Cursor cursor = query.run();
                        BigDecimal income, incomeTotal = new BigDecimal(0);
                        if (cursor != null) {
                            try {
                                if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                                    do {
                                        income = new BigDecimal(cursor.getString(cursor.getColumnIndex("total")));
                                        incomeTotal = incomeTotal.add(income);
                                    } while (cursor.moveToNext());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                cursor.close();
                            }
                            if (moneyJar == 1) {
                                Log.v(FILE_NAME, "imini " + endYear + " " + endMonth + " incomeTotal: " + incomeTotal);
                            }
                        }
                        return incomeTotal;
                    }
                });
        return myObservable;
    }

    public void close(){
        if (briteDb != null) {
            briteDb.close();
        }
    }
}


来源: stackexchange

问:
Vue - webpack vue-loader configuration
I keep getting error whenever I want to build a file. What is a reason of it?
It seems that .vue file is not recognizable by webpack, but webpack configuration file looks properly.
webpack error

```<code>bundle-app.js   189 kB       1  [emitted]  app
    + 12 hidden modules

ERROR in Unexpected token >
 @ ./app/application.js 7:11-31
</code>```

webpack.config.js

```<code>var path = require("path");

module.exports = {
  context: path.join(__dirname, 'src'),
  entry: {
    app: './app/application.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle-[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: /src/,
        query: {
          presets: ["es2015"]
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue',
      },
    ]
  },
  vue: {
    loaders: {
      js: 'babel'
    }
  }
}
</code>```

package.json

```<code>"devDependencies": {
    "webpack": "~2.2.1",
    "babel-core": "~6.23.1",
    "babel-loader": "~6.3.1",
    "babel-preset-es2015": "~6.22.0",
    "sass-loader": "~6.0.0",
    "node-sass": "~4.5.0",
    "extract-text-webpack-plugin": "~2.0.0-rc.3",
    "vue-template-compiler": "~2.2.4",
    "css-loader": "~0.27.3",
    "vue-loader": "~11.1.4"
  },
  "dependencies": {
    "vue": "~2.2.4"
  }
}
</code>```

app/application.js

```<code>import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: 'body',
  component: { App }
})
</code>```

app/app.vue

```<code><template>
  <div id="app">
  </div>
</template>

<script>

    export default {
      data () {
        return {
          msg: 'Hello from vue-loader!'
        }
      }
    }
</code>```

答:
Are you using vue-cli with ESLint?
If you do, you need a comma after every element event in the last and the semicolon.</p>

```<code>import Vue from 'vue';
import App from './app.vue';

new Vue({
  el: 'body',
  components: { App },
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Vue - webpack vue-loader configuration

Body:
I keep getting error whenever I want to build a file. What is a reason of it?
It seems that .vue file is not recognizable by webpack, but webpack configuration file looks properly.
webpack error

bundle-app.js   189 kB       1  [emitted]  app
    + 12 hidden modules

ERROR in Unexpected token >
 @ ./app/application.js 7:11-31

webpack.config.js

var path = require("path");

module.exports = {
  context: path.join(__dirname, 'src'),
  entry: {
    app: './app/application.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle-[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: /src/,
        query: {
          presets: ["es2015"]
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue',
      },
    ]
  },
  vue: {
    loaders: {
      js: 'babel'
    }
  }
}

package.json

"devDependencies": {
    "webpack": "~2.2.1",
    "babel-core": "~6.23.1",
    "babel-loader": "~6.3.1",
    "babel-preset-es2015": "~6.22.0",
    "sass-loader": "~6.0.0",
    "node-sass": "~4.5.0",
    "extract-text-webpack-plugin": "~2.0.0-rc.3",
    "vue-template-compiler": "~2.2.4",
    "css-loader": "~0.27.3",
    "vue-loader": "~11.1.4"
  },
  "dependencies": {
    "vue": "~2.2.4"
  }
}

app/application.js

import Vue from 'vue'
import App from './app.vue'

new Vue({
  el: 'body',
  component: { App }
})

app/app.vue

<template>

</template>

Body:
Are you using vue-cli with ESLint?
If you do, you need a comma after every element event in the last and the semicolon.

import Vue from 'vue';
import App from './app.vue';

new Vue({
  el: 'body',
  components: { App },
});


问:
Shell built-in execution
I'm a little confused about the definition of a shell built-in. According to the Bash Reference Manual, for any built-in, the shell executes the command directly, without invoking another program. What exactly does it mean that a "command is executed directly"? For example, let's look at the cd built-in:

```<code>$ which cd
/usr/bin/cd
$ type cd
cd is a shell builtin
</code>```

Now, let's look at the non built-ingrep:

```<code>$ which grep
/usr/bin/grep
$ type grep
grep is /usr/bin/grep
</code>```

It appears that cd is a separate binary. How is executing cd (or any other builtin) any different than executing grep (or any other non-builtin)?

答:
Some commands exist as both builtins to the shell, and as separate programs.  The which command (which is a separate program and not a builtin!) only finds separate programs, and will never bother with builtins.  Try type readarray and which readarray to see what happens for commands that exist only as builtins.

It is important to note that the builtin version and the external program may well differ.  In some cases, you may prefer relying on the builtin (i.e. if you know what shell your script will be used on, but are unsure which exact external version will execute), or the other way around.

You can call the external program by using its full path (this will bypass the builtin).

When calling an external program, the operating system will launch a separate process, whereas the builtin is part of the shell program itself, and will therefore have much, much lower overhead.  In many cases this overhead is insignificant, but if you are going to be executing the command many times, it may turn out to have a significant impact on the performance of your script.

Title: Shell built-in execution

Body:
I'm a little confused about the definition of a shell built-in. According to the Bash Reference Manual, for any built-in, the shell executes the command directly, without invoking another program. What exactly does it mean that a "command is executed directly"? For example, let's look at the cd built-in:

$ which cd
/usr/bin/cd
$ type cd
cd is a shell builtin

Now, let's look at the non built-ingrep:

$ which grep
/usr/bin/grep
$ type grep
grep is /usr/bin/grep

It appears that cd is a separate binary. How is executing cd (or any other builtin) any different than executing grep (or any other non-builtin)?


问:
Problems invoking View Component
Im working on my first asp.net core project, and therefore also my first view component. I thought I had followed every step in the tutorials, but I cant successfully invoke my view componenent.

Here's my code:

/ViewComponents/ItemListViewComponent.cs

```<code>using Microsoft.AspNetCore.Mvc;

namespace LC.CompuTECH._2017.ViewComponents
{
    public class ItemListViewComponent : ViewComponent
    {
        public ItemListViewComponent(string t)
        {
            switch (t.ToUpper())
            {
                case "STUDENT":
                    this.Type = ListTypes.Student;
                    break;

                case "WORK":
                    this.Type = ListTypes.Work;
                    break;

                case "GAMER":
                    this.Type = ListTypes.Gamer;
                    break;

                case "OTHER":
                    this.Type = ListTypes.Other;
                    break;
            }
        }

        public IViewComponentResult Invoke()
        {
            return View();
        }

        public ListTypes Type { get; internal set; }

        public enum ListTypes
        {
            Student,
            Work,
            Gamer,
            Other
        }
    }
}
</code>```

/Views/Shared/Components/ItemList/Default.cshtml

```<code>MY VIEW COMPONENT
</code>```

and I try to invoke like this:

```<code>@await  Component.InvokeAsync("ItemList", new { t = "student" })
</code>```

but I only get:

InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'LC.CompuTECH._2017.ViewComponents.ItemListViewComponent'.

This should be so basic so I cant figure out what Im doing wrong.

Any help will be highly highly appreciated

答:
your constructor should only take things that can be injected, ie dependencies of your component.

Whatever you want to pass in goes into the invoke method, not the constructor

```<code>using Microsoft.AspNetCore.Mvc;

namespace LC.CompuTECH._2017.ViewComponents
{
    public class ItemListViewComponent : ViewComponent
    {
        public ItemListViewComponent()
        {

        }

        public IViewComponentResult Invoke(string t)
        {
            switch (t.ToUpper())
            {
                case "STUDENT":
                    this.Type = ListTypes.Student;
                    break;

                case "WORK":
                    this.Type = ListTypes.Work;
                    break;

                case "GAMER":
                    this.Type = ListTypes.Gamer;
                    break;

                case "OTHER":
                    this.Type = ListTypes.Other;
                    break;
            }

            return View();
        }

        public ListTypes Type { get; internal set; }

        public enum ListTypes
        {
            Student,
            Work,
            Gamer,
            Other
        }
    }
}
</code>```

note also that unless you have something to await you use Invoke not InvokeAsync, if you use InvokeAsync then your method signature should be

```<code>Task<IViewComponentResult> InvokeAsync(string t)
</code>```

and inside that method you await something ie a call to a service

Title: Problems invoking View Component

Body:
Im working on my first asp.net core project, and therefore also my first view component. I thought I had followed every step in the tutorials, but I cant successfully invoke my view componenent.

Here's my code:

/ViewComponents/ItemListViewComponent.cs

using Microsoft.AspNetCore.Mvc;

namespace LC.CompuTECH._2017.ViewComponents
{
    public class ItemListViewComponent : ViewComponent
    {
        public ItemListViewComponent(string t)
        {
            switch (t.ToUpper())
            {
                case "STUDENT":
                    this.Type = ListTypes.Student;
                    break;

                case "WORK":
                    this.Type = ListTypes.Work;
                    break;

                case "GAMER":
                    this.Type = ListTypes.Gamer;
                    break;

                case "OTHER":
                    this.Type = ListTypes.Other;
                    break;
            }
        }

        public IViewComponentResult Invoke()
        {
            return View();
        }

        public ListTypes Type { get; internal set; }

        public enum ListTypes
        {
            Student,
            Work,
            Gamer,
            Other
        }
    }
}

/Views/Shared/Components/ItemList/Default.cshtml

MY VIEW COMPONENT

and I try to invoke like this:

@await  Component.InvokeAsync("ItemList", new { t = "student" })

but I only get:

InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'LC.CompuTECH._2017.ViewComponents.ItemListViewComponent'.

This should be so basic so I cant figure out what Im doing wrong.

Any help will be highly highly appreciated

Body:
your constructor should only take things that can be injected, ie dependencies of your component.

Whatever you want to pass in goes into the invoke method, not the constructor

using Microsoft.AspNetCore.Mvc;

namespace LC.CompuTECH._2017.ViewComponents
{
    public class ItemListViewComponent : ViewComponent
    {
        public ItemListViewComponent()
        {

        }

        public IViewComponentResult Invoke(string t)
        {
            switch (t.ToUpper())
            {
                case "STUDENT":
                    this.Type = ListTypes.Student;
                    break;

                case "WORK":
                    this.Type = ListTypes.Work;
                    break;

                case "GAMER":
                    this.Type = ListTypes.Gamer;
                    break;

                case "OTHER":
                    this.Type = ListTypes.Other;
                    break;
            }

            return View();
        }

        public ListTypes Type { get; internal set; }

        public enum ListTypes
        {
            Student,
            Work,
            Gamer,
            Other
        }
    }
}

note also that unless you have something to await you use Invoke not InvokeAsync, if you use InvokeAsync then your method signature should be

Task<IViewComponentResult> InvokeAsync(string t)

and inside that method you await something ie a call to a service


问:
Python pandas concatenation
I am downloading data and writing them to CSVs which are later read into python. Once in python (using pandas.read_csv), specific columns of data are meant to be concatenated. However, sometimes the data I'm downaloading into the CSVs is not available ultimately resulting in a non-existent CSV file. When the file is missing, the concatenation process (pandas.concat) chokes due to "NameError: 'xyz' is not defined." Is there a way for pandas.concat to ignore missing data like this?

My script below

```<code>#!/usr/bin/python3.5

import pandas
import time
import os

GFS = pandas.read_csv('/home/user/NWP/TEXT/GFS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_GFS_temps.csv', index_col=1)
ARW = pandas.read_csv('/home/user/NWP/TEXT/ARW/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_ARW_temps.csv', index_col=1)
HRDPS = pandas.read_csv('/home/user/NWP/TEXT/HRDPS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_HRDPS_temps.csv', index_col=1)
NAM4 = pandas.read_csv('/home/user/NWP/TEXT/NAM4/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_NAM4_temps.csv', index_col=1)
GFSMOS = pandas.read_csv('/home/user/NWP/TEXT/GFSMOS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_GFSMOS_temps.csv', index_col=1)
ICON = pandas.read_csv('/home/user/NWP/TEXT/ICON/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_ICON_temps.csv', index_col=1)

COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1)

path = "/home/user/NWP/TEXT/COMPOSITES/" + time.strftime("%Y%m%d")
COMP.to_csv(os.path.join(path,'PJMS_ALL_temps.csv'))

exit()
</code>```

And an example of the CSV. They are all formatted the same way.

```<code>,Date,SHD Temp,HEF Temp,OFP Temp,NTU Temp,PGV Temp,ROA Temp,ADW Temp,PJMS GFS Temp
0,2017040101,47.93,44.87,51.53,58.37,59.09,50.27,47.21,51.073885
1,2017040102,47.75,45.59,51.35,58.01,57.47,50.45,45.77,51.058891
2,2017040103,46.85,45.05,51.17,57.11,56.39,49.19,46.31,50.441292999999995
3,2017040104,46.85,45.23,50.09,55.85,56.03,49.01,46.31,49.91994100000001
4,2017040105,47.21,42.71,49.91,54.77,54.23,49.01,46.13,48.67237900000001
5,2017040106,47.75,43.79,50.09,53.69,53.15,49.73,45.41,48.780829
6,2017040107,47.93,44.51,49.55,53.15,52.25,50.09,44.51,48.728466999999995
7,2017040108,48.11,44.87,49.01,52.43,51.53,50.27,44.33,48.527857000000004
8,2017040109,48.29,45.95,48.83,51.53,50.99,50.09,43.97,48.578959000000005
9,2017040110,48.83,48.11,48.11,51.17,50.81,49.37,43.97,49.049803000000004
10,2017040111,48.83,48.11,47.21,50.99,50.63,48.29,45.23,48.790405
11,2017040112,49.37,47.39,49.19,52.25,52.43,48.11,47.03,49.451023000000006
</code>```

And here is the resulting error

COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1) Traceback (most recent call last):   File "", line 1, in  NameError: name 'GFSMOS' is not defined

答:
A simple fix would be to check for the column(s) you care about. Here's some code that investigates various things related to read_csv.

```<code>import pandas as pd

try:
    df = pd.read_csv('nosuchfile.csv')
    print("df=",df)
except Exception as e:
    print("no file raised:", e)

try:
    f = open('empty.csv', 'w')
    f.close()
    df = pd.read_csv('empty.csv')
    print(df)
except Exception as e:
    print('empty file raised:', e)

df = pd.DataFrame({'a': [1,2,3], 'b':[4,5,6]})
print(df)

if 'a' in df:
    print("yes a")
else:
    print("no a")

if 'xyz' in df:
    print("yes xyz")
else:
    print("no xyz")
</code>```

The output looks like this:

```<code>no file raised: File b'nosuchfile.csv' does not exist
empty file raised: No columns to parse from file
   a  b
0  1  4
1  2  5
2  3  6
yes a
no xyz
</code>```

Which tells me that your input csv files aren't empty/nonexistent (since you didn't ask about those errors), and also that you can just use the Python in operator to check for a column in advance.

(Of course, EAFP, so you could just catch the exception and go from there...)

Update

Based on the comment, I modified your code to store things in a dictionary, indexed by the obvious string names, instead of in separate variables. This makes it easier to process, and easier to manipulate with loops.

The modified version ignores FileNotFound errors, and simply skips over data that isn't available. I don't know if this is actually useful, but it seems to be what you were asking for.

```<code>import pandas
import time
import os

Csv_fmt = "{home}/TEXT/{type}/PJMS/{timestamp}/PJMS_{type}_temps.csv"
Home_dir = os.environ('HOME')
Timestamp = time.strftime("%Y%m%d")

# Note: ordering here taken from your concat statement.
Temp_types = "GFS ARW HRDPS NAM4 GFSMOS ICON".split()

Temp_dataframes = {}

for temp in Temp_types:
    try:
        path = Csv_fmt.format(home=Home_dir, type=temp, timestamp=Timestamp)
        df = pandas.read_csv(path, index_col=1)
        Temp_dataframes[temp] = df
    except FileNotFoundError:
        print("File not found: ",temp)
        pass

Col_fmt = 'PJMS {} Temp'

concat_cols = [Temp_dataframes[tt][Col_fmt.format(tt)] for tt in Temp_types if tt in Temp_dataframes]
COMP = pandas.concat(concat_cols)

#COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1)

path = "/home/user/NWP/TEXT/COMPOSITES/" + time.strftime("%Y%m%d")
COMP.to_csv(os.path.join(path,'PJMS_ALL_temps.csv'))

exit()
</code>```

Title: Python pandas concatenation

Body:
I am downloading data and writing them to CSVs which are later read into python. Once in python (using pandas.read_csv), specific columns of data are meant to be concatenated. However, sometimes the data I'm downaloading into the CSVs is not available ultimately resulting in a non-existent CSV file. When the file is missing, the concatenation process (pandas.concat) chokes due to "NameError: 'xyz' is not defined." Is there a way for pandas.concat to ignore missing data like this?

My script below

#!/usr/bin/python3.5

import pandas
import time
import os

GFS = pandas.read_csv('/home/user/NWP/TEXT/GFS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_GFS_temps.csv', index_col=1)
ARW = pandas.read_csv('/home/user/NWP/TEXT/ARW/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_ARW_temps.csv', index_col=1)
HRDPS = pandas.read_csv('/home/user/NWP/TEXT/HRDPS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_HRDPS_temps.csv', index_col=1)
NAM4 = pandas.read_csv('/home/user/NWP/TEXT/NAM4/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_NAM4_temps.csv', index_col=1)
GFSMOS = pandas.read_csv('/home/user/NWP/TEXT/GFSMOS/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_GFSMOS_temps.csv', index_col=1)
ICON = pandas.read_csv('/home/user/NWP/TEXT/ICON/PJMS/' + time.strftime("%Y%m%d") + '/' + 'PJMS_ICON_temps.csv', index_col=1)

COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1)

path = "/home/user/NWP/TEXT/COMPOSITES/" + time.strftime("%Y%m%d")
COMP.to_csv(os.path.join(path,'PJMS_ALL_temps.csv'))

exit()

And an example of the CSV. They are all formatted the same way.

,Date,SHD Temp,HEF Temp,OFP Temp,NTU Temp,PGV Temp,ROA Temp,ADW Temp,PJMS GFS Temp
0,2017040101,47.93,44.87,51.53,58.37,59.09,50.27,47.21,51.073885
1,2017040102,47.75,45.59,51.35,58.01,57.47,50.45,45.77,51.058891
2,2017040103,46.85,45.05,51.17,57.11,56.39,49.19,46.31,50.441292999999995
3,2017040104,46.85,45.23,50.09,55.85,56.03,49.01,46.31,49.91994100000001
4,2017040105,47.21,42.71,49.91,54.77,54.23,49.01,46.13,48.67237900000001
5,2017040106,47.75,43.79,50.09,53.69,53.15,49.73,45.41,48.780829
6,2017040107,47.93,44.51,49.55,53.15,52.25,50.09,44.51,48.728466999999995
7,2017040108,48.11,44.87,49.01,52.43,51.53,50.27,44.33,48.527857000000004
8,2017040109,48.29,45.95,48.83,51.53,50.99,50.09,43.97,48.578959000000005
9,2017040110,48.83,48.11,48.11,51.17,50.81,49.37,43.97,49.049803000000004
10,2017040111,48.83,48.11,47.21,50.99,50.63,48.29,45.23,48.790405
11,2017040112,49.37,47.39,49.19,52.25,52.43,48.11,47.03,49.451023000000006

And here is the resulting error

COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1) Traceback (most recent call last):   File "", line 1, in  NameError: name 'GFSMOS' is not defined

Body:
A simple fix would be to check for the column(s) you care about. Here's some code that investigates various things related to read_csv.

import pandas as pd

try:
    df = pd.read_csv('nosuchfile.csv')
    print("df=",df)
except Exception as e:
    print("no file raised:", e)

try:
    f = open('empty.csv', 'w')
    f.close()
    df = pd.read_csv('empty.csv')
    print(df)
except Exception as e:
    print('empty file raised:', e)

df = pd.DataFrame({'a': [1,2,3], 'b':[4,5,6]})
print(df)

if 'a' in df:
    print("yes a")
else:
    print("no a")

if 'xyz' in df:
    print("yes xyz")
else:
    print("no xyz")

The output looks like this:

no file raised: File b'nosuchfile.csv' does not exist
empty file raised: No columns to parse from file
   a  b
0  1  4
1  2  5
2  3  6
yes a
no xyz

Which tells me that your input csv files aren't empty/nonexistent (since you didn't ask about those errors), and also that you can just use the Python in operator to check for a column in advance.

(Of course, EAFP, so you could just catch the exception and go from there...)

Update

Based on the comment, I modified your code to store things in a dictionary, indexed by the obvious string names, instead of in separate variables. This makes it easier to process, and easier to manipulate with loops.

The modified version ignores FileNotFound errors, and simply skips over data that isn't available. I don't know if this is actually useful, but it seems to be what you were asking for.

import pandas
import time
import os

Csv_fmt = "{home}/TEXT/{type}/PJMS/{timestamp}/PJMS_{type}_temps.csv"
Home_dir = os.environ('HOME')
Timestamp = time.strftime("%Y%m%d")

# Note: ordering here taken from your concat statement.
Temp_types = "GFS ARW HRDPS NAM4 GFSMOS ICON".split()

Temp_dataframes = {}

for temp in Temp_types:
    try:
        path = Csv_fmt.format(home=Home_dir, type=temp, timestamp=Timestamp)
        df = pandas.read_csv(path, index_col=1)
        Temp_dataframes[temp] = df
    except FileNotFoundError:
        print("File not found: ",temp)
        pass

Col_fmt = 'PJMS {} Temp'

concat_cols = [Temp_dataframes[tt][Col_fmt.format(tt)] for tt in Temp_types if tt in Temp_dataframes]
COMP = pandas.concat(concat_cols)

#COMP = pandas.concat([GFS['PJMS GFS Temp'], ARW['PJMS ARW Temp'], HRDPS['PJMS HRDPS Temp'], NAM4['PJMS NAM4 Temp'], GFSMOS['PJMS GFSMOS Temp'], ICON['PJMS ICON Temp']], axis=1)

path = "/home/user/NWP/TEXT/COMPOSITES/" + time.strftime("%Y%m%d")
COMP.to_csv(os.path.join(path,'PJMS_ALL_temps.csv'))

exit()


问:
ggplot2 + loop results in "Error: Discrete value supplied to continuous scale"
I've been fumbling with this for a while now but let me start with the beginning.

This is how the first few lines of my data look like:

```<code>Year Action_mean_global Adventure_mean_global Fighting_mean_global Misc_mean_global Platform_mean_global
1 1980          0.3400000                   NaN                 0.77           0.6775                  NaN
2 1981          0.5936000                   NaN                  NaN              NaN               2.3100
3 1982          0.3622222                   NaN                  NaN           0.8700               1.0060
4 1983          0.4085714                   0.4                  NaN           2.1400               1.3860
5 1984          1.8500000                   NaN                  NaN           1.4500               0.6900
6 1985          1.7600000                   NaN                 1.05              NaN              10.7925
  Puzzle_mean_global Racing_mean_global Roleplaying_mean_global Shooter_mean_global Simulation_mean_global
1                NaN                NaN                     NaN             3.53500                    NaN
2           1.120000           0.480000                     NaN             1.00400                   0.45
3           3.343333           0.785000                     NaN             0.75800                    NaN
4           0.780000                NaN                     NaN             0.48000                    NaN
5           1.046667           1.983333                     NaN            10.36667                    NaN
6           0.802500                NaN                     NaN             1.00000                   0.03
  Sports_mean_global Strategy_mean_global Total_mean_global
1             0.4900                  NaN         1.2644444
2             0.1975                  NaN         0.7776087
3             0.5250                  NaN         0.8016667
4             3.2000                  NaN         0.9876471
5             3.0900                  NaN         3.5971429
6             1.9600                  NaN         3.8528571
</code>```

They are all numeric.

Now, I simply wanted to do a plot with ggplot() + geom_line() to visualize change over year per genre. It works when doing it step by step, i.e.:

```<code>ggplot(df)+
  geom_line(aes_string(x = 'Year', y = plot_vector[1]))
  geom_line(aes_string(x = 'Year', y = plot_vector[2]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[3]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[4]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[5]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[6]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[7]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[8]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[9]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[10]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[11]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[12]))
</code>```

(plot_vector simply contains all column-names except for Year)

However, doing it in a for-loop:

```<code>p1 <- ggplot(df)+
  geom_line(aes_string(x = 'Year', y = plot_vector[1]))

for (plotnumber in 2:length(plot_vector))
{
  p1 <- p1 +
    geom_line(aes_string(x = 'Year', y = plot_vector[plotnumber]))

}
</code>```

I get the error message. Anyone can muster an idea?

答:
Adding lines with a for loop to a ggplot object may have caused the reported error message but has a general problem caused by lazy evaluation. This has been asked frequently on SO, see, e.g., “for” loop only adds the final ggplot layer, or ggplot loop adding curves fails, but works one at a time.

However, ggplot2 works best when data are supplied in long format. Here, melt()from the data.table package is used to reshape df:

```<code>library(data.table)
molten <- melt(setDT(df), id.vars = c("Year"))

library(ggplot2)
ggplot(molten, aes(x = Year, y = value, group = variable, colour = variable)) +
  geom_line()
</code>```

This creates the following chart:

Data

```<code>df <- structure(list(Year = 1980:1985, Action_mean_global = c(0.34,
0.5936, 0.3622222, 0.4085714, 1.85, 1.76), Adventure_mean_global = c(NaN,
NaN, NaN, 0.4, NaN, NaN), Fighting_mean_global = c(0.77, NaN,
NaN, NaN, NaN, 1.05), Misc_mean_global = c(0.6775, NaN, 0.87,
2.14, 1.45, NaN), Platform_mean_global = c(NaN, 2.31, 1.006,
1.386, 0.69, 10.7925), Puzzle_mean_global = c(NaN, 1.12, 3.343333,
0.78, 1.046667, 0.8025), Racing_mean_global = c(NaN, 0.48, 0.785,
NaN, 1.983333, NaN), Roleplaying_mean_global = c(NaN, NaN, NaN,
NaN, NaN, NaN), Shooter_mean_global = c(3.535, 1.004, 0.758,
0.48, 10.36667, 1), Simulation_mean_global = c(NaN, 0.45, NaN,
NaN, NaN, 0.03), Sports_mean_global = c(0.49, 0.1975, 0.525,
3.2, 3.09, 1.96), Strategy_mean_global = c(NaN, NaN, NaN, NaN,
NaN, NaN), Total_mean_global = c(1.2644444, 0.7776087, 0.8016667,
0.9876471, 3.5971429, 3.8528571)), .Names = c("Year", "Action_mean_global",
"Adventure_mean_global", "Fighting_mean_global", "Misc_mean_global",
"Platform_mean_global", "Puzzle_mean_global", "Racing_mean_global",
"Roleplaying_mean_global", "Shooter_mean_global", "Simulation_mean_global",
"Sports_mean_global", "Strategy_mean_global", "Total_mean_global"
), class = "data.frame", row.names = c(NA, -6L))
</code>```

Body:
I've been fumbling with this for a while now but let me start with the beginning.

This is how the first few lines of my data look like:

Year Action_mean_global Adventure_mean_global Fighting_mean_global Misc_mean_global Platform_mean_global
1 1980          0.3400000                   NaN                 0.77           0.6775                  NaN
2 1981          0.5936000                   NaN                  NaN              NaN               2.3100
3 1982          0.3622222                   NaN                  NaN           0.8700               1.0060
4 1983          0.4085714                   0.4                  NaN           2.1400               1.3860
5 1984          1.8500000                   NaN                  NaN           1.4500               0.6900
6 1985          1.7600000                   NaN                 1.05              NaN              10.7925
  Puzzle_mean_global Racing_mean_global Roleplaying_mean_global Shooter_mean_global Simulation_mean_global
1                NaN                NaN                     NaN             3.53500                    NaN
2           1.120000           0.480000                     NaN             1.00400                   0.45
3           3.343333           0.785000                     NaN             0.75800                    NaN
4           0.780000                NaN                     NaN             0.48000                    NaN
5           1.046667           1.983333                     NaN            10.36667                    NaN
6           0.802500                NaN                     NaN             1.00000                   0.03
  Sports_mean_global Strategy_mean_global Total_mean_global
1             0.4900                  NaN         1.2644444
2             0.1975                  NaN         0.7776087
3             0.5250                  NaN         0.8016667
4             3.2000                  NaN         0.9876471
5             3.0900                  NaN         3.5971429
6             1.9600                  NaN         3.8528571

They are all numeric.

Now, I simply wanted to do a plot with ggplot() + geom_line() to visualize change over year per genre. It works when doing it step by step, i.e.:

ggplot(df)+
  geom_line(aes_string(x = 'Year', y = plot_vector[1]))
  geom_line(aes_string(x = 'Year', y = plot_vector[2]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[3]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[4]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[5]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[6]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[7]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[8]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[9]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[10]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[11]))+
  geom_line(aes_string(x = 'Year', y = plot_vector[12]))

(plot_vector simply contains all column-names except for Year)

However, doing it in a for-loop:

p1 <- ggplot(df)+
  geom_line(aes_string(x = 'Year', y = plot_vector[1]))

for (plotnumber in 2:length(plot_vector))
{
  p1 <- p1 +
    geom_line(aes_string(x = 'Year', y = plot_vector[plotnumber]))

}

I get the error message. Anyone can muster an idea?

Body:
Adding lines with a for loop to a ggplot object may have caused the reported error message but has a general problem caused by lazy evaluation. This has been asked frequently on SO, see, e.g., “for” loop only adds the final ggplot layer, or ggplot loop adding curves fails, but works one at a time.

However, ggplot2 works best when data are supplied in long format. Here, melt()from the data.table package is used to reshape df:

library(data.table)
molten <- melt(setDT(df), id.vars = c("Year"))

library(ggplot2)
ggplot(molten, aes(x = Year, y = value, group = variable, colour = variable)) +
  geom_line()

This creates the following chart:

Data

df <- structure(list(Year = 1980:1985, Action_mean_global = c(0.34,
0.5936, 0.3622222, 0.4085714, 1.85, 1.76), Adventure_mean_global = c(NaN,
NaN, NaN, 0.4, NaN, NaN), Fighting_mean_global = c(0.77, NaN,
NaN, NaN, NaN, 1.05), Misc_mean_global = c(0.6775, NaN, 0.87,
2.14, 1.45, NaN), Platform_mean_global = c(NaN, 2.31, 1.006,
1.386, 0.69, 10.7925), Puzzle_mean_global = c(NaN, 1.12, 3.343333,
0.78, 1.046667, 0.8025), Racing_mean_global = c(NaN, 0.48, 0.785,
NaN, 1.983333, NaN), Roleplaying_mean_global = c(NaN, NaN, NaN,
NaN, NaN, NaN), Shooter_mean_global = c(3.535, 1.004, 0.758,
0.48, 10.36667, 1), Simulation_mean_global = c(NaN, 0.45, NaN,
NaN, NaN, 0.03), Sports_mean_global = c(0.49, 0.1975, 0.525,
3.2, 3.09, 1.96), Strategy_mean_global = c(NaN, NaN, NaN, NaN,
NaN, NaN), Total_mean_global = c(1.2644444, 0.7776087, 0.8016667,
0.9876471, 3.5971429, 3.8528571)), .Names = c("Year", "Action_mean_global",
"Adventure_mean_global", "Fighting_mean_global", "Misc_mean_global",
"Platform_mean_global", "Puzzle_mean_global", "Racing_mean_global",
"Roleplaying_mean_global", "Shooter_mean_global", "Simulation_mean_global",
"Sports_mean_global", "Strategy_mean_global", "Total_mean_global"
), class = "data.frame", row.names = c(NA, -6L))


问:
Deploying a node.js application with Bluemix
I am trying to deploy a simple node.js application with the new Kubernetes support in Bluemix. When I run the container I made, I get a ImagePullBackOff error, which means it can't pull down the image.

NAME                                  READY     STATUS             RESTARTS   AGE
hello-node-2399519400-6m8dz           0/1       ImagePullBackOff   0          13m```
</div>
</div>
</p>

<p>My Docker image uses the node.js base image.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js</code>```

I deployed using:

docker build -t hello-node:v1 .
kubectl run hello-node --image=hello-node:v1 --port=8080```

I am thinking that Bluemix can't pull down the node.js image, but I am not certain.

答:
I had to first push the image to Bluemix with:</p>

```<code>docker build -t registry.ng.bluemix.net/namespace/hello-node:1
docker push registry.ng.bluemix.net/namespace/hello-node:1
kubectl run hello-node-deployment --image=registry.ng.bluemix.net/namespace/hello-node:1
</code>```

Body:
I am trying to deploy a simple node.js application with the new Kubernetes support in Bluemix. When I run the container I made, I get a ImagePullBackOff error, which means it can't pull down the image.

NAME                                  READY     STATUS             RESTARTS   AGE
hello-node-2399519400-6m8dz           0/1       ImagePullBackOff   0          13m

My Docker image uses the node.js base image.

FROM node:6.9.2
EXPOSE 8080
COPY server.js .
CMD node server.js

I deployed using:

docker build -t hello-node:v1 .
kubectl run hello-node --image=hello-node:v1 --port=8080

I am thinking that Bluemix can't pull down the node.js image, but I am not certain.

Body:
I had to first push the image to Bluemix with:

docker build -t registry.ng.bluemix.net/namespace/hello-node:1
docker push registry.ng.bluemix.net/namespace/hello-node:1
kubectl run hello-node-deployment --image=registry.ng.bluemix.net/namespace/hello-node:1


问:
dinner cost calculator trouble converting string to integer
I'm using parseInt to convert .values from strings to numbers. However, if the user inputs a decimal value the output is NaN. Here is my code:

```<code>Dinner Cost:<input type="text" id="cost" /><br /><br />
Tax Rate:<input type="text" id="taxRate" /><br /><br />

<button id="btn">Determine Total Costs</button><br /><br />

<p id="para"></p>

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = parseInt(taxRate);
  dinnerCosts = parseInt(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}
</code>```

What am I doing wrong? Is there a more rational way to convert these default strings into numbers instead of parseInt?

Thanks!

答:
Use parseFloat() instead of parseInt() Usage: taxRate = parseFloat(taxRate);

As a better programming practice you should avoid exceptions in such conversions.One easy way to do robust type-checking in this Javascript scenario is to avoid:

undeclared variables

undeclared properties on Javascript objects (aka dictionary)

Lnull values

NaN values

Here is a simple and quick overview:

```<code>//
var vfftest       = 0.05;                       // float
var viitest       = 3000;                       // integer
var vssblank      = '';                         // empty string
var vssnonblank   = 'hello';                    // non-empty string
var vddempty      = {};                         // dictionary with no name-value pairs
var vddnonempty   = {'alpha':1,'bravo':'two'};  // dictionary with name-    value pairs
var vnull         = null;                       // null

// check parseFloat
console.log( parseFloat(vssnonblank) ); // NaN
console.log( parseFloat(vssblank) );    // NaN
console.log( parseFloat(vfftest) );     // 0.05
console.log( parseFloat(viitest) );     // 3000
console.log( parseFloat(vnull) );       // NaN
console.log( parseFloat(vddempty) );    // NaN
console.log( parseFloat(vddnonempty) ); // NaN
console.log( parseFloat(vnoExisto) );   // EXCEPTION
</code>```

Other than that please refer this link and see how you avoid exceptions in such conversions.

Body:
I'm using parseInt to convert .values from strings to numbers. However, if the user inputs a decimal value the output is NaN. Here is my code:

Dinner Cost:<input type="text" id="cost" />

Tax Rate:<input type="text" id="taxRate" />

<button id="btn">Determine Total Costs</button>

document.getElementById("btn").addEventListener('click', totalCosts);

function totalCosts() {

  var dinnerCosts = document.getElementById("cost").value;
  var taxRate = document.getElementById("taxRate").value;
  taxRate = parseInt(taxRate);
  dinnerCosts = parseInt(dinnerCosts);

  var taxCost = dinnerCosts * taxRate;
  var totalCost = dinnerCosts + taxCost;

  return document.getElementById("para").innerHTML = "Your dinner cost " + dinnerCosts + ", your tax costs " + taxCost + ", for a total cost of " + totalCost;
}

What am I doing wrong? Is there a more rational way to convert these default strings into numbers instead of parseInt?

Thanks!

Body:
Use parseFloat() instead of parseInt() Usage: taxRate = parseFloat(taxRate);

As a better programming practice you should avoid exceptions in such conversions.One easy way to do robust type-checking in this Javascript scenario is to avoid:

undeclared variables

undeclared properties on Javascript objects (aka dictionary)

Lnull values

NaN values

Here is a simple and quick overview:

//
var vfftest       = 0.05;                       // float
var viitest       = 3000;                       // integer
var vssblank      = '';                         // empty string
var vssnonblank   = 'hello';                    // non-empty string
var vddempty      = {};                         // dictionary with no name-value pairs
var vddnonempty   = {'alpha':1,'bravo':'two'};  // dictionary with name-    value pairs
var vnull         = null;                       // null

// check parseFloat
console.log( parseFloat(vssnonblank) ); // NaN
console.log( parseFloat(vssblank) );    // NaN
console.log( parseFloat(vfftest) );     // 0.05
console.log( parseFloat(viitest) );     // 3000
console.log( parseFloat(vnull) );       // NaN
console.log( parseFloat(vddempty) );    // NaN
console.log( parseFloat(vddnonempty) ); // NaN
console.log( parseFloat(vnoExisto) );   // EXCEPTION

Other than that please refer this link and see how you avoid exceptions in such conversions.


问:
Mysql select only child from a table tree
I have a table name tbl_section this table is like that

```<code>db_secid   db_secname   db_secdesc    db_parent
1          Electrical                 NULL
2          Mechanical                 NULL
3          Plumbing                   NULL
4          Cables                      1
5          Lamps                       1
6          HDMI                        4
</code>```

I want to select only the children of a row with db_parent=NULL. From the table above the result will be only Cables and Lamps.

I try with this query

```<code>select
s1.db_secname
from tbl_section as s1
LEFT JOIN tbl_section as s2
ON
s1.db_secid=s2.db_parent
WHERE s2.db_parent IS NULL
</code>```

But this query give me a result I don't want this the result I have from this query

```<code>Mechanical,Plumbing,Lamps,HDMI
</code>```

How can i solve this problem and have only the children who have a parent with db_parent = NULL?

答:
you could use inner join </p>

```<code>select t1.db_secname
from tbl_section as t1
inner join tbl_section as t2
      on t2.db_parent is null and t2.db_secid = t1.db_parent
</code>```

Body:
I have a table name tbl_section this table is like that

db_secid   db_secname   db_secdesc    db_parent
1          Electrical                 NULL
2          Mechanical                 NULL
3          Plumbing                   NULL
4          Cables                      1
5          Lamps                       1
6          HDMI                        4

I want to select only the children of a row with db_parent=NULL. From the table above the result will be only Cables and Lamps.

I try with this query

select
s1.db_secname
from tbl_section as s1
LEFT JOIN tbl_section as s2
ON
s1.db_secid=s2.db_parent
WHERE s2.db_parent IS NULL

But this query give me a result I don't want this the result I have from this query

Mechanical,Plumbing,Lamps,HDMI

How can i solve this problem and have only the children who have a parent with db_parent = NULL?

Body:
you could use inner join

select t1.db_secname
from tbl_section as t1
inner join tbl_section as t2
      on t2.db_parent is null and t2.db_secid = t1.db_parent


问:
Any portable bit trick to select the positive maximum of 2 numbers in C++98?
I have a function

```<code>template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    T a = a<0? -a: a;
    T b = b<0? -b: b;
    return a>b? a: b;
}
</code>```

Can it be implemented more efficiently for all C++ basic types (at least 16/32 bit types) using some bit trick?

答:
Not sure about bit tricks, but you can reduce the number of comparisons from 3 to 2 like this:

```<code>template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    return (a>b) ? std::max(a,-b) : std::max(-a,b);
}
</code>```

Be sure to profile to check if there is any actual gain from this though, as there is a good chance that the compiler will avoid branches altogether for @rubenvb version (for built-in types, that is)

Body:
I have a function

template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    T a = a<0? -a: a;
    T b = b<0? -b: b;
    return a>b? a: b;
}

Can it be implemented more efficiently for all C++ basic types (at least 16/32 bit types) using some bit trick?

Body:
Not sure about bit tricks, but you can reduce the number of comparisons from 3 to 2 like this:

template< class T>
T MaxMagnitudeOf2( const T a, const T b)
{
    return (a>b) ? std::max(a,-b) : std::max(-a,b);
}

Be sure to profile to check if there is any actual gain from this though, as there is a good chance that the compiler will avoid branches altogether for @rubenvb version (for built-in types, that is)


问:
Create banner, dynamically using all images in directory
I am currently working on some code to try and make an ad banner they rotates through all the images in my banner folder. I know I can make a banner which rotates if I state every image in the Array, but what I am wanting to do is create a banner that uses all the images inside the folder so I do not have to go back and recode every time a new image is uploaded to the banner folder. The banner images do not need to have a url assigned as they are only for display at this stage. I am trying to get the banner to display inside this div:

```<code><div id="banner" name="RotateBanner"><img src="Images/banner/1.jpg" /></div>
</code>```

Can anyone please provide me with a way for me to do this? Is this even possible?

答:
Something like this, perhaps?</p>

```<code><!DOCTYPE html>
<html>
<body>
<?php
echo '<div id="banner">';

$dir    = 'Images/banner';
$images = glob("$dir/*.{jpg,jpeg,png,gif,bmp}", GLOB_BRACE);
foreach($images as $image){
  echo "<img class='bannerImages' src='$image'>";
}

echo '</div>';
?>
<script>
var myIndex = 0;
carousel();
function carousel() {
    var x = document.getElementsByClassName("bannerImages");
    for (var i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {
        myIndex = 1;
    }
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000);
}
</script>
</body>
</html>
</code>```

Body:
I am currently working on some code to try and make an ad banner they rotates through all the images in my banner folder. I know I can make a banner which rotates if I state every image in the Array, but what I am wanting to do is create a banner that uses all the images inside the folder so I do not have to go back and recode every time a new image is uploaded to the banner folder. The banner images do not need to have a url assigned as they are only for display at this stage. I am trying to get the banner to display inside this div:

Can anyone please provide me with a way for me to do this? Is this even possible?

Body:
Something like this, perhaps?

<!DOCTYPE html>
<html>
<body>
<?php
echo '<div id="banner">';

$dir    = 'Images/banner';
$images = glob("$dir/*.{jpg,jpeg,png,gif,bmp}", GLOB_BRACE);
foreach($images as $image){
  echo "<img class='bannerImages' src='$image'>";
}

echo '</div>';
?>
<script>
var myIndex = 0;
carousel();
function carousel() {
    var x = document.getElementsByClassName("bannerImages");
    for (var i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {
        myIndex = 1;
    }
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000);
}
</script>
</body>
</html>


问:
ng-cloak not working in Angular
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

```<code>.ng-cloak {
      display: none !important;
}
</code>```

Here is the form.

```<code><form name="register" method="post" id="register" role="form" ng-submit="registerForm()">
<div class="form-group" ng-class="{ 'has-error' : erroractype }">
        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
<span class="help-block" ng-show="errorName" class="ng-cloak">{{ erroractype }}</span>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorFname }">

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">
<div class = "alert alert-danger" ng-show="errorFname" class="ng-cloak">{{errorFname}}</div>

</div>

<div class="form-group" ng-class="{ 'has-error' : errorLname }">
<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">
<div class = "alert alert-danger" ng-show="errorLname" class="ng-cloak">{{ errorLname }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorEmail1 }">
<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">
<div class = "alert alert-danger" ng-show="errorEmail1" class="ng-cloak">{{ errorEmail1 }}</div>
</div>

<div class="form-group" ng-class="{ 'has-error' : errorPassword1 }">
<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">
<div class = "alert alert-danger" ng-show="errorPassword1" class="ng-cloak">{{ errorPassword1 }}</div>
{{ errorPassword1 }}
</div>

<div class="form-group" ng-class="{ 'has-error' : errormobile }">
    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">
    <div class = "alert alert-danger" ng-show="errormobile" class="ng-cloak">{{ errormobile }}</div>
 </div>

<div class="form-group">
<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>
</div>
</form>
</code>```

Any advice as to what am I doing wrong?

答:
You should apply ng-cloak to individual elements. Applying it to the root tag will also solve your problem but it might cause other problems. Quoted from ngCloak doc:

The directive can be applied to the  element, but the preferred usage is to apply multiple ngCloak directives to small portions of the page to permit progressive rendering of the browser view.

Also keep the following in mind:

For the best result, the angular.js script must be loaded in the head section of the html document; alternatively, the css rule above must be included in the external stylesheet of the application.

Title: ng-cloak not working in Angular

Body:
I am trying to remove {{ }} from my website. Basically it came if angular didn't load. So, I checked SO and found some answer to use ng-cloak. I tried that but I can still see {{ }}. I added the CSS code below in a CSS file as well as locally on the page.

CSS

.ng-cloak {
      display: none !important;
}

Here is the form.

<form name="register" method="post" id="register" role="form" ng-submit="registerForm()">

        <select id="actype" name="actype" class=" selector form-control" ng-model="formData.actype" required="required">
           <option value="" selected="selected" >I am</option>
          <option value="1"> Student</option>
          <option value="2"> Teacher</option>
          <option value="3"> School</option>
          </select>
{{ erroractype }}

<input type="text" id="fname" name="fname" placeholder="First Name" title="Please Enter Your First Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Fname">

{{errorFname}}

<input type="text" id="lname" name="lname" placeholder="Last Name" title="Please Enter Your Last Name" class="form-control input-sm textbox1" required="required" ng-model="formData.Lname">

{{ errorLname }}

<input type="email" id="email1" name="email1" placeholder="Email" class="form-control input-sm textbox1" title="Please Enter Your Valid Email" required="required" ng-model="formData.Email1">

{{ errorEmail1 }}

<input type="password" name="password1" id="password1" placeholder="Password" title="Please enter AlphaNumeric value" class="form-control input-sm textbox1" required="required" ng-model="formData.Password1">

{{ errorPassword1 }}

{{ errorPassword1 }}

    <input type="text" id="mobile" name="mobile" placeholder="Mobile Number (+1)" title="Please Enter Your Contact Number without Coutry Code." class="form-control input-sm textbox1" required="required" ng-model="formData.mobile">

{{ errormobile }}

<button type="submit" class="btn btn-home" name="btn-register" id="btn-register" required="required">Register</button>

</form>

Any advice as to what am I doing wrong?

Body:
You should apply ng-cloak to individual elements. Applying it to the root tag will also solve your problem but it might cause other problems. Quoted from ngCloak doc:

The directive can be applied to the <body> element, but the preferred usage is to apply multiple ngCloak directives to small portions of the page to permit progressive rendering of the browser view.

Also keep the following in mind:

For the best result, the angular.js script must be loaded in the head section of the html document; alternatively, the css rule above must be included in the external stylesheet of the application.