问:
How to disable SSLv3 in Jsoup android? (javax.net.ssl.SSLHandshakeException)
I've got this error while trying to connect to prozis.com website through Jsoup in android 4.2.2, but failing because the site only accepts TLS 1.2.
I've done some reading and I found it's a problem with the SSLv3 protocol not being enabled by default in this version of android.
But as I'm using Jsoup, I can't extend the main class and use a custom SSLSocketFactory class.
Is there some other way to disable SSLv3 or force TLS1.x in android 4?

```<code>String url;
@Override
protected Document doInBackground(String... params) {
    this.url = params[0];
    Document resultDocument = null;
    try {
        resultDocument = Jsoup
                .connect(url)
                .validateTLSCertificates(false)
                .userAgent(userAgent)
                .timeout(NET_TIMEOUT)
                .maxBodySize(0) //sem limite de tamanho do doc recebido
                .get();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultDocument;

09-29 01:45:51.662 3447-3471 W/System.err: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb835f708: Failure in SSL library, usually a protocol error
09-29 01:45:51.662 3447-3471 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.662 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:420)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:652)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:629)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:261)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection.get(HttpConnection.java:250)
09-29 01:45:51.674 3447-3471 W/System.err:     at com.cruz.sergio.myproteinpricechecker.VoucherFragment$GetPRZVouchersAsync.doInBackground(VoucherFragment.java:195)
09-29 01:45:51.674 3447-3471 W/System.err:     at com.cruz.sergio.myproteinpricechecker.VoucherFragment$GetPRZVouchersAsync.doInBackground(VoucherFragment.java:186)
09-29 01:45:51.674 3447-3471 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.lang.Thread.run(Thread.java:856)
09-29 01:45:51.674 3447-3471 W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb835f708: Failure in SSL library, usually a protocol error
09-29 01:45:51.674 3447-3471 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
09-29 01:45:51.674 3447-3471 W/System.err:  ... 18 more
09-29 01:45:51.682 3447-3465 W/System.err: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb836c108: Failure in SSL library, usually a protocol error
09-29 01:45:51.682 3447-3465 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:420)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:652)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:629)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:261)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection.get(HttpConnection.java:250)
09-29 01:45:51.682 3447-3465 W/System.err:     at com.cruz.sergio.myproteinpricechecker.NewsFragment$GetPRZNewsAsync.doInBackground(NewsFragment.java:346)
09-29 01:45:51.682 3447-3465 W/System.err:     at com.cruz.sergio.myproteinpricechecker.NewsFragment$GetPRZNewsAsync.doInBackground(NewsFragment.java:328)
09-29 01:45:51.682 3447-3465 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.lang.Thread.run(Thread.java:856)
09-29 01:45:51.682 3447-3465 W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb836c108: Failure in SSL library, usually a protocol error
09-29 01:45:51.682 3447-3465 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
</code>```

09-29 01:45:51.682 3447-3465 W/System.err:  ... 18 more

答:
try this work as well
make SSLHelper at first

key word : Jsoup SSl  SSLHandshakeException

```<code>import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Javad on 2017-12-05 at 8:29 PM.
 */
public class SSLHelper {

  public static void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new X509TrustManager[]{new X509TrustManager() {
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
      }

      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
      }

      public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
      }
    }}, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  }
}
</code>```

then conncet to your Server like this :

```<code>    private void connectToServer() {
  new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        SSLHelper.enableSSLSocket();
        Connection.Response response = Jsoup
          .connect("https://URL")
          .method(Connection.Method.POST)
          .data("KEY", "VALUE")
          .validateTLSCertificates(true)
          .followRedirects(true)
          .execute();
        Log.i("response", response.toString());
        Log.i("response", response.headers().toString());
        Log.i("response", response.body());

        Document doc = response.parse();
        String result = doc.body().text();

      } catch (IOException e) {
        e.printStackTrace();
        G.toast("ERROR !");
      } catch (java.security.NoSuchAlgorithmException | java.security.KeyManagementException e) {
        e.printStackTrace();
      }
    }
  }).start();
}
</code>```

Body:
I've got this error while trying to connect to prozis.com website through Jsoup in android 4.2.2, but failing because the site only accepts TLS 1.2.
I've done some reading and I found it's a problem with the SSLv3 protocol not being enabled by default in this version of android.
But as I'm using Jsoup, I can't extend the main class and use a custom SSLSocketFactory class.
Is there some other way to disable SSLv3 or force TLS1.x in android 4?

String url;
@Override
protected Document doInBackground(String... params) {
    this.url = params[0];
    Document resultDocument = null;
    try {
        resultDocument = Jsoup
                .connect(url)
                .validateTLSCertificates(false)
                .userAgent(userAgent)
                .timeout(NET_TIMEOUT)
                .maxBodySize(0) //sem limite de tamanho do doc recebido
                .get();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultDocument;

09-29 01:45:51.662 3447-3471 W/System.err: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb835f708: Failure in SSL library, usually a protocol error
09-29 01:45:51.662 3447-3471 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.662 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:420)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-29 01:45:51.674 3447-3471 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:652)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:629)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:261)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.jsoup.helper.HttpConnection.get(HttpConnection.java:250)
09-29 01:45:51.674 3447-3471 W/System.err:     at com.cruz.sergio.myproteinpricechecker.VoucherFragment$GetPRZVouchersAsync.doInBackground(VoucherFragment.java:195)
09-29 01:45:51.674 3447-3471 W/System.err:     at com.cruz.sergio.myproteinpricechecker.VoucherFragment$GetPRZVouchersAsync.doInBackground(VoucherFragment.java:186)
09-29 01:45:51.674 3447-3471 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-29 01:45:51.674 3447-3471 W/System.err:     at java.lang.Thread.run(Thread.java:856)
09-29 01:45:51.674 3447-3471 W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb835f708: Failure in SSL library, usually a protocol error
09-29 01:45:51.674 3447-3471 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
09-29 01:45:51.674 3447-3471 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
09-29 01:45:51.674 3447-3471 W/System.err:  ... 18 more
09-29 01:45:51.682 3447-3465 W/System.err: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb836c108: Failure in SSL library, usually a protocol error
09-29 01:45:51.682 3447-3465 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:420)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-29 01:45:51.682 3447-3465 W/System.err:     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:652)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:629)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:261)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.jsoup.helper.HttpConnection.get(HttpConnection.java:250)
09-29 01:45:51.682 3447-3465 W/System.err:     at com.cruz.sergio.myproteinpricechecker.NewsFragment$GetPRZNewsAsync.doInBackground(NewsFragment.java:346)
09-29 01:45:51.682 3447-3465 W/System.err:     at com.cruz.sergio.myproteinpricechecker.NewsFragment$GetPRZNewsAsync.doInBackground(NewsFragment.java:328)
09-29 01:45:51.682 3447-3465 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-29 01:45:51.682 3447-3465 W/System.err:     at java.lang.Thread.run(Thread.java:856)
09-29 01:45:51.682 3447-3465 W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb836c108: Failure in SSL library, usually a protocol error
09-29 01:45:51.682 3447-3465 W/System.err: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9db03901:0x00000000)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
09-29 01:45:51.682 3447-3465 W/System.err:     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)

