问:
IDX10634: Unable to create the SignatureProvider SignatureAlgorithm: 'SHA256',
I tried with the below suggestion,it is working for  SecurityAlgorithms.HmacSha256Signature.

Suggested Code:

```<code>SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(symmetricKey), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
</code>```

but it is not working for SecurityAlgorithms.RsaSha256Signature.

```<code>Microsoft.IdentityModel.Tokens.SigningCredentials SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature);
</code>```

I got the below error.

DX10634: Unable to create the SignatureProvider.

SignatureAlgorithm: 'SHA256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey' is not supported

I need to convert JWT token for Sha256. kindly provide solution with sample code.

Please find my code:

```<code>       string _privateSecretKey = "MIIEogIBAAKCAQEAytYejMhaYjZwFgqP7WKh2bkf08=";

        Microsoft.IdentityModel.Tokens.SymmetricSecurityKey _signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.ASCII.GetBytes(_privateSecretKey));
        Microsoft.IdentityModel.Tokens.SigningCredentials SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature);

        JwtHeader head = new JwtHeader();
        head.Add("kid", "firstpublickey");//TBD

        string sNewGuid = Guid.NewGuid().ToString("n");

        var claims = new[]
          {
              new Claim(JwtRegisteredClaimNames.Iss, oTokenPostData.ClientID),
            new Claim(JwtRegisteredClaimNames.Sub, oTokenPostData.ClientID),
            new Claim(JwtRegisteredClaimNames.Aud, oTokenPostData.tokenUri),
            new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
                new Claim(JwtRegisteredClaimNames.Exp, ((int)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture)),
                new Claim(JwtRegisteredClaimNames.Iat, ((int)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture))
          };

        JwtPayload payload = new JwtPayload(claims);

        JwtSecurityToken jwt = new JwtSecurityToken(head, payload);

        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
</code>```

答:
JWT is getting converted using the below code.

```<code>using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ConsoleApplication2
{

private class JWT
{
    private bool verbose = false;
    public  string GenerateJWT()
    {
        DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        // Provide proper private key
        string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN33XusJhrz9HXmIrdyX2F41xJHG4uj5/2Dzv3xjYYvqxexm3X3X5TOf3WoM1VNloJ7UnbqUJOiEjgK8sRdJntgfomO4U8s67cpysk0h9rc0He4xRspEjOapFfDg+VG8igidcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

        rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
        //convert to csp format
        var bytes = rsa.ExportCspBlob(false);
        var publicKey = Convert.ToBase64String(bytes);
        //

        RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);
        Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
               new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);

        JwtHeader head = new JwtHeader(signingCredentials);
        head.Add("kid", "lzo-firstpublickey");

        string sNewGuid = Guid.NewGuid().ToString("n");

        var claims = new[]
              {
                  new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
                  new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
                  new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
                  new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
                  new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
                  new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
              };

        JwtPayload payload = new JwtPayload(claims);
        JwtSecurityToken jwt = new JwtSecurityToken(head, payload);
        jwt.SigningKey = _signingKey;
        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
        return encodedJwt;
    }

    private static byte[] FromBase64Url(string base64Url)
    {
        string base64 = string.Empty;
        if (!string.IsNullOrEmpty(base64Url))
        {
            string padded = base64Url.Length % 4 == 0
                ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
            base64 = padded.Replace("_", "/")
                                    .Replace("-", "+");
        }
        return Convert.FromBase64String(base64);
    }

    private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
    {
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        System.IO.MemoryStream mem = new System.IO.MemoryStream(privkey);
        System.IO.BinaryReader binr = new System.IO.BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try
        {
            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();        //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();       //advance 2 bytes
            else
                return null;

            twobytes = binr.ReadUInt16();
            if (twobytes != 0x0102) //version number
                return null;
            bt = binr.ReadByte();
            if (bt != 0x00)
                return null;

            //------  all private key components are Integer sequences ----
            elems = GetIntegerSize(binr);
            MODULUS = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            E = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            D = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            P = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            Q = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DP = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DQ = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            IQ = binr.ReadBytes(elems);

            Console.WriteLine("showing components ..");
            if (verbose)
            {
                showBytes("\nModulus", MODULUS);
                showBytes("\nExponent", E);
                showBytes("\nD", D);
                showBytes("\nP", P);
                showBytes("\nQ", Q);
                showBytes("\nDP", DP);
                showBytes("\nDQ", DQ);
                showBytes("\nIQ", IQ);
            }

            // ------- create RSACryptoServiceProvider instance and initialize with public key -----
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAparams = new RSAParameters();
            RSAparams.Modulus = MODULUS;
            RSAparams.Exponent = E;
            RSAparams.D = D;
            RSAparams.P = P;
            RSAparams.Q = Q;
            RSAparams.DP = DP;
            RSAparams.DQ = DQ;
            RSAparams.InverseQ = IQ;
            RSA.ImportParameters(RSAparams);
            return RSA;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            binr.Close();
        }
    }

    private void showBytes(String info, byte[] data)
    {
        Console.WriteLine("{0}  [{1} bytes]", info, data.Length);
        for (int i = 1; i <= data.Length; i++)
        {
            Console.Write("{0:X2}  ", data[i - 1]);
            if (i % 16 == 0)
                Console.WriteLine();
        }
        Console.WriteLine("\n\n");
    }

    private int GetIntegerSize(System.IO.BinaryReader binr)
    {
        byte bt = 0;
        byte lowbyte = 0x00;
        byte highbyte = 0x00;
        int count = 0;
        bt = binr.ReadByte();
        if (bt != 0x02)     //expect integer
            return 0;
        bt = binr.ReadByte();

        if (bt == 0x81)
            count = binr.ReadByte();    // data size in next byte
        else
            if (bt == 0x82)
            {
                highbyte = binr.ReadByte(); // data size in next 2 bytes
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;     // we already have the data size
            }

        while (binr.ReadByte() == 0x00)
        {   //remove high order zeros in data
            count -= 1;
        }
        binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);     //last     ReadByte wasn't a removed zero, so back up a byte
        return count;
    }
}
</code>```

}

Body:
I tried with the below suggestion,it is working for  SecurityAlgorithms.HmacSha256Signature.

Suggested Code:

SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(symmetricKey), Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)

but it is not working for SecurityAlgorithms.RsaSha256Signature.

Microsoft.IdentityModel.Tokens.SigningCredentials SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature);

I got the below error.

DX10634: Unable to create the SignatureProvider.

SignatureAlgorithm: 'SHA256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey' is not supported

I need to convert JWT token for Sha256. kindly provide solution with sample code.

Please find my code:

       string _privateSecretKey = "MIIEogIBAAKCAQEAytYejMhaYjZwFgqP7WKh2bkf08=";

        Microsoft.IdentityModel.Tokens.SymmetricSecurityKey _signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.ASCII.GetBytes(_privateSecretKey));
        Microsoft.IdentityModel.Tokens.SigningCredentials SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256Signature);

        JwtHeader head = new JwtHeader();
        head.Add("kid", "firstpublickey");//TBD

        string sNewGuid = Guid.NewGuid().ToString("n");

        var claims = new[]
          {
              new Claim(JwtRegisteredClaimNames.Iss, oTokenPostData.ClientID),
            new Claim(JwtRegisteredClaimNames.Sub, oTokenPostData.ClientID),
            new Claim(JwtRegisteredClaimNames.Aud, oTokenPostData.tokenUri),
            new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
                new Claim(JwtRegisteredClaimNames.Exp, ((int)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture)),
                new Claim(JwtRegisteredClaimNames.Iat, ((int)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture))
          };

        JwtPayload payload = new JwtPayload(claims);

        JwtSecurityToken jwt = new JwtSecurityToken(head, payload);

        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

Body:
JWT is getting converted using the below code.

