问:
ASP.NET Identity, persistent cookie - is something like this build in?
We are using CookieAuthenticationProvider and would like to implement the 'Remember me' functionality in our application that would work like this:

No matter if the 'Remember me' checkbox is checked or not, the token expiration time should always be set to 30 minutes (with SlidingExpiration turned on)

If user doesn't check 'Remember me' all we do is check if token expired - if it did, then user is redirected to login screen (this is build in into OWIN and works fine)

However if user checks 'Remember me' his credentials should be saved in the additional cookie (with default lifetime of 30 days). If his token expires (the timeout should still be set to 30 minutes), OWIN should use that additional cookie to renew the token automatically in the background. So in other words - if user check 'Remember me' he should be logged in for 30 days or until he logs out.

Question is - how can something like this be done with OWIN? As far as I can see, the default implementation still uses ExpireTimeSpan parameter - the only difference is, that the cookie is marked as persistent, so if user restarts browser he is logged in - but token expiration is still limited by ExpireTimeSpan.

I guess I have to somehow manually save user credentials during the SignIn and override the OnApplyRedirect event (that seems to be the only event fired if an unauthorized user tries to access a view that requires authorization), and instead of redirecting, somehow regenerate user's token... but does anybody know how exactly to do that?

答:
Finally, I ended up writing custom middleware and plugging it in:

RememberMeTokenMiddleware.cs:

```<code>using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using WebApplicationtoRemove.Owin.HelperClasses;
using Microsoft.AspNet.Identity.Owin;

namespace WebApplicationtoRemove.Owin.Middleware
{
    public class RememberMeTokenMiddleware : OwinMiddleware
    {
        #region Private Members

        private static double RememberMeTokenPeriodOfvalidityInMinutes = 43200;

        private IOwinContext Context { get; set; }

        #endregion

        #region Public Static Members

        #endregion

        #region Constructor

        public RememberMeTokenMiddleware(OwinMiddleware next)
            : base(next)
        {
        }

        public RememberMeTokenMiddleware(OwinMiddleware next, double RememberMeTokenPeriodOfvalidityInMinutes)
            : base(next)
        {
            RememberMeTokenMiddleware.RememberMeTokenPeriodOfvalidityInMinutes = RememberMeTokenPeriodOfvalidityInMinutes;
        }

        #endregion

        #region Public Methods

        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                Context = context;

                bool shouldDeleteRememberMeToken = CheckIfRememberMeTokenShouldBeDeleted(context);

                if (shouldDeleteRememberMeToken)
                {
                    context.Response.Cookies.Delete("RemoveRememberMeToken");

                    context.Response.Cookies.Delete("RememberMeToken");
                }
                else
                {
                    if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated)
                    {
                        //User is either not set or is not authenticated - try to log him in, using the RememberMeCookie
                        Login(context);
                    }
                }
            }
            catch (Exception ex)
            {
                //Something went wrong - we assume that cookie and/or token was damaged and should be deleted
                context.Response.Cookies.Delete("RememberMeToken");
            }

            await this.Next.Invoke(context);
        }

        #endregion

        #region Static Methods

        /// <summary>
        /// Check conditions and creates RememberMeToken cookie if necessary. This should be called inside SidnedIn event of CookieProvider
        /// </summary>
        public static void CheckAndCreateRememberMeToken(CookieResponseSignedInContext ctx)
        {
            try
            {
                bool signedInFromRememberMeToken = CheckIfUserWasSignedInFromRememberMeToken(ctx.OwinContext);

                if (!signedInFromRememberMeToken && ctx.Properties.IsPersistent)
                {
                    //Login occured using 'normal' path and IsPersistant was set - generate RememberMeToken cookie
                    var claimsToAdd = GenerateSerializableClaimListFromIdentity(ctx.Identity);

                    SerializableClaim cookieExpirationDate = GenerateRememberMeTokenExpirationDateClaim();

                    claimsToAdd.Add(cookieExpirationDate);

                    var allClaimsInFinalCompressedAndProtectedBase64Token = GenerateProtectedAndBase64EncodedClaimsToken(claimsToAdd);

                    ctx.Response.Cookies.Append("RememberMeToken", allClaimsInFinalCompressedAndProtectedBase64Token, new CookieOptions()
                    {
                        Expires = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes)
                    });

                    //Remove the SignedInFromRememberMeToken cookie, to let the middleware know, that user was signed in using normal path
                    ctx.OwinContext.Set("SignedInFromRememberMeToken", false);
                }
            }
            catch (Exception ex)
            {
                //Log errors using your favorite logger here
            }
        }

        /// <summary>
        /// User logged out - sets information (using cookie) for RememberMeTokenMiddleware that RememberMeToken should be removed
        /// </summary>
        public static void Logout(IOwinContext ctx)
        {
            ctx.Response.Cookies.Append("RemoveRememberMeToken", "");
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Returns information if user was signed in from RememberMeToken cookie - this information should be used to determine if RememberMeToken lifetime should be regenerated or not (it should be, if user signed in using normal path)
        /// </summary>
        private static bool CheckIfUserWasSignedInFromRememberMeToken(IOwinContext ctx)
        {
            bool signedInFromRememberMeToken = ctx.Get<bool>("SignedInFromRememberMeToken");

            return signedInFromRememberMeToken;
        }

        /// <summary>
        /// Generates serializable collection of user claims, that will be saved inside the cookie token. Custom class is used because Claim class causes 'Circular Reference Exception.'
        /// </summary>
        private static List<SerializableClaim> GenerateSerializableClaimListFromIdentity(ClaimsIdentity identity)
        {
            var dataToReturn = identity.Claims.Select(x =>
                                new SerializableClaim()
                                {
                                    Type = x.Type,
                                    ValueType = x.ValueType,
                                    Value = x.Value
                                }).ToList();

            return dataToReturn;
        }

        /// <summary>
        /// Generates a special claim containing an expiration date of RememberMeToken cookie. This is necessary because we CANNOT rely on browsers here - since each one threat cookies differently
        /// </summary>
        private static SerializableClaim GenerateRememberMeTokenExpirationDateClaim()
        {
            SerializableClaim cookieExpirationDate = new SerializableClaim()
            {
                Type = "RememberMeTokenExpirationDate",
                Value = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes).ToBinary().ToString()
            };
            return cookieExpirationDate;
        }

        /// <summary>
        /// Generates token containing user claims. The token is compressed, encrypted using machine key and returned as base64 string - this string will be saved inside RememberMeToken cookie
        /// </summary>
        private static string GenerateProtectedAndBase64EncodedClaimsToken(List<SerializableClaim> claimsToAdd)
        {
            var allClaimsAsString = JsonConvert.SerializeObject(claimsToAdd);

            var allClaimsAsBytes = Encoding.UTF8.GetBytes(allClaimsAsString);

            var allClaimsAsCompressedBytes = CompressionHelper.CompressDeflate(allClaimsAsBytes);

            var allClaimsAsCompressedBytesProtected = MachineKey.Protect(allClaimsAsCompressedBytes, "RememberMeToken");

            var allClaimsInFinalCompressedAndProtectedBase64Token = Convert.ToBase64String(allClaimsAsCompressedBytesProtected);

            return allClaimsInFinalCompressedAndProtectedBase64Token;
        }

        /// <summary>
        /// Primary login method
        /// </summary>
        private void Login(IOwinContext context)
        {
            var base64ProtectedCompressedRememberMeTokenBytes = context.Request.Cookies["RememberMeToken"];

            if (!string.IsNullOrEmpty(base64ProtectedCompressedRememberMeTokenBytes))
            {
                var RememberMeToken = GetRememberMeTokenFromData(base64ProtectedCompressedRememberMeTokenBytes);

                var claims = JsonConvert.DeserializeObject<IEnumerable<SerializableClaim>>(RememberMeToken);

                bool isRememberMeTokenStillValid = IsRememberMeTokenStillValid(claims);

                if (isRememberMeTokenStillValid)
                {
                    //Token is still valid - sign in
                    SignInUser(context, claims);

                    //We set information that user was signed in using the RememberMeToken cookie
                    context.Set("SignedInFromRememberMeToken", true);
                }
                else
                {
                    //Token is invalid or expired - we remove unnecessary cookie
                    context.Response.Cookies.Delete("RememberMeToken");
                }
            }
        }

        /// <summary>
        /// We log user, using passed claims
        /// </summary>
        private void SignInUser(IOwinContext context, IEnumerable<SerializableClaim> claims)
        {
            List<Claim> claimList = new List<Claim>();

            foreach (var item in claims)
            {
                string type = item.Type;

                string value = item.Value;

                claimList.Add(new Claim(type, value));
            }

            ClaimsIdentity ci = new ClaimsIdentity(claimList, DefaultAuthenticationTypes.ApplicationCookie);

            context.Authentication.SignIn(ci);

            context.Authentication.User = context.Authentication.AuthenticationResponseGrant.Principal;
        }

        /// <summary>
        /// Get information if RememberMeToken cookie is still valid (checks not only the date, but also some additional information)
        /// </summary>
        private bool IsRememberMeTokenStillValid(IEnumerable<SerializableClaim> claims)
        {
            var userIdClaim = claims.Where(x => x.Type == ClaimTypes.NameIdentifier).SingleOrDefault();

            if (userIdClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Claim of type NameIdentifier was not found.");
            }

            var userSecurityStampClaim = claims.Where(x => x.Type == "AspNet.Identity.SecurityStamp").SingleOrDefault();

            if (userSecurityStampClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Claim of type SecurityStamp was not found.");
            }

            string userId = userIdClaim.Value;

            var userManager = Context.GetUserManager<ApplicationUserManager>();

            if (userManager == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Unable to get UserManager");
            }

            var currentUserData = userManager.FindById(userId);

            if (currentUserData == null)
            {
                return false;
            }

            if (currentUserData.LockoutEndDateUtc >=  DateTime.Now)
            {
                return false;
            }

            if (currentUserData.SecurityStamp != userSecurityStampClaim.Value)
            {
                //User Securitystamp was changed

                return false;
            }

            return GetRememberMeTokenExpirationMinutesLeft(claims) > 0;
        }

        /// <summary>
        /// Returns how many minutes the RememberMeToken will be valid - if it expired, returns zero or negative value
        /// </summary>
        private double GetRememberMeTokenExpirationMinutesLeft(IEnumerable<SerializableClaim> claims)
        {
            double dataToReturn = -1;

            var RememberMeTokenExpirationDate = GetRememberMeTokenExpirationDate(claims);

            dataToReturn = (RememberMeTokenExpirationDate - DateTime.Now).TotalMinutes;

            return dataToReturn;
        }

        /// <summary>
        /// Returns a DateTime object containing the expiration date of the RememberMeToken
        /// </summary>
        private DateTime GetRememberMeTokenExpirationDate(IEnumerable<SerializableClaim> claims)
        {
            DateTime RememberMeTokenExpirationDate = DateTime.Now.AddDays(-1);

            var RememberMeTokenExpirationClaim = GetRememberMeTokenExpirationDateClaim(claims);

            if (RememberMeTokenExpirationClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. RememberMeTokenExpirationClaim was not found.");
            }

            long binaryTime = Convert.ToInt64(RememberMeTokenExpirationClaim.Value);

            RememberMeTokenExpirationDate = DateTime.FromBinary(binaryTime);

            return RememberMeTokenExpirationDate;
        }

        /// <summary>
        /// Returns the claim determining the expiration date of the token
        /// </summary>
        private SerializableClaim GetRememberMeTokenExpirationDateClaim(IEnumerable<SerializableClaim> claims)
        {
            var RememberMeTokenExpirationClaim = claims.Where(x => x.Type == "RememberMeTokenExpirationDate").SingleOrDefault();

            return RememberMeTokenExpirationClaim;
        }

        /// <summary>
        /// Attempts to decipher the RememberMeToken to the JSON format containing claims
        /// </summary>
        private string GetRememberMeTokenFromData(string base64ProtectedCompressedRememberMeTokenBytes)
        {
            var protectedCompressedRememberMeTokenBytes = Convert.FromBase64String(base64ProtectedCompressedRememberMeTokenBytes);

            var compressedRememberMeTokenBytes = MachineKey.Unprotect(protectedCompressedRememberMeTokenBytes, "RememberMeToken");

            var RememberMeTokenBytes = CompressionHelper.DecompressDeflate(compressedRememberMeTokenBytes);

            var RememberMeToken = Encoding.UTF8.GetString(RememberMeTokenBytes);

            return RememberMeToken;
        }

        /// <summary>
        /// Returns information if token cookie should be delated (for example, when user click 'Logout')
        /// </summary>
        private bool CheckIfRememberMeTokenShouldBeDeleted(IOwinContext context)
        {
            bool shouldDeleteRememberMeToken = (context.Request.Cookies.Where(x => x.Key == "RemoveRememberMeToken").Count() > 0);

            return shouldDeleteRememberMeToken;
        }

        #endregion
    }
}
</code>```

