问:
HTTPS Volley Invalid header issue
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

```<code>mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));
</code>```

there is my SslHurlStuck

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}
</code>```

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

```<code>package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}
</code>```

And last one TrustStoreFactory

```<code>public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}
</code>```

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask

答:
So eventyally in my case, I don't know why , but I just deleted Content-type header with the value from the response, and all is ok.

My answer was found here

Android Volley gives me 400 error

Title: HTTPS Volley Invalid header issue

Body:
Before all : if you don't know the exact answer so just give me advice how to check. Thanks

I have alreary tried a lot of different way how to implement ssl to my volley request but without success.

I can not understand way I get this error

ResponseJsonString = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
                                                                  <TITLE>Bad Request</TITLE>
                                                                  <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

So step by step my code implementation

This is how I get the volley queue

mRequestQueue = Volley.newRequestQueue(this, new SslHurlStuck(SslUtils.KEYSTORE, SslUtils.PASSWORD_SSL, this));

there is my SslHurlStuck

package utils.ssl;

import android.content.Context;
import android.util.Log;

import com.android.volley.toolbox.HurlStack;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.global.AppUtils;

public class SslHurlStuck extends HurlStack
{
private final static String TAG = SslHurlStuck.class.getSimpleName();

private String mTrustStoreAssetName;
private String mTrustStorePassword;
private Context mContext;

public SslHurlStuck(final String iTrustStoreAssetName, final String iTrustStorePassword, Context iContext)
{
    super();

    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

@Override
protected HttpURLConnection createConnection(URL url) throws IOException
{
    HttpsURLConnection urlConnection = null;

    try
    {
        urlConnection = new PinnedCertificateHttpsURLConnectionFactory(mContext).createHttpsURLConnection(url.toString(), mTrustStoreAssetName, mTrustStorePassword);
    }
    catch (Throwable iThrowable)
    {
        AppUtils.printLog(Log.ERROR, TAG, iThrowable.getMessage());
    }

    return urlConnection;
}
}

And eventually there is my PinnedCertificateHttpsURLConnectionFactory

package utils.ssl;

import android.content.Context;
import android.util.Log;

import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

import utils.global.AppUtils;
import webServices.global.RequestStringBuilder;

public class PinnedCertificateHttpsURLConnectionFactory
{
private final static String TAG = PinnedCertificateHttpsURLConnectionFactory.class.getSimpleName();

private final Context mContext;

public PinnedCertificateHttpsURLConnectionFactory(Context iContext)
{
    mContext = iContext;
}

HttpsURLConnection createHttpsURLConnection(String urlString, final String iTrustStoreAssetName, final String iTrustStorePassword) throws Throwable
{
    // Initialize the trust manager factory instance with our trust store
    // as source of certificate authorities and trust material.
    KeyStore trustStore = new TrustStoreFactory(iTrustStoreAssetName, iTrustStorePassword, mContext).createTrustStore();
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(trustStore);

    // Initialize the SSL context.
    TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(trustManagerFactory.getTrustManagers());
    SSLContext sslContext = SSLContext.getInstance(SslUtils.PROTOCOL_TLS);
    sslContext.init(null, wrappedTrustManagers, null);

    // Create the https URL connection.
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    urlConnection.setHostnameVerifier(getHostnameVerifier());

    return urlConnection;
}

// Let's assume your server app is hosting inside a server machine
// which has a server certificate in which "Issued to" is "localhost",for example.
// Then, inside verify method you can verify "localhost".
// If not, you can temporarily return true
private HostnameVerifier getHostnameVerifier()
{
    return new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();

            String localHost = SslUtils.SSL_LOCAL_HOST_DEV;

            if (RequestStringBuilder.isEnvironmentProd())
            {
                localHost = SslUtils.SSL_LOCAL_HOST_PROD;
            }

            return hv.verify(localHost, session);
            //              return hv.verify("localhost", session);
            //              return true;
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers)
{
    final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];

    final X509TrustManager x509TrustManager = new X509TrustManager()
    {
        public X509Certificate[] getAcceptedIssuers()
        {
            return originalTrustManager.getAcceptedIssuers();
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkClientTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkClientTrusted" + e.toString());
            }
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
        {
            try
            {
                if (certs != null && certs.length > 0)
                {
                    for (X509Certificate cer : certs)
                    {
                        cer.checkValidity();
                    }
                }
                else
                {
                    originalTrustManager.checkServerTrusted(certs, authType);
                }
            }
            catch (CertificateException e)
            {
                AppUtils.printLog(Log.ERROR, TAG, "checkServerTrusted" + e.toString());
            }
        }
    };

    return new TrustManager[] {x509TrustManager};
}
}

And last one TrustStoreFactory

public class TrustStoreFactory
{
private String mTrustStoreAssetName;
private String mTrustStorePassword;

private Context mContext;

public TrustStoreFactory(final String iTrustStoreAssetName, final String iTrustStorePassword, final Context iContext)
{
    mTrustStoreAssetName = iTrustStoreAssetName;
    mTrustStorePassword = iTrustStorePassword;
    mContext = iContext;
}

KeyStore createTrustStore() throws Throwable
{
    // Retrieve the trust store file from the assets.
    InputStream inputStream = mContext.getAssets().open(mTrustStoreAssetName);

    try
    {
        // Create a key store with the retrieved input stream.
        KeyStore trustStore = KeyStore.getInstance(SslUtils.KEYSTORE_EXTENSION_BKS);

        trustStore.load(inputStream, mTrustStorePassword.toCharArray());

        return trustStore;
    }
    finally
    {
            inputStream.close();
    }
}
}

So, question is , what am I doing wrong?

My keystore consist 2 cer files, I tried different combinations to add the cer to the keystore... but nothing was changed.

Actually I don't think that there is a problems with a code, I think some issue with certificates , but I can not understand what exactly, and how to fix it

And also what is intresting that in iOS the same ssl checking work in another way, we just need to get certificate from response and then getPublicKey() on it, and compare if public key from response certificate equal to certificate public key that consist within app... But in android it is much more difficult...

Feel free to ask


来源: stackexchange

问:
ERROR 1137: Can't reopen table when joining a temporary table
I have a stored procedure:

```<code>DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
              UPDATE
                new_dijnodes AS src
                JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
                JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
              SET dest.Cost = CASE
                                WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                                WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                                ELSE dest.Cost
                              END,
                  dest.PathID = Paths.PathID
              WHERE
                src.NodeID = vNodeID
                AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
                AND dest.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
          SELECT
            src.NodeName,dest.NodeName,dest.Cost,dest.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes AS dest
            JOIN new_dijpaths AS Paths ON Paths.PathID = dest.PathID
            JOIN new_dijnodes AS src ON src.NodeID = Paths.FromNodeID
          WHERE dest.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;