using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ConsoleApplication2
{

private class JWT
{
    private bool verbose = false;
    public  string GenerateJWT()
    {
        DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        // Provide proper private key
        string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN33XusJhrz9HXmIrdyX2F41xJHG4uj5/2Dzv3xjYYvqxexm3X3X5TOf3WoM1VNloJ7UnbqUJOiEjgK8sRdJntgfomO4U8s67cpysk0h9rc0He4xRspEjOapFfDg+VG8igidcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

        rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
        //convert to csp format
        var bytes = rsa.ExportCspBlob(false);
        var publicKey = Convert.ToBase64String(bytes);
        //

        RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);
        Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
               new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);

        JwtHeader head = new JwtHeader(signingCredentials);
        head.Add("kid", "lzo-firstpublickey");

        string sNewGuid = Guid.NewGuid().ToString("n");

        var claims = new[]
              {
                  new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
                  new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
                  new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
                  new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
                  new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
                  new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
              };

        JwtPayload payload = new JwtPayload(claims);
        JwtSecurityToken jwt = new JwtSecurityToken(head, payload);
        jwt.SigningKey = _signingKey;
        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
        return encodedJwt;
    }

    private static byte[] FromBase64Url(string base64Url)
    {
        string base64 = string.Empty;
        if (!string.IsNullOrEmpty(base64Url))
        {
            string padded = base64Url.Length % 4 == 0
                ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
            base64 = padded.Replace("_", "/")
                                    .Replace("-", "+");
        }
        return Convert.FromBase64String(base64);
    }

    private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
    {
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        System.IO.MemoryStream mem = new System.IO.MemoryStream(privkey);
        System.IO.BinaryReader binr = new System.IO.BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try
        {
            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();        //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();       //advance 2 bytes
            else
                return null;

            twobytes = binr.ReadUInt16();
            if (twobytes != 0x0102) //version number
                return null;
            bt = binr.ReadByte();
            if (bt != 0x00)
                return null;

            //------  all private key components are Integer sequences ----
            elems = GetIntegerSize(binr);
            MODULUS = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            E = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            D = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            P = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            Q = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DP = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DQ = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            IQ = binr.ReadBytes(elems);

            Console.WriteLine("showing components ..");
            if (verbose)
            {
                showBytes("\nModulus", MODULUS);
                showBytes("\nExponent", E);
                showBytes("\nD", D);
                showBytes("\nP", P);
                showBytes("\nQ", Q);
                showBytes("\nDP", DP);
                showBytes("\nDQ", DQ);
                showBytes("\nIQ", IQ);
            }

            // ------- create RSACryptoServiceProvider instance and initialize with public key -----
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAparams = new RSAParameters();
            RSAparams.Modulus = MODULUS;
            RSAparams.Exponent = E;
            RSAparams.D = D;
            RSAparams.P = P;
            RSAparams.Q = Q;
            RSAparams.DP = DP;
            RSAparams.DQ = DQ;
            RSAparams.InverseQ = IQ;
            RSA.ImportParameters(RSAparams);
            return RSA;
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            binr.Close();
        }
    }

    private void showBytes(String info, byte[] data)
    {
        Console.WriteLine("{0}  [{1} bytes]", info, data.Length);
        for (int i = 1; i <= data.Length; i++)
        {
            Console.Write("{0:X2}  ", data[i - 1]);
            if (i % 16 == 0)
                Console.WriteLine();
        }
        Console.WriteLine("\n\n");
    }

    private int GetIntegerSize(System.IO.BinaryReader binr)
    {
        byte bt = 0;
        byte lowbyte = 0x00;
        byte highbyte = 0x00;
        int count = 0;
        bt = binr.ReadByte();
        if (bt != 0x02)     //expect integer
            return 0;
        bt = binr.ReadByte();

        if (bt == 0x81)
            count = binr.ReadByte();    // data size in next byte
        else
            if (bt == 0x82)
            {
                highbyte = binr.ReadByte(); // data size in next 2 bytes
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;     // we already have the data size
            }

        while (binr.ReadByte() == 0x00)
        {   //remove high order zeros in data
            count -= 1;
        }
        binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);     //last     ReadByte wasn't a removed zero, so back up a byte
        return count;
    }
}

}


来源: stackexchange

问:
How can i use a thousand separator in SQL Server?
```<code> SELECT count(id) FROM table a
</code>```

it gives me a number lets say 36136, how can i make thousand separator on top?

答:
Try (MSSQL)

```<code>SELECT REPLACE(REPLACE(
               CONVERT(VARCHAR,CONVERT(MONEY, COUNT(ID)),1)
        ,'.00','') ,',','''')
    FROM TABLE A
</code>```

Example

```<code>SELECT REPLACE(REPLACE(CONVERT(VARCHAR,CONVERT(MONEY, 1000),1),'.00','') ,',','''') X
</code>```

Output

```<code>X
----
1'000
</code>```

ContentLicense: CC BY-SA 3.0

Body:
 SELECT count(id) FROM table a

it gives me a number lets say 36136, how can i make thousand separator on top?

Body:
Try (MSSQL)

SELECT REPLACE(REPLACE(
               CONVERT(VARCHAR,CONVERT(MONEY, COUNT(ID)),1)
        ,'.00','') ,',','''')
    FROM TABLE A

Example

SELECT REPLACE(REPLACE(CONVERT(VARCHAR,CONVERT(MONEY, 1000),1),'.00','') ,',','''') X

Output

X
----
1'000


问:
Execute code in Django after response has been sent to the client
In my Django application I want to keep track of whether a response has been sent to the client successfully. I am well aware that there is no "watertight" way in a connectionless protocol like HTTP to ensure the client has received (and displayed) a response, so this will not be mission-critical functionality, but still I want to do this at the latest possible time. The response will not be HTML so any callbacks from the client (using Javascript or IMG tags etc.) are not possible.

The "latest" hook I can find would be adding a custom middleware implementing process_response at the first position of the middleware list, but to my understanding this is executed before the actual response is constructed and sent to the client. Are there any hooks/events in Django to execute code after the response has been sent successfully?

答:
I suppose when talking about middleware you are thinking about the middleware's process_request method, but there's also a process_response method that is called when the HttpResponse object is returned. I guess that will be the latest moment where you can find a hook that you can use.

Furthermore there's also a request_finished signal being fired.

ContentLicense: CC BY-SA 2.5


问:
gSheets horizontal with ARRAYFORMULA(SPLIT(...))
I'm creating a dashboard in gSheets to report key metrics for A/B tests on my company's billing page. The data auto-pulls from GA via gSheets' addon, and I've decided to dynamically populate the list of tests on the dashboard by using the UNIQUE(...) function. This, in turn, allows metrics matching each test (by name) to pull into the dashboard from the data dump.

Case: Because it's a dynamic list of tests that will change over time (there are currently 4, there may be 3 next time, or 7, who knows), I've decided to set up the names horizontally with the metrics vertical, like so:

```<code> New Users
                 | Test A | Test B | Test C | Test D |
 ----------------|--------|--------|--------|--------|
 Sessions        |
 Conversions     |
 Conversion Rate |

 Return Users
                 | Test A | Test B | Test C | Test D |
 ----------------|--------|--------|--------|--------|
 Sessions        |
 Conversions     |
 Conversion Rate |
</code>```

The example above is how I'd like it to look. In reality, the test names are extremely long due to identifying keywords, which help in GA but make it impossible to tell which is which in the spreadsheet dashboard. The test name is at the end.

Here's what I'm working with:
Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum): devicesImage

I want to split names on " ", preferably with an arrayformula so it populates horizontally for however many columns have a test. Then I can hide the row with the full name (allowing it to still be used for reference), while displaying the shorter name so people can tell what the test is.

Problem: I'm stuck trying to make the arrayformula go horizontally,

Current approach: =ARRAYFORMULA(TRANSPOSE(SPLIT(A13:13," ")))

Current approach output:

```<code>                 | coversImage | blank | blank | blank
 ----------------|-------------|-------|-------|-------|
 Sessions        |
 Conversions     |
 Conversion Rate |
</code>```

Desired output:

```<code>                 | coversImage | devicesImage | lifestyleImage | stringCentered |
 ----------------|-------------|--------------|----------------|----------------|
 Sessions        |
 Conversions     |
 Conversion Rate |
</code>```