And some helper classes:
CompressionHelper.cs:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Web;

namespace WebApplicationtoRemove.Owin.HelperClasses
{
    /// <summary>
    /// Data compression helper
    /// </summary>
    public static class CompressionHelper
    {
        public static byte[] CompressDeflate(byte[] data)
        {
            MemoryStream output = new MemoryStream();
            using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
            {
                dstream.Write(data, 0, data.Length);
            }
            return output.ToArray();
        }

        public static byte[] DecompressDeflate(byte[] data)
        {
            MemoryStream input = new MemoryStream(data);
            MemoryStream output = new MemoryStream();
            using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
            {
                dstream.CopyTo(output);
            }
            return output.ToArray();
        }
    }
}
</code>```

SerializableClaim.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplicationtoRemove.Owin.HelperClasses
{
    public class SerializableClaim
    {
        public string Type { get; set; }

        public string ValueType { get; set; }

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

To test the above - create new MVC 4.6.x project (authentication mode: Individual User Accounts), add the above classes to it and then modify the Startup.Auth.cs:

```<code>using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using WebApplicationtoRemove.Models;
using WebApplicationtoRemove.Owin.Middleware;

namespace WebApplicationtoRemove
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

                    OnResponseSignedIn = ctx =>
                    {
                        RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
                    },

                    OnResponseSignOut = ctx =>
                    {
                        RememberMeTokenMiddleware.Logout(ctx.OwinContext);
                    }
                }
            });

            app.Use<RememberMeTokenMiddleware>();
        }
    }
}
</code>```

What interests you there are these:

```<code>OnResponseSignedIn = ctx =>
{
    RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
},

