问:
Android: Why does my android app displays an empty layout then crash when I am trying to retrieve information from a website?
I am trying to retrieve the source of a website but my app neither displays my gui nor does it print to the logs.

Here is my code.

```<code>import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try{

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();           //start reading inputstream reader

            while(data!=-1){
                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        }
        catch (Exception e){

            e.printStackTrace();
            return null;
        }

    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTask task = new DownloadTask();
    String result = null;

    try {
        result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

        Log.i("Contents of the url:", result);

    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        e.printStackTrace();
    }

}
</code>```

}

This is what displays in my log

```<code>07-06 21:08:01.020 2025-2025/? I/art: Late-enabling -Xcheck:jni
07-06 21:08:01.050 2025-2031/? I/art: Debugger is no longer active
07-06 21:08:01.082 2025-2025/? W/System: ClassLoader referenced unknown path: /data/app/com.example.jimmy.guesstherich-1/lib/arm
07-06 21:08:01.116 2025-2025/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-06 21:08:01.138 2025-2025/? D/PhoneWindowEx: [PWEx][generateLayout] setLGNavigationBarColor : colors=0xff000000
07-06 21:08:01.138 2025-2025/? I/PhoneWindow: [setLGNavigationBarColor] color=0x ff000000
07-06 21:08:01.233 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:01.234 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err: java.net.ConnectException: failed to connect to www.therichest.com/34.202.89.146 (port 443): connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.Socket.connect(Socket.java:888)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:188)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:99)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:151)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:187)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:238)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:134)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:384)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:371)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:408)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:247)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:29)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:15)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.Posix.connect(Native Method)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:   ... 26 more
07-06 21:08:32.299 2025-2025/com.example.jimmy.guesstherich D/AndroidRuntime: Shutting down VM
</code>```

It shows a blank screen for 30-45 seconds then it crashes and the logs print the following

```<code>07-06 21:08:32.300 2025-2025/com.example.jimmy.guesstherich E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.jimmy.guesstherich, PID: 2025
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jimmy.guesstherich/com.example.jimmy.guesstherich.MainActivity}: java.lang.NullPointerException: println needs a message
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                at android.util.Log.println_native(Native Method)
                                                                                at android.util.Log.i(Log.java:160)
                                                                                at com.example.jimmy.guesstherich.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6279)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

Any idea whats going on?

I'm a beginner so I apologize for any mistakes.

I am also following a video tutorial and have triple checked that everything is the same. His works completely fine. If it matters it's Rob Percival's "The Complete Android Development Course"

Thanks in advance, I appreciate it!

答:
This line will always return you null(because asynktask is asynchronous):

```<code>result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();
</code>```

And the you try to print log with null object, this is causing the crash.

The empty layout is because application cannot connect to the website, and receiving timeout exception.

Body:
I am trying to retrieve the source of a website but my app neither displays my gui nor does it print to the logs.

Here is my code.

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try{

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();           //start reading inputstream reader

            while(data!=-1){
                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        }
        catch (Exception e){

            e.printStackTrace();
            return null;
        }

    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTask task = new DownloadTask();
    String result = null;

    try {
        result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

        Log.i("Contents of the url:", result);

    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}

This is what displays in my log

07-06 21:08:01.020 2025-2025/? I/art: Late-enabling -Xcheck:jni
07-06 21:08:01.050 2025-2031/? I/art: Debugger is no longer active
07-06 21:08:01.082 2025-2025/? W/System: ClassLoader referenced unknown path: /data/app/com.example.jimmy.guesstherich-1/lib/arm
07-06 21:08:01.116 2025-2025/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-06 21:08:01.138 2025-2025/? D/PhoneWindowEx: [PWEx][generateLayout] setLGNavigationBarColor : colors=0xff000000
07-06 21:08:01.138 2025-2025/? I/PhoneWindow: [setLGNavigationBarColor] color=0x ff000000
07-06 21:08:01.233 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:01.234 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err: java.net.ConnectException: failed to connect to www.therichest.com/34.202.89.146 (port 443): connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.Socket.connect(Socket.java:888)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:188)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:99)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:151)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:187)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:238)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:134)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:384)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:371)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:408)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:247)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:29)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:15)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.Posix.connect(Native Method)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:   ... 26 more
07-06 21:08:32.299 2025-2025/com.example.jimmy.guesstherich D/AndroidRuntime: Shutting down VM

It shows a blank screen for 30-45 seconds then it crashes and the logs print the following

07-06 21:08:32.300 2025-2025/com.example.jimmy.guesstherich E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.jimmy.guesstherich, PID: 2025
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jimmy.guesstherich/com.example.jimmy.guesstherich.MainActivity}: java.lang.NullPointerException: println needs a message
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                at android.util.Log.println_native(Native Method)
                                                                                at android.util.Log.i(Log.java:160)
                                                                                at com.example.jimmy.guesstherich.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6279)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Any idea whats going on?

I'm a beginner so I apologize for any mistakes.

I am also following a video tutorial and have triple checked that everything is the same. His works completely fine. If it matters it's Rob Percival's "The Complete Android Development Course"

Thanks in advance, I appreciate it!

Body:
This line will always return you null(because asynktask is asynchronous):

result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

And the you try to print log with null object, this is causing the crash.

The empty layout is because application cannot connect to the website, and receiving timeout exception.


来源: stackexchange

问:
Regex for counting occurrences of a string within a single cell in Google Sheets
I have a Google Sheet filled with data and cells, and would like to get the number of times a string appears in a particular cell, as well as how many times a string appears in total for a single column. For example, I am trying to count the number of "of" strings in a column as follows:

```<code>=COUNTA(FILTER('Data Sheet'!G3:G313, REGEXMATCH('Data Sheet'!G3:G313, "of")))
</code>```

However, this just returns the number of cells with an "of". How do I get the total count of "of" strings.

答:
You can do something like this

```<code>COUNTA(SPLIT(REGEXREPLACE('Data Sheet'!G3:G313,"of","$ ."),"$"));
</code>```

You can replace "of" with a symbol "$", and then count number of symbols in it.

ContentLicense: CC BY-SA 3.0

Body:
I have a Google Sheet filled with data and cells, and would like to get the number of times a string appears in a particular cell, as well as how many times a string appears in total for a single column. For example, I am trying to count the number of "of" strings in a column as follows:

=COUNTA(FILTER('Data Sheet'!G3:G313, REGEXMATCH('Data Sheet'!G3:G313, "of")))

However, this just returns the number of cells with an "of". How do I get the total count of "of" strings.

Body:
You can do something like this

COUNTA(SPLIT(REGEXREPLACE('Data Sheet'!G3:G313,"of","$ ."),"$"));

You can replace "of" with a symbol "$", and then count number of symbols in it.


问:
textarea resize upon content inside
How would I get a <textarea> to resize upon the content inside? Like how facebook does it also so there is no scrollbar? If anyone could give me an insight or a link of how to do this It would be greatly appreciated. Not really looking for a JS answer really but if u know any solutions I don't mind.

Thanks

答:
Firstly, the size of a <textarea> is somewhat dependent upon the browser you are running and how it is rendering the webpage on the screen, so while you can provide guidance to the browser with CSS style, you are really just giving the browser some advice about what should be done. The browser lays things out the way it darn well pleases.

Secondly, if the user can resize the window, you aren't going to be able to make the <textarea> larger than the parent in which it is contained -- unless you programatically force a window resize which means Javascript.

And since we are talking about resizing a <textarea> upon content, then we are talking about dynamic content of some fashion, which means Javascript (or Ajax) must be going on in the background to make this happen - so I'm curious about your aversion to using JS.

A solution to your problem is predicated upon a more complete description of what you are trying to do...

Can you provide some detail?

ContentLicense: CC BY-SA 2.5

Title: textarea resize upon content inside


问:
Better way to populate the options in a datalist
I have a datalist that contains 3360 options in a Flask application. I then have a input field which uses this list. The functionality I achieve with this is that a user can start typing a port name and the matching options show up in the dropdown. The problem is that this is quite slow, so I am trying to figure out if there is a way to use javascript with a json file to populate the datalist?</p>

```<code><datalist id="id_datalist">
    <option value="CLARENVILLE, CA">
    <option value="HOBRO, DK">
    ...