</code>```

This function is taken from this site
http://www.artfulsoftware.com/infotree/qrytip.php?id=766

well I have changed it to be able to do calculations on temporary tables so it is not any need to save data in tables. But I faced a problem, Mysql does not let to call a temporary table with other names. so In above code I'll face an error which says

```<code>#1137 - Can't reopen table: 'src'
</code>```

the above error comes from this query

```<code>      UPDATE
        new_dijnodes AS src
        JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
        JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
      SET dest.Cost = CASE
                        WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                        WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                        ELSE dest.Cost
                      END,
          dest.PathID = Paths.PathID
      WHERE
        src.NodeID = vNodeID
        AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
        AND dest.Calculated = 0;
</code>```

here is http://sqlfiddle.com/#!9/bc5a01c data of my tables
As you can see the above query joins the same table once as src and again as dest and updates their fields. I tried to create another  new_dijnodes but I could not make it work,Here is my try

```<code>DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;
</code>```

but it always returns  SELECT CONCAT( 'Node ',vNodeID, ' missed.' );  as It updates new_dijnodes_dst which is tables duplication.

I also can not make any real table as this procedure is unique for each user and its handling is not easy for multiuser.
what solutions are available to fix this problem?
thanks

答:
Adding another answer because it's too long for comment.

After update statement, I have brought both instances of temporary table on same page and it's working fine now. You can see output here

Please use stored procedure below.

```<code>DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

            DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
            CREATE TEMPORARY TABLE new_dijnodes AS SELECT * FROM new_dijnodes_dst;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a stored procedure:

DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
              UPDATE
                new_dijnodes AS src
                JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
                JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
              SET dest.Cost = CASE
                                WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                                WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                                ELSE dest.Cost
                              END,
                  dest.PathID = Paths.PathID
              WHERE
                src.NodeID = vNodeID
                AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
                AND dest.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
          SELECT
            src.NodeName,dest.NodeName,dest.Cost,dest.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes AS dest
            JOIN new_dijpaths AS Paths ON Paths.PathID = dest.PathID
            JOIN new_dijnodes AS src ON src.NodeID = Paths.FromNodeID
          WHERE dest.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;

This function is taken from this site
http://www.artfulsoftware.com/infotree/qrytip.php?id=766

well I have changed it to be able to do calculations on temporary tables so it is not any need to save data in tables. But I faced a problem, Mysql does not let to call a temporary table with other names. so In above code I'll face an error which says

#1137 - Can't reopen table: 'src'

the above error comes from this query

      UPDATE
        new_dijnodes AS src
        JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
        JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
      SET dest.Cost = CASE
                        WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                        WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                        ELSE dest.Cost
                      END,
          dest.PathID = Paths.PathID
      WHERE
        src.NodeID = vNodeID
        AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
        AND dest.Calculated = 0;

here is http://sqlfiddle.com/#!9/bc5a01c data of my tables
As you can see the above query joins the same table once as src and again as dest and updates their fields. I tried to create another  new_dijnodes but I could not make it work,Here is my try

DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;

but it always returns  SELECT CONCAT( 'Node ',vNodeID, ' missed.' );  as It updates new_dijnodes_dst which is tables duplication.

I also can not make any real table as this procedure is unique for each user and its handling is not easy for multiuser.
what solutions are available to fix this problem?
thanks

Body:
Adding another answer because it's too long for comment.

After update statement, I have brought both instances of temporary table on same page and it's working fine now. You can see output here

Please use stored procedure below.

DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

            DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
            CREATE TEMPORARY TABLE new_dijnodes AS SELECT * FROM new_dijnodes_dst;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;


问:
xCode Stripping extended attributes failed / xattr
When I try to upload an app to the app store I get the following error:

Stripping extended attributes failed.
"/usr/bin/xattr -crs /var/folders/t2/fjp18t212bdc6kgb3pjzk81m0000gn/T/XcodeDistPipeline.ZBT/Root/Payload/testvgd.app" exited with a non-zero status. The /usr/bin/xattr tool may be damaged.