OnResponseSignOut = ctx =>
{
    RememberMeTokenMiddleware.Logout(ctx.OwinContext);
}
</code>```

and this line:

```<code>app.Use<RememberMeTokenMiddleware>();
</code>```

This should enable the middleware. How this works: if the user checks 'Remember me' checkbox, a RememberMeToken cookie will be created (containing all the claims user had during login) alongside the 'AspNet.ApplicationCookie'.

When the session times out, the middleware will check if the RememberMeToken exists, and is still valid - if so: it will log in the user seamlessly in background.

Hope this helps anyone.

Body:
Finally, I ended up writing custom middleware and plugging it in:

RememberMeTokenMiddleware.cs:

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using WebApplicationtoRemove.Owin.HelperClasses;
using Microsoft.AspNet.Identity.Owin;

namespace WebApplicationtoRemove.Owin.Middleware
{
    public class RememberMeTokenMiddleware : OwinMiddleware
    {
        #region Private Members

        private static double RememberMeTokenPeriodOfvalidityInMinutes = 43200;

        private IOwinContext Context { get; set; }

        #endregion

        #region Public Static Members

        #endregion

        #region Constructor

        public RememberMeTokenMiddleware(OwinMiddleware next)
            : base(next)
        {
        }

        public RememberMeTokenMiddleware(OwinMiddleware next, double RememberMeTokenPeriodOfvalidityInMinutes)
            : base(next)
        {
            RememberMeTokenMiddleware.RememberMeTokenPeriodOfvalidityInMinutes = RememberMeTokenPeriodOfvalidityInMinutes;
        }

        #endregion

        #region Public Methods

        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                Context = context;

                bool shouldDeleteRememberMeToken = CheckIfRememberMeTokenShouldBeDeleted(context);

                if (shouldDeleteRememberMeToken)
                {
                    context.Response.Cookies.Delete("RemoveRememberMeToken");

                    context.Response.Cookies.Delete("RememberMeToken");
                }
                else
                {
                    if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated)
                    {
                        //User is either not set or is not authenticated - try to log him in, using the RememberMeCookie
                        Login(context);
                    }
                }
            }
            catch (Exception ex)
            {
                //Something went wrong - we assume that cookie and/or token was damaged and should be deleted
                context.Response.Cookies.Delete("RememberMeToken");
            }

            await this.Next.Invoke(context);
        }

        #endregion

        #region Static Methods

        /// <summary>
        /// Check conditions and creates RememberMeToken cookie if necessary. This should be called inside SidnedIn event of CookieProvider
        /// </summary>
        public static void CheckAndCreateRememberMeToken(CookieResponseSignedInContext ctx)
        {
            try
            {
                bool signedInFromRememberMeToken = CheckIfUserWasSignedInFromRememberMeToken(ctx.OwinContext);

                if (!signedInFromRememberMeToken && ctx.Properties.IsPersistent)
                {
                    //Login occured using 'normal' path and IsPersistant was set - generate RememberMeToken cookie
                    var claimsToAdd = GenerateSerializableClaimListFromIdentity(ctx.Identity);

                    SerializableClaim cookieExpirationDate = GenerateRememberMeTokenExpirationDateClaim();

                    claimsToAdd.Add(cookieExpirationDate);

                    var allClaimsInFinalCompressedAndProtectedBase64Token = GenerateProtectedAndBase64EncodedClaimsToken(claimsToAdd);

                    ctx.Response.Cookies.Append("RememberMeToken", allClaimsInFinalCompressedAndProtectedBase64Token, new CookieOptions()
                    {
                        Expires = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes)
                    });

                    //Remove the SignedInFromRememberMeToken cookie, to let the middleware know, that user was signed in using normal path
                    ctx.OwinContext.Set("SignedInFromRememberMeToken", false);
                }
            }
            catch (Exception ex)
            {
                //Log errors using your favorite logger here
            }
        }

        /// <summary>
        /// User logged out - sets information (using cookie) for RememberMeTokenMiddleware that RememberMeToken should be removed
        /// </summary>
        public static void Logout(IOwinContext ctx)
        {
            ctx.Response.Cookies.Append("RemoveRememberMeToken", "");
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Returns information if user was signed in from RememberMeToken cookie - this information should be used to determine if RememberMeToken lifetime should be regenerated or not (it should be, if user signed in using normal path)
        /// </summary>
        private static bool CheckIfUserWasSignedInFromRememberMeToken(IOwinContext ctx)
        {
            bool signedInFromRememberMeToken = ctx.Get<bool>("SignedInFromRememberMeToken");

            return signedInFromRememberMeToken;
        }

        /// <summary>
        /// Generates serializable collection of user claims, that will be saved inside the cookie token. Custom class is used because Claim class causes 'Circular Reference Exception.'
        /// </summary>
        private static List<SerializableClaim> GenerateSerializableClaimListFromIdentity(ClaimsIdentity identity)
        {
            var dataToReturn = identity.Claims.Select(x =>
                                new SerializableClaim()
                                {
                                    Type = x.Type,
                                    ValueType = x.ValueType,
                                    Value = x.Value
                                }).ToList();

            return dataToReturn;
        }

        /// <summary>
        /// Generates a special claim containing an expiration date of RememberMeToken cookie. This is necessary because we CANNOT rely on browsers here - since each one threat cookies differently
        /// </summary>
        private static SerializableClaim GenerateRememberMeTokenExpirationDateClaim()
        {
            SerializableClaim cookieExpirationDate = new SerializableClaim()
            {
                Type = "RememberMeTokenExpirationDate",
                Value = DateTime.Now.AddMinutes(RememberMeTokenPeriodOfvalidityInMinutes).ToBinary().ToString()
            };
            return cookieExpirationDate;
        }

        /// <summary>
        /// Generates token containing user claims. The token is compressed, encrypted using machine key and returned as base64 string - this string will be saved inside RememberMeToken cookie
        /// </summary>
        private static string GenerateProtectedAndBase64EncodedClaimsToken(List<SerializableClaim> claimsToAdd)
        {
            var allClaimsAsString = JsonConvert.SerializeObject(claimsToAdd);

            var allClaimsAsBytes = Encoding.UTF8.GetBytes(allClaimsAsString);

            var allClaimsAsCompressedBytes = CompressionHelper.CompressDeflate(allClaimsAsBytes);

            var allClaimsAsCompressedBytesProtected = MachineKey.Protect(allClaimsAsCompressedBytes, "RememberMeToken");

            var allClaimsInFinalCompressedAndProtectedBase64Token = Convert.ToBase64String(allClaimsAsCompressedBytesProtected);

            return allClaimsInFinalCompressedAndProtectedBase64Token;
        }

        /// <summary>
        /// Primary login method
        /// </summary>
        private void Login(IOwinContext context)
        {
            var base64ProtectedCompressedRememberMeTokenBytes = context.Request.Cookies["RememberMeToken"];

            if (!string.IsNullOrEmpty(base64ProtectedCompressedRememberMeTokenBytes))
            {
                var RememberMeToken = GetRememberMeTokenFromData(base64ProtectedCompressedRememberMeTokenBytes);

                var claims = JsonConvert.DeserializeObject<IEnumerable<SerializableClaim>>(RememberMeToken);

                bool isRememberMeTokenStillValid = IsRememberMeTokenStillValid(claims);

                if (isRememberMeTokenStillValid)
                {
                    //Token is still valid - sign in
                    SignInUser(context, claims);

                    //We set information that user was signed in using the RememberMeToken cookie
                    context.Set("SignedInFromRememberMeToken", true);
                }
                else
                {
                    //Token is invalid or expired - we remove unnecessary cookie
                    context.Response.Cookies.Delete("RememberMeToken");
                }
            }
        }

        /// <summary>
        /// We log user, using passed claims
        /// </summary>
        private void SignInUser(IOwinContext context, IEnumerable<SerializableClaim> claims)
        {
            List<Claim> claimList = new List<Claim>();

            foreach (var item in claims)
            {
                string type = item.Type;

                string value = item.Value;

                claimList.Add(new Claim(type, value));
            }

            ClaimsIdentity ci = new ClaimsIdentity(claimList, DefaultAuthenticationTypes.ApplicationCookie);

            context.Authentication.SignIn(ci);

            context.Authentication.User = context.Authentication.AuthenticationResponseGrant.Principal;
        }

        /// <summary>
        /// Get information if RememberMeToken cookie is still valid (checks not only the date, but also some additional information)
        /// </summary>
        private bool IsRememberMeTokenStillValid(IEnumerable<SerializableClaim> claims)
        {
            var userIdClaim = claims.Where(x => x.Type == ClaimTypes.NameIdentifier).SingleOrDefault();

            if (userIdClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Claim of type NameIdentifier was not found.");
            }

            var userSecurityStampClaim = claims.Where(x => x.Type == "AspNet.Identity.SecurityStamp").SingleOrDefault();

            if (userSecurityStampClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Claim of type SecurityStamp was not found.");
            }

            string userId = userIdClaim.Value;

            var userManager = Context.GetUserManager<ApplicationUserManager>();

            if (userManager == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. Unable to get UserManager");
            }

            var currentUserData = userManager.FindById(userId);

            if (currentUserData == null)
            {
                return false;
            }

            if (currentUserData.LockoutEndDateUtc >=  DateTime.Now)
            {
                return false;
            }

            if (currentUserData.SecurityStamp != userSecurityStampClaim.Value)
            {
                //User Securitystamp was changed

                return false;
            }

            return GetRememberMeTokenExpirationMinutesLeft(claims) > 0;
        }

        /// <summary>
        /// Returns how many minutes the RememberMeToken will be valid - if it expired, returns zero or negative value
        /// </summary>
        private double GetRememberMeTokenExpirationMinutesLeft(IEnumerable<SerializableClaim> claims)
        {
            double dataToReturn = -1;

            var RememberMeTokenExpirationDate = GetRememberMeTokenExpirationDate(claims);

            dataToReturn = (RememberMeTokenExpirationDate - DateTime.Now).TotalMinutes;

            return dataToReturn;
        }

        /// <summary>
        /// Returns a DateTime object containing the expiration date of the RememberMeToken
        /// </summary>
        private DateTime GetRememberMeTokenExpirationDate(IEnumerable<SerializableClaim> claims)
        {
            DateTime RememberMeTokenExpirationDate = DateTime.Now.AddDays(-1);

            var RememberMeTokenExpirationClaim = GetRememberMeTokenExpirationDateClaim(claims);

            if (RememberMeTokenExpirationClaim == null)
            {
                throw new Exception("RememberMeTokenAuthMiddleware. RememberMeTokenExpirationClaim was not found.");
            }

            long binaryTime = Convert.ToInt64(RememberMeTokenExpirationClaim.Value);

            RememberMeTokenExpirationDate = DateTime.FromBinary(binaryTime);

            return RememberMeTokenExpirationDate;
        }

        /// <summary>
        /// Returns the claim determining the expiration date of the token
        /// </summary>
        private SerializableClaim GetRememberMeTokenExpirationDateClaim(IEnumerable<SerializableClaim> claims)
        {
            var RememberMeTokenExpirationClaim = claims.Where(x => x.Type == "RememberMeTokenExpirationDate").SingleOrDefault();

            return RememberMeTokenExpirationClaim;
        }

        /// <summary>
        /// Attempts to decipher the RememberMeToken to the JSON format containing claims
        /// </summary>
        private string GetRememberMeTokenFromData(string base64ProtectedCompressedRememberMeTokenBytes)
        {
            var protectedCompressedRememberMeTokenBytes = Convert.FromBase64String(base64ProtectedCompressedRememberMeTokenBytes);

            var compressedRememberMeTokenBytes = MachineKey.Unprotect(protectedCompressedRememberMeTokenBytes, "RememberMeToken");

            var RememberMeTokenBytes = CompressionHelper.DecompressDeflate(compressedRememberMeTokenBytes);

            var RememberMeToken = Encoding.UTF8.GetString(RememberMeTokenBytes);

            return RememberMeToken;
        }

        /// <summary>
        /// Returns information if token cookie should be delated (for example, when user click 'Logout')
        /// </summary>
        private bool CheckIfRememberMeTokenShouldBeDeleted(IOwinContext context)
        {
            bool shouldDeleteRememberMeToken = (context.Request.Cookies.Where(x => x.Key == "RemoveRememberMeToken").Count() > 0);

            return shouldDeleteRememberMeToken;
        }

        #endregion
    }
}

And some helper classes:
CompressionHelper.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Web;

namespace WebApplicationtoRemove.Owin.HelperClasses
{
    /// <summary>
    /// Data compression helper
    /// </summary>
    public static class CompressionHelper
    {
        public static byte[] CompressDeflate(byte[] data)
        {
            MemoryStream output = new MemoryStream();
            using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
            {
                dstream.Write(data, 0, data.Length);
            }
            return output.ToArray();
        }

        public static byte[] DecompressDeflate(byte[] data)
        {
            MemoryStream input = new MemoryStream(data);
            MemoryStream output = new MemoryStream();
            using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
            {
                dstream.CopyTo(output);
            }
            return output.ToArray();
        }
    }
}

SerializableClaim.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplicationtoRemove.Owin.HelperClasses
{
    public class SerializableClaim
    {
        public string Type { get; set; }

        public string ValueType { get; set; }

        public string Value { get; set; }
    }
}

To test the above - create new MVC 4.6.x project (authentication mode: Individual User Accounts), add the above classes to it and then modify the Startup.Auth.cs:

using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using WebApplicationtoRemove.Models;
using WebApplicationtoRemove.Owin.Middleware;

namespace WebApplicationtoRemove
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),

                    OnResponseSignedIn = ctx =>
                    {
                        RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
                    },

                    OnResponseSignOut = ctx =>
                    {
                        RememberMeTokenMiddleware.Logout(ctx.OwinContext);
                    }
                }
            });

            app.Use<RememberMeTokenMiddleware>();
        }
    }
}

What interests you there are these:

OnResponseSignedIn = ctx =>
{
    RememberMeTokenMiddleware.CheckAndCreateRememberMeToken(ctx);
},

OnResponseSignOut = ctx =>
{
    RememberMeTokenMiddleware.Logout(ctx.OwinContext);
}

and this line:

app.Use<RememberMeTokenMiddleware>();

This should enable the middleware. How this works: if the user checks 'Remember me' checkbox, a RememberMeToken cookie will be created (containing all the claims user had during login) alongside the 'AspNet.ApplicationCookie'.

When the session times out, the middleware will check if the RememberMeToken exists, and is still valid - if so: it will log in the user seamlessly in background.

Hope this helps anyone.


来源: stackexchange

问:
Why am I getting a list index out of range error?
I'm not sure why I am getting the following error:

```<code>builtins.IndexError: list index out of range
</code>```

at the following line (line 5):

```<code>C[A[key(a)]] == C[A[key(a)]] + 1
</code>```

An example of input for this code would be A = [2, -2, 1] and key = lambda x: x**2, and in the loop on line 4-5, it takes the key of item at A[a] as the chosen index for array C, and increments the value at that index by 1. For example: C[A[key(0)]], or C[4], is 0, and it is incremented to 1.

```<code>def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[A[key(a)]] == C[A[key(a)]] + 1
    for i in range(0, k):
        sum = C[i]
    return C