</code>```

答:
I believe what you need is a good old javascript autocomplete plugin from the time before <datalist>.
This article describes some of the more popular ones (with examples), pick your favorite and implement it: https://www.sitepoint.com/14-jquery-live-search-plugins/

Body:
I have a datalist that contains 3360 options in a Flask application. I then have a input field which uses this list. The functionality I achieve with this is that a user can start typing a port name and the matching options show up in the dropdown. The problem is that this is quite slow, so I am trying to figure out if there is a way to use javascript with a json file to populate the datalist?

<datalist id="id_datalist">
    <option value="CLARENVILLE, CA">
    <option value="HOBRO, DK">
    ...


问:
Fatal error: Uncaught Error: Call to a member function format() on string
```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>
</code>```

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

```<code>$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");
</code>```

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

答:
Change the line:

```<code>$newDate = $row[4]-> format('d/m/Y');
</code>```

to

```<code>$newDate = new DateTime($row[4])->format('d/m/Y');
</code>```

You were calling format method on string.

Body:
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

Body:
Change the line:

$newDate = $row[4]-> format('d/m/Y');

to

$newDate = new DateTime($row[4])->format('d/m/Y');

You were calling format method on string.


问:
How to convert Observable<any> to array[]
I have following method in typescript, I need to bind to angular grid

CountryService

```<code>GetCountries()  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json().RestResponse["result"]);
}
</code>```

GridComponent

```<code>  template: `
        <ag-grid-ng2 style="width: 100%" #agGrid class="ag-material"
                    rowHeight="50"
                    [gridOptions]="myGridOptions"
                     >
            </ag-grid-ng2>
        `,

  this.myGridOptions.rowData= this.CountryService.GetCountries();
</code>```

CountryData

```<code>export class CountryData{
  name: string;
  alpha2_code: string;
  alpha3_code: string;
}
</code>```

But GetCoutries will return Observable of any, unable to bind to rowData?

How to convert Observable to CountryData[] in typescript ?

you find JSON data here: http://services.groupkt.com/country/get/all

答:
This should work:

```<code>GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}
</code>```

For this to work you will need to import the following:

```<code>import 'rxjs/add/operator/map'
</code>```

Body:
I have following method in typescript, I need to bind to angular grid

CountryService

GetCountries()  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json().RestResponse["result"]);
}

GridComponent

  template: `
        <ag-grid-ng2 style="width: 100%" #agGrid class="ag-material"
                    rowHeight="50"
                    [gridOptions]="myGridOptions"
                     >
            </ag-grid-ng2>
        `,

  this.myGridOptions.rowData= this.CountryService.GetCountries();

CountryData

export class CountryData{
  name: string;
  alpha2_code: string;
  alpha3_code: string;
}

But GetCoutries will return Observable of any, unable to bind to rowData?

How to convert Observable to CountryData[] in typescript ?

you find JSON data here: http://services.groupkt.com/country/get/all

Body:
This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

ContentLicense: CC BY-SA 4.0


问:
This application has no explicit mapping for /error, so you areseeing this as a fallback
I have this error when I try to get access to the loginCheck method, don’t redirect me to see CONTACTS view or redirect me to LOGIN view, for both, I added an if sentence.

I don’t know the reason for this error, only for method request of type POST.

I added logs to see what's happen when I do request to those methods and I obtain this: Logs

When going to URL “localhost/8080/” I redirect to LOGIN view as appear in the image and when I push button to sign in in LOGIN view the error are present. This is the code of my controller:

```<code>@Controller

public class LoginController {

private static final Log LOG = LogFactory.getLog(LoginController.class);
@GetMapping("/")
public String redirectToLogin() {
    LOG.info("METHOD: redirectToLogin()");
    return "redirect:/login";
}

@GetMapping("/login")
public String showLoginForm(Model model,
        @RequestParam(name="error", required=false) String error,
        @RequestParam(name="logout", required=false) String logout) {
    LOG.info("METHOD: showLoginForm() -- PARAMS: error"+ error + ", logout:" + logout);
    model.addAttribute("error", error);
    model.addAttribute("logout", logout);
    model.addAttribute("userCredentials", new UserCredential());
    LOG.info("Returning to login view");
    return "login";
}

@PostMapping("/logincheck")
public String loginCheck(@ModelAttribute(name="userCredentials") UserCredential userCredential) {
    LOG.info("METHOD: loginCheck() -- PARAMS: " + userCredential.toString());
    if(userCredential.getUsername().equals("user") && userCredential.getPassword().equals("user")) {
        LOG.info("Returning to contacts view");
        return "contacts";
    }
    LOG.info("Redirect to login?error");
    return "redirect:/login?error";
}
}
</code>```

this is the LOGIN view code:

Signin

```<code><div class="container">

  <form class="form-signin" action="#" th:action="@{/logincheck}" th:object="${userCredentials}" metod="post">
    <h2 class="form-signin-heading">Sign in</h2>
    <label for="inputEmail" class="sr-only">Username</label>
    <input type="text" id="inputUsername" class="form-control" placeholder="Username" th:field="*{username}"/>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" th:field="*{password}"/>
    <div th:if="${error != null}" class="alert alert-danger" role="alert">Invalid username or password</div>
    <button class="btn btn-lg btn-primary btn-black" type="submit">
        <span class="glyphicon glyphicon-log-in" aria-hiden="true"></span>Sign in
    </button>
  </form>