09-29 01:45:51.682 3447-3465 W/System.err:  ... 18 more

Body:
try this work as well
make SSLHelper at first

key word : Jsoup SSl  SSLHandshakeException

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Javad on 2017-12-05 at 8:29 PM.
 */
public class SSLHelper {

  public static void enableSSLSocket() throws KeyManagementException, NoSuchAlgorithmException {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new X509TrustManager[]{new X509TrustManager() {
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
      }

      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
      }

      public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
      }
    }}, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  }
}

then conncet to your Server like this :

    private void connectToServer() {
  new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        SSLHelper.enableSSLSocket();
        Connection.Response response = Jsoup
          .connect("https://URL")
          .method(Connection.Method.POST)
          .data("KEY", "VALUE")
          .validateTLSCertificates(true)
          .followRedirects(true)
          .execute();
        Log.i("response", response.toString());
        Log.i("response", response.headers().toString());
        Log.i("response", response.body());

        Document doc = response.parse();
        String result = doc.body().text();

      } catch (IOException e) {
        e.printStackTrace();
        G.toast("ERROR !");
      } catch (java.security.NoSuchAlgorithmException | java.security.KeyManagementException e) {
        e.printStackTrace();
      }
    }
  }).start();
}


来源: stackexchange

问:
C Control Strings?
I know that in other languages such as Java when I use System.out.println(); and I put a variable inside of it like an int that holds the number 22 it will print 22 to the console.

In C if I do the same thing with printf(); I need to specify the type in the string such as printf("%d", n); I also know that Java has its own printf function.

What I am trying to get at here is how the C control String works compared to other languages such as Java where you don't have to provide the type identifier in the System.out.println(); and it automatically recognizes the variable is an int.

Is this part of C's way of efficiency and does it not actually check the type and rely's on the programmer to understand the type they are providing?

答:
Control strings are also known as format specifiers. They are used in formatted input and output operations of the data. Remember, format specifiers are used for formatting the data, for example, in  printf() and scanf().

Control strings in scanf() are used to transfer the data to the processor's memory  in a formatted way, whereas printf () transfers the data to the output device e.g. monitor screen in a formatted way.

Some common Format Specifierss are listed below:

```<code>________________________________________________________________
FORMAT SPECIFIER               ::          DESCRIPTION
________________________________________________________________
%c                                          Character
%d                                       Signed Integer

%e or %E                              Scientific notation

%f                                       Floating point

%g or %G.                             Similar as %e or %E

%hi.                                     Signed Integer

%hu                                 Unsigned Integer(Short)

%i                                       Signed Integer

%l or %ld or %li                         Signed Integer

%lf                                      Floating point

%Lf                                      Floating point

%lu                                     Unsigned integer

%lli, %lld                            Signed long long int

%llu.                                unsigned long long int

%o.                              Octal representation of Integer.

%p                              Address of pointer to void void *
                                              void *

%s                                       String char *
%u                                       Unsigned int

                                      Unsigned short int

%n                                      Prints nothing

%%                                    Prints % character

%o                                   Octal representation

%p                            Address of pointer to void void *
                                             void *

%s                                       String char *

%u                                     Unsigned Integer

%x or %X                         Hexadecimal representation of
                                         Unsigned Int.

%n                                      Prints nothing

%%                                   Prints % character
________________________________________________________________

</code>```

ContentLicense: CC BY-SA 3.0

Title: C Control Strings?

Body:
Control strings are also known as format specifiers. They are used in formatted input and output operations of the data. Remember, format specifiers are used for formatting the data, for example, in  printf() and scanf().

Control strings in scanf() are used to transfer the data to the processor's memory  in a formatted way, whereas printf () transfers the data to the output device e.g. monitor screen in a formatted way.

Some common Format Specifierss are listed below:

________________________________________________________________
FORMAT SPECIFIER               ::          DESCRIPTION
________________________________________________________________
%c                                          Character
%d                                       Signed Integer

%e or %E                              Scientific notation

%f                                       Floating point

%g or %G.                             Similar as %e or %E

%hi.                                     Signed Integer

%hu                                 Unsigned Integer(Short)

%i                                       Signed Integer

%l or %ld or %li                         Signed Integer

%lf                                      Floating point

%Lf                                      Floating point

%lu                                     Unsigned integer

%lli, %lld                            Signed long long int

%llu.                                unsigned long long int

%o.                              Octal representation of Integer.

%p                              Address of pointer to void void *
                                              void *

%s                                       String char *
%u                                       Unsigned int

                                      Unsigned short int

%n                                      Prints nothing

%%                                    Prints % character

%o                                   Octal representation

%p                            Address of pointer to void void *
                                             void *

%s                                       String char *

%u                                     Unsigned Integer

%x or %X                         Hexadecimal representation of
                                         Unsigned Int.

%n                                      Prints nothing

%%                                   Prints % character
________________________________________________________________

ContentLicense: CC BY-SA 4.0


问:
OCIEnvCreate failed with return code -1 but error message text was not available. at DataObjectSupport(721,6)
I recently installed the latest Oracle Data Provider for .NET(ODP.NET 11.2.0.1.2), due to the fact that Microsoft Oracle Client is deprecated. Ever since the new installation, my SqlDataSource control stopped working. When I try to configure the data source and test the connection, it gives me the following error message:

Database schema could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online.

OCIEnvCreate failed with return code -1 but error message text was not available. at DataObjectSupport(721,6)

The connection settings are definitely correct and the database is online for sure, because any databinding I did manually works perfectly well. For instance, I can manually bind to a Gridview, ListBox etc. with ODP.NET and display the data without any problem. But I can not configure and use SqlDataSource control. This is painful because Gridview and Listview have a lot of cool built-in features. When you databind the controls in the code behind file, you lose all the features.

I have added ASPNET to Oracle home and grant it full access control, and restarted the computer, but it does not work. I'm using Visual Studio 2010 and connecting to a remote Oracle database which is Oracle 10g. Does anybody know why I'm having the SqlDataSource problem?

答:
I had a similar problem and solved it editing the .csproj file.
In my case, I was using a project to connect to the database and in another application, a console application, I was doing the logic of my program and calling that library.
To solve the problem I've checked the section  of my .csproj.
In the database connection project the "Debug | Any CPU" property was different in comparisson with my console application .csproj.
I've replaced it by this:</p>

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
</code>```

Body:
I had a similar problem and solved it editing the .csproj file.
In my case, I was using a project to connect to the database and in another application, a console application, I was doing the logic of my program and calling that library.
To solve the problem I've checked the section  of my .csproj.
In the database connection project the "Debug | Any CPU" property was different in comparisson with my console application .csproj.
I've replaced it by this:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 <DebugSymbols>true</DebugSymbols>
 <DebugType>full</DebugType>
 <Optimize>false</Optimize>
 <OutputPath>bin\Debug\</OutputPath>
 <DefineConstants>TRACE;DEBUG</DefineConstants>
 <ErrorReport>prompt</ErrorReport>
 <WarningLevel>4</WarningLevel>
 <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>


问:
How to get string between a character and first occurrence of double quotes?
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

```<code>public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}
</code>```

output for case 3 input:

```<code>Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies
</code>```

Expected output for all types of input cases:

```<code>Logo:http://awebsite/logos/TestChannel.png
</code>```

答:
Here's another using regex.

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloWorld {

    public static void main(String[] args) {

        String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

        // Pattern matcher looking for shortest string surrounded with escaped quotes
        // following tvg-logo=\"
        // Two groups, first is string tvg-logo and second is the logo string
        Matcher tvgMatcher = Pattern.compile("(tvg-logo)=\\\"([^\\\"]+)\\\"").matcher(s);

        while (tvgMatcher.find()) {
            String icon = tvgMatcher.group(2);
            System.out.println(tvgMatcher.group(1)+": "+icon);
        }
    }
}
</code>```