When I try to run this tool /usr/bin/xattr from command-line I get:
"pkg_resources.DistributionNotFound: The 'xattr==0.6.4' distribution was not found and is required by the application"

Where and how can I add this xattr distribution? I downloaded it from: https://pypi.python.org/pypi/xattr/0.6.4, but when I try to install this, I get: error: package directory 'xattr' does not exist.

Is there a fix or workaround for this? Thanks!

答: I restart the MAC computer solved the problem.</p>


问:
Android Kotlin how to check checkbox in multiple choice list view
I have a multiple choice list view. I wanting to check some of the checkboxes but not all of them. I am trying the code below but not sure where to go from there, or if that is even a start.</p>

```<code>val listView = findViewById<ListView>(R.id.mylist_listview)
        val values = arrayOf("One", "Two", "Three")

        val list = ArrayList<String>()
        for (i in values.indices) {
            list.add(values[i])
        }
        val adapter = ArrayAdapter(this,
                android.R.layout.simple_list_item_multiple_choice, list)
        listView.setAdapter(adapter)

        val cntChoice = listView.getCount()

        for (i in 0 until cntChoice) {

            listView. //Something to check boxes

            }

        }
</code>```

答:
To use multiple choice add listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE

and to check items you need to use listView.setItemChecked(position, true)

Body:
I have a multiple choice list view. I wanting to check some of the checkboxes but not all of them. I am trying the code below but not sure where to go from there, or if that is even a start.

val listView = findViewById<ListView>(R.id.mylist_listview)
        val values = arrayOf("One", "Two", "Three")

        val list = ArrayList<String>()
        for (i in values.indices) {
            list.add(values[i])
        }
        val adapter = ArrayAdapter(this,
                android.R.layout.simple_list_item_multiple_choice, list)
        listView.setAdapter(adapter)

        val cntChoice = listView.getCount()

        for (i in 0 until cntChoice) {

            listView. //Something to check boxes

            }

        }


问:
How can I uncheck the options from multiple selected select pickers
I want to uncheck the selected options from the select picker based on the  values passed into a function.

To achieve this I'm using the below code. I'm using the onclick event to uncheck the options a,b...

```<code>$("#select1 option[value='"+myname+"']").prop("selected", false);
</code>```

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
</div>

<button onclick=r em( 'a,b')>Unselect</button></code>```

答:
Update your function

$("#select1").selectpicker("refresh"); is missing in your function which is proper way to update selectpicker

```<code>function rem(myname) {

  $("#select1 option[value='"+myname+"']").prop("selected", false);

  $("#select1").selectpicker("refresh");
}
</code>```

function rem(myname) {

  $("#select1 option[value='"+myname+"']").prop("selected", false);

  $("#select1").selectpicker("refresh");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
<select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true"  multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
  </div>

  <button onclick = rem('a,b')>Unselect</button></code>```

Body:
I want to uncheck the selected options from the select picker based on the  values passed into a function.

To achieve this I'm using the below code. I'm using the onclick event to uncheck the options a,b...

$("#select1 option[value='"+myname+"']").prop("selected", false);