</code>```

答:
The reason is that you access the List A = [2, -2, 1]  with a index that is out of bounds of your list A.

For every iteration of your first for loop,
you calculates the square of a (through your key lamba) and this leads to the index error.

You have to make sure that you don't access the list A with index values that are bigger than the size of the List A.

For example:

```<code>for a in A:
  # key(a) will be 4, 4, 1
  # but for key(2) it will be 4
  # and larger than the list A.
  C[A[key(a)]] == C[A[key(a)]] + 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure why I am getting the following error:

builtins.IndexError: list index out of range

at the following line (line 5):

C[A[key(a)]] == C[A[key(a)]] + 1

An example of input for this code would be A = [2, -2, 1] and key = lambda x: x**2, and in the loop on line 4-5, it takes the key of item at A[a] as the chosen index for array C, and increments the value at that index by 1. For example: C[A[key(0)]], or C[4], is 0, and it is incremented to 1.

def key_positions(A, key):
    k = key(max(A, key = key))
    C = [0] * (k+1)
    for a in A:
        C[A[key(a)]] == C[A[key(a)]] + 1
    for i in range(0, k):
        sum = C[i]
    return C

Body:
The reason is that you access the List A = [2, -2, 1]  with a index that is out of bounds of your list A.

For every iteration of your first for loop,
you calculates the square of a (through your key lamba) and this leads to the index error.

You have to make sure that you don't access the list A with index values that are bigger than the size of the List A.

For example:

for a in A:
  # key(a) will be 4, 4, 1
  # but for key(2) it will be 4
  # and larger than the list A.
  C[A[key(a)]] == C[A[key(a)]] + 1


问:
PHP - Object of class could not be converted to string
I'm trying to print a property of the simple class below. But instead i get the error above. I haven't found an answer on similar questions on here. The error triggers on this line:

```<code>echo "$object1 name = " . $object1->name . "<br>";
</code>```

Using XAMPP on Windows Help?

```<code><?php
    $object1 = new User("Pickle", "YouGotIt");
    print_r($object1);
    $object1->name  = "Alice";

    echo "$object1 name = " . $object1->name . "<br>"; /* this triggers the error */

    class User
    {
        public $name, $password;

        function __construct($n, $p) { // class constructor
            $name = $n;
            $password = $p;
        }
    }
?>
</code>```

答:
There are two things wrong in your code,

You're using local variables in your class constructor, not instance properties. Your constructor method should be like this:

```<code>function __construct($n, $p) {
    $this->name = $n;
    $this->password = $p;
}
</code>```

Now comes to your error, Object of class could not be converted to string. This is because of this $object in echo statement,

```<code>echo "$object1 name = " ...
      ^^^^^^^^
</code>```

You need to escape this $object1 with backslash, like this:

```<code>echo "\$object1 name = " . $object1->name . "<br>";
</code>```

Body:
I'm trying to print a property of the simple class below. But instead i get the error above. I haven't found an answer on similar questions on here. The error triggers on this line:

echo "$object1 name = " . $object1->name . "
";

Using XAMPP on Windows Help?

<?php
    $object1 = new User("Pickle", "YouGotIt");
    print_r($object1);
    $object1->name  = "Alice";

    echo "$object1 name = " . $object1->name . "
"; /* this triggers the error */

    class User
    {
        public $name, $password;

        function __construct($n, $p) { // class constructor
            $name = $n;
            $password = $p;
        }
    }
?>

Body:
There are two things wrong in your code,

You're using local variables in your class constructor, not instance properties. Your constructor method should be like this:

function __construct($n, $p) {
    $this->name = $n;
    $this->password = $p;
}

Now comes to your error, Object of class could not be converted to string. This is because of this $object in echo statement,

echo "$object1 name = " ...
      ^^^^^^^^

You need to escape this $object1 with backslash, like this:

echo "\$object1 name = " . $object1->name . "<br>";


问:
PHP Namespaces, the use command
I'm just learning about PHP Namespaces and I have a very simple code which is not working and I'm wondering why:

we have n1.php containing one namespace and a function:

```<code><?php
namespace app\cat1;
function echoo(){
    echo "from cat 1";
}
?>
</code>```

n2.php:

```<code><?php
    namespace app\cat2;
    function echoo(){
        echo "from cat 2";
    }
?>
</code>```

now in index.php I have included both n1.php and n2.php to use the echoo function:

```<code><?php

require_once('n1.php');
require_once('n2.php');

use app\cat1;
echoo();

?>
</code>```

As far as I understood the namespacing, the above code should work but it isn't and I don't know why!? I told PHP to use app\cat1; and the called echoo() function but I get:

```<code>Fatal error: Call to undefined function echoo() in E:\xampp\htdocs\test\index.php on line 7
</code>```

Ofcourse I can do this and it's gonna work:

```<code><?php

require_once('n1.php');
require_once('n2.php');

//use app\cat1; <-- this is commented
app\cat1\echoo(); // <-- and now I'm using full path to run the echoo()
?>
</code>```

the above is working, but now what's the reason we have use in namespacing?

Another thing: how can we put namespaces in multiple files like I did above and also not use include method? I see in Laravel framework files that this is happening. files only have use etc\blah and there is no inclusion and it's working just fine. so how is that happening?

答:
by default use keyword will import the object under the namespace , you need to define that you are using function

another thing that you need to pass the function name to use so to solve your issue :

```<code>use function app\cat1\echoo;
</code>```

the docs:

```<code>// importing a function (PHP 5.6+)
use function My\Full\functionName;
</code>```

so , in your example -here I'm using grouping name spaces instead of including files as long as most of online IDEs does not support including- :

```<code>namespace app\cat1 {
    function echoo(){
        echo "from cat 1";
    }
}

namespace app\cat2 {
    function echoo(){
        echo "from cat 2";
    }
}

namespace {
    use function app\cat2\echoo;
    //  ^^^^^^^^ see this
    echoo();
    // Output : from cat 2
}
</code>```

live example : https://3v4l.org/TATgp

Title: PHP Namespaces, the use command

Body:
I'm just learning about PHP Namespaces and I have a very simple code which is not working and I'm wondering why:

we have n1.php containing one namespace and a function:

<?php
namespace app\cat1;
function echoo(){
    echo "from cat 1";
}
?>

n2.php:

<?php
    namespace app\cat2;
    function echoo(){
        echo "from cat 2";
    }
?>

now in index.php I have included both n1.php and n2.php to use the echoo function:

<?php

require_once('n1.php');
require_once('n2.php');

use app\cat1;
echoo();

?>

As far as I understood the namespacing, the above code should work but it isn't and I don't know why!? I told PHP to use app\cat1; and the called echoo() function but I get:

Fatal error: Call to undefined function echoo() in E:\xampp\htdocs\test\index.php on line 7

Ofcourse I can do this and it's gonna work:

<?php

require_once('n1.php');
require_once('n2.php');

//use app\cat1; <-- this is commented
app\cat1\echoo(); // <-- and now I'm using full path to run the echoo()
?>

the above is working, but now what's the reason we have use in namespacing?

Another thing: how can we put namespaces in multiple files like I did above and also not use include method? I see in Laravel framework files that this is happening. files only have use etc\blah and there is no inclusion and it's working just fine. so how is that happening?