答:
I have to assume your test names are initially this:

Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum):
  devicesImage Optimizely_AB_Test_Alternate_Billing_(Prod)(Property)
  (AccountNum): coversImage
  Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum):
  lifestyleImage Optimizely_AB_Test_Alternate_Billing_(Prod)(Property)
  (AccountNum): stringCentered

In that case we can extract with regular expressions everything atfer ": ":

```<code>=ArrayFormula(TRANSPOSE(REGEXEXTRACT(E26:E29, "(?:\: )(\w*)$")))
</code>```

Body:
I'm creating a dashboard in gSheets to report key metrics for A/B tests on my company's billing page. The data auto-pulls from GA via gSheets' addon, and I've decided to dynamically populate the list of tests on the dashboard by using the UNIQUE(...) function. This, in turn, allows metrics matching each test (by name) to pull into the dashboard from the data dump.

Case: Because it's a dynamic list of tests that will change over time (there are currently 4, there may be 3 next time, or 7, who knows), I've decided to set up the names horizontally with the metrics vertical, like so:

 New Users
                 | Test A | Test B | Test C | Test D |
 ----------------|--------|--------|--------|--------|
 Sessions        |
 Conversions     |
 Conversion Rate |

 Return Users
                 | Test A | Test B | Test C | Test D |
 ----------------|--------|--------|--------|--------|
 Sessions        |
 Conversions     |
 Conversion Rate |

The example above is how I'd like it to look. In reality, the test names are extremely long due to identifying keywords, which help in GA but make it impossible to tell which is which in the spreadsheet dashboard. The test name is at the end.

Here's what I'm working with:
Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum): devicesImage

I want to split names on " ", preferably with an arrayformula so it populates horizontally for however many columns have a test. Then I can hide the row with the full name (allowing it to still be used for reference), while displaying the shorter name so people can tell what the test is.

Problem: I'm stuck trying to make the arrayformula go horizontally,

Current approach: =ARRAYFORMULA(TRANSPOSE(SPLIT(A13:13," ")))

Current approach output:

                 | coversImage | blank | blank | blank
 ----------------|-------------|-------|-------|-------|
 Sessions        |
 Conversions     |
 Conversion Rate |

Desired output:

                 | coversImage | devicesImage | lifestyleImage | stringCentered |
 ----------------|-------------|--------------|----------------|----------------|
 Sessions        |
 Conversions     |
 Conversion Rate |

Body:
I have to assume your test names are initially this:

Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum):
  devicesImage Optimizely_AB_Test_Alternate_Billing_(Prod)(Property)
  (AccountNum): coversImage
  Optimizely_AB_Test_Alternate_Billing_(Prod)(Property) (AccountNum):
  lifestyleImage Optimizely_AB_Test_Alternate_Billing_(Prod)(Property)
  (AccountNum): stringCentered

In that case we can extract with regular expressions everything atfer ": ":

=ArrayFormula(TRANSPOSE(REGEXEXTRACT(E26:E29, "(?:\: )(\w*)$")))


问:
MVC: Keep alive or make the initial load super fast
The goal is that I want my overall website response time to be instantaneous.

The problem is that I do no have IIS access, my website is hosted using external service and I have no control to the IIS panel.

My current approach now is having a scheduled code that keeps my website alive. The problem with this only approach is the hosting service has an algorithm to shutdown all their hosted website like every some hours.

This is why I need to implement another approach which to warm up / pre-load the website each time it runs.

How to do this when there is no access to the IIS panel?

答:
There are a number of things you can do but a real simple solution is to use a website monitoring site something like statuscake or uptime robot there are a large number of them out there. You set them up call a page or pages on your website at set intervals to ensure it is still up this has the added bonus of keeping the site warm.

I would also precompile your mvc app if you arent already doing that.

HTH


问:
replace string php with html mailto tag
I have an string email address that comes from user input($option['footer_email']) and I want to replace it with mailto html tag. So far I tried couple of approaches and tried to use str_replace() as followed, but it didn't work out.

```<code>$email = array($option['footer_email']);
$replace = array('<a href="mailto:$option['footer_email']">$option['footer_email']</a>');
echo str_replace($email, $replace, $option['footer_email']);
</code>```

and it returns syntax error, unexpected 'footer_email' (T_STRING), expecting ')'

I also tried to use preg_replace() but that one didn't help. How can I fix this issue?

答:
Try this

```<code>$email = $option['footer_email'];
$replace = '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';
echo str_replace($email, $replace, $option['footer_email']);
</code>```

Basically your variable is not read as it is part of the string.

Why do you have to do the str_replace? Why not just do this?

```<code>echo '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';
</code>```

Title: replace string php with html mailto tag

Body:
I have an string email address that comes from user input($option['footer_email']) and I want to replace it with mailto html tag. So far I tried couple of approaches and tried to use str_replace() as followed, but it didn't work out.

$email = array($option['footer_email']);
$replace = array('$option['footer_email']');
echo str_replace($email, $replace, $option['footer_email']);

and it returns syntax error, unexpected 'footer_email' (T_STRING), expecting ')'

I also tried to use preg_replace() but that one didn't help. How can I fix this issue?

Body:
Try this

$email = $option['footer_email'];
$replace = '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';
echo str_replace($email, $replace, $option['footer_email']);

Basically your variable is not read as it is part of the string.

Why do you have to do the str_replace? Why not just do this?

echo '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';


问:
How to code HTML for fast rendering in IE
Layout and rendering of HTML content can take some time if the HTML is complex enough. I couldn't find a set best practices for how to code HTML in order to help the layout engine (specially in IE) so that page redraws are faster. Does such a set of best practices exist?

My current specific problem is that my tabular data (in a table element) that causes drawing the page too slow, and making DOM updates (hover effects) and animations very sluggish. I'm sure it's not JavaScript performance. I've checked the page using dynaTrace AJAX. The CPU becomes too busy when I hover my mouse over elements, but there's no JS running. And the hover is realized by adding/removing a class to TR elements. I've also tried YSlow in Firefox, it doesn't show any particular issue. It's not network-related either. (Firefox lays out the page faster, but it's not because of its JS engine being faster)

Is there a tool to profile drawing and layout in IE, so that I can find out where the problem is coming from? And what can cause the drawing to be so slow, so that I can avoid them in HTML code?

答:
Internet Explorer is known to be slow with rendering large HTML tables.

Refer to this nice article on MSDN: Building High Performance HTML Pages and specifically to the section about tables:

Set the table-layout CSS attribute to fixed on the table.

Explicitly define col objects for each column.

Set the WIDTH attribute on each col.

Then there is also a nice blog post on the ieblog about table rendering: Table Rendering.

It comes down to this: Try to make the content within the tables less complex, i.e. set fixed width and don't have too much dynamic rendering action going on. IE first loads the content and then has to calculate the correct width for the contents == slow.


问:
What is the difference between ${pageContext.request.contextPath} and request.getContextPath()
So I have a .jsp that displays the header part of my web application.  This is a very standard looking page.  I have a bar at the top with things like Login, Register, Contact Us, etc...   And below that we have a horizontal navigation bar.

This is a standard Spring web application with a maven build.  It produces a file, web.war, that we deploy to tomcat.  on dev, this works fine.

We are testing production, and want this war to be the root,  so we rename the war to ROOT.war and restart.  everything fine.

Now sometimes,  we get the navigation section from a Content Management System. We set the text as a variable and display that.  No obviously we can't use ${pageContext.request.contextPath} as that wont get parsed this way,  so before we display the text we do this in the jsp

```<code><%  navcopy = navcopy.replace("${pageContext.request.contextPath}", request.getContextPath()); %>
</code>```

Now this is adding the /web to the URL.  Now this is baffling to me as registration link in the jsp works:

```<code> <a id="home-left-menu-item" href="${pageContext.request.contextPath}/register.html">Register Now!</a>
</code>```

So hoe does ${pageContext.request.contextPath} parsed in the jsp return the correct root but the call request.getContextPath() returns "/web"

Aren't they essentially the same call to the same object to the same method?

Any insight would be appreciated.