function rem(myname) {
  $("#select1 option[value='" + myname + "']").prop("selected", false);

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

  Select Fee Types
  <select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true" multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>

<button onclick=r em( 'a,b')>Unselect</button>

Body:
Update your function

$("#select1").selectpicker("refresh"); is missing in your function which is proper way to update selectpicker

function rem(myname) {

  $("#select1 option[value='"+myname+"']").prop("selected", false);

  $("#select1").selectpicker("refresh");
}

function rem(myname) {

  $("#select1 option[value='"+myname+"']").prop("selected", false);

  $("#select1").selectpicker("refresh");
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>

<div class="container body-content">
  Select Fee Types
<select class="selectpicker form-control" id="select1" name="select1" data-width="200px" data-size="4" data-live-search="true"  multiple>
<option disabled>Select</option>
<option value="a,b" selected>a</option>
<option value="d,c" selected>c</option>
<option value="f,e">e</option>
 </select>
  </div>

  <button onclick = rem('a,b')>Unselect</button>


问:
EMGU CV camera capture in WPF?
All I am trying to display camera captured frames in WPF. I already can display image. But can't figure out the event handling method? In WinForm it is Application.Idle but what should I use in WPF? I have seen this thread already ..I couldn't make it .</p>

答:
Why can't you use Timer.Elapsed event?

Just remember that Elapsed callback occurs in Worker Thread, that makes impossible update of  UI. So you should use SynchronizationContext to direct UI update actions to proper thread.

```<code>    private SynchronizationContext _context = SynchronizationContext.Current;

    void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                this._context.Send(o =>
                    {
                        using (var stream = new MemoryStream())
                        {
                            // My way to display frame
                            frame.Bitmap.Save(stream, ImageFormat.Bmp);

                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = new MemoryStream(stream.ToArray());
                            bitmap.EndInit();

                            webcam.Source = bitmap;
                        }

                    },
                    null);
            }
        }
    }
</code>```

Alternatively, as all UI tasks go through Dispatcher, you could react on DispatcherInactive event:

```<code>    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //...
        this.Dispatcher.Hooks.DispatcherInactive += new EventHandler(Hooks_DispatcherInactive);
    }

    void Hooks_DispatcherInactive(object sender, EventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                using (var stream = new MemoryStream())
                {
                    // My way to display frame
                    frame.Bitmap.Save(stream, ImageFormat.Bmp);

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = new MemoryStream(stream.ToArray());
                    bitmap.EndInit();

                    webcam.Source = bitmap;
                };
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: EMGU CV camera capture in WPF?

Body:
Why can't you use Timer.Elapsed event?

Just remember that Elapsed callback occurs in Worker Thread, that makes impossible update of  UI. So you should use SynchronizationContext to direct UI update actions to proper thread.

    private SynchronizationContext _context = SynchronizationContext.Current;

    void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                this._context.Send(o =>
                    {
                        using (var stream = new MemoryStream())
                        {
                            // My way to display frame
                            frame.Bitmap.Save(stream, ImageFormat.Bmp);

                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = new MemoryStream(stream.ToArray());
                            bitmap.EndInit();

                            webcam.Source = bitmap;
                        }

                    },
                    null);
            }
        }
    }

Alternatively, as all UI tasks go through Dispatcher, you could react on DispatcherInactive event:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //...
        this.Dispatcher.Hooks.DispatcherInactive += new EventHandler(Hooks_DispatcherInactive);
    }

    void Hooks_DispatcherInactive(object sender, EventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                using (var stream = new MemoryStream())
                {
                    // My way to display frame
                    frame.Bitmap.Save(stream, ImageFormat.Bmp);

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = new MemoryStream(stream.ToArray());
                    bitmap.EndInit();

                    webcam.Source = bitmap;
                };
            }
        }
    }


问:
Get OS version through IoTHub Device Twin / Direct Method
How can we get the Windows version installed on the device through IotHub Device Twin or Direct Method or Any other means?</p>

答: IoTHub SDKs can not get the version of the windows system installed on the device,they have no related API.AnalyticsVersionInfo Class provides version information about the device family. Please see this topic of Windows 10 get DeviceFamilyVersion.</p>


问:
How to disable csrf in Spring using application.properties?
The following property exists:

security.enable-csrf=false

BUT csrf protection is still on if I add the property to application.properties.

What works is to disable it programatically.

But I'd prefer properties configuration. Why could it not be working?

```<code>@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.csrf().disable();

    }
}
</code>```

答:
An update:

Looks like there is an issue with disabling CSRF using application.properties on spring-boot 1.x (and thanks to Eliux for openning this case).

So my solution for spring-boot 1.5.7 with an embedded tomcat is disabling CSRF via SecurityConfig class (note that this way I keep the tomcat ootb basic authentication):

```<code>@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Note:
        // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
        // Note that the CSRf token is disabled for all requests (change it as you wish...)
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // Add here any custom code you need in order to get the credentials from the user...
        auth.inMemoryAuthentication()
            .withUser("myUserName")
            .password("myPassword")
            .roles("USER");
    }
}
</code>```

Body:
The following property exists:

security.enable-csrf=false

BUT csrf protection is still on if I add the property to application.properties.

What works is to disable it programatically.

But I'd prefer properties configuration. Why could it not be working?

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.csrf().disable();

    }
}

Body:
An update:

Looks like there is an issue with disabling CSRF using application.properties on spring-boot 1.x (and thanks to Eliux for openning this case).

So my solution for spring-boot 1.5.7 with an embedded tomcat is disabling CSRF via SecurityConfig class (note that this way I keep the tomcat ootb basic authentication):

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Note:
        // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
        // Note that the CSRf token is disabled for all requests (change it as you wish...)
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // Add here any custom code you need in order to get the credentials from the user...
        auth.inMemoryAuthentication()
            .withUser("myUserName")
            .password("myPassword")
            .roles("USER");
    }
}


问:
minimum Age validation laravel
I want to validation a users information like date of birth for that i have used following line of statement in validation, But how do i make it dynamic so users minimum age could be 13. below that can't register?</p>

```<code>  return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:2011-06-08',
        ]);
</code>```

答:
To check user's age as minimum 13 years use after rule. Change rule for date_of_birth to

```<code>'date_of_birth' =>'required|date|after:13 years',
</code>```

before will not work as it is opposite of after

Title: minimum Age validation laravel

Body:
I want to validation a users information like date of birth for that i have used following line of statement in validation, But how do i make it dynamic so users minimum age could be 13. below that can't register?

  return Validator::make($data, [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'date_of_birth' =>'required|date|before:2011-06-08',
        ]);

Body:
To check user's age as minimum 13 years use after rule. Change rule for date_of_birth to

'date_of_birth' =>'required|date|after:13 years',

before will not work as it is opposite of after


问:
Where are Android Emulator Images Stored?
On the emulator, I downloaded an image from Google. I can find the image on the emulator, but I have no idea what the file location of the image is. To debug my app I need to know where that image is. How can I get the full path of the image?</p>

答:
The system images are downloaded in
[ {android_version_home_dir}/sdk/system-images/{android-version-number}/system.img> ]

and the avd are created in C:\Users\.android\avd\ (windows) or ~/.android/avd/ (linux/mac)

ContentLicense: CC BY-SA 4.0


问:
Stream and Filter operations on a Map
I have an EdmPortfolio type that has id (int), name (String) and tags which is a  map as its members.

EdmPortfolio say has an id 1, and name as Portfolio1 and Map could have the following values,
analyst, John
region, US

I have a List,  At the end i want to have a Map which has all the map values combined from all portfolios. Another EdmPortfolio  might have the id as 2, name as Portfolio2 and Map with values analyst, Smith
region , UK

I want to have a combined Map with Values
region 'US','UK'
analyst 'John','Smith'

analyst and region are the keys to the map.
It has both the maps combined. I have the following code but i am a little lost

```<code>List<Map<Tag,String>> portfolioTagsList = new ArrayList<>();
            for (EdmPortfolio edmPortfolio : edmPortfolioList) {
              Map<Tag,String> portfolioTags =  edmPortfolio.getPortfolioTags().entrySet()
                        .stream()

                        .filter(e -> (e.getValue() != ""|| e.getValue() !=null))
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                Map.Entry::getValue
                        ));

                portfolioTagsList.add(portfolioTags);
            }
            Map<Tag,String> finalTags = portfolioTagsList.stream()
                    .flatMap(m -> m.entrySet().stream())
                    .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.joining(",",Map.Entry::getValue)));