Body:
by default use keyword will import the object under the namespace , you need to define that you are using function

another thing that you need to pass the function name to use so to solve your issue :

use function app\cat1\echoo;

the docs:

// importing a function (PHP 5.6+)
use function My\Full\functionName;

so , in your example -here I'm using grouping name spaces instead of including files as long as most of online IDEs does not support including- :

namespace app\cat1 {
    function echoo(){
        echo "from cat 1";
    }
}

namespace app\cat2 {
    function echoo(){
        echo "from cat 2";
    }
}

namespace {
    use function app\cat2\echoo;
    //  ^^^^^^^^ see this
    echoo();
    // Output : from cat 2
}

live example : https://3v4l.org/TATgp


问:
Using self.image and current_frame to animate the sprite of an enemy in pygame
I am trying to animate a TRUMP enemy for a video game in pygame. I have all my images loaded and I would like to have him move around at random. I am having a hard time getting the enemy TRUMP character's image to animate. I can get his initial frame to display but after that I am lost. You will see the troubled area in the code in the animate2 function.

I am confused about how I will use current_frame2 or self.image to update his sprite. Does anyone know how to proceed?

```<code>class TRUMP(pg.sprite.Sprite):
    def __init__(self, game):
        pg.sprite.Sprite.__init__(self)
        self.game = game
        self.current_frame2 = 0
        self.last_update2 = 0
        self.load_images()
        self.animate2()

        self.image = self.TRUMP_fingers_l[0]
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH *3/4), (589)
        self.pos = vec((WIDTH/2), (HEIGHT/2))
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)

        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        self.clock = pg.time.Clock()

    def load_images(self):

        self.TRUMP_fingers_l = [self.game.spritesheet.get_image(503, 1, 248, 559)]
        for frame in self.TRUMP_fingers_l:
            frame.set_colorkey(BLACK)
        self.TRUMP_walk1_l = [self.game.spritesheet.get_image(643, 562, 249, 448)]
        self.TRUMP_walk2_l = [self.game.spritesheet.get_image(894, 474, 249, 448)]
        self.TRUMP_hailing = [self.game.spritesheet.get_image(1, 571, 248, 439)]
        self.TRUMP_throwing = [self.game.spritesheet.get_image(753, 1, 248, 471)]
        self.TRUMP_smug = [self.game.spritesheet.get_image(252, 1, 249, 562)]
        self.TRUMP_flexing_l = [self.game.spritesheet.get_image(1, 1, 249, 568)]

    def animate2(self):

       now = pg.time.get_ticks()
       if now - self.last_update2 > 200:
            self.last_update2 = now
            self.current_frame2 = self.TRUMP_hailing[0]
            self.image = self.TRUMP_hailing[0]
</code>```

答:
It seems to me that you only need a index variable (if the timer works correctly) that you  increment to cycle through the image lists. Use modulo % len(self.TRUMP_hailing) to keep the index in the correct range.

```<code>    # In the __init__ method:
    self.index = 0

def animate2(self):
    now = pg.time.get_ticks()
    if now - self.last_update2 > 200:
        self.index += 1
        self.index %= len(self.TRUMP_hailing)
        self.last_update2 = now
        self.current_frame2 = self.TRUMP_hailing[self.index]
        self.image = self.TRUMP_hailing[self.index]
</code>```

Body:
I am trying to animate a TRUMP enemy for a video game in pygame. I have all my images loaded and I would like to have him move around at random. I am having a hard time getting the enemy TRUMP character's image to animate. I can get his initial frame to display but after that I am lost. You will see the troubled area in the code in the animate2 function.

I am confused about how I will use current_frame2 or self.image to update his sprite. Does anyone know how to proceed?

class TRUMP(pg.sprite.Sprite):
    def __init__(self, game):
        pg.sprite.Sprite.__init__(self)
        self.game = game
        self.current_frame2 = 0
        self.last_update2 = 0
        self.load_images()
        self.animate2()

        self.image = self.TRUMP_fingers_l[0]
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH *3/4), (589)
        self.pos = vec((WIDTH/2), (HEIGHT/2))
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)

        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        self.clock = pg.time.Clock()

    def load_images(self):

        self.TRUMP_fingers_l = [self.game.spritesheet.get_image(503, 1, 248, 559)]
        for frame in self.TRUMP_fingers_l:
            frame.set_colorkey(BLACK)
        self.TRUMP_walk1_l = [self.game.spritesheet.get_image(643, 562, 249, 448)]
        self.TRUMP_walk2_l = [self.game.spritesheet.get_image(894, 474, 249, 448)]
        self.TRUMP_hailing = [self.game.spritesheet.get_image(1, 571, 248, 439)]
        self.TRUMP_throwing = [self.game.spritesheet.get_image(753, 1, 248, 471)]
        self.TRUMP_smug = [self.game.spritesheet.get_image(252, 1, 249, 562)]
        self.TRUMP_flexing_l = [self.game.spritesheet.get_image(1, 1, 249, 568)]

    def animate2(self):

       now = pg.time.get_ticks()
       if now - self.last_update2 > 200:
            self.last_update2 = now
            self.current_frame2 = self.TRUMP_hailing[0]
            self.image = self.TRUMP_hailing[0]

Body:
It seems to me that you only need a index variable (if the timer works correctly) that you  increment to cycle through the image lists. Use modulo % len(self.TRUMP_hailing) to keep the index in the correct range.

    # In the __init__ method:
    self.index = 0

def animate2(self):
    now = pg.time.get_ticks()
    if now - self.last_update2 > 200:
        self.index += 1
        self.index %= len(self.TRUMP_hailing)
        self.last_update2 = now
        self.current_frame2 = self.TRUMP_hailing[self.index]
        self.image = self.TRUMP_hailing[self.index]


问:
C# String Array to Double
Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.

First, here's my code so far:

```<code>        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }

    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());
</code>```

So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.

Thanks

答:
As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double.

But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles.

```<code>Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);
</code>```

Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach

Title: C# String Array to Double

Body:
Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.

First, here's my code so far:

        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }

    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());

So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.

Thanks

Body:
As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double.

But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles.

Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);

Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach


问:
Calling `std::get` on `std::tuple` with elements deriving from `std::tuple` - ill-formed?
```<code>struct Y { };
struct X : std::tuple<Y> { };

int main()
{
    std::get<0>(std::make_tuple(X{}));
}
</code>```

on wandbox

The above code compiles and works as expected with clang++ when using libc++.

The above code fails to compile with both clang++ and g++ when using libstdc++ with the following error:

```<code>include/c++/7.0.1/tuple:1302:36:
error: no matching function for call to ‘__get_helper<0>(std::tuple<X>&)’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~

include/c++/7.0.1/tuple:1290:5:
note: candidate: template<long unsigned int __i, class _Head, class ... _Tail>
                constexpr _Head& std::__get_helper(std::_Tuple_impl<_Idx, _Head, _Tail ...>&)
    __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
    ^~~~~~~~~~~~

include/c++/7.0.1/tuple:1290:5:
note:   template argument deduction/substitution failed:
include/c++/7.0.1/tuple:1302:36:
note:   ‘std::_Tuple_impl<0, _Head, _Tail ...>’ is an ambiguous base class of ‘std::tuple<X>’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~

include/c++/7.0.1/tuple:1295:5:
note: candidate: template<long unsigned int __i, class _Head, class ... _Tail>
                constexpr const _Head& std::__get_helper(const std::_Tuple_impl<_Idx, _Head, _Tail ...>&)
    __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
    ^~~~~~~~~~~~

include/c++/7.0.1/tuple:1295:5:
note:   template argument deduction/substitution failed:
include/c++/7.0.1/tuple:1302:36:
note:   ‘const std::_Tuple_impl<0, _Head, _Tail ...>’ is an ambiguous base class of ‘std::tuple<X>’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~
</code>```

It seems that libstdc++'s inheritance-based implementation of std::tuple causes ambiguity when tuple elements derive from std::tuple upon calling std::get. I'm inclined to think that this is an implementation defect in libstdc++ - is that the case? Or is there something in the Standard that would make the code snippet ill-formed?

答: As mentioned by T.C. in the comments, this is caused by the known bug #71096.</p>

Body:
struct Y { };
struct X : std::tuple<Y> { };

int main()
{
    std::get<0>(std::make_tuple(X{}));
}

on wandbox

The above code compiles and works as expected with clang++ when using libc++.

The above code fails to compile with both clang++ and g++ when using libstdc++ with the following error:

include/c++/7.0.1/tuple:1302:36:
error: no matching function for call to ‘__get_helper<0>(std::tuple<X>&)’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~

include/c++/7.0.1/tuple:1290:5:
note: candidate: template<long unsigned int __i, class _Head, class ... _Tail>
                constexpr _Head& std::__get_helper(std::_Tuple_impl<_Idx, _Head, _Tail ...>&)
    __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
    ^~~~~~~~~~~~

include/c++/7.0.1/tuple:1290:5:
note:   template argument deduction/substitution failed:
include/c++/7.0.1/tuple:1302:36:
note:   ‘std::_Tuple_impl<0, _Head, _Tail ...>’ is an ambiguous base class of ‘std::tuple<X>’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~

include/c++/7.0.1/tuple:1295:5:
note: candidate: template<long unsigned int __i, class _Head, class ... _Tail>
                constexpr const _Head& std::__get_helper(const std::_Tuple_impl<_Idx, _Head, _Tail ...>&)
    __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept
    ^~~~~~~~~~~~