答:
${pageContext.request.contextPath} : Returns the portion of the request URI that indicates the context of the request.
In fact, it is identical to request.getContextPath(), since ${pageContext.request} refers to the HttpServletRequest of the current request.

For example:

```<code>http://localhost:80/myProjectName/path/servlet
</code>```

${pageContext.request.contextPath} returns /myProjectName

request.getServletPath() Returns the part of this request's URL that calls the servlet, e.g. /path/servlet

${pageContext.request.servletPath} returns /path/servlet

For this code try this:

```<code><a id="home-left-menu-item" href="<%=request.getContextPath()%>/register.html">Register Now!</a>
</code>```

Body:
So I have a .jsp that displays the header part of my web application.  This is a very standard looking page.  I have a bar at the top with things like Login, Register, Contact Us, etc...   And below that we have a horizontal navigation bar.

This is a standard Spring web application with a maven build.  It produces a file, web.war, that we deploy to tomcat.  on dev, this works fine.

We are testing production, and want this war to be the root,  so we rename the war to ROOT.war and restart.  everything fine.

Now sometimes,  we get the navigation section from a Content Management System. We set the text as a variable and display that.  No obviously we can't use ${pageContext.request.contextPath} as that wont get parsed this way,  so before we display the text we do this in the jsp

<%  navcopy = navcopy.replace("${pageContext.request.contextPath}", request.getContextPath()); %>

Now this is adding the /web to the URL.  Now this is baffling to me as registration link in the jsp works:

 Register Now!

So hoe does ${pageContext.request.contextPath} parsed in the jsp return the correct root but the call request.getContextPath() returns "/web"

Aren't they essentially the same call to the same object to the same method?

Any insight would be appreciated.

Body:
${pageContext.request.contextPath} : Returns the portion of the request URI that indicates the context of the request.
In fact, it is identical to request.getContextPath(), since ${pageContext.request} refers to the HttpServletRequest of the current request.

For example:

http://localhost:80/myProjectName/path/servlet

${pageContext.request.contextPath} returns /myProjectName

request.getServletPath() Returns the part of this request's URL that calls the servlet, e.g. /path/servlet

${pageContext.request.servletPath} returns /path/servlet

For this code try this:

<a id="home-left-menu-item" href="<%=request.getContextPath()%>/register.html">Register Now!</a>


问:
MongoDB behavior on simple instance fail
I've seen that the standard MongoDB service on Swisscom Application Cloud is not in HA, so which level of service we should expect in case of an instance failure:

data loss?

automatic recover?

how much downtime should I expect?

from the application point of view it would be enough to trigger automatic reconnection?

答:
For the public offering Swisscom does not provide any guarantees concerning SLAs. That is including uptime. In case of the failure that is is within the responsibility of Swisscom, they are able detect the failure and start the recovery procedure in reasonable time.  Swisscom strongly recommends using the HA services.
I suggest reading through the terms of Swisscom Application Cloud:
http://developer.swisscom.com/terms/

According to my experience the services restart quite fast, so automatic reconnect should be sufficient.

Generally the MongoDB Docs answer a lot of your questions:
If a single instance MongoDB service fails, it will automatically recover all information stored on the disk as long as no corruption of the data happened.
Have a look at:
https://docs.mongodb.com/manual/core/journaling/

I also strongly suggest you perform regular backups trough the Application Clouds Portal. So In case of disk corruption you can restore your data.

TL:DR

The service will restart on a crash.

Restart time varies as it heavily depends on why and how it was triggered. Generally it takes longer if MongoDB has to restore data and reapply the journal.

Always enable automatic reconnect for your database backend.

Additionally: regularly backup your database.

ContentLicense: CC BY-SA 4.0


问:
Algorithm to create non-overlapping POI icons on a map
I want to create various-sized icons on a map representing Points of Interest (POIs). When there is ample space, larger icons should be used. In more crowded areas, smaller icons are used.

For example:

This is from Sygic Travel. The density is maintained at various zoom levels. I assume there is some kind of weighting given to prominent POIs to make them appear bigger at various zoom levels.

What I've explored so far includes:

Binning by grid poisition. This method divides the map into grid squares and counts how many POIs occur on each square. If there's only one POI on a square it can appear as the largest icon. If two or more appear they should be smaller. This method uses the center of POIs so when two POIs occur on adjoining corners they still overlap.

Spreading icons apart. This method simply pushes POIs away from each other when they are closer than a certain threshold. The problem is they can be pushed into other POIs that then overlap. It is also less accurate because the POI positions on the map are not preserved.

Now I'm thinking about exploring some kind of collision detection like those in physics engines. It would prevent overlap but I'm not sure how it could achieve the requirement of various-sized icons. Another technique might be multi-pass binning with detection of grid space overlap.

Is there an algorithm I'm missing here? Or are there any existing solutions to this problem that I can refer to?

答:
The algorithm is quite simple:

The map area is defined by some boundary usually using latitude and longitude degrees (for example south:51.482238, west: -0.18462181, north: 51.529571733, east: -0.058450698) Also the points you want to draw have some latitude and longitude coordinates, which are within the boundary.

You can think of map as pixel canvas for example 1200x800 pixels (the size is usually defined by size of a map in browser)

Choose one corner of the map as starting coordinate [0,0] (for example [south, west]) and transform latitude, longitude coordinates of points to canvas pixels coordinates.

Then we just order points by some priority and put them one by one on the map. We know size of the marker we want to draw and also markers that have already been drawn, so on the pixel canvas it easy to detect possible collision. The detected collision means than place was taken by point with higher priority. If the point does not fit on map as huge marker, we try to place it as smaller one and so on...


问:
Observable pattern in Remote EJB
I have 2 applications. One 'main' and a second one with a Remote EJB. The first application calls the Remote EJB in the second one.

Now I want to implement the Observable pattern. But it doesn't seem to work cross-application.

So I want my Observable inside the second application, and my Observers in the first. When I try it, it doesn't seem to work. It only works if I make the Observable and Observers in the same application.

I got another solution, but I think it's dirty. I could use a MDB inside the second application, and publish a message on a Topic, and then consume those messages inside the first application. But then again, that seems kinda dirty.

I'm using JEE7 on a Payara 4.1.1.171 server.

Edit:
Because I figured out that triggered Events don't exit an EAR file, I'm now using the MDB method. But that still does not work.
More information, this is the package structure of the EAR file.

```<code>my-application.ear
+--- common-ejb.jar (EJB)
|       +--- MessageDrivenBean.java (Triggers the event)
+--- my-application.jar (EJB)
+--- my-application.war (WEB)
        +--- WEB-INF
                +--- lib
                |       +--- common-web.jar (Resources WEB jar)
                |           +--- SessionBean1 to receive the events
                +--- classes
                        +--- SessionBean2 to receive the events
</code>```

As you can see there are 2 session beans to receive the events, but none of the 2 actually receive them.

答:
With Payara Server version 171 and Hazelcast enabled, you can fire CDI events and observe them in another application. See the documentation about remote CDI events

If both applications are deployed on the same Payara Server instance, you would fire an event of type MyEvent.class like this:

```<code>@Inject
@Outbound(loopBack = true) // loopBack true is required if the observing application is deployed on the same Payara Server instance
Event<MyEvent> event;

...
event.fire(new MyEvent());
</code>```

And the other application would observe these events with:

```<code>public void receiveEvent(@Observes @Inbound MyEvent event) {
}
</code>```

If the observing application is running on another Payara Server instance in the same Hazelcast cluster, it would also receive the event. In that case, loopBack attribute is not required, but would do no harm either.

Remote CDI events are dispatched via embedded Hazelcast data grid, which will reliably deliver the events to all observing applications across the cluster. The observing application has to be running at the time when the event is fire - a similar behavior to broadcasting events via a JMS topic.

Title: Observable pattern in Remote EJB

Body:
I have 2 applications. One 'main' and a second one with a Remote EJB. The first application calls the Remote EJB in the second one.

Now I want to implement the Observable pattern. But it doesn't seem to work cross-application.

So I want my Observable inside the second application, and my Observers in the first. When I try it, it doesn't seem to work. It only works if I make the Observable and Observers in the same application.