</code>```

I am getting nonstatic method cannot be referenced from static context. How do i achieve this?

Thanks for your time

答:
Unfortunately, “nonstatic method cannot be referenced from static context” is the error that javac often ends up when type inference fails, especially in the context of method references or lambda expressions. The actual cause could be a wrong generic type parameter, a forgotten import statement, the use of a lambda expression or method reference at an inappropriate place, or even a misplaced or forgotten brace somewhere.

In your case, it’s Collectors.joining(",",Map.Entry::getValue) as that collector has no parameter of a function type that could accept a method reference.

You should use Collectors.mapping(Map.Entry::getValue, Collectors.joining(",")) instead.

Besides that, follow BrunoJCM’s suggestion to use a single stream operation and pay attention to the filter condition. e.getValue() != "" || e.getValue() !=null makes no sense as a reference can never be both, a reference to "" and the null reference, hence, this condition is always fulfilled. You most likely wanted to express that the string must not be null and not an empty string. In this regard, you should not compare strings by reference but use equals. For testing for an empty string, there is the alternative to use isEmpty() instead of equals(""). So the condition should be e.getValue()!=null && !e.getValue().isEmpty(). Mind the order, as we can invoke isEmpty() only after having verified that it is not null.

Title: Stream and Filter operations on a Map

Body:
I have an EdmPortfolio type that has id (int), name (String) and tags which is a  map as its members.

EdmPortfolio say has an id 1, and name as Portfolio1 and Map could have the following values,
analyst, John
region, US

I have a List,  At the end i want to have a Map which has all the map values combined from all portfolios. Another EdmPortfolio  might have the id as 2, name as Portfolio2 and Map with values analyst, Smith
region , UK

I want to have a combined Map with Values
region 'US','UK'
analyst 'John','Smith'

analyst and region are the keys to the map.
It has both the maps combined. I have the following code but i am a little lost

List<Map<Tag,String>> portfolioTagsList = new ArrayList<>();
            for (EdmPortfolio edmPortfolio : edmPortfolioList) {
              Map<Tag,String> portfolioTags =  edmPortfolio.getPortfolioTags().entrySet()
                        .stream()

                        .filter(e -> (e.getValue() != ""|| e.getValue() !=null))
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                Map.Entry::getValue
                        ));

                portfolioTagsList.add(portfolioTags);
            }
            Map<Tag,String> finalTags = portfolioTagsList.stream()
                    .flatMap(m -> m.entrySet().stream())
                    .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.joining(",",Map.Entry::getValue)));

I am getting nonstatic method cannot be referenced from static context. How do i achieve this?

Thanks for your time


问:
Running a programm until a specified key is pressed outside of the programm
I want a console application to run as long as i press a specified key, even outside of the programm.
For example the programm is running in the background und when i am writing something e.g. in word and press a specific key, the console application does something.

I started with this:

```<code>static void Main(string[] args)
    {
        ConsoleKeyInfo keyinfo;

        do
        {
            keyinfo = Console.ReadKey();
            //Do something
        }
        while (keyinfo.Key != ConsoleKey.F10);
    }
</code>```

But the problem here is, that it stops and waits for a key pressed until it keeps going.
I want to run it in the background and always checking when i am pressing a specific key.

Any solutions?

答:
You can use the events provided by the static class HookManager.

You only need to add one of the events (included mouse activity):

```<code>UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
    actHook= new UserActivityHook(); // crate an instance

    // hang on events

    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}
</code>```

Example for KeyDown event:

```<code>public void MouseMoved(object sender, KeyEventArgs e)
        {
            Keys key = e.KeyCode;
            Console.WriteLine(key.ToString());
        }