Outputs

```<code>tvg-logo: http://awebsite/logos/TestChannel.png
</code>```

Body:
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}

output for case 3 input:

Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies

Expected output for all types of input cases:

Logo:http://awebsite/logos/TestChannel.png

Body:
Here's another using regex.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloWorld {

    public static void main(String[] args) {

        String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

        // Pattern matcher looking for shortest string surrounded with escaped quotes
        // following tvg-logo=\"
        // Two groups, first is string tvg-logo and second is the logo string
        Matcher tvgMatcher = Pattern.compile("(tvg-logo)=\\\"([^\\\"]+)\\\"").matcher(s);

        while (tvgMatcher.find()) {
            String icon = tvgMatcher.group(2);
            System.out.println(tvgMatcher.group(1)+": "+icon);
        }
    }
}

Outputs

tvg-logo: http://awebsite/logos/TestChannel.png


问:
UnicodeDecodeError: 'utf-16-le'
I'm trying to pull a list of tables from an access database. The script goes through and displays about a third of the tables and gets the following error:

Traceback (most recent call last):   File "C:/GageInfo/sourcecode for
  GageTrakNotify/__test script.py", line 31, in
      for fld in cursor2.columns(rows.table_name): UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 132-133: illegal
  encoding

Any tips would be appreciated.

```<code>import pyodbc

cursor1 = conn.cursor()
cursor2 = conn.cursor()

tblCount = 0
for rows in cursor1.tables():
   if rows.table_type == "TABLE":
       tblCount += 1
       print(rows.table_name)
       for fld in cursor2.columns(rows.table_name):
           print(fld.table_name, fld.column_name)

conn.close()
</code>```

答:
It sounds like you have a Unicode (non-ASCII) embedded in a table name somewhere. Figuring out what table it's stopping on will confirm whether that's the case or not, but ultimately you want the Python script to just handle Unicode, which can be done with the string decode method:

```<code>for fld in cursor2.columns(rows.table_name.decode('utf-16-le')):
</code>```

This should be done anywhere there is a possibility of Unicode characters cropping up (for instance, the column names as well).

Title: UnicodeDecodeError: 'utf-16-le'

Body:
I'm trying to pull a list of tables from an access database. The script goes through and displays about a third of the tables and gets the following error:

Traceback (most recent call last):   File "C:/GageInfo/sourcecode for
  GageTrakNotify/__test script.py", line 31, in
      for fld in cursor2.columns(rows.table_name): UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 132-133: illegal
  encoding

Any tips would be appreciated.

import pyodbc

cursor1 = conn.cursor()
cursor2 = conn.cursor()

tblCount = 0
for rows in cursor1.tables():
   if rows.table_type == "TABLE":
       tblCount += 1
       print(rows.table_name)
       for fld in cursor2.columns(rows.table_name):
           print(fld.table_name, fld.column_name)

conn.close()

Body:
It sounds like you have a Unicode (non-ASCII) embedded in a table name somewhere. Figuring out what table it's stopping on will confirm whether that's the case or not, but ultimately you want the Python script to just handle Unicode, which can be done with the string decode method:

for fld in cursor2.columns(rows.table_name.decode('utf-16-le')):

This should be done anywhere there is a possibility of Unicode characters cropping up (for instance, the column names as well).


问:
TF IDF using dictionaries
I calculated tf and idf for all terms in documents, so I have two objects:
1) tf  dictionaries(there are about 10k):

```<code>{'doc_1': {'rain':0.4, 'sun':0.6}}
{'doc_2': {'............
{'doc_3': {'rain':0.1, .......
</code>```

2) idf ONE single dictionary:

```<code>{'rain': 0.18, 'sun': 0.12......
</code>```

3) I have my list index for all terms:

```<code>[{'term1':[[doc_1, 2],[doc_2, 3]]}, {'term2': [[doc_6, 6],[doc3,1]]}
</code>```

....and so on for every term

How can I calculate tf*idf now for example for a list of words? I was trying:

```<code>def tf_idf(list_of words):
    t_id={}
    for i in list_of_words:
        score= {}
        for j in terms:
            score[j[0]]=(idf[i]*tf[j[0]][i])
        t_id[i]=score
    return t_id
</code>```

it give me an error:

```<code>KeyError: 0
</code>```

答:
Some general programming advice here:

```<code>def tf_idf(list_of words, tf, idf):   # Pass your variables in, as opposed to using the global scope.
    t_id={}
    for word in list_of_words:  # Name your variables to avoid confusion
        score= {}
        for term in terms:
            score[term[0]]=(idf[word]*tf[term[0]][word])
        t_id[i]=score
    return t_id
</code>```

I think your issue here is in referring to term[0] (you had this as j[0]).   According to your post, terms looks like this:

```<code>[{'term1':[[doc_1, 2],[doc_2, 3]]}...]
</code>```

So term (or j) is just:

```<code>{'term1':[[doc_1, 2],[doc_2, 3]]}
</code>```

When you refer to term[0] (or j[0]), there would need to be an element in that dictionary with 0 as its key.

Since that key is missing, you get a KeyError.

Title: TF IDF using dictionaries

Body:
I calculated tf and idf for all terms in documents, so I have two objects:
1) tf  dictionaries(there are about 10k):