include/c++/7.0.1/tuple:1295:5:
note:   template argument deduction/substitution failed:
include/c++/7.0.1/tuple:1302:36:
note:   ‘const std::_Tuple_impl<0, _Head, _Tail ...>’ is an ambiguous base class of ‘std::tuple<X>’
    { return std::__get_helper<__i>(__t); }
            ~~~~~~~~~~~~~~~~~~~~~~^~~~~

It seems that libstdc++'s inheritance-based implementation of std::tuple causes ambiguity when tuple elements derive from std::tuple upon calling std::get. I'm inclined to think that this is an implementation defect in libstdc++ - is that the case? Or is there something in the Standard that would make the code snippet ill-formed?


问:
How does uboot print information during board bring up
During bootup of the target board we see uboot (bootloader) printing some information such as Image name, Image type, Load Address, Verifying checksum etc on the console. Which printing mechanism does it use? Does it use something like printk or it has its own definition for printing info even before kernel boots up? Where can I find the code for its printing implementation?

答:
In the normal U-boot boot process,a limited amount of information is printed to the console. It use the the same kind of functions to print information as we use during the C programming.

u-boot use printf and puts to print the information on the console. you can find the same function implementations in the u-boot source code (u-boot boardfile and drivers).

There are a lot of commands which you can try from u-boot command prompts for more information.

To enable more messages you can either:

Using debug_cond (cond, fmt, args...): if you define some cond, once it is met, the U-boot will print out this message.

Using debug(fmt, args...): you can define DEBUG in the file u-boot-include/configs/<boardfile>_common.h (like in my case mx6_common.h), once do that and recompile the code, the U-boot will print out all debug message

Note:  If you put too much debug into the code, it might make u-boot hang up.


问:
Java Generics: Who is right, javac or Eclipse compile?
Calling this method:

```<code>public static @Nonnull <TV, TG extends TV> Maybe<TV> something(final @Nonnull TG value) {
    return new Maybe<TV>(value);
}
</code>```

like this:

```<code>public @Nonnull Maybe<Foo> visit() {
    return Maybe.something(new BarExtendsFoo());
}
</code>```

compiles just fine in Eclipse, but javac gives an "incompatable types" warning:

```<code>found   : BarExtendsFoo
</code>```

required: Foo

答:
Two comments:

a. As you mentioned in one of your comments, The TG type parameter in something()'s signature is not necessary at all, as there is nothing specific to the subclass TG that you're doing in the method.

b. The easiest soluion to this would be to help the compiler to understand which type you're using by explicitly assigning the newly created object to a variable (which is usually good practice anyway). It's now clearer to both the compiler and human readers how you'd like to call the method:

```<code>public @Nonnull Maybe<Foo> visit() {
    final Foo bar = new BarExtendsFoo();
    return Maybe.something(bar);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Calling this method:

public static @Nonnull <TV, TG extends TV> Maybe<TV> something(final @Nonnull TG value) {
    return new Maybe<TV>(value);
}

like this:

public @Nonnull Maybe<Foo> visit() {
    return Maybe.something(new BarExtendsFoo());
}

compiles just fine in Eclipse, but javac gives an "incompatable types" warning:

found   : BarExtendsFoo

required: Foo

Body:
Two comments:

a. As you mentioned in one of your comments, The TG type parameter in something()'s signature is not necessary at all, as there is nothing specific to the subclass TG that you're doing in the method.

b. The easiest soluion to this would be to help the compiler to understand which type you're using by explicitly assigning the newly created object to a variable (which is usually good practice anyway). It's now clearer to both the compiler and human readers how you'd like to call the method:

public @Nonnull Maybe<Foo> visit() {
    final Foo bar = new BarExtendsFoo();
    return Maybe.something(bar);
}


问:
What's the pythonic way to pass arguments between functions?
I have some arguments taken from the user and passed along function to function (each function in a different class), until it eventually gets to a function that does some processing and then the solution is returned up the chain. Up the chain, the functions become more and more abstract merging results from multiple runs of the lower functions.

Where should I use *args and **kwargs?

I think *args and *kwargs can be used for every function where the function doesn't use the arguments explicitly. But, the actual arguments need to be defined at the top_level so that the user knows what the function expects.

Where should I define what the inputs mean?

I think they should be defined at the top_level because that's the one the end-user might want to see the documentation for.

Where should I define what default values?

Again, I think they should be defined at the top_level because that's the one the end-user interacts with.

This is a simple example to demonstrate the passing of the arguments, where I haven't shown how the functions become more and more abstract or how they interact with different classes, as I felt it was unnecessary detail.

```<code>def top_level(a=1, b=1, c=1, d=1, e=1):
    """ Compute sum of five numbers.
    :param a: int, a
    :param b: int, b
    :param c: int, c
    :param d: int, d
    :param e: int, e
    :return: int, sum
    """
    return mid_level(a, b, c, d, e)

def mid_level(*args, **kwargs):
    return bottom_level(*args, **kwargs)

def bottom_level(a, b, c, d, e):
    return a + b + c + d + e

print top_level(1, 2, 3)
8
</code>```

Is there a Python convention for passing arguments like this?

答:
I would argue that passing arguments down several levels of functions is not pythonic in itself.

From the Zen of Python:

Simple is better than complex

Flat is better than nested

Edit:

If there are a lot of arguments and the functions inbetween just pass them down, I would probably wrap them up in a tuple and unwrap them at the lowest level.

Body:
I have some arguments taken from the user and passed along function to function (each function in a different class), until it eventually gets to a function that does some processing and then the solution is returned up the chain. Up the chain, the functions become more and more abstract merging results from multiple runs of the lower functions.

Where should I use *args and **kwargs?

I think *args and *kwargs can be used for every function where the function doesn't use the arguments explicitly. But, the actual arguments need to be defined at the top_level so that the user knows what the function expects.

Where should I define what the inputs mean?

I think they should be defined at the top_level because that's the one the end-user might want to see the documentation for.

Where should I define what default values?

Again, I think they should be defined at the top_level because that's the one the end-user interacts with.

This is a simple example to demonstrate the passing of the arguments, where I haven't shown how the functions become more and more abstract or how they interact with different classes, as I felt it was unnecessary detail.

def top_level(a=1, b=1, c=1, d=1, e=1):
    """ Compute sum of five numbers.
    :param a: int, a
    :param b: int, b
    :param c: int, c
    :param d: int, d
    :param e: int, e
    :return: int, sum
    """
    return mid_level(a, b, c, d, e)

def mid_level(*args, **kwargs):
    return bottom_level(*args, **kwargs)

def bottom_level(a, b, c, d, e):
    return a + b + c + d + e

print top_level(1, 2, 3)
8

Is there a Python convention for passing arguments like this?


问:
How to open a new page inside component on button click in angular2?
dashboard.component.ts file

import { Injectable } from '@angular/core';
import {Router} from '@angular/router';
import {Http, Headers, Response,RequestOptions} from '@angular/http';
import { Component } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Rx';

import { Login }    from './login';

@Component({
  moduleId: module.id,
  selector: 'dashboard',
  templateUrl: './dashboard.html',
  template : '<router-outlet></router-outlet>'
})

export class DashboardComponent {

}
```

<p>module.ts file in which I have defined routes</p>

<pre class="lang-ts prettyprint-override"><code> import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import {Router} from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent }          from './app.component';
import { LoginFormComponent } from './login-form.component';
import { DashboardComponent } from './dashboard.component';
const appRoutes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
];
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
    RouterModule.forRoot(appRoutes)
  ],
  declarations: [
    AppComponent,
  LoginFormComponent,
  DashboardComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

I am new to angular2, and I am designing a login page. Now I want to open a new page when user is properly authenticated after clicking on submit button . Please suggest me some alternatives of how should I do this? Below is the login.component.ts file . Thanks
Updated code

    import { Injectable } from '@angular/core';
    import {Router} from '@angular/router';
    import {Http, Headers, Response,RequestOptions} from '@angular/http';
    import { Component } from '@angular/core';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import {Observable} from 'rxjs/Rx';
    import { Login }    from './login';
    @Component({
      moduleId: module.id,
      selector: 'login-form',
      templateUrl: './login-form.component.html',
    })

    export class LoginFormComponent {
         constructor (private http: Http,private _router:Router) {}
        data = {
            'email': '',
               'password': ''
        };
        formSubmit (body: Object): Observable<Login[]>{
           let bodyString = JSON.stringify(body);
            let headers      = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); // ... Set content type to JSON
            let options       = new RequestOptions({ headers: headers });
           var params = "username=" + this.data.email + "&password=" + this.data.password;
           var resp = this.http.post("http://localhost:8000/login", params, options) // ...using post request
                             .subscribe((res:Response) => {
                                 if(res.json().status_code == 200)
                                 {
                                                          this._router.navigate(["../dashboard"]);
                                     console.log("success");
                                 }
                                 } );
                             return;
    }
    }
```

答:
use

```<code>constructor (private http: Http,private _router:Router) {}