</code>```

ReadKey method runs only when you type something inside the console.

More details: https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C

Body:
I want a console application to run as long as i press a specified key, even outside of the programm.
For example the programm is running in the background und when i am writing something e.g. in word and press a specific key, the console application does something.

I started with this:

static void Main(string[] args)
    {
        ConsoleKeyInfo keyinfo;

        do
        {
            keyinfo = Console.ReadKey();
            //Do something
        }
        while (keyinfo.Key != ConsoleKey.F10);
    }

But the problem here is, that it stops and waits for a key pressed until it keeps going.
I want to run it in the background and always checking when i am pressing a specific key.

Any solutions?

Body:
You can use the events provided by the static class HookManager.

You only need to add one of the events (included mouse activity):

UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
    actHook= new UserActivityHook(); // crate an instance

    // hang on events

    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}

Example for KeyDown event:

public void MouseMoved(object sender, KeyEventArgs e)
        {
            Keys key = e.KeyCode;
            Console.WriteLine(key.ToString());
        }

ReadKey method runs only when you type something inside the console.

More details: https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C


问:
how to filter duplicate rows with different value
I hv a table like this

```<code>Model     Qty        Date
ABC        1         20110102
ABC       -1         20110105
QWE        1         20110103
ZXC        1         20110103
ABC        1         20110110
QWE       -1         20110110
</code>```

I wish to hv the final output like this:-

```<code>Model     Qty        Date
ZXC        1         20110103
ABC        1         20110110
</code>```

How can I do this via SQL ?

Thanks

答:
You want the sum of the Qty and the latest Date for each Model:

```<code>SELECT Model, SUM(Qty), MAX(Date)
FROM YourTable
GROUP BY Model
HAVING SUM(Qty) <> 0
</code>```

QWE has a sum of Qty = 0 and therefore should not be returned, right?

Body:
I hv a table like this

Model     Qty        Date
ABC        1         20110102
ABC       -1         20110105
QWE        1         20110103
ZXC        1         20110103
ABC        1         20110110
QWE       -1         20110110

I wish to hv the final output like this:-

Model     Qty        Date
ZXC        1         20110103
ABC        1         20110110

How can I do this via SQL ?

Thanks

Body:
You want the sum of the Qty and the latest Date for each Model:

SELECT Model, SUM(Qty), MAX(Date)
FROM YourTable
GROUP BY Model
HAVING SUM(Qty) <> 0

QWE has a sum of Qty = 0 and therefore should not be returned, right?


问:
Raspberry Pi 3 + official touchscreen display app just shows black screen on DP6
I've connected the offical touchscreen display via DSI to my Raspberry Pi 3 running the latest Android Things developer preview.

While booting the android things logo shows up and afterwards the new DP6 settings appear just fine.
When I install an app via adb the screen stays black and no suspicious log message shows up.
In DP 5.1 I had no problems with this.

Also tried running this example:
https://github.com/androidthings/sample-simpleui

Furthermore maxing out the screen brightness with the ScreenManager didn't help.

Any ideas?

答: Reflashing the image with the Android Things Setup Utility fixed my issue.</p>


问:
Why getAll method of Guava LoadingCache returns different types of ImmutableMap?
I have simple Guava LoadingCache use case where I pass list of key objects to getAll and implemented loadAll to get results when not available in cache.

The problem is When cache is empty,

Calling getAll for collection of records returns Map of type RegularImmutableMap.

And calling getAll for collection of single record returns Map of type SingletonImmutableBiMap.

This eventually leads to another problem. When I try to collect map.values() on it, RegularImmutableMap returns a type of ImmutableList and SingletonImmutableBiMap returns a type of ImmutableSet.

From user perspective is there any specific reason/advantage why getAll method returns different types of ImmutableMap?

答:
Note this has nothing to do with Cache - the LocalCache implementation you're presumably using simply calls ImmutableMap.copyOf() before returning the collected results.

So your underlying question is really why does ImmutableMap.of(K, V) return an ImmutableBiMap?

This has been the behavior since 2012 and the short answer is because ImmutableBiMap extends ImmutableMap, therefore there's no need to have both a SingletonImmutableMap and SingletonImmutableBiMap implementation.

As matoni has said, ImmutableMap.values() returns an ImmutableCollection, therefore you cannot rely on a particular implementation to return an ImmutableList or an ImmutableSet (or some other mysterious type that extends ImmutableCollection). Not only that, you cannot rely on the existing behavior staying this way! For a brief while (from February to June) ImmutableMap actually didn't use ImmutableBiMap.

This means you should not expect ImmutableMap.values() to return an ImmutableList, and any code that does so is broken. If you need an ImmutableList from an ImmutableCollection use .asList() - for most immutable collections this can return a view in O(1) time and space.


问:
django rest framework installation fails
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

```<code>pip install djangorestframework-jsonapi
</code>```

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi

答:
Are you installing Django Rest Framework or are you installing the JSON API?  If it is just DRF, check the installation docs:
http://www.django-rest-framework.org/#installation

Otherwise, please provide more info like what version of Python and your OS as well as what version of the library you are installing.

Body:
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

pip install djangorestframework-jsonapi

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi


问:
How do I change the color of a specific printed letter in python?
I am trying to make a short quiz and I want to display Incorrect Answer in red.
Welcome to my Quiz!
Would you like to begin?: yes
Goodluck
What is the capital of France?:  france # random answer
Incorrect Answer # i am trying to display it in red.

My code is:

```<code>print ("Welcome to my Quiz!")
begin = input("Would you like to begin?: ")
if begin == ("yes")  or begin == ("Yes"):
print ("Goodluck")
Q1 = input("What is the capital of France?:  ")
if Q1 == ("Paris") or Q1 == ("paris"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

Q2 = input("What is the capital of India?:  ")
if Q2 == ("New Delhi") or Q2 == ("new delhi"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

else:
    print ("Goodbye :)")
</code>```

答:
YOu need to include termcolor as follows:

```<code>from termcolor import colored
</code>```

and then the specific print line as follows:

```<code>print( colored( "Incorrect Answer", "red" ) )
</code>```

Body:
I am trying to make a short quiz and I want to display Incorrect Answer in red.
Welcome to my Quiz!
Would you like to begin?: yes
Goodluck
What is the capital of France?:  france # random answer
Incorrect Answer # i am trying to display it in red.

My code is:

print ("Welcome to my Quiz!")
begin = input("Would you like to begin?: ")
if begin == ("yes")  or begin == ("Yes"):
print ("Goodluck")
Q1 = input("What is the capital of France?:  ")
if Q1 == ("Paris") or Q1 == ("paris"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

Q2 = input("What is the capital of India?:  ")
if Q2 == ("New Delhi") or Q2 == ("new delhi"):
    print ("Correct Answer!")
    print (" ")
else:
    print ("Incorrect Answer")
    print (" ")

else:
    print ("Goodbye :)")

Body:
YOu need to include termcolor as follows:

from termcolor import colored

and then the specific print line as follows:

print( colored( "Incorrect Answer", "red" ) )


答:
I found the solution.</p>

```<code>  for (i in 0 until cntChoice) {
        listView.setItemChecked(i,true)
    }
</code>```

Title: Android Kotlin how to check checkbox in multiple choice list view

Body:
I found the solution.

  for (i in 0 until cntChoice) {
        listView.setItemChecked(i,true)
    }


问:
How to convert Python project into executable
I have a Python project that I want to convert into an executable. I have installed Pyinstaller. I only know how to convert one single script into .exe, but I have multiple packages with multiple python scripts.</p>

答: Converting the main script into .exe should solve the problem, use -onefile to convert it to one exe and rest of the .py files should be included.</p>


问:
Caesar Cipher in Java. Encode, decode an rotate a String

Hi, I am trying to make a program, which allows the user to encode, decode and rotate a String. For example:

User Input: "Caesar"
System  Output: "Fdhvdu"

The user may decide how much the word is to be rotated. The program is not finished yet, I just made a method for option V: encode and wanted to know if I made it is appropriate? or if it works completely different way!

```<code>public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=V; //Input.readChar();
        System.out.println("Enter text to encode:");
        benutzerText=Input.readString();
        System.out.println("which rotation do you want?");
        rotation=Input.readInt();

        switch (benutzerBefehl){
        case V: System.out.println(": Encoded text: "+Caesar.encode(benutzerText,rotation));
            break;
        case E: (": Decoded text: "+Ceasar.decode(benutzerText,rotation));
            break;
        case B: // will be filled
            break;
        default:
            System.out.println("Invalid option..");
        }

        public static String Caesar.encode(String original_text, int rot){

            String []s= original_text.split(" ");

            for(int i=0;i<s.length();i++){
                Stringbuilder letter=new StringBuilder();
                letter.append(s.[i]+rot);
            }

            return String;

        }

    }

}
</code>```

答:
```<code>        for(int i=0;i<s.length();i++){
            Stringbuilder letter=new StringBuilder();
            letter.append(s.[i]+rot);
        }