</div> <!-- /container -->
</code>```

答: When you access the loginCheck url on the browser it sends a GET request to the application server. But your controller is expecting a POST request, hence the error. You can modify the controller to handle GET or use another way, for example AJAX, to login with a POST.

Body:
I have this error when I try to get access to the loginCheck method, don’t redirect me to see CONTACTS view or redirect me to LOGIN view, for both, I added an if sentence.

I don’t know the reason for this error, only for method request of type POST.

I added logs to see what's happen when I do request to those methods and I obtain this: Logs

When going to URL “localhost/8080/” I redirect to LOGIN view as appear in the image and when I push button to sign in in LOGIN view the error are present. This is the code of my controller:

@Controller

public class LoginController {

private static final Log LOG = LogFactory.getLog(LoginController.class);
@GetMapping("/")
public String redirectToLogin() {
    LOG.info("METHOD: redirectToLogin()");
    return "redirect:/login";
}

@GetMapping("/login")
public String showLoginForm(Model model,
        @RequestParam(name="error", required=false) String error,
        @RequestParam(name="logout", required=false) String logout) {
    LOG.info("METHOD: showLoginForm() -- PARAMS: error"+ error + ", logout:" + logout);
    model.addAttribute("error", error);
    model.addAttribute("logout", logout);
    model.addAttribute("userCredentials", new UserCredential());
    LOG.info("Returning to login view");
    return "login";
}

@PostMapping("/logincheck")
public String loginCheck(@ModelAttribute(name="userCredentials") UserCredential userCredential) {
    LOG.info("METHOD: loginCheck() -- PARAMS: " + userCredential.toString());
    if(userCredential.getUsername().equals("user") && userCredential.getPassword().equals("user")) {
        LOG.info("Returning to contacts view");
        return "contacts";
    }
    LOG.info("Redirect to login?error");
    return "redirect:/login?error";
}
}

this is the LOGIN view code:

Signin

  <form class="form-signin" action="#" th:action="@{/logincheck}" th:object="${userCredentials}" metod="post">

Sign in

    Username
    <input type="text" id="inputUsername" class="form-control" placeholder="Username" th:field="*{username}"/>
    Password
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" th:field="*{password}"/>

Invalid username or password

    <button class="btn btn-lg btn-primary btn-black" type="submit">
        Sign in
    </button>
  </form>


问:
Convert a list of dictionaries with similar/duplicate keys into a single dictionary (values would be list) using reduce method
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

```<code>dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}
</code>```

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

答:
Okay, taking inspiration from the linked question, you can do this:

```<code>In [12]: from collections import defaultdict
    ...: from functools import reduce

In [13]: lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

In [14]: def foo(r, d):
    ...:     for k in d:
    ...:         r[k].append(d[k])
    ...:

In [16]: d = reduce(lambda r, d: foo(r, d) or r, lst, defaultdict(list))