if(res.json().status_code == 200)
{
 this._router.navigate(["../Dashboard"]);
}
</code>```

This will redirect user to Dashboard , defined in routes.

If you want to learn more about : Router

Inside module :

```<code>const appRoutes: Routes = [
  { path: 'dashbaord', component: DashboardComponent }
];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  .......
})
</code>```

Body:
dashboard.component.ts file

import { Injectable } from '@angular/core';
import {Router} from '@angular/router';
import {Http, Headers, Response,RequestOptions} from '@angular/http';
import { Component } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Rx';

import { Login }    from './login';

@Component({
  moduleId: module.id,
  selector: 'dashboard',
  templateUrl: './dashboard.html',
  template : '<router-outlet></router-outlet>'
})

export class DashboardComponent {

}

module.ts file in which I have defined routes

 import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import {Router} from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent }          from './app.component';
import { LoginFormComponent } from './login-form.component';
import { DashboardComponent } from './dashboard.component';
const appRoutes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
];
@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
    RouterModule.forRoot(appRoutes)
  ],
  declarations: [
    AppComponent,
  LoginFormComponent,
  DashboardComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

I am new to angular2, and I am designing a login page. Now I want to open a new page when user is properly authenticated after clicking on submit button . Please suggest me some alternatives of how should I do this? Below is the login.component.ts file . Thanks
Updated code

    import { Injectable } from '@angular/core';
    import {Router} from '@angular/router';
    import {Http, Headers, Response,RequestOptions} from '@angular/http';
    import { Component } from '@angular/core';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import {Observable} from 'rxjs/Rx';
    import { Login }    from './login';
    @Component({
      moduleId: module.id,
      selector: 'login-form',
      templateUrl: './login-form.component.html',
    })

    export class LoginFormComponent {
         constructor (private http: Http,private _router:Router) {}
        data = {
            'email': '',
               'password': ''
        };
        formSubmit (body: Object): Observable<Login[]>{
           let bodyString = JSON.stringify(body);
            let headers      = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); // ... Set content type to JSON
            let options       = new RequestOptions({ headers: headers });
           var params = "username=" + this.data.email + "&password=" + this.data.password;
           var resp = this.http.post("http://localhost:8000/login", params, options) // ...using post request
                             .subscribe((res:Response) => {
                                 if(res.json().status_code == 200)
                                 {
                                                          this._router.navigate(["../dashboard"]);
                                     console.log("success");
                                 }
                                 } );
                             return;
    }
    }

Body:
use

constructor (private http: Http,private _router:Router) {}

if(res.json().status_code == 200)
{
 this._router.navigate(["../Dashboard"]);
}

This will redirect user to Dashboard , defined in routes.

If you want to learn more about : Router

Inside module :

const appRoutes: Routes = [
  { path: 'dashbaord', component: DashboardComponent }
];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  .......
})


问:
Are all event handlers always called when unsubscribing other handlers within a handler?
I wrote a test that shows that when invoking an event, all handlers are called even though one of the handlers (not the last one) unsubscribe all the handlers.

The test is in this gist, repeated below.

My question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on? Or is it perhaps just due to some peculiarities of how I've written the test?

```<code>namespace EventUnsubscriptionTest
{
    using System;

    using NUnit.Framework;

    public class EventSource
    {
        public event Action Event;

        public void TriggerEvent()
        {
            this.Event?.Invoke();
        }
    }

    public class EventSourceTests
    {
        [Test]
        public void When_Unsubscribing_Should_InvokeAllBeforeUnsubscribing()
        {
            // Arrange
            var invokeCounter = 0;
            var listener1InvokedOrder = 0;
            var listener2InvokedOrder = 0;
            var listener3InvokedOrder = 0;

            var sut = new EventSource();

            Action listener1 = null;
            Action listener2 = null;
            Action listener3 = null;

            listener1 = () => listener1InvokedOrder = ++invokeCounter;
            listener2 = () =>
            {
                listener2InvokedOrder = ++invokeCounter;
                sut.Event -= listener1;
                sut.Event -= listener2;
                sut.Event -= listener3;
            };

            listener3 = () => listener3InvokedOrder = ++invokeCounter;

            sut.Event += listener1;
            sut.Event += listener2;
            sut.Event += listener3;

            // Act
            sut.TriggerEvent();

            // Assert
            Assert.That(listener1InvokedOrder, Is.EqualTo(1));
            Assert.That(listener2InvokedOrder, Is.EqualTo(2));
            Assert.That(listener3InvokedOrder, Is.EqualTo(3));

            // Ensure that we actually unsubscribed
            sut.TriggerEvent();
            Assert.That(invokeCounter, Is.EqualTo(3));
        }
    }
}
</code>```

答:
Yes, this is the expected behavior, because multicast delegates are immutable.

From MSDN:

Delegates are immutable; once created, the invocation list of a delegate does not change.

Thus, any ongoing invocation of the multicast delegate (event handlers) will not be affected by subscriptions and unsubscriptions in the delegates (or generally between calling the first and last delegates). All handlers at the time of Invoke() will get called (barring any thrown exceptions in the handlers). More details in this answer.

Body:
I wrote a test that shows that when invoking an event, all handlers are called even though one of the handlers (not the last one) unsubscribe all the handlers.

The test is in this gist, repeated below.

My question is: Is this behavior expected and documented (I haven't found any mention of it), and can it be counted on? Or is it perhaps just due to some peculiarities of how I've written the test?

namespace EventUnsubscriptionTest
{
    using System;

    using NUnit.Framework;

    public class EventSource
    {
        public event Action Event;

        public void TriggerEvent()
        {
            this.Event?.Invoke();
        }
    }

    public class EventSourceTests
    {
        [Test]
        public void When_Unsubscribing_Should_InvokeAllBeforeUnsubscribing()
        {
            // Arrange
            var invokeCounter = 0;
            var listener1InvokedOrder = 0;
            var listener2InvokedOrder = 0;
            var listener3InvokedOrder = 0;

            var sut = new EventSource();

            Action listener1 = null;
            Action listener2 = null;
            Action listener3 = null;

            listener1 = () => listener1InvokedOrder = ++invokeCounter;
            listener2 = () =>
            {
                listener2InvokedOrder = ++invokeCounter;
                sut.Event -= listener1;
                sut.Event -= listener2;
                sut.Event -= listener3;
            };

            listener3 = () => listener3InvokedOrder = ++invokeCounter;

            sut.Event += listener1;
            sut.Event += listener2;
            sut.Event += listener3;

            // Act
            sut.TriggerEvent();

            // Assert
            Assert.That(listener1InvokedOrder, Is.EqualTo(1));
            Assert.That(listener2InvokedOrder, Is.EqualTo(2));
            Assert.That(listener3InvokedOrder, Is.EqualTo(3));

            // Ensure that we actually unsubscribed
            sut.TriggerEvent();
            Assert.That(invokeCounter, Is.EqualTo(3));
        }
    }
}


问:
In PowerShell, how can I test if a variable holds a numeric value?
In PowerShell, how can I test if a variable holds a numeric value?

Currently, I'm trying to do it like this, but it always seems to return false.

```<code>add-type -Language CSharpVersion3 @'
    public class Helpers {
        public static bool IsNumeric(object o) {
            return o is byte  || o is short  || o is int  || o is long
                || o is sbyte || o is ushort || o is uint || o is ulong
                || o is float || o is double || o is decimal
                ;
        }
    }
'@

filter isNumeric($InputObject) {
    [Helpers]::IsNumeric($InputObject)
}

PS> 1 | isNumeric
False
</code>```

答:
```<code>filter isNumeric {
    $_ -is [ValueType]
}
</code>```

-

```<code>1 -is [ValueType]
True
"1" -is [ValueType]
False
</code>```

-

```<code>function isNumeric ($Value) {
    return $Value -is [ValueType]
}