</code>```

This loop will not work since you create (and dissmiss) the Stringbuilder object with every iteration of the loop.

BTW: letter is the wrong name for the variable since it will contain a word (at least) not a single letter...

Body:
Hi, I am trying to make a program, which allows the user to encode, decode and rotate a String. For example:

User Input: "Caesar"
System  Output: "Fdhvdu"

The user may decide how much the word is to be rotated. The program is not finished yet, I just made a method for option V: encode and wanted to know if I made it is appropriate? or if it works completely different way!

public class CaesarsChiffre {

    public static void main(String[] args) {

        char benutzerBefehl;
        String benutzerText;
        int rotation=0;

        System.out.println("Caesars Chiffre encode, decode, rotate.");
        System.out.println("Waehlen Sie:");
        System.out.println("V for encode");
        System.out.println("E for decode");
        System.out.println("B for rotation");
        benutzerBefehl=V; //Input.readChar();
        System.out.println("Enter text to encode:");
        benutzerText=Input.readString();
        System.out.println("which rotation do you want?");
        rotation=Input.readInt();

        switch (benutzerBefehl){
        case V: System.out.println(": Encoded text: "+Caesar.encode(benutzerText,rotation));
            break;
        case E: (": Decoded text: "+Ceasar.decode(benutzerText,rotation));
            break;
        case B: // will be filled
            break;
        default:
            System.out.println("Invalid option..");
        }

        public static String Caesar.encode(String original_text, int rot){

            String []s= original_text.split(" ");

            for(int i=0;i<s.length();i++){
                Stringbuilder letter=new StringBuilder();
                letter.append(s.[i]+rot);
            }

            return String;

        }

    }

}

Body:
        for(int i=0;i<s.length();i++){
            Stringbuilder letter=new StringBuilder();
            letter.append(s.[i]+rot);
        }

This loop will not work since you create (and dissmiss) the Stringbuilder object with every iteration of the loop.

BTW: letter is the wrong name for the variable since it will contain a word (at least) not a single letter...


问:
Bottom TabLayout leaving space at bottom
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efeded"
android:weightSum="11"
android:orientation="vertical">

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>
</code>```

答:
For bottom tabs you can use bottomnavigationview it provides better performance and works in MOTO devices with out any problem. Check this

https://developer.android.com/reference/android/support/design/widget/BottomNavigationView.html

Body:
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efeded"
android:weightSum="11"
android:orientation="vertical">

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>


问:
Display coordinates from db in Google Maps
So after getting myself informed about how to retrieve x and y coordinates from my database and display them in Google Maps: I went to work. So to make a connection with my mySQL database is wrote this:

```<code><?php
  $server     = '132.3.2.1.';
  $username   = 'you';
  $password   = 'notyou';
  $database   = 'youapp';
  $dsn        = "mysql:host=$server;dbname=$database";

  (This is all made up)
</code>```