I got another solution, but I think it's dirty. I could use a MDB inside the second application, and publish a message on a Topic, and then consume those messages inside the first application. But then again, that seems kinda dirty.

I'm using JEE7 on a Payara 4.1.1.171 server.

Edit:
Because I figured out that triggered Events don't exit an EAR file, I'm now using the MDB method. But that still does not work.
More information, this is the package structure of the EAR file.

my-application.ear
+--- common-ejb.jar (EJB)
|       +--- MessageDrivenBean.java (Triggers the event)
+--- my-application.jar (EJB)
+--- my-application.war (WEB)
        +--- WEB-INF
                +--- lib
                |       +--- common-web.jar (Resources WEB jar)
                |           +--- SessionBean1 to receive the events
                +--- classes
                        +--- SessionBean2 to receive the events

As you can see there are 2 session beans to receive the events, but none of the 2 actually receive them.

Body:
With Payara Server version 171 and Hazelcast enabled, you can fire CDI events and observe them in another application. See the documentation about remote CDI events

If both applications are deployed on the same Payara Server instance, you would fire an event of type MyEvent.class like this:

@Inject
@Outbound(loopBack = true) // loopBack true is required if the observing application is deployed on the same Payara Server instance
Event<MyEvent> event;

...
event.fire(new MyEvent());

And the other application would observe these events with:

public void receiveEvent(@Observes @Inbound MyEvent event) {
}

If the observing application is running on another Payara Server instance in the same Hazelcast cluster, it would also receive the event. In that case, loopBack attribute is not required, but would do no harm either.

Remote CDI events are dispatched via embedded Hazelcast data grid, which will reliably deliver the events to all observing applications across the cluster. The observing application has to be running at the time when the event is fire - a similar behavior to broadcasting events via a JMS topic.


问:
Boolean != false
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?

答:
If someBool is Boolean

```<code>if (someBull != null && someBull) {
  //Yeah, true.
}
</code>```

Since Boolean can be null make sure you avoid NullPointerException by checking for not null.

Title: Boolean != false

Body:
If someBool is Boolean

if (someBull != null && someBull) {
  //Yeah, true.
}

Since Boolean can be null make sure you avoid NullPointerException by checking for not null.


问:
List Comprehension that has more elements than array
I am trying to create an array with list comprehensions like:

```<code>array = [(x,y)|(x,y,z)<-oldArray, z == 10]
</code>```

Let's say that oldArray is a previously made array that has 3 Int values, but the new array I want to make only needs the first two, but whether or not they get added depends on a condition of the third.

I can't tell if this is working correctly or not though.

答:
The sample code you've written solves the problem you've described.
You filter out elements where z is not 10, and then take only 2 first parts of a tuple to build a new array.</p>

Body:
I am trying to create an array with list comprehensions like:

array = [(x,y)|(x,y,z)<-oldArray, z == 10]

Let's say that oldArray is a previously made array that has 3 Int values, but the new array I want to make only needs the first two, but whether or not they get added depends on a condition of the third.

I can't tell if this is working correctly or not though.


问:
bootstrap PowerMock with @Rule ,but failed
```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({ SessionUtil.class})
public class FundControllerTest {
     XXXXXXXXXXXXXXX.......
}
</code>```

Run Junit as above, it works well.

But when I try to run Junit as below, it failed. Because I need use Eclemma to

coverage my test, so I switch to use @Rule to bootstrap PowerMock, but failed. Please help.

```<code>@PrepareForTest({ SessionUtil.class})
public class FundControllerTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    /*
    static{
        PowerMockAgent.initializeIfNeeded();
    }
    */
   XXXXXXXXXXXXXXXXXXXXXXXXX..........
}
</code>```

```<code>java.lang.RuntimeException: com.sun.tools.attach.AttachNotSupportedException: Unable to enqueue operation: the target VM does not support attach mechanism
    at org.powermock.modules.agent.AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(AgentLoader.java:122)
    at org.powermock.modules.agent.AgentLoader.loadAgent(AgentLoader.java:81)
    at org.powermock.modules.agent.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:40)
    at org.powermock.modules.agent.PowerMockAgent.initializeIfNeeded(PowerMockAgent.java:91)
    at com.hsbc.mf.frtend.twfunds.controller.FundControllerTest.<clinit>(FundControllerTest.java:53)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:199)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:56)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:527)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.sun.tools.attach.AttachNotSupportedException: Unable to enqueue operation: the target VM does not support attach mechanism
    at sun.tools.attach.WindowsVirtualMachine.<init>(WindowsVirtualMachine.java:64)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:56)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:527)
    at org.powermock.reflect.internal.WhiteboxImpl.createInstance(WhiteboxImpl.java:1455)
    at org.powermock.reflect.internal.WhiteboxImpl.invokeConstructor(WhiteboxImpl.java:1303)
    at org.powermock.reflect.Whitebox.invokeConstructor(Whitebox.java:497)
    at org.powermock.modules.agent.AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(AgentLoader.java:120)
    ... 28 more
</code>```

答:
When you find a snake in your bed, does it matter whether it crawled through the open window; or came through the front door?

In other words: in order to allow for mocking static code; PowerMock needs to manipulate the byte code of that production class SessionUtils. And EclEmma also relies on byte code manipulation.

Perhaps, at some future point, the implementations of both frameworks will work together (but the corresponding bug is almost two years old; and there isn't much activity around it; so don't hold your breath on it).

But today, PowerMock and EclEmma do not work together. End of story.

And it doesn't matter to "pull in" PowerMock using its own runner; or using the "rule approach". Because as said: the problem is that you found that snake in your bed; and not "how did it get there".

Now you simply have to decide what is more important to you: to keep your production code as is (and its design, that forces you to mock static calls with PowerMock); or to acquire coverage information.

My personal two cents: that is one of the reasons why my team gave up on PowerMock completely. Instead, we focus on writing code that is testable without mocking static/new calls; and guess what: that works fine. And our production code is better than before.

Body:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ SessionUtil.class})
public class FundControllerTest {
     XXXXXXXXXXXXXXX.......
}

Run Junit as above, it works well.

But when I try to run Junit as below, it failed. Because I need use Eclemma to

coverage my test, so I switch to use @Rule to bootstrap PowerMock, but failed. Please help.

@PrepareForTest({ SessionUtil.class})
public class FundControllerTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    /*
    static{
        PowerMockAgent.initializeIfNeeded();
    }
    */
   XXXXXXXXXXXXXXXXXXXXXXXXX..........
}

java.lang.RuntimeException: com.sun.tools.attach.AttachNotSupportedException: Unable to enqueue operation: the target VM does not support attach mechanism
    at org.powermock.modules.agent.AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(AgentLoader.java:122)
    at org.powermock.modules.agent.AgentLoader.loadAgent(AgentLoader.java:81)
    at org.powermock.modules.agent.AgentInitialization.initializeAccordingToJDKVersion(AgentInitialization.java:40)
    at org.powermock.modules.agent.PowerMockAgent.initializeIfNeeded(PowerMockAgent.java:91)
    at com.hsbc.mf.frtend.twfunds.controller.FundControllerTest.<clinit>(FundControllerTest.java:53)
    at java.lang.J9VMInternals.initializeImpl(Native Method)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:199)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:56)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:527)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.sun.tools.attach.AttachNotSupportedException: Unable to enqueue operation: the target VM does not support attach mechanism
    at sun.tools.attach.WindowsVirtualMachine.<init>(WindowsVirtualMachine.java:64)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:56)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:527)
    at org.powermock.reflect.internal.WhiteboxImpl.createInstance(WhiteboxImpl.java:1455)
    at org.powermock.reflect.internal.WhiteboxImpl.invokeConstructor(WhiteboxImpl.java:1303)
    at org.powermock.reflect.Whitebox.invokeConstructor(Whitebox.java:497)
    at org.powermock.modules.agent.AgentLoader.getVirtualMachineImplementationFromEmbeddedOnes(AgentLoader.java:120)
    ... 28 more