isNumeric 1.23
True
isNumeric 123
True
isNumeric ""
False
isNumeric "asdf123"
False
</code>```

-

```<code>(Invoke-Expression '1.5') -is [ValueType]
</code>```

Body:
In PowerShell, how can I test if a variable holds a numeric value?

Currently, I'm trying to do it like this, but it always seems to return false.

add-type -Language CSharpVersion3 @'
    public class Helpers {
        public static bool IsNumeric(object o) {
            return o is byte  || o is short  || o is int  || o is long
                || o is sbyte || o is ushort || o is uint || o is ulong
                || o is float || o is double || o is decimal
                ;
        }
    }
'@

filter isNumeric($InputObject) {
    [Helpers]::IsNumeric($InputObject)
}

PS> 1 | isNumeric
False

Body:
filter isNumeric {
    $_ -is [ValueType]
}

-

1 -is [ValueType]
True
"1" -is [ValueType]
False

-

function isNumeric ($Value) {
    return $Value -is [ValueType]
}

isNumeric 1.23
True
isNumeric 123
True
isNumeric ""
False
isNumeric "asdf123"
False

-

(Invoke-Expression '1.5') -is [ValueType]


问:
Recommended structure for high traffic website
I'm rewriting a big website, that needs very solid architecture, here are my few questions, and pardon me for mixing apples and oranges and probably kiwi too:) I did a lot of research and ended up totally confused.

Main question: Which approach would you take in building a big website expected to grow in every way?

Single entry point, pages data in the database, pulled by associating GET variable with database entry (?pageid=whatever)

Single entry point, pages data in separate files, included based on GET variable (?pageid=whatever would include whatever.php)

MVC (Alright guys, I'm all for it, but can't grasp the concept besides checking all tutorials and frameworks out there, do they store "view" in database? Seems to me from examples that if you have 1000 pages of same kind they can be shaped by 1 model, but I'll still need to have 1000 "views" files?)

PAC - this sounds even more logical to me, but didn't find much resources - if this is a good way to go, can you recommend any books or links?

DAL/DAO/DDD - i learned about these terms by diligently reading through stack overflow before posting question. Not sure if it belongs to this list

Sit down and create my own architecture (likely to do if nobody enlightens me here:)

Something not mentioned...

Thanks.

答:
I'm a fan of MVC because I've found it easier to scale your team when everything has a place and is nice and compartmentalized. It takes some getting used to, but the easiest way to get a handle on it is to dive in.

That said definitely check your local library to see if they have the O'Reilley book on scaling: http://oreilly.com/catalog/9780596102357 which is a good place to start.


问:
Add Branding Images in salesforce TrailHead
I am working on SalesForce TrailHead: https://trailhead.salesforce.com/projects/build_branded_chat/steps/build_branded_chat_build and looking to implement the Add Branding Images.

答: Yes, I got the solution to the above problem. First load all the required static resources.


问:
sum rows in a nested list in R
I have a nested list coming out of a program its length is 100. I need to sum all elements of first row and all elements of 2nd row. Here a a small reproducible example. What I need is sum of 1+3+5+7= 16 and sum of 2+4+6+8= 20 as a vector or matrix. </p>

```<code> l1<-as.matrix(c(1,2))
 l2<-as.matrix(c(3,4))
 l3<-as.matrix(c(5,6))
 l4<-as.matrix(c(7,8))
 ll1<-list(l1,l2)
 ll2<-list(l3,l4)
 lll<-list(ll1,ll2)

   lll
 [[1]]
 [[1]][[1]]
      [,1]
 [1,]    1
 [2,]    2

 [[1]][[2]]
      [,1]
 [1,]    3
 [2,]    4

 [[2]]
 [[2]][[1]]
      [,1]
 [1,]    5
 [2,]    6

 [[2]][[2]]
      [,1]
 [1,]    7
 [2,]    8
</code>```

答:
Reducein base R:

```<code>Reduce("+", lapply(Reduce(c, lll), rowSums))
#[1] 16 20
</code>```

Title: sum rows in a nested list in R

Body:
I have a nested list coming out of a program its length is 100. I need to sum all elements of first row and all elements of 2nd row. Here a a small reproducible example. What I need is sum of 1+3+5+7= 16 and sum of 2+4+6+8= 20 as a vector or matrix.

 l1<-as.matrix(c(1,2))
 l2<-as.matrix(c(3,4))
 l3<-as.matrix(c(5,6))
 l4<-as.matrix(c(7,8))
 ll1<-list(l1,l2)
 ll2<-list(l3,l4)
 lll<-list(ll1,ll2)

   lll
 [[1]]
 [[1]][[1]]
      [,1]
 [1,]    1
 [2,]    2

 [[1]][[2]]
      [,1]
 [1,]    3
 [2,]    4

 [[2]]
 [[2]][[1]]
      [,1]
 [1,]    5
 [2,]    6

 [[2]][[2]]
      [,1]
 [1,]    7
 [2,]    8

Body:
Reducein base R:

Reduce("+", lapply(Reduce(c, lll), rowSums))
#[1] 16 20


问:
How to create a method that counts how large a group is in an array?
I need some help making my Java method (getNumGroupsOfSize) work. It should tally how large an array "group" (consecutive elements that share the same value) is, and then print out how many other groups share that size. So for example, array [1,1,1,2,2,2,3,3,3,4,5,6,7] would print:

```<code>size 1=4

size 3=3
</code>```

and then would stop running.

This is what I have so far:

```<code>import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats {
  int[] numArray;
  int number;

  public ArrayStats(int[] array) {
    setArray(array);
  }

  public void setArray(int[] array) {
    numArray = array;
  }

  public int getNumGroupsOfSize() {
    int cnt = 0;
    for (int x = 0; x < numArray.length - 1; x++) {
    if (numArray[x] == numArray[x + 1]);
    cnt++;
    for (int y = 2; y <= 9; y++) {
      if (cnt == y)
        number = cnt;
      else if (cnt == 1)
        number = 1;
    }
  }
  return number;
}

public String toString() {
  return "size count" + " == " + getNumGroupsOfSize() + Arrays.toString(numArray);
}
}
</code>```

I'm pretty sure my getNumGroupsOfSize is not coded correctly, but I'm not sure how to make it work. I would genuinely appreciate any help that can be offered. If you need any more information, don't hesitate to comment. Thank you!

答:
For each encountered series, you have to count its size and update the information about how many series has this size.

So the int number field you are using is clearly not enough to achieve it as it persists only a very elementary information.

In your case, you need to have two associated information : for each series size, you want to know the number of series that have this size.

A Map object should do the job.
It would use as key the size of the series and as value the number of series that have this size.

```<code>Map<Integer, Integer> occurrenceBySeriesSize = new HashMap<>();
</code>```

At each time an encountered series is finished, update the map with the new count :

```<code> int serieSize = ...;

 Integer occurrences = occurrenceBySeriesSize.get(serieSize);
 if (occurrences == null){
    occurrences = 0;
 }
 occurrenceBySeriesSize.put(serieSize, ++occurrences);
</code>```

Body:
I need some help making my Java method (getNumGroupsOfSize) work. It should tally how large an array "group" (consecutive elements that share the same value) is, and then print out how many other groups share that size. So for example, array [1,1,1,2,2,2,3,3,3,4,5,6,7] would print:

size 1=4

size 3=3

and then would stop running.

This is what I have so far:

import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats {
  int[] numArray;
  int number;

  public ArrayStats(int[] array) {
    setArray(array);
  }

  public void setArray(int[] array) {
    numArray = array;
  }

  public int getNumGroupsOfSize() {
    int cnt = 0;
    for (int x = 0; x < numArray.length - 1; x++) {
    if (numArray[x] == numArray[x + 1]);
    cnt++;
    for (int y = 2; y <= 9; y++) {
      if (cnt == y)
        number = cnt;
      else if (cnt == 1)
        number = 1;
    }
  }
  return number;
}

public String toString() {
  return "size count" + " == " + getNumGroupsOfSize() + Arrays.toString(numArray);
}
}

I'm pretty sure my getNumGroupsOfSize is not coded correctly, but I'm not sure how to make it work. I would genuinely appreciate any help that can be offered. If you need any more information, don't hesitate to comment. Thank you!

Body:
For each encountered series, you have to count its size and update the information about how many series has this size.

So the int number field you are using is clearly not enough to achieve it as it persists only a very elementary information.

In your case, you need to have two associated information : for each series size, you want to know the number of series that have this size.

A Map object should do the job.
It would use as key the size of the series and as value the number of series that have this size.

Map<Integer, Integer> occurrenceBySeriesSize = new HashMap<>();

At each time an encountered series is finished, update the map with the new count :

 int serieSize = ...;

 Integer occurrences = occurrenceBySeriesSize.get(serieSize);
 if (occurrences == null){
    occurrences = 0;
 }
 occurrenceBySeriesSize.put(serieSize, ++occurrences);


问:
Static ArrayList always Replacing the older values
i have class in which i declare a static variable id

```<code>class id
{
  private static int id;
  public int getid()
 {
  return this.id
 }
public void setid(int id)
 {
    this.id=id;
 }
}
</code>```

i have another class in which i create the object of this class and call these methods

```<code>class abc
{
    id obj=new id();
      int a=obj.getid();
    obj.setid(a+1);

}
</code>```

now i am storing it to an static ArrayList in another class

```<code>class ser
{
  private static ArrayList<id>al=new ArrayList<id>();

  public static addid(id obj)
 {
   al.add(obj);
 }
}
</code>```

now the problem is that it replaces the object every time i add the object to the list what is the error please help

答: All the objects id have the same value for the variable id because it is a static member of the class. So when you add several instances of the class id to the list, all instances have the same value for id. Are you sure you want the variable id to be static?</p>

Body:
i have class in which i declare a static variable id

class id
{
  private static int id;
  public int getid()
 {
  return this.id
 }
public void setid(int id)
 {
    this.id=id;
 }
}

i have another class in which i create the object of this class and call these methods

class abc
{
    id obj=new id();
      int a=obj.getid();
    obj.setid(a+1);

}

now i am storing it to an static ArrayList in another class

class ser
{
  private static ArrayList<id>al=new ArrayList<id>();

  public static addid(id obj)
 {
   al.add(obj);
 }
}

now the problem is that it replaces the object every time i add the object to the list what is the error please help


问:
How to text filter an Android ListView backed by a SimpleCursorAdapter?
I have a ListView that is backed by a SimpleCursorAdapter.

I'd like to be able to filter the list like you would a contacts list, just by typing, and I came across the textFilterEnabled()

Problem is, I couldn't see how to get it to work with a SimpleCursorAdapter.

Is this even possible?

If so, how is it done?

答:
i found this article helpful http://androidcookbook.oreilly.com/Recipe.seam;jsessionid=CE37400B3E545937B70BE2E9F94E78BB?recipeId=404

basically, you setTextFilterEnabled(true) on your listview, and you use setStringConversionColumn() and setFilterQueryProvider() on your SimpleCursorAdapter.