{'doc_1': {'rain':0.4, 'sun':0.6}}
{'doc_2': {'............
{'doc_3': {'rain':0.1, .......

2) idf ONE single dictionary:

{'rain': 0.18, 'sun': 0.12......

3) I have my list index for all terms:

[{'term1':[[doc_1, 2],[doc_2, 3]]}, {'term2': [[doc_6, 6],[doc3,1]]}

....and so on for every term

How can I calculate tf*idf now for example for a list of words? I was trying:

def tf_idf(list_of words):
    t_id={}
    for i in list_of_words:
        score= {}
        for j in terms:
            score[j[0]]=(idf[i]*tf[j[0]][i])
        t_id[i]=score
    return t_id

it give me an error:

KeyError: 0

Body:
Some general programming advice here:

def tf_idf(list_of words, tf, idf):   # Pass your variables in, as opposed to using the global scope.
    t_id={}
    for word in list_of_words:  # Name your variables to avoid confusion
        score= {}
        for term in terms:
            score[term[0]]=(idf[word]*tf[term[0]][word])
        t_id[i]=score
    return t_id

I think your issue here is in referring to term[0] (you had this as j[0]).   According to your post, terms looks like this:

[{'term1':[[doc_1, 2],[doc_2, 3]]}...]

So term (or j) is just:

{'term1':[[doc_1, 2],[doc_2, 3]]}

When you refer to term[0] (or j[0]), there would need to be an element in that dictionary with 0 as its key.

Since that key is missing, you get a KeyError.


问:
In Tensorflow, is there a direct way to construct an array tensor from a scalar tensor?
For example, something similar to:

```<code>x = 12
y = np.array([[x, x], [0, 0]])
</code>```

Is there a direct to construct the array tensor y given scalar tensor x in Tensorflow? Without using tf.expand_dims and tf.pad.

```<code>x = tf.placeholder(tf.int32)
y = ?
</code>```

Thank you very much.

答:
You can use the tf.convert_to_tensor() function to do this:

```<code>x = tf.placeholder(tf.int32)  # NOTE: You should probably pass `shape=[]` as well.
y = tf.convert_to_tensor([[x, x], [0, 0]])
</code>```

Also note that TensorFlow will implicitly call tf.convert_to_tensor() on the inputs to any function that expects a tf.Tensor as input, so you may be able to pass [[x, x], [0, 0]] directly to many functions.

Body:
For example, something similar to:

x = 12
y = np.array([[x, x], [0, 0]])

Is there a direct to construct the array tensor y given scalar tensor x in Tensorflow? Without using tf.expand_dims and tf.pad.

x = tf.placeholder(tf.int32)
y = ?

Thank you very much.

Body:
You can use the tf.convert_to_tensor() function to do this:

x = tf.placeholder(tf.int32)  # NOTE: You should probably pass `shape=[]` as well.
y = tf.convert_to_tensor([[x, x], [0, 0]])

Also note that TensorFlow will implicitly call tf.convert_to_tensor() on the inputs to any function that expects a tf.Tensor as input, so you may be able to pass [[x, x], [0, 0]] directly to many functions.


问:
How to set variable to for each items
I have the below code
c:set var = "device" value = "{a.sortList}"

Now i neeed to iterate the loop with device

Like below

```<code>c: forEach items = "device"
</code>```

this will throw error.

So Please help me , I want to declare the variable globally and use that list inside foreach with that variable , how to achieve. Sorry for any syntax mistakes as I am typing from a mobile

答:
You can directly use:</p>

```<code><c:forEach items="${a.sortList}" var="device" varStatus="count">
     ${device}
</c:forEach>
</code>```

Title: How to set variable to for each items

Body:
I have the below code
c:set var = "device" value = "{a.sortList}"

Now i neeed to iterate the loop with device

Like below

c: forEach items = "device"

this will throw error.

So Please help me , I want to declare the variable globally and use that list inside foreach with that variable , how to achieve. Sorry for any syntax mistakes as I am typing from a mobile

Body:
You can directly use:

<c:forEach items="${a.sortList}" var="device" varStatus="count">
     ${device}
</c:forEach>


问:
Sort values that come from different instances of the same class
I want to sort the order of the football clubs based on their points. I have created a class that get the values from the internet and process that values to calculate points based on the number of wins, loses and draws. Then I want to write the standings and their data onto a text file in that order. I created 20 different instances for 20 different clubs. However, I don't know what is the best way to sort the order.

```<code>import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculateStandings {
    private int matches;
    private int homeWin;
    private int homeDraw;
    private int homeLost;
    private int homeForGoal;
    private int homeAgainstGoal;
    private int awayWin;
    private int awayDraw;
    private int awayLost;
    private int awayForGoal;
    private int awayAgainstGoal;
    private int point;
    private int totalWin;
    private int totalLost;
    private int totalDraw;
    private int totalAgainstGoal;
    private int totalForGoal;

    void getResult(String team_Name) {
        try {
            URL url = new URL("https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt");
        Scanner input = new Scanner(url.openStream());
        while (input.hasNext()) {
            String mydata = input.nextLine();
            if (mydata.contains(team_Name)) {
                Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
                Matcher matcher = pattern.matcher(mydata);
                String result;
                if (matcher.find()) {
                    matches += 1;
                    result = matcher.group();

                    if (mydata.startsWith("  " + team_Name)) {
                        homeForGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                        homeAgainstGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                    } else if (mydata.endsWith("  " + team_Name)) {
                        awayForGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                        awayAgainstGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                    }

                    if (Integer.parseInt(Character.toString(result.charAt(0))) > Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 3;
                            homeWin += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            awayLost += 1;
                        }
                    } else if (Integer.parseInt(Character.toString(result.charAt(0))) < Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            homeLost += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 3;
                            awayWin += 1;
                        }

                    } else {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 1;
                            homeDraw += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 1;
                            awayDraw += 1;
                        }
                    }
                }
            }
        }
        totalWin = homeWin + awayWin;
        totalLost = homeLost + awayLost;
        totalDraw = homeDraw + awayDraw;
        totalAgainstGoal = homeAgainstGoal + awayAgainstGoal;
        totalForGoal = homeForGoal + awayForGoal;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}
</code>```

And this is my main class:

```<code>public class Launcher {
public static void main(String[] args) {

    CalculateStandings Arsenal = new CalculateStandings();
    CalculateStandings Tottenham = new CalculateStandings();
    CalculateStandings WHam = new CalculateStandings();
    CalculateStandings CPalace = new CalculateStandings();
    CalculateStandings MU = new CalculateStandings();
    CalculateStandings MC = new CalculateStandings();
    CalculateStandings Everton = new CalculateStandings();
    CalculateStandings Liv = new CalculateStandings();
    CalculateStandings WBAlbion = new CalculateStandings();
    CalculateStandings NU = new CalculateStandings();
    CalculateStandings Stoke_City = new CalculateStandings();
    CalculateStandings Southampton = new CalculateStandings();
    CalculateStandings Leicester_City = new CalculateStandings();
    CalculateStandings Bournemouth = new CalculateStandings();
    CalculateStandings Watford = new CalculateStandings();
    CalculateStandings Brighton = new CalculateStandings();
    CalculateStandings Burnley = new CalculateStandings();
    CalculateStandings Huddersfield = new CalculateStandings();
    CalculateStandings Swansea = new CalculateStandings();

    Arsenal.getResult("Arsenal FC");
    Tottenham.getResult("Tottenham Hotspur");
    WHam.getResult("West Ham United");
    CPalace.getResult("Crystal Palace");
    MU.getResult("Manchester United");
    MC.getResult("Manchester City");
    Everton.getResult("Everton FC");
    Liv.getResult("Liverpool FC");
    WBAlbion.getResult("West Bromwich Albion");
    NU.getResult("Newcastle United");
    Stoke_City.getResult("Stoke City");
    Southampton.getResult("Southampton FC");
    Leicester_City.getResult("Leicester City");
    Bournemouth.getResult("AFC Bournemouth");
    Watford.getResult("Watford FC");
    Brighton.getResult("Brighton & Hove Albion");
    Burnley.getResult("Burnley FC");
    Huddersfield.getResult("Huddersfield Town");
    Swansea.getResult("Swansea City");

}

}
</code>```

I am thinking about storing the values into several arrays using Getter then sort them using sorting algorithm such as Bubble sort. However, as you can see, the number of instances and the number of fields inside each instances are numerous and write them into the arrays manually using Getter would take too much time. Therefore, I would like to ask you if there is a more optimized approach for this.

答:
You could use:

```<code>ArrayList < CalculateStandings > footballClubs = new ArrayList < CalculateStandings >();
</code>```

in main class to create array of objects, then use the

```<code>void add(footballClubName: CalculateStandings)
</code>```

method to add the football clubs instances to the arrayList.

-the next step to force the sorting of the objects is to implement the CalculateStandings class to the Comparable interface by editing the head of the class as this

```<code>class CalculateStandings implements Comparable < CalculateStandings >
</code>```

and override the implementation of the compareTo method in the body of class to how to compare between to instance of this class. as this

```<code>@Override
public int compareTo(CalculateStandings o) {
      if(somthing_field(as_your_calculations) > o.somthing_field)
         return 1;
      else if (the_something_field < o.something_field)
         return -1;
      else
         return 0;
}
</code>```

-then by easy in your main class you can just use the java.util.Collections.
sort(arraylist) to sort it in an increasing order as this

```<code>java.util.Collections.sort(footballClubs);
</code>```

then if you want it in a decreasing order u may use the for loop to reverse it.

That's all, but i have a side note on your code, you could shorten it and epitomize reading by using instructors with args instead of this no-arg instructors, and use the club name string as your args and in the implementation of the instructor use your calculations without need to use an instance method,

```<code>public CalculateStandings(String footballClubName) {
   //put your calculations here and assign the class fields.
}
</code>```

just use the instructor to instantiate ones and add them to the array like this

```<code>footballClubs.add(new CalculateStandings(footballClubName));
</code>```

I wish it help.

Body:
I want to sort the order of the football clubs based on their points. I have created a class that get the values from the internet and process that values to calculate points based on the number of wins, loses and draws. Then I want to write the standings and their data onto a text file in that order. I created 20 different instances for 20 different clubs. However, I don't know what is the best way to sort the order.

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculateStandings {
    private int matches;
    private int homeWin;
    private int homeDraw;
    private int homeLost;
    private int homeForGoal;
    private int homeAgainstGoal;
    private int awayWin;
    private int awayDraw;
    private int awayLost;
    private int awayForGoal;
    private int awayAgainstGoal;
    private int point;
    private int totalWin;
    private int totalLost;
    private int totalDraw;
    private int totalAgainstGoal;
    private int totalForGoal;

    void getResult(String team_Name) {
        try {
            URL url = new URL("https://raw.githubusercontent.com/openfootball/eng-england/master/2017-18/1-premierleague-i.txt");
        Scanner input = new Scanner(url.openStream());
        while (input.hasNext()) {
            String mydata = input.nextLine();
            if (mydata.contains(team_Name)) {
                Pattern pattern = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}");
                Matcher matcher = pattern.matcher(mydata);
                String result;
                if (matcher.find()) {
                    matches += 1;
                    result = matcher.group();

                    if (mydata.startsWith("  " + team_Name)) {
                        homeForGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                        homeAgainstGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                    } else if (mydata.endsWith("  " + team_Name)) {
                        awayForGoal += Integer.parseInt(Character.toString(result.charAt(2)));
                        awayAgainstGoal += Integer.parseInt(Character.toString(result.charAt(0)));
                    }

                    if (Integer.parseInt(Character.toString(result.charAt(0))) > Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 3;
                            homeWin += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            awayLost += 1;
                        }
                    } else if (Integer.parseInt(Character.toString(result.charAt(0))) < Integer.parseInt(Character.toString(result.charAt(2)))) {
                        if (mydata.startsWith("  " + team_Name)) {
                            homeLost += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 3;
                            awayWin += 1;
                        }

                    } else {
                        if (mydata.startsWith("  " + team_Name)) {
                            point += 1;
                            homeDraw += 1;
                        } else if (mydata.endsWith("  " + team_Name)) {
                            point += 1;
                            awayDraw += 1;
                        }
                    }
                }
            }
        }
        totalWin = homeWin + awayWin;
        totalLost = homeLost + awayLost;
        totalDraw = homeDraw + awayDraw;
        totalAgainstGoal = homeAgainstGoal + awayAgainstGoal;
        totalForGoal = homeForGoal + awayForGoal;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

And this is my main class:

public class Launcher {
public static void main(String[] args) {

    CalculateStandings Arsenal = new CalculateStandings();
    CalculateStandings Tottenham = new CalculateStandings();
    CalculateStandings WHam = new CalculateStandings();
    CalculateStandings CPalace = new CalculateStandings();
    CalculateStandings MU = new CalculateStandings();
    CalculateStandings MC = new CalculateStandings();
    CalculateStandings Everton = new CalculateStandings();
    CalculateStandings Liv = new CalculateStandings();
    CalculateStandings WBAlbion = new CalculateStandings();
    CalculateStandings NU = new CalculateStandings();
    CalculateStandings Stoke_City = new CalculateStandings();
    CalculateStandings Southampton = new CalculateStandings();
    CalculateStandings Leicester_City = new CalculateStandings();
    CalculateStandings Bournemouth = new CalculateStandings();
    CalculateStandings Watford = new CalculateStandings();
    CalculateStandings Brighton = new CalculateStandings();
    CalculateStandings Burnley = new CalculateStandings();
    CalculateStandings Huddersfield = new CalculateStandings();
    CalculateStandings Swansea = new CalculateStandings();

    Arsenal.getResult("Arsenal FC");
    Tottenham.getResult("Tottenham Hotspur");
    WHam.getResult("West Ham United");
    CPalace.getResult("Crystal Palace");
    MU.getResult("Manchester United");
    MC.getResult("Manchester City");
    Everton.getResult("Everton FC");
    Liv.getResult("Liverpool FC");
    WBAlbion.getResult("West Bromwich Albion");
    NU.getResult("Newcastle United");
    Stoke_City.getResult("Stoke City");
    Southampton.getResult("Southampton FC");
    Leicester_City.getResult("Leicester City");
    Bournemouth.getResult("AFC Bournemouth");
    Watford.getResult("Watford FC");
    Brighton.getResult("Brighton & Hove Albion");
    Burnley.getResult("Burnley FC");
    Huddersfield.getResult("Huddersfield Town");
    Swansea.getResult("Swansea City");

}

}

I am thinking about storing the values into several arrays using Getter then sort them using sorting algorithm such as Bubble sort. However, as you can see, the number of instances and the number of fields inside each instances are numerous and write them into the arrays manually using Getter would take too much time. Therefore, I would like to ask you if there is a more optimized approach for this.

Body:
You could use:

ArrayList < CalculateStandings > footballClubs = new ArrayList < CalculateStandings >();

in main class to create array of objects, then use the

void add(footballClubName: CalculateStandings)

method to add the football clubs instances to the arrayList.

-the next step to force the sorting of the objects is to implement the CalculateStandings class to the Comparable interface by editing the head of the class as this

class CalculateStandings implements Comparable < CalculateStandings >

and override the implementation of the compareTo method in the body of class to how to compare between to instance of this class. as this

@Override
public int compareTo(CalculateStandings o) {
      if(somthing_field(as_your_calculations) > o.somthing_field)
         return 1;
      else if (the_something_field < o.something_field)
         return -1;
      else
         return 0;
}

-then by easy in your main class you can just use the java.util.Collections.
sort(arraylist) to sort it in an increasing order as this

java.util.Collections.sort(footballClubs);

then if you want it in a decreasing order u may use the for loop to reverse it.

That's all, but i have a side note on your code, you could shorten it and epitomize reading by using instructors with args instead of this no-arg instructors, and use the club name string as your args and in the implementation of the instructor use your calculations without need to use an instance method,

public CalculateStandings(String footballClubName) {
   //put your calculations here and assign the class fields.
}

just use the instructor to instantiate ones and add them to the array like this

footballClubs.add(new CalculateStandings(footballClubName));

I wish it help.


问:
Trouble configuring Autofac in .NET Core 2.0
I started of with my first .NET CORE 2.0 project which would be a webapi. So far so good until I ran into the issue trying to configure Autofac. I followed the instructions described here. But unfortunately I get build errors in my StartUp. Apparently ContainerBuilder does not contain the definition of Populate(). Also the type AutofacServiceProvider could not be found. I've search the net for some time, trying to find the correct documentation for 2.0. It's scattered and not always clear if the source is targeting 1.0 or 2.0. Unfortunately all options end up with build error so I thought I'd stick with the implementation provided by the official documentation. Is it possible that Autofac does not support this form of initiation in .NET Core 2.0.

FYI:

```<code>using Autofac;
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TEST.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterModule<ServiceModule>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();
            return new AutofacServiceProvider(container);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Model\Recipy.Model.csproj" />
    <ProjectReference Include="..\Service\Recipy.Service.csproj" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.6.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>
</code>```

答:
Fairly easy solution to this,
both the Populate method and the AutofacServiceProvider are in a namespace you arent using at the moment.

You also need "Autofac.Extensions.DependencyInjection"

and then those two issues should resolve

Body:
I started of with my first .NET CORE 2.0 project which would be a webapi. So far so good until I ran into the issue trying to configure Autofac. I followed the instructions described here. But unfortunately I get build errors in my StartUp. Apparently ContainerBuilder does not contain the definition of Populate(). Also the type AutofacServiceProvider could not be found. I've search the net for some time, trying to find the correct documentation for 2.0. It's scattered and not always clear if the source is targeting 1.0 or 2.0. Unfortunately all options end up with build error so I thought I'd stick with the implementation provided by the official documentation. Is it possible that Autofac does not support this form of initiation in .NET Core 2.0.

FYI:

using Autofac;
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TEST.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterModule<ServiceModule>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();
            return new AutofacServiceProvider(container);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Model\Recipy.Model.csproj" />
    <ProjectReference Include="..\Service\Recipy.Service.csproj" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.6.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>


问:
Navigating to Angular Sourcecode in VisualStudio?
In my Angular app sourcecode (built using node), I use some type from Angular itself e.g. like this:

```<code>import {HashLocationStrategy} from '@angular/common';
</code>```

When I now try to navigate to the HashLocationStrategy Angular type in VisualStudio, e.g. by choosing "Go to definition" from the context menu, I end up in the file node_modules/@angular/common/src/location/hash_location_strategy.d.ts. That file is only a Declaration File, containing only the type signatures and not the actual implementation itself.

How can I navigate to the actual sourcecode of HashLocationStrategy?

答:
Why do you want to navigate to the Source File?

Though, parallel to the .d.ts file you will have a .js file which
  consist of the JavaScript version of the Source Code.

If you want to explore .ts version, you can explore it here, https://github.com/angular/angular/blob/5.0.5/packages/common/src/location/hash_location_strategy.ts#L15-L88

Body:
In my Angular app sourcecode (built using node), I use some type from Angular itself e.g. like this:

import {HashLocationStrategy} from '@angular/common';

When I now try to navigate to the HashLocationStrategy Angular type in VisualStudio, e.g. by choosing "Go to definition" from the context menu, I end up in the file node_modules/@angular/common/src/location/hash_location_strategy.d.ts. That file is only a Declaration File, containing only the type signatures and not the actual implementation itself.

How can I navigate to the actual sourcecode of HashLocationStrategy?


问:
Marklogic Search in multiple databases
Does Marklogic provides a way to search across multiple databases(These databases are in same Marklogic server).

We could manually search in both and collate result but if Marklogic provides then it will be easier and better solution.

答:
MarkLogic has the ability to create sub-databases as part of the Tiered Storage features.

You may be interested in the specific feature of a Super Database

However.... I suggest you consider when this is the best option vs collections or specific forests (range or query indexes as part of the assignment policy) that can be included or excluded as part of your queries.. There are many considerations when using a super-database. As an example, I seem to remember that the total index size may be larger and the sub and super databases need the same index settings. Different databases is the right choice sometimes. I just urge you to consider strongly when to isolate content in completely separate databases that you then want to query together. At the same time, a single sub-database can belong to multiple super-databases - a powerful feature for some use-cases.

Title: Marklogic Search in multiple databases


问:
How to format decimal using JsRender templates
i am using JsRender templates in my cshtml page. I have some decimal values in my data and want to show 2 numbers afer comma like 17,89 or 3,00. When i have 3 in my data it show only 3 in my template.

How can i format my decimal data?

Just a little example from my template that show how i use data  {{>rate}}

Thanks

答:
If rate is guaranteed to be a number, you can use JavaScript toFixed() like this:

```<code>{{:rate.toFixed(2)}}
</code>```

If rate could be a string, you can coerce it to number, by writing

```<code>{{:(+rate).toFixed(2)}}
</code>```

If you want to make a better separation of code and markup, you can define a converter:

```<code>$.views.converters("dec",
  function(val) {
    return (+val).toFixed(2);
  }
);
</code>```

And then write:

```<code>{{dec:rate}}
</code>```

You can even make the converter smart, and accept a places=n property, to configure the number of decimal places:

```<code>$.views.converters("dec",
  function(val) {
    return (+val).toFixed(this.tagCtx.props.places || 2);
  }
);
</code>```

then optionally specify the number of decimal places:

```<code>{{dec:rate places=3}}
</code>```

Body:
If rate is guaranteed to be a number, you can use JavaScript toFixed() like this:

{{:rate.toFixed(2)}}

If rate could be a string, you can coerce it to number, by writing

{{:(+rate).toFixed(2)}}

If you want to make a better separation of code and markup, you can define a converter:

$.views.converters("dec",
  function(val) {
    return (+val).toFixed(2);
  }
);

And then write:

{{dec:rate}}

You can even make the converter smart, and accept a places=n property, to configure the number of decimal places:

$.views.converters("dec",
  function(val) {
    return (+val).toFixed(this.tagCtx.props.places || 2);
  }
);

then optionally specify the number of decimal places:

{{dec:rate places=3}}


问:
async/await: can't access array value of function directly
This works:

var getArray = function(id) {
  return [1, 2];
}

console.log(getArray()[0]); // returns 1```
</div>
</div>
</p>

<p>This does not work:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var getArray = async function(id) {
  return [1, 2];
}

console.log(await getArray()[0]); // syntax error</code>```

Why? How can I change the async/await syntax so it works?

答:
You can use await keyword in another async function to get the desired result via - (await getArray())[0].

If you use async function not inside another async function, it must be used like simple Promise function with calling then.

var getArray =  async function(id) {
    return [1,2];
}

getArray().then(res => console.log(res[0])).catch(err => {/* ... */});```
</div>
</div>
</p>

<p>If you want to use <code>await</code>, you need another wrapper <code>async</code> function which will do the logic there and will be just called. Also you can use <code>try/catch</code> within your function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var getArray =  async function(id) {
    return [1,2];
}

async function printFirst() {
  try {
     const first = (await getArray())[0];
     console.log(first);
  } catch(e) {

  }
}

printFirst();</code>```

Body:
This works:

var getArray = function(id) {
  return [1, 2];
}

console.log(getArray()[0]); // returns 1

This does not work:

var getArray = async function(id) {
  return [1, 2];
}

console.log(await getArray()[0]); // syntax error

Why? How can I change the async/await syntax so it works?

Body:
You can use await keyword in another async function to get the desired result via - (await getArray())[0].

If you use async function not inside another async function, it must be used like simple Promise function with calling then.

var getArray =  async function(id) {
    return [1,2];
}

getArray().then(res => console.log(res[0])).catch(err => {/* ... */});

If you want to use await, you need another wrapper async function which will do the logic there and will be just called. Also you can use try/catch within your function

var getArray =  async function(id) {
    return [1,2];
}

async function printFirst() {
  try {
     const first = (await getArray())[0];
     console.log(first);
  } catch(e) {

  }
}

printFirst();


问:
Dynamic SortBy over anonymous type
How could I perform a SortBy operation over a list of an anonymous type?

I mean, considering that enumerable is an IEnumerable of an anonymous type that comes as a parameter. For instance:

```<code>public IQueryable<object> MyMethod(IQueryable<object> enumerable)
{
    return enumerable.SortBy("Name");
}
</code>```

Of course, the anonymous type has a Name property

How the SortBy inside should be implemented?

答:
You can perform it by using System.Linq.Dynamic;

```<code>public static class LinqExtensions
{
    public static IQueryable<T> OrderByName<T>(this IQueryable<T> queryable, string sortOrder = null)
    {
        if (string.IsNullOrEmpty(sortOrder))
        {
            sortOrder = "ASC";
        }
        return queryable.OrderBy(string.Format("Name {0}", sortOrder));
    }
}
</code>```

Usage

```<code>   var query = yourContext.Products.OrderByName("DESC");
   var productList = query.ToList();

   public class Product
   {
      public int Id { get;set; }

      public string Name { get; set; }
   }
</code>```

Note : It would be better if you use Enum for sortOrder parameter

Title: Dynamic SortBy over anonymous type

Body:
How could I perform a SortBy operation over a list of an anonymous type?

I mean, considering that enumerable is an IEnumerable of an anonymous type that comes as a parameter. For instance:

public IQueryable<object> MyMethod(IQueryable<object> enumerable)
{
    return enumerable.SortBy("Name");
}

Of course, the anonymous type has a Name property

How the SortBy inside should be implemented?

Body:
You can perform it by using System.Linq.Dynamic;

public static class LinqExtensions
{
    public static IQueryable<T> OrderByName<T>(this IQueryable<T> queryable, string sortOrder = null)
    {
        if (string.IsNullOrEmpty(sortOrder))
        {
            sortOrder = "ASC";
        }
        return queryable.OrderBy(string.Format("Name {0}", sortOrder));
    }
}

Usage

   var query = yourContext.Products.OrderByName("DESC");
   var productList = query.ToList();

   public class Product
   {
      public int Id { get;set; }

      public string Name { get; set; }
   }

Note : It would be better if you use Enum for sortOrder parameter


问:
why producer thread producing more one item even iam setting capacity to 1 also
```<code>import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerAndConsummerUsingBlockingqueue {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(1);
        Thread t1 = new Thread(new Producerqueue(blockingQueue));
        Thread t2 = new Thread(new Consumner(blockingQueue));
        t1.start();
        t2.start();

    }

}

class Producerqueue implements Runnable {

    BlockingQueue<Integer> blockingQueue;

    public Producerqueue(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 1; i <= 10; i++) {
            try {
                System.out.println("produced item " + i);
                blockingQueue.put(i);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

class Consumner implements Runnable {
    BlockingQueue<Integer> blockingQueue;

    public Consumner(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                System.out.println("consumed item " + blockingQueue.take());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}
</code>```

<p>Even i was set capacity 1 for producer then also the output like below.I am not understanding producing item is more than 1 even i am setting capacity to 1 </p>

```<code>produced item 1
produced item 2
consumed item 1
produced item 3
consumed item 2
produced item 4
consumed item 3
produced item 5
consumed item 4
produced item 6
consumed item 5
produced item 7
consumed item 6
produced item 8
consumed item 7
produced item 9
consumed item 8
produced item 10
consumed item 9
consumed item 10
</code>```

答:
Capacity means how many items the queue can hold at one time. Also, the way you've set up your Producerqueue it will print the message before trying to put new items into the queue. That means that your will see a message like produced item 2  but the blockingQueue.put(i); statement will block until it can add a new item to the queue without surpassing its capacity.

For short, your producer prints its message before it adds new items to the queue.

Body:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerAndConsummerUsingBlockingqueue {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(1);
        Thread t1 = new Thread(new Producerqueue(blockingQueue));
        Thread t2 = new Thread(new Consumner(blockingQueue));
        t1.start();
        t2.start();

    }

}

class Producerqueue implements Runnable {

    BlockingQueue<Integer> blockingQueue;

    public Producerqueue(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 1; i <= 10; i++) {
            try {
                System.out.println("produced item " + i);
                blockingQueue.put(i);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

class Consumner implements Runnable {
    BlockingQueue<Integer> blockingQueue;

    public Consumner(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                System.out.println("consumed item " + blockingQueue.take());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

Even i was set capacity 1 for producer then also the output like below.I am not understanding producing item is more than 1 even i am setting capacity to 1

produced item 1
produced item 2
consumed item 1
produced item 3
consumed item 2
produced item 4
consumed item 3
produced item 5
consumed item 4
produced item 6
consumed item 5
produced item 7
consumed item 6
produced item 8
consumed item 7
produced item 9
consumed item 8
produced item 10
consumed item 9
consumed item 10


问:
Handling device data using ionic v2 and the BLE Central plugin
I've been having some issues with how to best handle the device data of discovered peripherals and wanted to see if anyone can shine some light on this. </p>

<p>I am able to scan for devices perfectly fine, and my "success" callback works as well. What I want to do is create a list that displays the found devices and connects to the one that is selected. I have no problem with creating the list with ng repeat, however I am unsure as to how to proceed with the data that is returned by the success function. How can I go about saving each peripheral into an array so that I can access each individual peripheral's name, id , rssi, etc? I have tried something along the lines of creating an array outside the function to store the peripherals in, and this works perfectly fine inside the starScanning function, however I can't push them into an array from inside the success callback function. If I just store the scan results into an array from inside the startScanning function, is that sufficient? </p>

```<code>startScanning = function() {

this.ble.startScan([], this.success).subscribe(device => {
  console.log(JSON.stringify(device.name));
});
this.isScanning = true;
this.presentLoading();

setTimeout(() => {
  this.ble.stopScan().then(() => {
  console.log("Scanning has stopped");

  this.isScanning = false;
  });
  }, 3000);

 }

success = function(peripheral) {

  console.log("Success Callback called");
  console.log(peripheral.rssi);

}
</code>```

答:
You can handle data returned from the scan in the subscribe callback (the startScan method is supposed to only take an array of services as the parameters according to the docs:

```<code> this.scanSubscription = this.ble.startScan([])
  .subscribe( device => {
    // device will have an id property that you can use to connect
    this.devices.push(device); // devices is an array on your component
  });
</code>```

Now, you can use *ngFor to loop over the devices array and attach a click handler that passes the device's id:

```<code>    <ion-list>
        <ion-item *ngFor="let device of devices" (click)="connectToDevice(device.id)">{{device.id}}</ion-item>
    </ion-list>
</code>```

The connectToDevice() takes a device id and connects:

```<code>connectToDevice(id: string) {
    this.connectSubscription = this.ble.connect(id)
      .subscribe((data) => {
        console.log('Successfully connected!');
      });
}
</code>```

A couple of notes:

It's considered good practice to store subscriptions as properties of your page/component so that you can call unsubscribe()on them when a page/component is destroyed to prevent memory leaks

I'd recommend checking out the startScanWithOptions function since you can pass the option reportDuplicates with a value of false to ignore duplicate devices

Check out my Github repo (especially the page file bluetooth.ts) for a working demo app (this uses the startScanWithOptions function I mentioned above, but the functionality is the same)

Body:
I've been having some issues with how to best handle the device data of discovered peripherals and wanted to see if anyone can shine some light on this.

I am able to scan for devices perfectly fine, and my "success" callback works as well. What I want to do is create a list that displays the found devices and connects to the one that is selected. I have no problem with creating the list with ng repeat, however I am unsure as to how to proceed with the data that is returned by the success function. How can I go about saving each peripheral into an array so that I can access each individual peripheral's name, id , rssi, etc? I have tried something along the lines of creating an array outside the function to store the peripherals in, and this works perfectly fine inside the starScanning function, however I can't push them into an array from inside the success callback function. If I just store the scan results into an array from inside the startScanning function, is that sufficient?

startScanning = function() {

this.ble.startScan([], this.success).subscribe(device => {
  console.log(JSON.stringify(device.name));
});
this.isScanning = true;
this.presentLoading();

setTimeout(() => {
  this.ble.stopScan().then(() => {
  console.log("Scanning has stopped");

  this.isScanning = false;
  });
  }, 3000);

 }

success = function(peripheral) {

  console.log("Success Callback called");
  console.log(peripheral.rssi);

}

Body:
You can handle data returned from the scan in the subscribe callback (the startScan method is supposed to only take an array of services as the parameters according to the docs:

 this.scanSubscription = this.ble.startScan([])
  .subscribe( device => {
    // device will have an id property that you can use to connect
    this.devices.push(device); // devices is an array on your component
  });

Now, you can use *ngFor to loop over the devices array and attach a click handler that passes the device's id:

    <ion-list>
        <ion-item *ngFor="let device of devices" (click)="connectToDevice(device.id)">{{device.id}}</ion-item>
    </ion-list>

The connectToDevice() takes a device id and connects:

connectToDevice(id: string) {
    this.connectSubscription = this.ble.connect(id)
      .subscribe((data) => {
        console.log('Successfully connected!');
      });
}

A couple of notes:

It's considered good practice to store subscriptions as properties of your page/component so that you can call unsubscribe()on them when a page/component is destroyed to prevent memory leaks

I'd recommend checking out the startScanWithOptions function since you can pass the option reportDuplicates with a value of false to ignore duplicate devices

Check out my Github repo (especially the page file bluetooth.ts) for a working demo app (this uses the startScanWithOptions function I mentioned above, but the functionality is the same)


问:
Start new numbered list using jQuery
```<code><ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>

<script>
$(document).ready(function(){
    var increment=3;
    var start=8;
    $("ul").children().each(function(i) {
        $(this).prepend('<tag>'+(start+i*increment).toString()+'.</tag>');
    });
});
</script>
</code>```

Is there a way to start a new count for another ul list?
With the code above this is what i get!

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>1. test
2. test
3. test
</code>```

second ul list

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>4. test
5. test
6. test
</code>```

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

答:
```<code>$('ul').each(function() {
    $(this).children().each(function(i) {
        $(this).prepend('<span>' + (i + 1) + '.</span> ');
    });
});
</code>```

Demo: http://jsfiddle.net/vSyK6/1/

ContentLicense: CC BY-SA 2.5

Title: Start new numbered list using jQuery

Body:
test

test

test

test

test

test

test

Is there a way to start a new count for another ul list?
With the code above this is what i get!

 test

 test

 test

Output

1. test
2. test
3. test

second ul list

 test

 test

 test

Output

4. test
5. test
6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

Body:
$('ul').each(function() {
    $(this).children().each(function(i) {
        $(this).prepend('<span>' + (i + 1) + '.</span> ');
    });
});

Demo: http://jsfiddle.net/vSyK6/1/


问:
If not multiple conditions with certain values
I have 2 variables:

1) $key : this variable can either contain the word Unknown or not.

2) $val : this variable can contain 0,0 or some other values

I want to run a script in case that $key not containing Unknown AND $val not equal 0,0. So skip the script if BOTH variables have the above mentioned values ONLY.

So I have the following code:

```<code>if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   /* do nothing! */
}
else {
   /* continue script */
}
</code>```

So is there a better way to achieve the above without having this empty if condition

答:
Just simply negate the conditional statements.</p>

```<code>if(strpos($key, 'Unknown') === false || $val != '0,0') {
    /* continue script */
}
</code>```

Body:
I have 2 variables:

1) $key : this variable can either contain the word Unknown or not.

2) $val : this variable can contain 0,0 or some other values

I want to run a script in case that $key not containing Unknown AND $val not equal 0,0. So skip the script if BOTH variables have the above mentioned values ONLY.

So I have the following code:

if(strpos($key, 'Unknown') !== false && $val == '0,0') {
   /* do nothing! */
}
else {
   /* continue script */
}

So is there a better way to achieve the above without having this empty if condition

Body:
Just simply negate the conditional statements.

if(strpos($key, 'Unknown') === false || $val != '0,0') {
    /* continue script */
}