问:
Playgrounds broken in Xcode 8.3
Since I started working Xcode 8.2 (and 8.3 lately), playgrounds are completely broken for me.

When opening a playground I see the message "Failed to launch process. Error returned in reply: Connection Interrupted"

Complete re-installation of Xcode or removing / re-creating /private/tmp folder (as suggested by some other posts) did not help.

Did someone encounter a similar problem? Are there other known work-arounds?
(http://www.openradar.me/31296836)

Here is some sample output from CoreSimulator.log

```<code>Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error from finding pasteboard support port, Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error from finding pasteboard support port, Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
</code>```

答: (Unfortunately) I solved the problem by clean installing macOS (which is not the proper way of solving it, of course, but I needed to get playgrounds to work ASAP).</p>

Title: Playgrounds broken in Xcode 8.3

Body:
Since I started working Xcode 8.2 (and 8.3 lately), playgrounds are completely broken for me.

When opening a playground I see the message "Failed to launch process. Error returned in reply: Connection Interrupted"

Complete re-installation of Xcode or removing / re-creating /private/tmp folder (as suggested by some other posts) did not help.

Did someone encounter a similar problem? Are there other known work-arounds?
(http://www.openradar.me/31296836)

Here is some sample output from CoreSimulator.log

Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error from finding pasteboard support port, Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error from finding pasteboard support port, Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}


问:
Using LINQ to return average of distinct values
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

```<code>ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...
</code>```

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

```<code>int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();
</code>```

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

```<code>string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();
</code>```

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

答:
Here's the problem reproduced and solved, only using linq 1-liners:</p>
```<code>using System;
using System.Linq;

namespace StackOverflow_StatisticsLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var reports = new int[][]
            {
                new int[] {80424, 9, 1, 7},
                new int[] {80424, 9, 2, 3},
                new int[] {80424, 9, 2, 2},
                new int[] {80423, 5, 1, 5},
                new int[] {80425, 4, 1, 5},
                new int[] {80423, 7, 1, 4},
                new int[] {80541, 7, 1, 5}
            };

            var reportsTat5Plus = (
                    from int[] r in reports
                    where r[1] > 5
                    orderby r[1] descending
                    select r)
                .GroupBy(r => r[0])
                .Select(r => r.First()); // ensure ids are distinct

            var average = reportsTat5Plus.Select(r => r[1]).Average();

            var mode = reportsTat5Plus.GroupBy(v => v)
                .OrderByDescending(g => g.Count())
                .First()
                .Select(r => r[1])
                .First();

            var median = reportsTat5Plus.Count() % 2 == 1
                ? reportsTat5Plus.Skip(reportsTat5Plus.Count() / 2 + 1).Select(r => r[1]).First()
                : reportsTat5Plus.Skip(reportsTat5Plus.Count() / 2 - 1).Take(2).Select(r => r[1]).Average();

            Console.WriteLine($"Average: {average}");
            Console.WriteLine($"mode: {mode}");
            Console.WriteLine($"median: {median}");
            Console.ReadKey();
        }
    }
}
</code>```

Body:
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

Body:
Here's the problem reproduced and solved, only using linq 1-liners:

using System;
using System.Linq;

namespace StackOverflow_StatisticsLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            var reports = new int[][]
            {
                new int[] {80424, 9, 1, 7},
                new int[] {80424, 9, 2, 3},
                new int[] {80424, 9, 2, 2},
                new int[] {80423, 5, 1, 5},
                new int[] {80425, 4, 1, 5},
                new int[] {80423, 7, 1, 4},
                new int[] {80541, 7, 1, 5}
            };

            var reportsTat5Plus = (
                    from int[] r in reports
                    where r[1] > 5
                    orderby r[1] descending
                    select r)
                .GroupBy(r => r[0])
                .Select(r => r.First()); // ensure ids are distinct

            var average = reportsTat5Plus.Select(r => r[1]).Average();

            var mode = reportsTat5Plus.GroupBy(v => v)
                .OrderByDescending(g => g.Count())
                .First()
                .Select(r => r[1])
                .First();

            var median = reportsTat5Plus.Count() % 2 == 1
                ? reportsTat5Plus.Skip(reportsTat5Plus.Count() / 2 + 1).Select(r => r[1]).First()
                : reportsTat5Plus.Skip(reportsTat5Plus.Count() / 2 - 1).Take(2).Select(r => r[1]).Average();

            Console.WriteLine($"Average: {average}");
            Console.WriteLine($"mode: {mode}");
            Console.WriteLine($"median: {median}");
            Console.ReadKey();
        }
    }
}


答: If its null then you'll get a NullPointerException</p>

Title: Boolean != false

Body:
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?


问:
Android DatePicker dialog, date should come from tomorrow
```<code> Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();
</code>```

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

```<code>int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}
</code>```

答:
```<code>   if (CustomVerticalCalendarView.isPreviousDateDisabled()) { // disable previous date disable flow
                int daysOfYear = listCalender.get(Calendar.DAY_OF_YEAR);
                int currentDate = today.get(Calendar.DAY_OF_YEAR);
                int listYear = listCalender.get(Calendar.YEAR);
                int currentYear = today.get(Calendar.YEAR);
                if (daysOfYear < currentDate || listYear < currentYear) {
                    checkBox.setEnabled(false);
    checkBox.setTextColor(ContextCompat.getColor(checkBox.getContext(), R.color.dark_gray));
                }
            }
</code>```

Hope this code helps you.

Body:
 Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}

Body:
   if (CustomVerticalCalendarView.isPreviousDateDisabled()) { // disable previous date disable flow
                int daysOfYear = listCalender.get(Calendar.DAY_OF_YEAR);
                int currentDate = today.get(Calendar.DAY_OF_YEAR);
                int listYear = listCalender.get(Calendar.YEAR);
                int currentYear = today.get(Calendar.YEAR);
                if (daysOfYear < currentDate || listYear < currentYear) {
                    checkBox.setEnabled(false);
    checkBox.setTextColor(ContextCompat.getColor(checkBox.getContext(), R.color.dark_gray));
                }
            }

Hope this code helps you.


问:
kivy textinput can't enter text
I'm currently working on a code where I plot a histogram with matplotlib. I'm using kivy to display. When I run my code I'm able to see the plot, so no problem there. I want to enter the bins manually by using a textbox and a update button. If I enter the text with python (like default: 50), the plot will update itself if I click on the button, but when I want to click on the textbox to enter text, nothing happens. I don't see my cursor in the textbox.

My code:

```<code>import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from kivy.app import App
import csv

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas, NavigationToolbar2Kivy
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from mpldatacursor import datacursor
from kivy.uix.floatlayout import FloatLayout
import matplotlib.pyplot as plt

with open("c:/Users/test.csv", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    data = []
    for column in reader:
        data.append(column[1])

    results = data
    results = [int(i) for i in results]

bins = 200
plt.hist(results, bins=bins, color=[0,0,1])
fig = plt.gcf()

ax = fig.add_subplot(111)
ax.hist(results, bins=200, edgecolor=[0,0,0,1], alpha = 0.8, color= 'b')
datacursor(ax)

canvas = fig.canvas

def callback(bins):

    global fig, results
    plt.clf()
    bins = int(bins)

    plt.hist(results,bins=bins, color=[0,0,1])
    ax = fig.add_subplot(111)
    ax.hist(results, bins=bins, edgecolor=[0, 0, 0, 1], alpha=0.8, color='b')
    datacursor(ax)

    canvas.draw()

class HistogramApp(App):

    def build(self):
        f = FloatLayout(orientation='vertical')
        g = GridLayout(size_hint=(1,0.05), cols=2)

        self.btn1 = Button(size_hint=(0.5,0.1), pos_hint={'x':0, 'y':0}, text="Update")
        self.textbox = TextInput(text="50", size_hint=(0.5,0.1), pos_hint={'x':0.5, 'y':0})

        self.btn1.bind(on_press=lambda x: callback(self.textbox.text))

        nav1 = NavigationToolbar2Kivy(canvas)

        f.add_widget(canvas)
        f.add_widget(nav1.actionbar)
        f.add_widget(g)
        g.add_widget(self.btn1)
        g.add_widget(self.textbox)

        return f

if __name__ == '__main__':
    HistogramApp().run()
</code>```