In [17]: d
Out[17]: defaultdict(list, {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']})
</code>```

You need an intermediate function to do the update... I think there's a better way to do this, but this is the crux of it.

Now, if you want a cleaner, more readable way, you can do this:

```<code>In [12]: from collections import defaultdict

In [30]: lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

In [31]: d = defaultdict(list)

In [32]: for i in lst:
    ...:     k, v = list(i.items())[0] # an alternative to the single-iterating inner loop from the previous solution
    ...:     d[k].append(v)
    ...:

In [33]: d
Out[33]: defaultdict(list, {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']})
</code>```

Body:
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

Body:
Okay, taking inspiration from the linked question, you can do this:

In [12]: from collections import defaultdict
    ...: from functools import reduce

In [13]: lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

In [14]: def foo(r, d):
    ...:     for k in d:
    ...:         r[k].append(d[k])
    ...:

In [16]: d = reduce(lambda r, d: foo(r, d) or r, lst, defaultdict(list))

In [17]: d
Out[17]: defaultdict(list, {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']})

You need an intermediate function to do the update... I think there's a better way to do this, but this is the crux of it.

Now, if you want a cleaner, more readable way, you can do this:

In [12]: from collections import defaultdict

In [30]: lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

In [31]: d = defaultdict(list)

In [32]: for i in lst:
    ...:     k, v = list(i.items())[0] # an alternative to the single-iterating inner loop from the previous solution
    ...:     d[k].append(v)
    ...:

In [33]: d
Out[33]: defaultdict(list, {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']})


问:
Can't SSH using Net::OpenSSH, can through command line
This is my first time working with Net::OpenSSH, and I am attempting to create an SSH for loop, where I print the hostname of the server I am on using whoami. I am ale to SSH to my intended servers from the command line, but when I run my script, I encounter the following error...

ssh: could not resolve hostname

  : Name or service not known

  username

To get more information, I printed the the output of $ssh->error, where $ssh is my Net::OpenSSH object.

unable to establish master SSH connection: bad password or master process exited unexpectedly at line 24, $fh line 1

This is the script so far...

```<code>#!/usr/bin/perl

 use strict;
 use warnings;
 use Net::OpenSSH;
 my $file = 'servers.txt';
 open (my $fh, $file) or die "Could not open";

 while (my $row = <$fh>) {
   my $user = "username";
   my $password = "password";
   my $ssh = Net::OpenSSH->new(host => $row, user => $user, password => $password);
   $ssh-error and die "SSH connection failed: " . $ssh->error;
   my $whoami = `whoami`;
   print $whoami;
 }
</code>```

The servers.txt file is a plain text file with a list of the servers hostnames, one after another.

My understanding is that if I can SSH to these servers from the command line, the problem must lie in the script, and not the servers/network. Any insight into why I Net::OpenSSH cannot resolve a seemingly accessible server would be appreciated.

答:
"the problem must lie in the script" Yes, there are two problems with the script that I executed. The first one is a syntax error. Other commenters have noted it.

The line

```<code>   $ssh-error and die "SSH connection failed: " . $ssh->error;
</code>```

should be

```<code>   $ssh->error and die "SSH connection failed: " . $ssh->error;
</code>```

The other problem, which is coming from a version of the script that you haven't shown yet, and which was also noted by others, is that you didn't remove the trailing newline from $row. You do that with

```<code>chomp($row)
</code>```

Do that as the opening instruction of the while block and you should be good to go.

I have to stress the importance of being extra careful in posting MCVs. Before you press that submit button, copy the code in your post to a temp file and execute it, and you will get fewer complaints from responders.

By the way, a good debugging habit that might have let you solve the problem on your own is to have added this line before executing Net::OpenSSH->new

```<code>print STDERR ";$row;\n" if $debugging;  # or something to this effect
</code>```

If you had done this, you would have seen something like this on STDERR

```<code>;myhost
;
</code>```

Additionally, the module you're using has a decent debugging feature mentioned in its pod. The debugging output is not so easy to interpret but if you have no idea where the problem is, then you might start there. If you had added this line

```<code>$Net::OpenSSH::debug = 8;
</code>```

Then you would have seen this on STDERR

```<code>$ cat servers.txt
localhostx
$ perl x.pl
...
ssh: Could not resolve hostname localhostx
: nodename nor servname provided, or not known
</code>```

which would have looked like this if you had called chomp but the hostname truly did not exist

```<code>ssh: Could not resolve hostname localhostx: nodename nor servname provided, or not known
</code>```

Body:
This is my first time working with Net::OpenSSH, and I am attempting to create an SSH for loop, where I print the hostname of the server I am on using whoami. I am ale to SSH to my intended servers from the command line, but when I run my script, I encounter the following error...

ssh: could not resolve hostname

  : Name or service not known

  username

To get more information, I printed the the output of $ssh->error, where $ssh is my Net::OpenSSH object.

unable to establish master SSH connection: bad password or master process exited unexpectedly at line 24, $fh line 1

This is the script so far...

#!/usr/bin/perl

 use strict;
 use warnings;
 use Net::OpenSSH;
 my $file = 'servers.txt';
 open (my $fh, $file) or die "Could not open";

 while (my $row = <$fh>) {
   my $user = "username";
   my $password = "password";
   my $ssh = Net::OpenSSH->new(host => $row, user => $user, password => $password);
   $ssh-error and die "SSH connection failed: " . $ssh->error;
   my $whoami = `whoami`;
   print $whoami;
 }

The servers.txt file is a plain text file with a list of the servers hostnames, one after another.

My understanding is that if I can SSH to these servers from the command line, the problem must lie in the script, and not the servers/network. Any insight into why I Net::OpenSSH cannot resolve a seemingly accessible server would be appreciated.

Body:
"the problem must lie in the script" Yes, there are two problems with the script that I executed. The first one is a syntax error. Other commenters have noted it.

The line

   $ssh-error and die "SSH connection failed: " . $ssh->error;

should be

   $ssh->error and die "SSH connection failed: " . $ssh->error;

The other problem, which is coming from a version of the script that you haven't shown yet, and which was also noted by others, is that you didn't remove the trailing newline from $row. You do that with

chomp($row)

Do that as the opening instruction of the while block and you should be good to go.

I have to stress the importance of being extra careful in posting MCVs. Before you press that submit button, copy the code in your post to a temp file and execute it, and you will get fewer complaints from responders.

By the way, a good debugging habit that might have let you solve the problem on your own is to have added this line before executing Net::OpenSSH->new

print STDERR ";$row;\n" if $debugging;  # or something to this effect

If you had done this, you would have seen something like this on STDERR

;myhost
;

Additionally, the module you're using has a decent debugging feature mentioned in its pod. The debugging output is not so easy to interpret but if you have no idea where the problem is, then you might start there. If you had added this line

$Net::OpenSSH::debug = 8;

Then you would have seen this on STDERR

$ cat servers.txt
localhostx
$ perl x.pl
...
ssh: Could not resolve hostname localhostx
: nodename nor servname provided, or not known

which would have looked like this if you had called chomp but the hostname truly did not exist

ssh: Could not resolve hostname localhostx: nodename nor servname provided, or not known


问:
How to implement mod partitioning on sql server 2008 r2?
I'm probably going to implement partitioning on a huge table (billions of rows).

Each table row has some kind of status about a particular device, which is inserted from minute to minute. Therefore, there will be 1440 (24 x 60) rows per day per device. Each device has a unique ID (DeviceID).

I thought about partitioning using DeviceID MOD {TheNumberOfPartitionsThatIWant}, I think TheNumberOfPartitionsThatIWant being 250 is a good compromise. Using this strategy, I can equally distribute the devices throughout the partitions, and also, when querying for a particular device, the query engine just needs to touch one partition, and not all the 250 partitions.

The problem is that I need to add an extra column to my table, just to indicate the partition that the row belongs to, so that I can define the table on a Partition Schema using this column. It would be much better to supply (DeviceID MOD 250) to the Partition Schema instead of having this column with that so simple expression. Is there a workaround for that?

答: I created a computed column, solves the problem.</p>


问:
Correct approach to solve turn based puzzles
I am simulating a game in python. It involves two players, each has a set of turns. Based on a hit or a miss, we decide if that player will get another turn.

I not able to craft this logic programmatically, here is what I have so far:

Let's simulate each player separately for the sake of simplicity

```<code>for coordinate in list_of_player1_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'

for coordinate in list_of_player2_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'
</code>```

Now, in order to have individual turns for each player, I did:

```<code>turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)

for turn in range(0, turns):
    r = move_player1(turn) #move player inturn calls fire()
    if(r == 'Hit'):
        break #start over, giving them another turn
    r = move_player2(turn)
    if r == 'Hit':
        #how do give player 2 another turn?
</code>```

I am out of ideas on how to approach this further. Please suggest. Also please advice on alternative/better approaches.

Thanks!

Edit:

Sample Output for better understanding,

```<code>Player1 fires got miss
Player2 fires which got hit
Player2 fires which got miss
Player1 fires which got hit
Player1 fires which got hit
Player1 fires which got miss
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 no more missiles left to launch
Player2 fires which got hit
Player2 won the battle
</code>```

答:
Your problem description is a bit ambiguous, so I am assuming that

Every time a player hits another player, he gets 1 more move

The game doesn't terminate until both of the players run out of moves

Thus I rewrote the function

```<code>counter = 0
no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)

while counter < no_of_player1_moves or counter < no_of_player2_moves:
    # won't terminate until both players run out of turns
    r = move_player1(turn)
    if(r == 'Hit'):
        no_of_player1_moves += 1 #if player1 hits, player1 gets 1 more turn
    r = move_player2(turn)
    if(r == 'Hit'):
        no_of_player2_moves += 1 #if player2 hits, player2 gets 1 more turn
    counter += 1
</code>```

P.S:
Instead of your long statement

```<code>turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)
</code>```

You can simply use

```<code>turns = max(len(list_of_player2_moves),len(list_of_player1_moves))
</code>```

Edit:

```<code>no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)

while no_of_player1_moves>0 or no_of_player2_moves>0:
    # won't terminate until both players run out of turns
    while move_player1(turn)=="Hit" and no_of_player1_moves!=0:
        no_of_player1_moves -= 1
    while move_player2(turn)=="Hit" and no_of_player2_moves!=0:
        no_of_player2_moves -= 1