To retrieve the coordinates from my database and put them in a JSON string I wrote this:

```<code><?php
  include 'config.php';
  try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $sth = $db->query("SELECT * FROM youapp");
    $youapp = $sth->fetchAll();
    echo json_encode( $youapp );
  } catch (Exception $e) {
    echo $e->getMessage();
  }
</code>```

I am pretty sure that what I have coded up till now is correct. But I am not sure on the Google Maps part.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Beer Me</title>
    <link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    var map;
    function init() {
      var mapOptions = {
        zoom: 13,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      makeRequest('get_locations.php', function(data) {
        var data = JSON.parse(data.responseText);
        for (var i = 0; i < data.length; i++) {
          displayLocation(data[i]);
        }
      });
    }
    function makeRequest(url, callback) {
      var request;
      if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
      // IE7+, Firefox, Chrome, Opera, Safari
      } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      // IE6, IE5
      }
      request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
          callback(request);
        }
      }
      request.open("GET", url, true);
      request.send();
    }
  </script>
</head>
<body onload="init();">
  <div id="map_canvas" style="width:400px; height: 400px;"></div>
</body>
</html>
</code>```

So the function makerequest is a standard Ajax call. But I am not sure how to display the results in Google Maps. If anyone could look at my code to make a connection with my database and give some advice or something on how to display the results from the makerequest in Google Maps, that would be greatly appreciated.

答:
TRY this.</p>

```<code>function displayLocation(item) {
    var marker = new google.maps.Marker({
        // might need to change item.lat/item.lng
        //  to match the column name in your DB
        position: new google.maps.LatLng(item.lat, item.lng),
        map: map
    });
}
</code>```

Body:
So after getting myself informed about how to retrieve x and y coordinates from my database and display them in Google Maps: I went to work. So to make a connection with my mySQL database is wrote this:

<?php
  $server     = '132.3.2.1.';
  $username   = 'you';
  $password   = 'notyou';
  $database   = 'youapp';
  $dsn        = "mysql:host=$server;dbname=$database";

  (This is all made up)

To retrieve the coordinates from my database and put them in a JSON string I wrote this:

<?php
  include 'config.php';
  try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $sth = $db->query("SELECT * FROM youapp");
    $youapp = $sth->fetchAll();
    echo json_encode( $youapp );
  } catch (Exception $e) {
    echo $e->getMessage();
  }

I am pretty sure that what I have coded up till now is correct. But I am not sure on the Google Maps part.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Beer Me</title>
    <link rel="stylesheet" href="/master.css" type="text/css" media="screen" />

    var map;
    function init() {
      var mapOptions = {
        zoom: 13,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
      makeRequest('get_locations.php', function(data) {
        var data = JSON.parse(data.responseText);
        for (var i = 0; i < data.length; i++) {
          displayLocation(data[i]);
        }
      });
    }
    function makeRequest(url, callback) {
      var request;
      if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
      // IE7+, Firefox, Chrome, Opera, Safari
      } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      // IE6, IE5
      }
      request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
          callback(request);
        }
      }
      request.open("GET", url, true);
      request.send();
    }
  </script>

So the function makerequest is a standard Ajax call. But I am not sure how to display the results in Google Maps. If anyone could look at my code to make a connection with my database and give some advice or something on how to display the results from the makerequest in Google Maps, that would be greatly appreciated.

Body:
TRY this.

function displayLocation(item) {
    var marker = new google.maps.Marker({
        // might need to change item.lat/item.lng
        //  to match the column name in your DB
        position: new google.maps.LatLng(item.lat, item.lng),
        map: map
    });
}


问:
Modifying specific array elements in Python 3.1
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

```<code> for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))
</code>```

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

答:
In Python, what you are trying to do is done using lists. There is another separate data type called arrays, but that is for totally different purpose. Please don't confuse and use the proper terminology, list.

Lists can be iterated through. You need to not index the elements out of the list and then access them using the index. That is C or C++ way of doing things and not python.

You use a list or a dictionary called mod in your original code. It is a bad idea to override builtin names. I tried to understand what you are trying, came up with the following code.  Take it further, but before that, I think some beginner tutorials might help you as well.

```<code>new_array = []
somevalue = 0.001

for elem in array:
   for anotherelem in least_common:
            if elem == anotherelem[0]:
                    new_array.append(elem + (elem * somevalue))
</code>```

Body:
I have two arrays: array and least_common (filter array)

The following code iterates through array, checks for elements that match least_common, and if finds it, modifies it and appends it to a new array.

 for i in range (len(array)):
        for j in range(len(least_common)):
            if array[i] is least_common[j][0]:
                new_array.append ((array[i]) + (array[i] * (mod[1]/100)))

However, if the element in array does not match any of the elements in least_common I wan't to append it to new_array, then iterate to the next element in array to begin the checking process again.

Body:
In Python, what you are trying to do is done using lists. There is another separate data type called arrays, but that is for totally different purpose. Please don't confuse and use the proper terminology, list.

Lists can be iterated through. You need to not index the elements out of the list and then access them using the index. That is C or C++ way of doing things and not python.

You use a list or a dictionary called mod in your original code. It is a bad idea to override builtin names. I tried to understand what you are trying, came up with the following code.  Take it further, but before that, I think some beginner tutorials might help you as well.

new_array = []
somevalue = 0.001

for elem in array:
   for anotherelem in least_common:
            if elem == anotherelem[0]:
                    new_array.append(elem + (elem * somevalue))