How can I solve this?

答:
I solved it myself. My mistake was by using a floatlayout. A better way is using two gridlayouts:</p>

```<code>import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from kivy.app import App
import csv

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas, NavigationToolbar2Kivy
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from mpldatacursor import datacursor
from kivy.uix.floatlayout import FloatLayout
import matplotlib.pyplot as plt

with open("c:/Users/test.csv", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    data = []
    for column in reader:
        data.append(column[1])

    results = data
    results = [int(i) for i in results]

bins = 200
plt.hist(results, bins=bins, color=[0,0,1])
fig = plt.gcf()

ax = fig.add_subplot(111)
ax.hist(results, bins=200, edgecolor=[0,0,0,1], alpha = 0.8, color= 'b')
datacursor(ax)

canvas = fig.canvas

def callback(bins):

    global fig, results
    plt.clf()
    bins = int(bins)

    plt.hist(results,bins=bins, color=[0,0,1])
    ax = fig.add_subplot(111)
    ax.hist(results, bins=bins, edgecolor=[0, 0, 0, 1], alpha=0.8, color='b')
    datacursor(ax)

    canvas.draw()

class HistogramApp(App):

    def build(self):
        g1 = GridLayout(orientation="horizontal", rows=3)
        g2 = GridLayout(orientation='horizontal', cols=2, size_hint=(0.05, 0.05))

        self.btn1 = Button(size_hint=(0.5, 0.1), pos_hint={'x': 0, 'y': 0}, text="Update")
        self.tekstvak = TextInput(text="50", size_hint=(0.5, 0.1), pos_hint={'x': 0.5, 'y': 0},cursor_color=[0, 0, 0, 1])

        self.btn1.bind(on_press=lambda x: callback(self.tekstvak.text))

        nav1 = NavigationToolbar2Kivy(canvas)

        g1.add_widget(nav1.actionbar)
        g1.add_widget(canvas)
        g2.add_widget(self.tekstvak)
        g2.add_widget(self.btn1)
        g1.add_widget(g2)

        return g1

if __name__ == '__main__':
    HistogramApp().run()
</code>```

Title: kivy textinput can't enter text

Body:
I'm currently working on a code where I plot a histogram with matplotlib. I'm using kivy to display. When I run my code I'm able to see the plot, so no problem there. I want to enter the bins manually by using a textbox and a update button. If I enter the text with python (like default: 50), the plot will update itself if I click on the button, but when I want to click on the textbox to enter text, nothing happens. I don't see my cursor in the textbox.

My code:

import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from kivy.app import App
import csv

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas, NavigationToolbar2Kivy
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from mpldatacursor import datacursor
from kivy.uix.floatlayout import FloatLayout
import matplotlib.pyplot as plt