</code>```

This would probably solve your problem, but the design doesn't scale well (imagine if you have 10 players, you wouldn't want to write it 10 times).

For that, I would suggest creating a Player object, and placing them in a list, then keep cycling through the list (nested while loop) until all players run out of moves. There is probably a better solution out there too (even compared to this), but that would at least be scalable.

Body:
I am simulating a game in python. It involves two players, each has a set of turns. Based on a hit or a miss, we decide if that player will get another turn.

I not able to craft this logic programmatically, here is what I have so far:

Let's simulate each player separately for the sake of simplicity

for coordinate in list_of_player1_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'

for coordinate in list_of_player2_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'

Now, in order to have individual turns for each player, I did:

turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)

for turn in range(0, turns):
    r = move_player1(turn) #move player inturn calls fire()
    if(r == 'Hit'):
        break #start over, giving them another turn
    r = move_player2(turn)
    if r == 'Hit':
        #how do give player 2 another turn?

I am out of ideas on how to approach this further. Please suggest. Also please advice on alternative/better approaches.

Thanks!

Edit:

Sample Output for better understanding,

Player1 fires got miss
Player2 fires which got hit
Player2 fires which got miss
Player1 fires which got hit
Player1 fires which got hit
Player1 fires which got miss
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 no more missiles left to launch
Player2 fires which got hit
Player2 won the battle

Body:
Your problem description is a bit ambiguous, so I am assuming that

Every time a player hits another player, he gets 1 more move

The game doesn't terminate until both of the players run out of moves

Thus I rewrote the function

counter = 0
no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)

while counter < no_of_player1_moves or counter < no_of_player2_moves:
    # won't terminate until both players run out of turns
    r = move_player1(turn)
    if(r == 'Hit'):
        no_of_player1_moves += 1 #if player1 hits, player1 gets 1 more turn
    r = move_player2(turn)
    if(r == 'Hit'):
        no_of_player2_moves += 1 #if player2 hits, player2 gets 1 more turn
    counter += 1

P.S:
Instead of your long statement

turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)

You can simply use

turns = max(len(list_of_player2_moves),len(list_of_player1_moves))

Edit:

no_of_player1_moves = len(list_of_player1_moves)
no_of_player2_moves = len(list_of_player2_moves)

while no_of_player1_moves>0 or no_of_player2_moves>0:
    # won't terminate until both players run out of turns
    while move_player1(turn)=="Hit" and no_of_player1_moves!=0:
        no_of_player1_moves -= 1
    while move_player2(turn)=="Hit" and no_of_player2_moves!=0:
        no_of_player2_moves -= 1

This would probably solve your problem, but the design doesn't scale well (imagine if you have 10 players, you wouldn't want to write it 10 times).

For that, I would suggest creating a Player object, and placing them in a list, then keep cycling through the list (nested while loop) until all players run out of moves. There is probably a better solution out there too (even compared to this), but that would at least be scalable.


问:
Can see databases and empty tables in hive but not on WEB UI filesystem
I had an database named default and test user /user/hive/warehouse/ and I was messing with --delete-target-dir in sqoop and unfortunately deleted both the databases so the tables are also gone.

Luckily I have everything backed and there was not much in those databases. So i tried to go create both the databases again and it says that databases with those names already exists. So I tried to see those databases and tables in hive terminal. I can see both the databases and all the tables in both the databases using show databases; and show tables; in hive but the tables are empty.

I also tried to use desc database default and the location it shows I can't see them on WEB UI file system.

Is there a way to get them back? or should I drop the databases and recreate them with tables?

I am using Hadoop 2.6.0-cdh5.10.0

Thank you in advance.

答:
The data is gone, not the metadata.

The database and tables definitions are still stored in the metastore, pointing to non existing locations.

If the trash feature is turned on, your data might still exist (moved to another location instead of deleted immediately).

If it is, it would be under /user/{The user who owned the data}/.Trash.

Check the values of fs.trash.interval and fs.trash.checkpoint.interval.

fs.trash.interval

Number of minutes after which the checkpoint gets deleted. If zero,
  the trash feature is disabled. This option may be configured both on
  the server and the client. If trash is disabled server side then the
  client side configuration is checked. If trash is enabled on the
  server side then the value configured on the server is used and the
  client configuration value is ignored.

fs.trash.checkpoint.interval

Number of minutes between trash checkpoints. Should be smaller or
  equal to fs.trash.interval. If zero, the value is set to the value of
  fs.trash.interval. Every time the checkpointer runs it creates a new
  checkpoint out of current and removes checkpoints created more than
  fs.trash.interval minutes ago.

https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/core-default.xml


问:
Extra space at the end of UITextView
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

```<code>- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }
</code>```

setTextViewHeight

```<code>- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }
</code>```

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

答:
To remove all padding:

```<code>[textView setTextContainerInset:UIEdgeInsetsZero];
textView.textContainer.lineFragmentPadding = 0; // to remove left padding
</code>```

If you want to remove Multiple new lines into single one,
In textViewDidEndEditing:

```<code>NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *trimmedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@" "];
textView.text = trimmedString;
</code>```

Title: Extra space at the end of UITextView

Body:
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }

setTextViewHeight

- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

Body:
To remove all padding:

[textView setTextContainerInset:UIEdgeInsetsZero];
textView.textContainer.lineFragmentPadding = 0; // to remove left padding

If you want to remove Multiple new lines into single one,
In textViewDidEndEditing:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *trimmedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@" "];
textView.text = trimmedString;


问:
Sublimelinter - How to disable window popup on error
Everytime there's an error, Sublimelinter fires up, marks the error, and intrusively pops out a window showing the first error.

How to set it, to just mark the error without popping out the window?

How to make it mark ALL errors, instead of just the first one

I'm currently using save-only mode and sublime3 on Ubuntu. I am editing php files

Can someone help? Thanks heaps

And my settings below ...

```<code>{
    "user": {
    "debug": false,
    "delay": 0.25,
    "error_color": "D02000",
    "gutter_theme": "Packages/SublimeLinter/gutter-themes/Default/Default.gutter-theme",
    "gutter_theme_excludes": [],
    "lint_mode": "save only",
    "linters": {
        "php": {
            "@disable": false,
            "args": [],
            "excludes": []
        }
    },
    "mark_style": "squiggly underline",
    "no_column_highlights_line": false,
    "passive_warnings": true,
    "paths": {
        "linux": [],
        "osx": [],
        "windows": []
    },
    "python_paths": {
        "linux": [],
        "osx": [],
        "windows": []
    },
    "rc_search_limit": 3,
    "shell_timeout": 10,
    "show_errors_on_save": true,
    "show_marks_in_minimap": true,
    "syntax_map": {
        "html (django)": "html",
        "html (rails)": "html",
        "html 5": "html",
        "php": "html",
        "python django": "python"
    },
    "warning_color": "DDB700",
    "wrap_find": true
}
</code>```

}

答:
I had the same issue, to solve it just remove the line:

"tooltips": true

From SublimeLinter » user settings file.

Body:
Everytime there's an error, Sublimelinter fires up, marks the error, and intrusively pops out a window showing the first error.

How to set it, to just mark the error without popping out the window?

How to make it mark ALL errors, instead of just the first one

I'm currently using save-only mode and sublime3 on Ubuntu. I am editing php files

Can someone help? Thanks heaps

And my settings below ...

{
    "user": {
    "debug": false,
    "delay": 0.25,
    "error_color": "D02000",
    "gutter_theme": "Packages/SublimeLinter/gutter-themes/Default/Default.gutter-theme",
    "gutter_theme_excludes": [],
    "lint_mode": "save only",
    "linters": {
        "php": {
            "@disable": false,
            "args": [],
            "excludes": []
        }
    },
    "mark_style": "squiggly underline",
    "no_column_highlights_line": false,
    "passive_warnings": true,
    "paths": {
        "linux": [],
        "osx": [],
        "windows": []
    },
    "python_paths": {
        "linux": [],
        "osx": [],
        "windows": []
    },
    "rc_search_limit": 3,
    "shell_timeout": 10,
    "show_errors_on_save": true,
    "show_marks_in_minimap": true,
    "syntax_map": {
        "html (django)": "html",
        "html (rails)": "html",
        "html 5": "html",
        "php": "html",
        "python django": "python"
    },
    "warning_color": "DDB700",
    "wrap_find": true
}

}


问:
How to use env variable which is set in a child process in the path to the called shell script
I am calling a shell script from java code using process builder class.
In this,the path to the shell script is : /{ENV_VARIABLE}/idm_migration/oim/bin/mySrcipt.sh.

Before calling processbuilder.start(), I have set the env variable ENV_VARIABLE as /u01/myPath.

But when the script is getting started, it is not taking the value of the ENV_VARIABLE as set by the code.
Here is the code :

```<code>ProcessBuilder pb = new ProcessBuilder (new String[]
{"$ENV_VARIABLE/idm_migration/oim/bin/OIMV2Migration.sh");

Map<String, String> env = pb.environment();
env.put("ENV_VARIABLE", "/u01/myPath");

Process p = pb.start();
</code>```

How to call the script using this env variable?

答:
I dont think that we can use the environment variable "$ENV_VARIABLE" while giving the entire path to the script ("$ENV_VARIABLE/idm_migration/oim/bin/OIMV2Migration.sh") because the environment variable has not been set for this child process yet.

By doing the way I was doing , the value of the "$ENV_VARIABLE" set in the path of the script will always be fetched from the System environment and not from the child process's environment.

Body:
I am calling a shell script from java code using process builder class.
In this,the path to the shell script is : /{ENV_VARIABLE}/idm_migration/oim/bin/mySrcipt.sh.

Before calling processbuilder.start(), I have set the env variable ENV_VARIABLE as /u01/myPath.

But when the script is getting started, it is not taking the value of the ENV_VARIABLE as set by the code.
Here is the code :

ProcessBuilder pb = new ProcessBuilder (new String[]
{"$ENV_VARIABLE/idm_migration/oim/bin/OIMV2Migration.sh");

Map<String, String> env = pb.environment();
env.put("ENV_VARIABLE", "/u01/myPath");

Process p = pb.start();

How to call the script using this env variable?


问:
Adding extra columns while appending from table to another
enter image description hereHere I am trying to append from one table(3 columns) to another. That works fine.And I need some extra columns in that. Can anyone please help me. My snippet.</p>

```<code>function table2(){
 $('#one').on("click", function(){
    $('#one tbody input:checked').parent().parent().appendTo("#two");
 }
</code>```

答:
This might be helpful, this is a example.</p>

```<code>// First of all this is an example, you has to modify this make as you wish
// Here we can add dynamic columns & rows
// Also , I have given an option to specify the row/column name
<table border="1" id="mtable">
    <thead>
        <tr>
            <td>Item</td><td>Red</td><td>Green</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Some Item</td><td><input type="checkbox"/></td><td><input type="checkbox"/></td>
        </tr>
    </tbody>
</table>
<br/><br/>
<input id="row" placeholder="Enter Item Name"/><button id="irow">Insert Row</button><br/><br/>
<input id="col" placeholder="Enter Heading"/><button id="icol">Insert Column</button>

<script>
    // This is add additional row to a table
    $('#irow').click(function(){
        if($('#row').val()){
            // Creates a copy of last row and you specify the name of row as well as
            // each <td>. Here I'm given a checkbox.
            $('#mtable tbody').append($("#mtable tbody tr:last").clone());
            $('#mtable tbody tr:last :checkbox').attr('checked',false);
            $('#mtable tbody tr:last td:first').html($('#row').val());
        }else{alert('Enter Text');}
    });
    $('#icol').click(function(){
        // This is add additional column to a table
        if($('#col').val()){
            // This is to append/add column to a table
            $('#mtable tr').append($("<td>"));
            $('#mtable thead tr>td:last').html($('#col').val());
            // This is to add a column to each rows in a table
            $('#mtable tbody tr').each(function(){
                $(this).children('td:last').append($('<input type="checkbox">'));
            });
        } else { alert('Enter Text'); }
    });
</script>
</code>```

Body:
enter image description hereHere I am trying to append from one table(3 columns) to another. That works fine.And I need some extra columns in that. Can anyone please help me. My snippet.

function table2(){
 $('#one').on("click", function(){
    $('#one tbody input:checked').parent().parent().appendTo("#two");
 }

Body:
This might be helpful, this is a example.

// First of all this is an example, you has to modify this make as you wish
// Here we can add dynamic columns & rows
// Also , I have given an option to specify the row/column name
<table border="1" id="mtable">
    <thead>
        <tr>
            <td>Item</td><td>Red</td><td>Green</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Some Item</td><td><input type="checkbox"/></td><td><input type="checkbox"/></td>
        </tr>
    </tbody>
</table>
<br/><br/>
<input id="row" placeholder="Enter Item Name"/><button id="irow">Insert Row</button><br/><br/>
<input id="col" placeholder="Enter Heading"/><button id="icol">Insert Column</button>

<script>
    // This is add additional row to a table
    $('#irow').click(function(){
        if($('#row').val()){
            // Creates a copy of last row and you specify the name of row as well as
            // each <td>. Here I'm given a checkbox.
            $('#mtable tbody').append($("#mtable tbody tr:last").clone());
            $('#mtable tbody tr:last :checkbox').attr('checked',false);
            $('#mtable tbody tr:last td:first').html($('#row').val());
        }else{alert('Enter Text');}
    });
    $('#icol').click(function(){
        // This is add additional column to a table
        if($('#col').val()){
            // This is to append/add column to a table
            $('#mtable tr').append($("<td>"));
            $('#mtable thead tr>td:last').html($('#col').val());
            // This is to add a column to each rows in a table
            $('#mtable tbody tr').each(function(){
                $(this).children('td:last').append($('<input type="checkbox">'));
            });
        } else { alert('Enter Text'); }
    });
</script>


问:
Is it possible to cancel a SqlBulkCopy.WriteToServer (c#)?
I am using SqlBulkCopy.WriteToServer (C#) to copy billions of rows, and which takes hours to complete. Sometimes I need to stop the operation for some urgent tasks, but I don't know how to do so. Can I do something on the arriving of the notification event (with SqlBulkCopy.NotifyAfter and SqlBulkCopy.SqlRowsCopied)?</p>

答:
The MSDN documentation says:

If the user wants to cancel the operation from the event, the Abort
  property of the SqlRowsCopiedEventArgs can be used.

So the following code should do the trick:

```<code>    SqlBulkCopy cp = new SqlBulkCopy("your connection string");
    cp.NotifyAfter = 1000; // use here whatever number floats your boat
    cp.SqlRowsCopied += (sender, eventArgs) => eventArgs.Abort = true; // add some more conditions here
</code>```

Body:
The MSDN documentation says:

If the user wants to cancel the operation from the event, the Abort
  property of the SqlRowsCopiedEventArgs can be used.

So the following code should do the trick:

    SqlBulkCopy cp = new SqlBulkCopy("your connection string");
    cp.NotifyAfter = 1000; // use here whatever number floats your boat
    cp.SqlRowsCopied += (sender, eventArgs) => eventArgs.Abort = true; // add some more conditions here


问:
Pass variables between two different pages with GA
i'm trying to get custom dimensions and metrics with GA from one page to other. Is there some method that i can use like .get() method that used in this example for clientId :

```<code>ga(function(a) {clientId = a.get("clientId"); })
</code>```

I mean, if i have some 'dimension5' how can i get it?

答:
You are not able to retrieve data this way using Google Analytics. You will need to use cookies, session, or some other method (outside of GA) to pass data across pages like that.

If I am misunderstanding your question, please elaborate with more information.

Body:
i'm trying to get custom dimensions and metrics with GA from one page to other. Is there some method that i can use like .get() method that used in this example for clientId :

ga(function(a) {clientId = a.get("clientId"); })

I mean, if i have some 'dimension5' how can i get it?


问:
vb.net transfer a object to multiple forms?
I am programming in vb.net.  I am making a platformer and I made the first level and I realized, how am I gonna put all the objects into the second level!?  Please help me!</p>

答:
If you are talking about Windows Forms, each form has a parent property. You can make your objects public properties on Form1 and access them from Form2 by cast ParentForm as Form1.

Additionally, you can defined public shared properties and fields in SomeClass and any code in your application can access those fields or properties. For example:

```<code>Public Class SomeClass
    Public Shared Field1 as String
    Public Shared Property Field2 as String
End Class
</code>```

Then any form in your application can access those values without needing an object reference like this:

```<code>Public Class Form1
    Public Sub Foo()
        Dim Param As String = SomeClass.Field2
    End Sub
End Class
</code>```

You also can create a class in which all public members are 'Shared'. It is called a Module

```<code>Public Module MyModule
    Public ModuleValue As String
End Module
</code>```

Then anywhere in your code you can access it like this:

```<code>Dim Title As String = ModuleValue
</code>```

Using a combination of these methods you can share and pass information between objects in your code.

Other Frameworks, such as WebForms, WebApi and MVC have different ways of sharing data across the application.

Body:
If you are talking about Windows Forms, each form has a parent property. You can make your objects public properties on Form1 and access them from Form2 by cast ParentForm as Form1.

Additionally, you can defined public shared properties and fields in SomeClass and any code in your application can access those fields or properties. For example:

Public Class SomeClass
    Public Shared Field1 as String
    Public Shared Property Field2 as String
End Class

Then any form in your application can access those values without needing an object reference like this:

Public Class Form1
    Public Sub Foo()
        Dim Param As String = SomeClass.Field2
    End Sub
End Class

You also can create a class in which all public members are 'Shared'. It is called a Module

Public Module MyModule
    Public ModuleValue As String
End Module

Then anywhere in your code you can access it like this:

Dim Title As String = ModuleValue

Using a combination of these methods you can share and pass information between objects in your code.

Other Frameworks, such as WebForms, WebApi and MVC have different ways of sharing data across the application.


问:
Eclipse: add JPanel in JFrame
I wrote a simple project about Swing (without action listener).
I want to add a button to a JPanel and add the panel (named panel) to a JFrame (named frame). But when I added the panel to the frame, Eclipse had an error:

```<code>The type javax.swing.JComponent cannot be resolved. It is
    indirectly referenced from required .class files
</code>```

This is my source:

```<code>import javax.swing.*;

public class Click {

    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("oooooo");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    frame.add(panel); //the error
    }
}
</code>```

What should I do?

答:
It seems there is an issue with JRE your eclipse is running on and jre build path is pointing.
I suggest you to follow steps:

Right click on your project -> Build Path -> Configure Build Path

Go to 'Libraries' tab

Remove Previous Version

Add Library -> JRE System Library -> Next -> Workspace default JRE
(or you can Choose Alternate JRE from your System) -> Finish

Title: Eclipse: add JPanel in JFrame

Body:
I wrote a simple project about Swing (without action listener).
I want to add a button to a JPanel and add the panel (named panel) to a JFrame (named frame). But when I added the panel to the frame, Eclipse had an error:

The type javax.swing.JComponent cannot be resolved. It is
    indirectly referenced from required .class files

This is my source:

import javax.swing.*;

public class Click {

    public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("oooooo");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();

    frame.add(panel); //the error
    }
}

What should I do?


问:
Cannot execute "rails console" due to an error with readline
I cannot execute rails console due to this error:

```<code>localhost:TwitterForZombies wiz$ rails c
/Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.rb:9:in `require': dlopen(/Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle, 9): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.2.dylib (LoadError)
  Referenced from: /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle
  Reason: image not found - /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.rb:9:in `<top (required)>'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:3:in `require'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:3:in `<top (required)>'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands.rb:38:in `require'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands.rb:38:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
</code>```

I have installed readline via homebrew.
I'd like to keep using rbenv instead of rvm.

Thank you for reading my question.

答:
taken from github user @enderahmetyurt (this is the only solution that worked for me).

Solution: Add gem 'rb-readline' to your Gemfile in development group and bundle install.

It's the easiest solution for silly "readline" errors.

Body:
I cannot execute rails console due to this error:

localhost:TwitterForZombies wiz$ rails c
/Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.rb:9:in `require': dlopen(/Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle, 9): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.2.dylib (LoadError)
  Referenced from: /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle
  Reason: image not found - /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/x86_64-darwin12.2.1/readline.bundle
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.rb:9:in `<top (required)>'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:3:in `require'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands/console.rb:3:in `<top (required)>'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands.rb:38:in `require'
    from /Users/wiz/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railties-3.2.9/lib/rails/commands.rb:38:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `'

I have installed readline via homebrew.
I'd like to keep using rbenv instead of rvm.

Thank you for reading my question.


问:
What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?
I get Illegal Instruction: 4 errors with binaries compiled with GCC 4.7.2 under Mac OS X 10.8.2 ("Mountain Lion"), when those binaries are run under Mac OS X 10.7.x ("Lion") and earlier versions. The binaries work properly under Mac OS X 10.8.x.

I added -mmacosx-version-min=10.5 to my compile flags and this seems to help resolve the issue for 10.5.x, 10.6.x and 10.7.x clients, whatever that issue is.

Which gets to my question(s):

What is the Illegal Instruction: 4 error?

Why does -mmacosx-version-min=10.x fix this specific error on 10.x and greater clients?

I'd like to apply this fix to my makefiles, but would like to know what it is doing before I pull the trigger. (Will I have larger binaries? Do I still have 64-bit binaries? Are there gotchas with this approach I should know about? Unintended side-effects? Etc.)

答:
I found my issue was an improper

if (leaf = NULL) {...}

where it should have been

if (leaf == NULL){...}

Check those compiler warnings!


问:
Is it possible to undo import in oracle 11g done using sql plus? If possible how to do it?
I have done import of database from .sql file into my database using import command in sql plus. I'm using Oracle 11g. Is it possible to UNDO it? If possible how to do it?</p>

答:
I don't think you can undo it.

I think you will just have to DROP the database by running following commands :

1.SHOW DATABASES;Find your database name in the list,then

2.DROP DATABASE database_name;


问:
How to set image1 overlap image2 android
How to set image1 overlap image2

I want to set image1(by Drawable) overlap image2(by bitmap)

example

In the example above

icon play is image1 and picture is image2

I found slove is only image1 and image2 is by drawable

and If image2 is by bitmap ,I have no idea to set it

ps. sorry my english is not good.

答: On ImageView object you can set a background image and as well as the ImageResource. Another way of doing this is RelativeLayout, place two ImageView overlapping each other.</p>


问:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given
unable to find the error in the loop...please help me</p>

```<code>foreach($cat1 as $category){
    $query="SELECT parent FROM categories where id=".$category;
    $result = mysql_query($query);
    $line = mysql_fetch_assoc($result);
    array_push($cat1,$line['parent']);
    }
</code>```

答:
```<code>if (mysql_fetch_assoc($result) == 1) {

    $score ++;
}
</code>```

Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
  boolean given in C:\xampp\htdocs\answer\get_answer.php on line 24

Body:
unable to find the error in the loop...please help me

foreach($cat1 as $category){
    $query="SELECT parent FROM categories where id=".$category;
    $result = mysql_query($query);
    $line = mysql_fetch_assoc($result);
    array_push($cat1,$line['parent']);
    }

Body:
if (mysql_fetch_assoc($result) == 1) {

    $score ++;
}

Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
  boolean given in C:\xampp\htdocs\answer\get_answer.php on line 24


问:
cannot add button in lavavel backpack controller exeption view not found
flowing the doc in laravel backpack i wnated to add a specifique button beside the create button
heer : https://laravel-backpack.readme.io/docs/crud-buttons

i created a updatem.blade.php for my button

then i declared my button as flow :

$this->xPanel->addButton('top', 'view','ok','updatem', 'end');

xpanel replaced Crud :
but i keep getting the folowing error

ErrorException in FileViewFinder.php line 137:
  View [updatem] not found. (View: /Applications/MAMP/htdocs/smm/packages/larapen/admin/src/resources/views/panel/inc/button_stack.blade.php) (View: /Applications/MAMP/htdocs/smm/packages/larapen/admin/src/resources/views/panel/inc/button_stack.blade.php)

答:
This should work for you:</p>

```<code>$this->crud->addButtonFromView('top', 'ok', 'updatem', 'end');
</code>```

Body:
This should work for you:

$this->crud->addButtonFromView('top', 'ok', 'updatem', 'end');


答:
file.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <ImageView
            android:id="@+id/image_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/bacground_pic"
          />

     <ImageView
            android:id="@+id/image_1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="trues"
          />
    </RelativeLayout>
</code>```

secondly you have to set Bitmap to second image with this

```<code>ImageView image_1=(ImageView) findviewbyid(R.id.image_1);
image_1.setImageBitmap(bitmap);
</code>```

Title: How to set image1 overlap image2 android

Body:
How to set image1 overlap image2

I want to set image1(by Drawable) overlap image2(by bitmap)

example

In the example above

icon play is image1 and picture is image2

I found slove is only image1 and image2 is by drawable

and If image2 is by bitmap ,I have no idea to set it

ps. sorry my english is not good.

Body:
file.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <ImageView
            android:id="@+id/image_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/bacground_pic"
          />

     <ImageView
            android:id="@+id/image_1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="trues"
          />
    </RelativeLayout>

secondly you have to set Bitmap to second image with this

ImageView image_1=(ImageView) findviewbyid(R.id.image_1);
image_1.setImageBitmap(bitmap);


问:
lodash check object properties has values
I have object with several properties, says it's something like this

```<code>{ a: "", b: undefined }
</code>```

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

```<code>const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})
</code>```

答:
Possible ways:

Iterate all the keys and check the value:

let obj = {a:0, b:2, c: undefined};

let isEmpty = false;

Object.keys(obj).forEach(key => {
    if(obj[key] == undefined)
        isEmpty = true;
})

console.log('isEmpty: ', isEmpty);```
</div>
</div>
</p>

<p>Use Array.prototype.some(), like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {a:0, b:1, c: undefined};

let isEmpty = Object.values(obj).some(el => el == undefined);

console.log('isEmpty: ', isEmpty);</code>```

Check the index of undefined and null:

let obj = {a:1, b:2, c: undefined};

let isEmpty = Object.values(obj).indexOf(undefined) >= 0;

console.log('isEmpty: ', isEmpty);```

Body:
I have object with several properties, says it's something like this

{ a: "", b: undefined }

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})

Body:
Possible ways:

Iterate all the keys and check the value:

let obj = {a:0, b:2, c: undefined};

let isEmpty = false;

Object.keys(obj).forEach(key => {
    if(obj[key] == undefined)
        isEmpty = true;
})

console.log('isEmpty: ', isEmpty);

Use Array.prototype.some(), like this:

let obj = {a:0, b:1, c: undefined};

let isEmpty = Object.values(obj).some(el => el == undefined);

console.log('isEmpty: ', isEmpty);

Check the index of undefined and null:

let obj = {a:1, b:2, c: undefined};

let isEmpty = Object.values(obj).indexOf(undefined) >= 0;

console.log('isEmpty: ', isEmpty);