with open("c:/Users/test.csv", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    data = []
    for column in reader:
        data.append(column[1])

    results = data
    results = [int(i) for i in results]

bins = 200
plt.hist(results, bins=bins, color=[0,0,1])
fig = plt.gcf()

ax = fig.add_subplot(111)
ax.hist(results, bins=200, edgecolor=[0,0,0,1], alpha = 0.8, color= 'b')
datacursor(ax)

canvas = fig.canvas

def callback(bins):

    global fig, results
    plt.clf()
    bins = int(bins)

    plt.hist(results,bins=bins, color=[0,0,1])
    ax = fig.add_subplot(111)
    ax.hist(results, bins=bins, edgecolor=[0, 0, 0, 1], alpha=0.8, color='b')
    datacursor(ax)

    canvas.draw()

class HistogramApp(App):

    def build(self):
        f = FloatLayout(orientation='vertical')
        g = GridLayout(size_hint=(1,0.05), cols=2)

        self.btn1 = Button(size_hint=(0.5,0.1), pos_hint={'x':0, 'y':0}, text="Update")
        self.textbox = TextInput(text="50", size_hint=(0.5,0.1), pos_hint={'x':0.5, 'y':0})

        self.btn1.bind(on_press=lambda x: callback(self.textbox.text))

        nav1 = NavigationToolbar2Kivy(canvas)

        f.add_widget(canvas)
        f.add_widget(nav1.actionbar)
        f.add_widget(g)
        g.add_widget(self.btn1)
        g.add_widget(self.textbox)

        return f

if __name__ == '__main__':
    HistogramApp().run()

How can I solve this?

Body:
I solved it myself. My mistake was by using a floatlayout. A better way is using two gridlayouts:

import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from kivy.app import App
import csv

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvas, NavigationToolbar2Kivy
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.gridlayout import GridLayout
from mpldatacursor import datacursor
from kivy.uix.floatlayout import FloatLayout
import matplotlib.pyplot as plt

with open("c:/Users/test.csv", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    data = []
    for column in reader:
        data.append(column[1])

    results = data
    results = [int(i) for i in results]

bins = 200
plt.hist(results, bins=bins, color=[0,0,1])
fig = plt.gcf()

ax = fig.add_subplot(111)
ax.hist(results, bins=200, edgecolor=[0,0,0,1], alpha = 0.8, color= 'b')
datacursor(ax)

canvas = fig.canvas

def callback(bins):

    global fig, results
    plt.clf()
    bins = int(bins)

    plt.hist(results,bins=bins, color=[0,0,1])
    ax = fig.add_subplot(111)
    ax.hist(results, bins=bins, edgecolor=[0, 0, 0, 1], alpha=0.8, color='b')
    datacursor(ax)

    canvas.draw()

class HistogramApp(App):

    def build(self):
        g1 = GridLayout(orientation="horizontal", rows=3)
        g2 = GridLayout(orientation='horizontal', cols=2, size_hint=(0.05, 0.05))

        self.btn1 = Button(size_hint=(0.5, 0.1), pos_hint={'x': 0, 'y': 0}, text="Update")
        self.tekstvak = TextInput(text="50", size_hint=(0.5, 0.1), pos_hint={'x': 0.5, 'y': 0},cursor_color=[0, 0, 0, 1])

        self.btn1.bind(on_press=lambda x: callback(self.tekstvak.text))

        nav1 = NavigationToolbar2Kivy(canvas)

        g1.add_widget(nav1.actionbar)
        g1.add_widget(canvas)
        g2.add_widget(self.tekstvak)
        g2.add_widget(self.btn1)
        g1.add_widget(g2)

        return g1

if __name__ == '__main__':
    HistogramApp().run()


问:
How to access WKWebView from didReceiveScriptMessage in iOS?
I am trying to achieve communication between web and native application by using WKWebView and Javascript interfaces.

I have a UITableView and each UITableViewCell contains a WKWebView.
I add each WKWebView a WKUserContentController and in those content controllers, I add a scriptMessageHandler.

However, in my didReceiveScriptMessage method, I don't know which WKWebView received the message from web.

How do I access the WKWebView from didReceiveScriptMessage method?

What is best way to determine which WKWebView received the message?

My Code:

```<code>func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {

        if message.name == "callbackHandler"{

            self.title = message.body as? String ?? "none"

        }
}
</code>```

WKWebView initialization

```<code>let config = WKWebViewConfiguration()
config.preferences.javaScriptEnabled = true
let contentController = WKUserContentController()
contentController.addScriptMessageHandler(self, name: "callbackHandler")
let webview = WKWebView(frame: CGRectZero, configuration: config)
</code>```

答: It appears WKScriptMessage have a property called webview.</p>

Body:
I am trying to achieve communication between web and native application by using WKWebView and Javascript interfaces.

I have a UITableView and each UITableViewCell contains a WKWebView.
I add each WKWebView a WKUserContentController and in those content controllers, I add a scriptMessageHandler.

However, in my didReceiveScriptMessage method, I don't know which WKWebView received the message from web.

How do I access the WKWebView from didReceiveScriptMessage method?

What is best way to determine which WKWebView received the message?

My Code:

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {

        if message.name == "callbackHandler"{

            self.title = message.body as? String ?? "none"

        }
}

WKWebView initialization

let config = WKWebViewConfiguration()
config.preferences.javaScriptEnabled = true
let contentController = WKUserContentController()
contentController.addScriptMessageHandler(self, name: "callbackHandler")
let webview = WKWebView(frame: CGRectZero, configuration: config)


问:
install new foundation email occurred error
I Want to install new Foundation Email framework as said in documentation.

Step one has No problem, But when I run foundation new --framework emails to fire up a blank Foundation for Emails project, This error has occurred:

ERROR: "foundation new" was called with arguments ["--framework",
  "emails"]

What's wrong?

答: You may also try just calling foundation new and select the email framework from there


答:
please check your Apostrophe opening and closing properly, here this is working example with a dummy value</p>

```<code>$option['footer_email'] = 'test@test.com';
$email = array($option['footer_email']);
$replace = array("<a href='mailto:$option[footer_email]'>$option[footer_email]</a>");
echo str_replace($email, $replace, $option['footer_email']);
</code>```

Title: replace string php with html mailto tag

Body:
I have an string email address that comes from user input($option['footer_email']) and I want to replace it with mailto html tag. So far I tried couple of approaches and tried to use str_replace() as followed, but it didn't work out.

$email = array($option['footer_email']);
$replace = array('$option['footer_email']');
echo str_replace($email, $replace, $option['footer_email']);

and it returns syntax error, unexpected 'footer_email' (T_STRING), expecting ')'

I also tried to use preg_replace() but that one didn't help. How can I fix this issue?

Body:
please check your Apostrophe opening and closing properly, here this is working example with a dummy value

$option['footer_email'] = 'test@test.com';
$email = array($option['footer_email']);
$replace = array("<a href='mailto:$option[footer_email]'>$option[footer_email]</a>");
echo str_replace($email, $replace, $option['footer_email']);


问:
get user's create events from facebook by user id using graph api
I've developed an mvc 5 based application. What i actually need if i am a normal facebook user and i created some events on my facebook after i login on my developed website then i want that events to display on my website.
I set the user_events permission and i get my access_token as my code is below.

```<code>var client = new Facebook.FacebookClient(accessToken);
dynamic facebookEvents = client.Get("/v2.8/me/events/created");
</code>```

but this is only returns owners created events if my appid and my app_secret then it's returning only my created events not returning other users events who's login with facebook on my website.

答:
If you want to return the events of other users, you have to authorize them with user_events too, and use THEIR user access token with that API call.

Make sure you know "Login Review" too, most permissions don´t just work for every user without approval: https://developers.facebook.com/docs/facebook-login/review

Body:
I've developed an mvc 5 based application. What i actually need if i am a normal facebook user and i created some events on my facebook after i login on my developed website then i want that events to display on my website.
I set the user_events permission and i get my access_token as my code is below.

var client = new Facebook.FacebookClient(accessToken);
dynamic facebookEvents = client.Get("/v2.8/me/events/created");

but this is only returns owners created events if my appid and my app_secret then it's returning only my created events not returning other users events who's login with facebook on my website.


问:
SqlCE update subquery
I wrote a query for Sql and now I am trying to make it work with SqlCE. The problem is that it seems the sub query is not supported by SqlCE. Using FROM in an UPDATE statement is also not allowed. I have done quite a bit of research and it seems that this might not be doable in SqlCE. I might have to do a SELECT and then UPDATE each record individually. Any ideas?</p>

```<code>UPDATE Items2 SET Name = (SELECT Name FROM Items WHERE Items.ID = Items2.ID)
</code>```

答: With SQL Server Compact you have to do it in two steps, first the SELCCT and then the UPDATEs</p>

Title: SqlCE update subquery

Body:
I wrote a query for Sql and now I am trying to make it work with SqlCE. The problem is that it seems the sub query is not supported by SqlCE. Using FROM in an UPDATE statement is also not allowed. I have done quite a bit of research and it seems that this might not be doable in SqlCE. I might have to do a SELECT and then UPDATE each record individually. Any ideas?

UPDATE Items2 SET Name = (SELECT Name FROM Items WHERE Items.ID = Items2.ID)


问:
Calling (helper) function in redux
I'm using react-native-router-flux with react-redux and I think that I should ask this question here, correct me if I'm wrong.

I have ActivityModal Container which I call to show up whenever there is an API call or similar thing where I want to show that modal. Currently I'm calling it like this:

Actions.refresh({key: 'activityModal', visible: true}); to show and
Actions.refresh({key: 'activityModal', visible: false}); to hide.

This works but I'd like rather to make some more elegant solution. I added two actions (for show and hide) and added there those lines of code and it works but I'm not sure if that's correct way to do it (and without using reducers, only action - i'm new to the redux). I'm thinking about another way to do this: adding some helper functions where I'll have those Actions.refresh calls and importing them where I need to access activityModal visibility.

Please tell me or suggest me what is the most correct way to do this?

Thanks!

edit:
I succeeded but I'd like you to confirm if it's good practice. Here is what I did:

containers/LoginContainer.js

```<code>...
this.props.showActivityModal(); // calling this on button press
...
</code>```

actions/activityModal.js

```<code>...
export function showActivityModal() {
  return {
    type: types.ACTIVITY_MODAL_SHOW,
    payload: {}
  }
}
...
</code>```

reducers/activityModal.js

```<code>...
return {
   visible: true,
   text: ''
};
...
</code>```

components/ActivityModal.js

```<code>...
class ActivityModal extends Component {
   ...
   componentWillReceiveProps(nextProps) {
      this.setState({
        visible: nextProps.activityModal.visible
      })
   }
   ...
}

function mapStateToProps(state) {
  return {
    activityModal: state.activityModal
  };
}

export default connect(mapStateToProps)(ActivityModal);
</code>```

Thanks!

答:
To do this what I wanted, all I had to do is:

```<code>function mapStateToProps(state) {
  return {
    activityModal: state.activityModal
  };
}

export default connect(mapStateToProps)(ActivityModal);
</code>```

to component I wanted to change state. And to dispatch an action to actually change state of activityModal.

I guess that's normal behavior for react redux but I was on the wrong track when I first started but hey, I figured it out.

Title: Calling (helper) function in redux

Body:
I'm using react-native-router-flux with react-redux and I think that I should ask this question here, correct me if I'm wrong.

I have ActivityModal Container which I call to show up whenever there is an API call or similar thing where I want to show that modal. Currently I'm calling it like this:

Actions.refresh({key: 'activityModal', visible: true}); to show and
Actions.refresh({key: 'activityModal', visible: false}); to hide.

This works but I'd like rather to make some more elegant solution. I added two actions (for show and hide) and added there those lines of code and it works but I'm not sure if that's correct way to do it (and without using reducers, only action - i'm new to the redux). I'm thinking about another way to do this: adding some helper functions where I'll have those Actions.refresh calls and importing them where I need to access activityModal visibility.

Please tell me or suggest me what is the most correct way to do this?

Thanks!

edit:
I succeeded but I'd like you to confirm if it's good practice. Here is what I did:

containers/LoginContainer.js

...
this.props.showActivityModal(); // calling this on button press
...

actions/activityModal.js

...
export function showActivityModal() {
  return {
    type: types.ACTIVITY_MODAL_SHOW,
    payload: {}
  }
}
...

reducers/activityModal.js

...
return {
   visible: true,
   text: ''
};
...

components/ActivityModal.js

...
class ActivityModal extends Component {
   ...
   componentWillReceiveProps(nextProps) {
      this.setState({
        visible: nextProps.activityModal.visible
      })
   }
   ...
}

function mapStateToProps(state) {
  return {
    activityModal: state.activityModal
  };
}

export default connect(mapStateToProps)(ActivityModal);

Thanks!

Body:
To do this what I wanted, all I had to do is:

function mapStateToProps(state) {
  return {
    activityModal: state.activityModal
  };
}

export default connect(mapStateToProps)(ActivityModal);

to component I wanted to change state. And to dispatch an action to actually change state of activityModal.

I guess that's normal behavior for react redux but I was on the wrong track when I first started but hey, I figured it out.