问:
Can this Entity Framework Query be improved for performance?
* UPDATE *

I am unable to delete this question even though it was actually not a problem in the long run... I still had some code from when I was working on it that did separate queries and populated some of these fields... when I stripped out that code... the following query runs very fast (2 seconds):

```<code>public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}
</code>```

* ORIGINAL QUESTION *

I am trying to load a list of users (about 600 of them) using Entity Framework… I want to preload with the query account records for each user and a broker record for each account (along with roles for each user)… this SQL gets me results very quickly ( < 1 second):

```<code>select ISNULL(ur.RoleId, 0) as IsAdmin, u.*, a.*, b.*
  from AspNetUsers u
 inner join Accounts a on u.Id = a.ClientId
 inner join Brokers b on a.Brokerid = b.BrokerId
 left outer join AspNetUserRoles ur on u.id = ur.UserId and ur.RoleId = 1
order by u.UserName
</code>```

But this Entity Framework query takes a long time (something like 20 - 25 seconds)... especially in production where the database is on a different server:

```<code>public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}
</code>```

Any thoughts on how the Entity Framework query could be improved and/or what it would take to get it to be faster like the native SQL query is?. (Note: I do need all the data from all the above object for my list so lazy loading isn’t going to help.) I was hoping it would generate a single query along the lines of what I show above… but it is generating several queries (below) for each user it seems.

I eventually want to use this IQueryable to get paginated data as well.

My objects are defined like this:

```<code>public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>/
{
    public List<Account> Accounts { get; set; }
…
    public bool isAdmin { get {  return this.Roles != null && this.Roles.Any(r => r.RoleId == 1); } }
…
}

public class Account
{
    public int AccountId { get; set; }
…
    public int BrokerId { get; set; }
    public virtual Broker Broker { get; set; }
…
}

public class Broker
{
    public int BrokerId { get; set; }
    public string Name { get; set; }
…
}
</code>```

With the entity framework query using SQL Server profiler I see one of these:

```<code>SELECT
[Project1].[Id] AS [Id],
[Project1].[UserName] AS [UserName],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[PhoneNumber] AS [PhoneNumber],
[Project1].[Email] AS [Email],
[Project1].[Address] AS [Address],
[Project1].[City] AS [City],
[Project1].[State] AS [State],
[Project1].[Zip] AS [Zip],
[Project1].[DateAdded] AS [DateAdded],
[Project1].[IsActive] AS [IsActive],
[Project1].[C1] AS [C1],
[Project1].[AccountId] AS [AccountId],
[Project1].[ClientId] AS [ClientId],
[Project1].[BrokerId] AS [BrokerId],
[Project1].[AccountNumber] AS [AccountNumber],
[Project1].[BrokerUserName] AS [BrokerUserName],
[Project1].[BrokerPasswordHash] AS [BrokerPasswordHash],
[Project1].[EquityCurve] AS [EquityCurve],
[Project1].[CapitalInvested] AS [CapitalInvested],
[Project1].[IsSimulated] AS [IsSimulated],
[Project1].[ClosedProfit] AS [ClosedProfit],
[Project1].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
[Project1].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
[Project1].[ActivatedOn] AS [ActivatedOn]
FROM ( SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[FirstName] AS [FirstName],
    [Extent1].[LastName] AS [LastName],
    [Extent1].[Address] AS [Address],
    [Extent1].[Zip] AS [Zip],
    [Extent1].[City] AS [City],
    [Extent1].[State] AS [State],
    [Extent1].[DateAdded] AS [DateAdded],
    [Extent1].[IsActive] AS [IsActive],
    [Extent1].[Email] AS [Email],
    [Extent1].[PhoneNumber] AS [PhoneNumber],
    [Extent1].[UserName] AS [UserName],
    [Extent2].[AccountId] AS [AccountId],
    [Extent2].[ClientId] AS [ClientId],
    [Extent2].[BrokerId] AS [BrokerId],
    [Extent2].[AccountNumber] AS [AccountNumber],
    [Extent2].[BrokerUserName] AS [BrokerUserName],
    [Extent2].[BrokerPasswordHash] AS [BrokerPasswordHash],
    [Extent2].[EquityCurve] AS [EquityCurve],
    [Extent2].[CapitalInvested] AS [CapitalInvested],
    [Extent2].[IsSimulated] AS [IsSimulated],
    [Extent2].[ClosedProfit] AS [ClosedProfit],
    [Extent2].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
    [Extent2].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
    [Extent2].[ActivatedOn] AS [ActivatedOn],
    CASE WHEN ([Extent2].[AccountId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM  [dbo].[AspNetUsers] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Accounts] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ClientId]
)  AS [Project1]
ORDER BY [Project1].[UserName] ASC, [Project1].[Id] ASC, [Project1].[C1] ASC
</code>```

Then seemingly one of these for each user:

```<code>SELECT TOP (1)
[Extent1].[BrokerId] AS [BrokerId],
[Extent1].[Name] AS [Name],
[Extent1].[Code] AS [Code],
[Extent1].[IsExternal] AS [IsExternal]
FROM [dbo].[Brokers] AS [Extent1]
WHERE [Extent1].[BrokerId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=2
</code>```

And also one of these for each user:

```<code>SELECT
[Project2].[Id] AS [Id],
[Project2].[ReferralId] AS [ReferralId],
[Project2].[FirstName] AS [FirstName],
[Project2].[LastName] AS [LastName],
[Project2].[Address] AS [Address],
[Project2].[Address2] AS [Address2],
[Project2].[Zip] AS [Zip],
[Project2].[City] AS [City],
[Project2].[StateProvince] AS [StateProvince],
[Project2].[Country] AS [Country],
[Project2].[State] AS [State],
[Project2].[startPopupChecked] AS [startPopupChecked],
[Project2].[DateAdded] AS [DateAdded],
[Project2].[CurrentPortfolioId] AS [CurrentPortfolioId],
[Project2].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
[Project2].[NotificationMobileNumber] AS [NotificationMobileNumber],
[Project2].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
[Project2].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
[Project2].[IsActive] AS [IsActive],
[Project2].[HasSeen] AS [HasSeen],
[Project2].[Email] AS [Email],
[Project2].[EmailConfirmed] AS [EmailConfirmed],
[Project2].[PasswordHash] AS [PasswordHash],
[Project2].[SecurityStamp] AS [SecurityStamp],
[Project2].[PhoneNumber] AS [PhoneNumber],
[Project2].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project2].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project2].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project2].[LockoutEnabled] AS [LockoutEnabled],
[Project2].[AccessFailedCount] AS [AccessFailedCount],
[Project2].[UserName] AS [UserName],
[Project2].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
[Project2].[C1] AS [C1],
[Project2].[UserId] AS [UserId],
[Project2].[RoleId] AS [RoleId]
FROM ( SELECT
    [Limit1].[Id] AS [Id],
    [Limit1].[ReferralId] AS [ReferralId],
    [Limit1].[FirstName] AS [FirstName],
    [Limit1].[LastName] AS [LastName],
    [Limit1].[Address] AS [Address],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[Zip] AS [Zip],
    [Limit1].[City] AS [City],
    [Limit1].[StateProvince] AS [StateProvince],
    [Limit1].[Country] AS [Country],
    [Limit1].[State] AS [State],
    [Limit1].[startPopupChecked] AS [startPopupChecked],
    [Limit1].[DateAdded] AS [DateAdded],
    [Limit1].[CurrentPortfolioId] AS [CurrentPortfolioId],
    [Limit1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
    [Limit1].[NotificationMobileNumber] AS [NotificationMobileNumber],
    [Limit1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
    [Limit1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
    [Limit1].[IsActive] AS [IsActive],
    [Limit1].[HasSeen] AS [HasSeen],
    [Limit1].[Email] AS [Email],
    [Limit1].[EmailConfirmed] AS [EmailConfirmed],
    [Limit1].[PasswordHash] AS [PasswordHash],
    [Limit1].[SecurityStamp] AS [SecurityStamp],
    [Limit1].[PhoneNumber] AS [PhoneNumber],
    [Limit1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Limit1].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Limit1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Limit1].[LockoutEnabled] AS [LockoutEnabled],
    [Limit1].[AccessFailedCount] AS [AccessFailedCount],
    [Limit1].[UserName] AS [UserName],
    [Limit1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
    [Extent2].[UserId] AS [UserId],
    [Extent2].[RoleId] AS [RoleId],
    CASE WHEN ([Extent2].[UserId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM   (SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[ReferralId] AS [ReferralId],
        [Extent1].[FirstName] AS [FirstName],
        [Extent1].[LastName] AS [LastName],
        [Extent1].[Address] AS [Address],
        [Extent1].[Address2] AS [Address2],
        [Extent1].[Zip] AS [Zip],
        [Extent1].[City] AS [City],
        [Extent1].[StateProvince] AS [StateProvince],
        [Extent1].[Country] AS [Country],
        [Extent1].[State] AS [State],
        [Extent1].[startPopupChecked] AS [startPopupChecked],
        [Extent1].[DateAdded] AS [DateAdded],
        [Extent1].[CurrentPortfolioId] AS [CurrentPortfolioId],
        [Extent1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
        [Extent1].[NotificationMobileNumber] AS [NotificationMobileNumber],
        [Extent1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
        [Extent1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
        [Extent1].[IsActive] AS [IsActive],
        [Extent1].[HasSeen] AS [HasSeen],
        [Extent1].[Email] AS [Email],
        [Extent1].[EmailConfirmed] AS [EmailConfirmed],
        [Extent1].[PasswordHash] AS [PasswordHash],
        [Extent1].[SecurityStamp] AS [SecurityStamp],
        [Extent1].[PhoneNumber] AS [PhoneNumber],
        [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Extent1].[LockoutEnabled] AS [LockoutEnabled],
        [Extent1].[AccessFailedCount] AS [AccessFailedCount],
        [Extent1].[UserName] AS [UserName],
        [Extent1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId]
        FROM [dbo].[AspNetUsers] AS [Extent1]
        WHERE [Extent1].[Id] = @p__linq__0 ) AS [Limit1]
    LEFT OUTER JOIN [dbo].[AspNetUserRoles] AS [Extent2] ON [Limit1].[Id] = [Extent2].[UserId]
)  AS [Project2]
ORDER BY [Project2].[Id] ASC, [Project2].[C1] ASC',N'@p__linq__0 int',@p__linq__0=346
</code>```

答:
You can use .FromSql and pass in the query you want. Or you can use a View (unless using EF Core of course) that encapsulates your query.

Honestly though, if performance is a concern you are much better off using something like Dapper or Chain. Even for basic CRUD operations EF is significantly slower than the other two.

Body:
* UPDATE *

I am unable to delete this question even though it was actually not a problem in the long run... I still had some code from when I was working on it that did separate queries and populated some of these fields... when I stripped out that code... the following query runs very fast (2 seconds):

public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}

* ORIGINAL QUESTION *

I am trying to load a list of users (about 600 of them) using Entity Framework… I want to preload with the query account records for each user and a broker record for each account (along with roles for each user)… this SQL gets me results very quickly ( < 1 second):

select ISNULL(ur.RoleId, 0) as IsAdmin, u.*, a.*, b.*
  from AspNetUsers u
 inner join Accounts a on u.Id = a.ClientId
 inner join Brokers b on a.Brokerid = b.BrokerId
 left outer join AspNetUserRoles ur on u.id = ur.UserId and ur.RoleId = 1
order by u.UserName

But this Entity Framework query takes a long time (something like 20 - 25 seconds)... especially in production where the database is on a different server:

public IQueryable<ApplicationUser> QueriableUsersList()
{
    return _context.Users.OrderBy(u => u.UserName)
        .Include(u => u.Accounts.Select(a => a.Broker))
        .Include(u => u.Roles);
}

Any thoughts on how the Entity Framework query could be improved and/or what it would take to get it to be faster like the native SQL query is?. (Note: I do need all the data from all the above object for my list so lazy loading isn’t going to help.) I was hoping it would generate a single query along the lines of what I show above… but it is generating several queries (below) for each user it seems.

I eventually want to use this IQueryable to get paginated data as well.

My objects are defined like this:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>/
{
    public List<Account> Accounts { get; set; }
…
    public bool isAdmin { get {  return this.Roles != null && this.Roles.Any(r => r.RoleId == 1); } }
…
}

public class Account
{
    public int AccountId { get; set; }
…
    public int BrokerId { get; set; }
    public virtual Broker Broker { get; set; }
…
}

public class Broker
{
    public int BrokerId { get; set; }
    public string Name { get; set; }
…
}

With the entity framework query using SQL Server profiler I see one of these:

SELECT
[Project1].[Id] AS [Id],
[Project1].[UserName] AS [UserName],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[PhoneNumber] AS [PhoneNumber],
[Project1].[Email] AS [Email],
[Project1].[Address] AS [Address],
[Project1].[City] AS [City],
[Project1].[State] AS [State],
[Project1].[Zip] AS [Zip],
[Project1].[DateAdded] AS [DateAdded],
[Project1].[IsActive] AS [IsActive],
[Project1].[C1] AS [C1],
[Project1].[AccountId] AS [AccountId],
[Project1].[ClientId] AS [ClientId],
[Project1].[BrokerId] AS [BrokerId],
[Project1].[AccountNumber] AS [AccountNumber],
[Project1].[BrokerUserName] AS [BrokerUserName],
[Project1].[BrokerPasswordHash] AS [BrokerPasswordHash],
[Project1].[EquityCurve] AS [EquityCurve],
[Project1].[CapitalInvested] AS [CapitalInvested],
[Project1].[IsSimulated] AS [IsSimulated],
[Project1].[ClosedProfit] AS [ClosedProfit],
[Project1].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
[Project1].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
[Project1].[ActivatedOn] AS [ActivatedOn]
FROM ( SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[FirstName] AS [FirstName],
    [Extent1].[LastName] AS [LastName],
    [Extent1].[Address] AS [Address],
    [Extent1].[Zip] AS [Zip],
    [Extent1].[City] AS [City],
    [Extent1].[State] AS [State],
    [Extent1].[DateAdded] AS [DateAdded],
    [Extent1].[IsActive] AS [IsActive],
    [Extent1].[Email] AS [Email],
    [Extent1].[PhoneNumber] AS [PhoneNumber],
    [Extent1].[UserName] AS [UserName],
    [Extent2].[AccountId] AS [AccountId],
    [Extent2].[ClientId] AS [ClientId],
    [Extent2].[BrokerId] AS [BrokerId],
    [Extent2].[AccountNumber] AS [AccountNumber],
    [Extent2].[BrokerUserName] AS [BrokerUserName],
    [Extent2].[BrokerPasswordHash] AS [BrokerPasswordHash],
    [Extent2].[EquityCurve] AS [EquityCurve],
    [Extent2].[CapitalInvested] AS [CapitalInvested],
    [Extent2].[IsSimulated] AS [IsSimulated],
    [Extent2].[ClosedProfit] AS [ClosedProfit],
    [Extent2].[MarketValueTimeStamp] AS [MarketValueTimeStamp],
    [Extent2].[IsAuthorizedForLiveTrading] AS [IsAuthorizedForLiveTrading],
    [Extent2].[ActivatedOn] AS [ActivatedOn],
    CASE WHEN ([Extent2].[AccountId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM  [dbo].[AspNetUsers] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Accounts] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ClientId]
)  AS [Project1]
ORDER BY [Project1].[UserName] ASC, [Project1].[Id] ASC, [Project1].[C1] ASC

Then seemingly one of these for each user:

SELECT TOP (1)
[Extent1].[BrokerId] AS [BrokerId],
[Extent1].[Name] AS [Name],
[Extent1].[Code] AS [Code],
[Extent1].[IsExternal] AS [IsExternal]
FROM [dbo].[Brokers] AS [Extent1]
WHERE [Extent1].[BrokerId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=2

And also one of these for each user:

SELECT
[Project2].[Id] AS [Id],
[Project2].[ReferralId] AS [ReferralId],
[Project2].[FirstName] AS [FirstName],
[Project2].[LastName] AS [LastName],
[Project2].[Address] AS [Address],
[Project2].[Address2] AS [Address2],
[Project2].[Zip] AS [Zip],
[Project2].[City] AS [City],
[Project2].[StateProvince] AS [StateProvince],
[Project2].[Country] AS [Country],
[Project2].[State] AS [State],
[Project2].[startPopupChecked] AS [startPopupChecked],
[Project2].[DateAdded] AS [DateAdded],
[Project2].[CurrentPortfolioId] AS [CurrentPortfolioId],
[Project2].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
[Project2].[NotificationMobileNumber] AS [NotificationMobileNumber],
[Project2].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
[Project2].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
[Project2].[IsActive] AS [IsActive],
[Project2].[HasSeen] AS [HasSeen],
[Project2].[Email] AS [Email],
[Project2].[EmailConfirmed] AS [EmailConfirmed],
[Project2].[PasswordHash] AS [PasswordHash],
[Project2].[SecurityStamp] AS [SecurityStamp],
[Project2].[PhoneNumber] AS [PhoneNumber],
[Project2].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project2].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project2].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project2].[LockoutEnabled] AS [LockoutEnabled],
[Project2].[AccessFailedCount] AS [AccessFailedCount],
[Project2].[UserName] AS [UserName],
[Project2].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
[Project2].[C1] AS [C1],
[Project2].[UserId] AS [UserId],
[Project2].[RoleId] AS [RoleId]
FROM ( SELECT
    [Limit1].[Id] AS [Id],
    [Limit1].[ReferralId] AS [ReferralId],
    [Limit1].[FirstName] AS [FirstName],
    [Limit1].[LastName] AS [LastName],
    [Limit1].[Address] AS [Address],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[Zip] AS [Zip],
    [Limit1].[City] AS [City],
    [Limit1].[StateProvince] AS [StateProvince],
    [Limit1].[Country] AS [Country],
    [Limit1].[State] AS [State],
    [Limit1].[startPopupChecked] AS [startPopupChecked],
    [Limit1].[DateAdded] AS [DateAdded],
    [Limit1].[CurrentPortfolioId] AS [CurrentPortfolioId],
    [Limit1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
    [Limit1].[NotificationMobileNumber] AS [NotificationMobileNumber],
    [Limit1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
    [Limit1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
    [Limit1].[IsActive] AS [IsActive],
    [Limit1].[HasSeen] AS [HasSeen],
    [Limit1].[Email] AS [Email],
    [Limit1].[EmailConfirmed] AS [EmailConfirmed],
    [Limit1].[PasswordHash] AS [PasswordHash],
    [Limit1].[SecurityStamp] AS [SecurityStamp],
    [Limit1].[PhoneNumber] AS [PhoneNumber],
    [Limit1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Limit1].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Limit1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Limit1].[LockoutEnabled] AS [LockoutEnabled],
    [Limit1].[AccessFailedCount] AS [AccessFailedCount],
    [Limit1].[UserName] AS [UserName],
    [Limit1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId],
    [Extent2].[UserId] AS [UserId],
    [Extent2].[RoleId] AS [RoleId],
    CASE WHEN ([Extent2].[UserId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
    FROM   (SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[ReferralId] AS [ReferralId],
        [Extent1].[FirstName] AS [FirstName],
        [Extent1].[LastName] AS [LastName],
        [Extent1].[Address] AS [Address],
        [Extent1].[Address2] AS [Address2],
        [Extent1].[Zip] AS [Zip],
        [Extent1].[City] AS [City],
        [Extent1].[StateProvince] AS [StateProvince],
        [Extent1].[Country] AS [Country],
        [Extent1].[State] AS [State],
        [Extent1].[startPopupChecked] AS [startPopupChecked],
        [Extent1].[DateAdded] AS [DateAdded],
        [Extent1].[CurrentPortfolioId] AS [CurrentPortfolioId],
        [Extent1].[NotificationsEmailAddress] AS [NotificationsEmailAddress],
        [Extent1].[NotificationMobileNumber] AS [NotificationMobileNumber],
        [Extent1].[ReceivesEmailNotifications] AS [ReceivesEmailNotifications],
        [Extent1].[ReceivesTextNotifications] AS [ReceivesTextNotifications],
        [Extent1].[IsActive] AS [IsActive],
        [Extent1].[HasSeen] AS [HasSeen],
        [Extent1].[Email] AS [Email],
        [Extent1].[EmailConfirmed] AS [EmailConfirmed],
        [Extent1].[PasswordHash] AS [PasswordHash],
        [Extent1].[SecurityStamp] AS [SecurityStamp],
        [Extent1].[PhoneNumber] AS [PhoneNumber],
        [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Extent1].[LockoutEnabled] AS [LockoutEnabled],
        [Extent1].[AccessFailedCount] AS [AccessFailedCount],
        [Extent1].[UserName] AS [UserName],
        [Extent1].[BlockOrder_BlockOrderId] AS [BlockOrder_BlockOrderId]
        FROM [dbo].[AspNetUsers] AS [Extent1]
        WHERE [Extent1].[Id] = @p__linq__0 ) AS [Limit1]
    LEFT OUTER JOIN [dbo].[AspNetUserRoles] AS [Extent2] ON [Limit1].[Id] = [Extent2].[UserId]
)  AS [Project2]
ORDER BY [Project2].[Id] ASC, [Project2].[C1] ASC',N'@p__linq__0 int',@p__linq__0=346


来源: stackexchange

问:
Not sure how to handle this in react - multiple promises
So the easiest way to explain this is that I am trying to search your package.json for all your packages, then use the npm registry to see if there are new updates. I have most of that done. Accept for the following for loop:

```<code>import request from 'request'

export const findAllUpdates = (packageInfo) => {
  for(prop in packageInfo) {
    request('https://registry.npmjs.org/' + prop, function(err, resp) {
      json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }
    });
  }
}
</code>```

Your packageInfo is a object of key=>value which represents either a dependency or a dev dependency from the package.json and the package-lock.json or the yarn.lock

The important part is we look at, in the above function, what you have installed, we then use the registry to get that package info and compare the latest version on the registry to that of what you have installed and then we want, ideally, to update the state of the component with the total count.

how ever the issue is that we have entered callback hell, especially with a for loop, looping over every package, making a request.

I cannot create a variable and store the response in there because it cannot be accessed after the request is made. I cannot see how using events here would work because you might have 40 packages installed as either dep or dev and thats a lot of events to fire.

And finally the proper solution might be to use promises, but the whole concept of promises is yet more callbacks with the .then(() => {}), .catch(() => {}) which puts me back at square one.

The goal is to call this in a component and have the state of that component be updated with the total amount of packages that have to be updated (or at least have new versions)

Any ideas? Am I going about this all wrong?

答:
I would recommend using Promise. You can make several async calls, and then wait for them using Promise.all.

If you also return a Promise from your "findAllUpdates" method, then it is easy for the caller to just update its own state when the information is available.

In React that would be something like:

```<code>findAllUpdates(..)
  .then(result => this.setState({
    packagesNeedUpdate: result.filter(p => !p.latest).length
  }));
</code>```

I've created a simple example below that uses promises. It fakes the requests, but otherwise should be pretty accurate.

// Fake requests. Will return version '1.0.0' after one second.
const makeRequest = url => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(JSON.stringify({
        'dist-tags': {
          'latest': '1.0.0'
        }
      }, null, 2));
    }, 1000);
  });
}

const findAllUpdates = (packageInfo) => {
  return new Promise(resolve => {
    const promises = Object.keys(packageInfo)
      .map(prop => makeRequest('https://registry.npmjs.org/' + prop).then(JSON.parse));

    Promise.all(promises) // Wait for all promises
      .then(jsons => {
        const results = Object.keys(packageInfo)
          .map((prop, i) => {
            const latestInNpm = jsons[i]['dist-tags'].latest;
            const current = packageInfo[prop].version
            return {
              prop,
              latest: latestInNpm === current
            }
          });
        resolve(results); // Return result to caller
      });
  });
}

function run() {
  console.log('Loading..');

  const packages = {
    'react': {version: '0.0.1'},
    'angular': {version: '1.0.0'},
    'ember': {version: '0.5.0'},
    'mithril': {version: '0.9.0'}
  };

  findAllUpdates(packages).then(result => {
    const needUpdates = result.filter(p => !p.latest).length;
    console.log('Need updates: ', needUpdates);
  });
}

run();```

ContentLicense: CC BY-SA 3.0

Body:
So the easiest way to explain this is that I am trying to search your package.json for all your packages, then use the npm registry to see if there are new updates. I have most of that done. Accept for the following for loop:

import request from 'request'

export const findAllUpdates = (packageInfo) => {
  for(prop in packageInfo) {
    request('https://registry.npmjs.org/' + prop, function(err, resp) {
      json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }
    });
  }
}

Your packageInfo is a object of key=>value which represents either a dependency or a dev dependency from the package.json and the package-lock.json or the yarn.lock

The important part is we look at, in the above function, what you have installed, we then use the registry to get that package info and compare the latest version on the registry to that of what you have installed and then we want, ideally, to update the state of the component with the total count.

how ever the issue is that we have entered callback hell, especially with a for loop, looping over every package, making a request.

I cannot create a variable and store the response in there because it cannot be accessed after the request is made. I cannot see how using events here would work because you might have 40 packages installed as either dep or dev and thats a lot of events to fire.

And finally the proper solution might be to use promises, but the whole concept of promises is yet more callbacks with the .then(() => {}), .catch(() => {}) which puts me back at square one.

The goal is to call this in a component and have the state of that component be updated with the total amount of packages that have to be updated (or at least have new versions)

Any ideas? Am I going about this all wrong?

Body:
I would recommend using Promise. You can make several async calls, and then wait for them using Promise.all.

If you also return a Promise from your "findAllUpdates" method, then it is easy for the caller to just update its own state when the information is available.

In React that would be something like:

findAllUpdates(..)
  .then(result => this.setState({
    packagesNeedUpdate: result.filter(p => !p.latest).length
  }));

I've created a simple example below that uses promises. It fakes the requests, but otherwise should be pretty accurate.

// Fake requests. Will return version '1.0.0' after one second.
const makeRequest = url => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(JSON.stringify({
        'dist-tags': {
          'latest': '1.0.0'
        }
      }, null, 2));
    }, 1000);
  });
}

const findAllUpdates = (packageInfo) => {
  return new Promise(resolve => {
    const promises = Object.keys(packageInfo)
      .map(prop => makeRequest('https://registry.npmjs.org/' + prop).then(JSON.parse));

    Promise.all(promises) // Wait for all promises
      .then(jsons => {
        const results = Object.keys(packageInfo)
          .map((prop, i) => {
            const latestInNpm = jsons[i]['dist-tags'].latest;
            const current = packageInfo[prop].version
            return {
              prop,
              latest: latestInNpm === current
            }
          });
        resolve(results); // Return result to caller
      });
  });
}

function run() {
  console.log('Loading..');

  const packages = {
    'react': {version: '0.0.1'},
    'angular': {version: '1.0.0'},
    'ember': {version: '0.5.0'},
    'mithril': {version: '0.9.0'}
  };

  findAllUpdates(packages).then(result => {
    const needUpdates = result.filter(p => !p.latest).length;
    console.log('Need updates: ', needUpdates);
  });
}

run();


问:
C++ Qt Timer For Each Object
How can implement Timer for each object

for example i have class like this

---------------------------------------> person.h

```<code>#ifndef PERSON_H
#define PERSON_H

#include <QMainWindow>

namespace Ui {
class person;
}

class person : public QMainWindow
{
    Q_OBJECT

public:
    explicit person(QWidget *parent = 0);
    ~person();
    QString Name;
    QTimer *timer;

private:
    Ui::person *ui;
signals:

public slots:

    void onTimer();
private slots:

};

#endif // PERSON_H
</code>```

person.cpp ---------------------->

```<code>#include "person.h"
#include "ui_person.h"
#include <QString>
#include <QDebug>
#include <QTimer>

person::person(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::person)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(this->onTimer()));
    timer->start(1000);

}

person::~person()
{
    delete ui;
}

void person::onTimer()
{
    qDebug() << "timer call for "<< Name  ;
</code>```

------------------> main.cpp

```<code>#include "person.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    person first;
    person second;
    first.Name="jack";
    second.Name="frank";

    return a.exec();
}
</code>```

this code work but the timer should interval in constructor and both of object have same interval!

OUtPut picture

you can see the out put in attached image

Problem is I want start , setInterval the Timer with object like:

```<code>person first;
first Name= "jack";
first.timer->start(200);
person second;
second Name "frank";
second.timer->start(500);
</code>```

and after my command timer start work not in constractor

in my code when i try to inpet first.timer the ponter sign -> didnt apear!!! and not working

答: first of all what is your timer going to do, cause if it needs to call onTimeout the person class method, you need to inherit from QObject and specify the Q_OBJECT macro under your class name, then create the slot handling the signal from the timer and in the constructor instantiate the your qtimer pointer and connect its signal to this instance slot</p>

Title: C++ Qt Timer For Each Object

Body:
How can implement Timer for each object

for example i have class like this

---------------------------------------> person.h

#ifndef PERSON_H
#define PERSON_H

#include <QMainWindow>

namespace Ui {
class person;
}

class person : public QMainWindow
{
    Q_OBJECT

public:
    explicit person(QWidget *parent = 0);
    ~person();
    QString Name;
    QTimer *timer;

private:
    Ui::person *ui;
signals:

public slots:

    void onTimer();
private slots:

};

#endif // PERSON_H

person.cpp ---------------------->

#include "person.h"
#include "ui_person.h"
#include <QString>
#include <QDebug>
#include <QTimer>

person::person(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::person)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(this->onTimer()));
    timer->start(1000);

}

person::~person()
{
    delete ui;
}

void person::onTimer()
{
    qDebug() << "timer call for "<< Name  ;

------------------> main.cpp

#include "person.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    person first;
    person second;
    first.Name="jack";
    second.Name="frank";

    return a.exec();
}

this code work but the timer should interval in constructor and both of object have same interval!

OUtPut picture

you can see the out put in attached image

Problem is I want start , setInterval the Timer with object like:

person first;
first Name= "jack";
first.timer->start(200);
person second;
second Name "frank";
second.timer->start(500);

and after my command timer start work not in constractor

in my code when i try to inpet first.timer the ponter sign -> didnt apear!!! and not working


问:
javascript counter using for loop
I've created a simple counter using javascript but there is a problem Field "display" starts from 1, but it should start from 100 and goes low. The console logs shows values correctly from 100 to 1.
I have to use loops to do this tasks, so please not replace it using recursion :) Also the timeout is for sure does not equal to 100ms, it's more

function wyswietlLiczbe(j) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, 100);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

答:
I don't know exactly what you want but I think this is what you're looking for.

function wyswietlLiczbe(j) {
    if (j >= 0) {
        setTimeout(function() {
            document.getElementById("display").innerHTML = j;
            j--;
            wyswietlLiczbe(j);
        }, 100);
    }
}

wyswietlLiczbe(100);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

Title: javascript counter using for loop

Body:
I don't know exactly what you want but I think this is what you're looking for.

function wyswietlLiczbe(j) {
    if (j >= 0) {
        setTimeout(function() {
            document.getElementById("display").innerHTML = j;
            j--;
            wyswietlLiczbe(j);
        }, 100);
    }
}

wyswietlLiczbe(100);

<p id="display"></p>


问:
Using debug symbols with perf
I monitor a process on a PowerPC system in order to extract performance information.
How I can load the debug symbols of this process?
I use the following command

```<code>perf record -g dwarf -p 4591
</code>```

and I take an error that the "dwarf cannot be found (no such file or directory)"
Could you please give me a hint how to load debug information about the functions that have been called when the report is generated?

答:
```<code>perf record -g dwarf -p 4591
</code>```

These days the correct option to chose a method is --call-graph whereas -g is only a flag to enable call stacks with it's default method fp.

from man perf-record.

```<code>-g
    Enables call-graph (stack chain/backtrace) recording.

--call-graph
    Setup and enable call-graph (stack chain/backtrace) recording,
    implies -g.  Default is "fp".

    Allows specifying "fp" (frame pointer) or "dwarf"
    (DWARF's CFI - Call Frame Information) or "lbr"
    (Hardware Last Branch Record facility) as the method to collect
    the information used to show the call graphs.

    In some systems, where binaries are build with gcc
    --fomit-frame-pointer, using the "fp" method will produce bogus
    call graphs, using "dwarf", if available (perf tools linked to
    the libunwind or libdw library) should be used instead.
    Using the "lbr" method doesn't require any compiler options. It
    will produce call graphs from the hardware LBR registers. The
    main limitation is that it is only available on new Intel
    platforms, such as Haswell. It can only get user call chain. It
    doesn't work with branch stack sampling at the same time.

    When "dwarf" recording is used, perf also records (user) stack dump
    when sampled.  Default size of the stack dump is 8192 (bytes).
    User can change the size by passing the size after comma like
    "--call-graph dwarf,4096".
</code>```

By the way, try fp first - it's much more efficient, but doesn't work well with optimized binaries (e.g. --fomit-frame-pointer). Also this has very little to do with debug information. If you do not need to know the stack trace, you needn't add -g.

Title: Using debug symbols with perf

Body:
I monitor a process on a PowerPC system in order to extract performance information.
How I can load the debug symbols of this process?
I use the following command

perf record -g dwarf -p 4591

and I take an error that the "dwarf cannot be found (no such file or directory)"
Could you please give me a hint how to load debug information about the functions that have been called when the report is generated?

Body:
perf record -g dwarf -p 4591

These days the correct option to chose a method is --call-graph whereas -g is only a flag to enable call stacks with it's default method fp.

from man perf-record.

-g
    Enables call-graph (stack chain/backtrace) recording.

--call-graph
    Setup and enable call-graph (stack chain/backtrace) recording,
    implies -g.  Default is "fp".

    Allows specifying "fp" (frame pointer) or "dwarf"
    (DWARF's CFI - Call Frame Information) or "lbr"
    (Hardware Last Branch Record facility) as the method to collect
    the information used to show the call graphs.

    In some systems, where binaries are build with gcc
    --fomit-frame-pointer, using the "fp" method will produce bogus
    call graphs, using "dwarf", if available (perf tools linked to
    the libunwind or libdw library) should be used instead.
    Using the "lbr" method doesn't require any compiler options. It
    will produce call graphs from the hardware LBR registers. The
    main limitation is that it is only available on new Intel
    platforms, such as Haswell. It can only get user call chain. It
    doesn't work with branch stack sampling at the same time.

    When "dwarf" recording is used, perf also records (user) stack dump
    when sampled.  Default size of the stack dump is 8192 (bytes).
    User can change the size by passing the size after comma like
    "--call-graph dwarf,4096".

By the way, try fp first - it's much more efficient, but doesn't work well with optimized binaries (e.g. --fomit-frame-pointer). Also this has very little to do with debug information. If you do not need to know the stack trace, you needn't add -g.


问:
Wordpress author name coming twice
I am using Wordpress to create a blog. I am showing author name in the article but it is repeating. I am using the get_the_author(); function

Here is my wordpress site: http://hideawayharbor.org/blog/

答:
Solutions

You might be accidently writing it twice?

If it shows twice in all the themes then there might be something attached to the author name hook and displaying it twice

ContentLicense: CC BY-SA 2.5

Title: Wordpress author name coming twice


问:
Lightbox not working on subdirectory
I relatively new to bootstrap in general. I am currently working on a site. On the main site, lightbox works. When I put it in a subdirectory it ceases to work.

My directory structure is as follows.

PUBLIC

- css

- images

- other php files

- SECONDARY SITE

  + css

  + images

  + other php files

If I move any of the files from the PUBLIC main site (where bootstrap works) to the SECONDARY SITE lightbox ceases to work.

Whenever I do the opposite, from SECONDARY SITE to PUBLIC main, it all of sudden works.

Im pretty much using the same code on both sites. I made sure that the links were pointing to the right sites.

Here are my definitions.

```<code><link rel="stylesheet" href="css/defined.css">
<link href="css/ekko-lightbox.css" rel="stylesheet">
<link href="css/ekko-lightbox.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="css/ekko-lightbox.js"></script>
<script src="css/ekko-lightbox.min.js"></script>
<script type="text/javascript">
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
    event.preventDefault();
    $(this).ekkoLightbox();
});

<div class="container-fluid">
<div class="row">
  <div class="col-lg-3 col-md-6 col-sm-12 col-xs-12" align="center"><a href="images/tm_application_swatches/tm01.jpg" data-title="IMAGE NAME" data-toggle="lightbox"><img class="thumbnail" height="250" style="display:inline" src="images/tm_application_swatches/tm01.jpg"></a><p></p></div>
</div>
</div>
</code>```

On Chrome's Developer Tools it caught this.

```<code>Uncaught TypeError: this.lightbox_body.htmll is not a function
    at b.showLoading (ekko-lightbox.min.js:7)
    at new b (ekko-lightbox.min.js:7)
    at HTMLAnchorElement.<anonymous> (ekko-lightbox.min.js:7)
    at Function.each (jquery.min.js:2)
    at r.fn.init.each (jquery.min.js:2)
    at r.fn.init.a.fn.ekkoLightbox (ekko-lightbox.min.js:7)
    at HTMLAnchorElement.<anonymous> (tm_swatch.php:22)
    at HTMLDocument.dispatch (jquery.min.js:3)
    at HTMLDocument.q.handle (jquery.min.js:3)
</code>```

I'm out of ideas, your assistance is greatly appreciated.

答: You are using relative links like href="css.., but most likely you need to have root-relative links, like href="/css

Title: Lightbox not working on subdirectory

Body:
I relatively new to bootstrap in general. I am currently working on a site. On the main site, lightbox works. When I put it in a subdirectory it ceases to work.

My directory structure is as follows.

PUBLIC

- css

- images

- other php files

- SECONDARY SITE

  + css

  + images

  + other php files

If I move any of the files from the PUBLIC main site (where bootstrap works) to the SECONDARY SITE lightbox ceases to work.

Whenever I do the opposite, from SECONDARY SITE to PUBLIC main, it all of sudden works.

Im pretty much using the same code on both sites. I made sure that the links were pointing to the right sites.

Here are my definitions.

<link rel="stylesheet" href="css/defined.css">
<link href="css/ekko-lightbox.css" rel="stylesheet">
<link href="css/ekko-lightbox.min.css" rel="stylesheet">


问:
How to check values of an attribute if it is present in json schema using karate framework
I can have a response as:

```<code> { id: '123', name: 'foo' }`
</code>```

if the user has not a dog

OR

```<code>{ id: '123', name: 'foo', dog: {id: '123', color: 'brown'} }`
</code>```

if the user has a dog.

In my feature I have:

```<code>* def schema = { id: '#string', name: '#string', dog: {id: '#string', color: '#string'} }`
* match response == schema
</code>```

The prb is that if I have a user without dog in response, I have this error:

```<code>path: $[0].dog, actual: null, expected: {id=#string, label=#string}, reason: actual value is null
</code>```

How can I check the attribute 'dog' in my schema?
Thanks

答:
It is not possible to do this in one step, also refer to the doc on schema validation:

```<code>* def dogSchema = { id: '#string', color: '#string' }
* def schema = { id: '#string', name: '#string', dog: '##object' }

* def response1 = { id: '123', name: 'foo' }
* match response1 == schema
* match response1 contains { dog: '##(dogSchema)' }

* def response2 = { id: '123', name: 'foo', dog: { id: '123', color: 'brown' } }
* match response2 == schema
* match response1 contains { dog: '##(dogSchema)' }
</code>```

Edit: well this is embarassing, I realized this trick is not well documented:

```<code>* def dogSchema = { id: '#string', color: '#string' }
* def schema = { id: '#string', name: '#string', dog: "#('##(dogSchema)')" }

* def response1 = { id: '123', name: 'foo' }
* match response1 == schema

* def response2 = { id: '123', name: 'foo', dog: { id: '123', color: 'brown' } }
* match response2 == schema
</code>```

Edit2: this will be improved in the next version: https://github.com/intuit/karate/issues/248

Body:
I can have a response as:

 { id: '123', name: 'foo' }`

if the user has not a dog

OR

{ id: '123', name: 'foo', dog: {id: '123', color: 'brown'} }`

if the user has a dog.

In my feature I have:

* def schema = { id: '#string', name: '#string', dog: {id: '#string', color: '#string'} }`
* match response == schema

The prb is that if I have a user without dog in response, I have this error:

path: $[0].dog, actual: null, expected: {id=#string, label=#string}, reason: actual value is null

How can I check the attribute 'dog' in my schema?
Thanks

Body:
It is not possible to do this in one step, also refer to the doc on schema validation:

* def dogSchema = { id: '#string', color: '#string' }
* def schema = { id: '#string', name: '#string', dog: '##object' }

* def response1 = { id: '123', name: 'foo' }
* match response1 == schema
* match response1 contains { dog: '##(dogSchema)' }

* def response2 = { id: '123', name: 'foo', dog: { id: '123', color: 'brown' } }
* match response2 == schema
* match response1 contains { dog: '##(dogSchema)' }

Edit: well this is embarassing, I realized this trick is not well documented:

* def dogSchema = { id: '#string', color: '#string' }
* def schema = { id: '#string', name: '#string', dog: "#('##(dogSchema)')" }

* def response1 = { id: '123', name: 'foo' }
* match response1 == schema

* def response2 = { id: '123', name: 'foo', dog: { id: '123', color: 'brown' } }
* match response2 == schema

Edit2: this will be improved in the next version: https://github.com/intuit/karate/issues/248


问:
Is scalability applicable with Kafka stream if each topic has single partition
My understanding as per Kafka stream documentation,
Maximum possible parallel tasks is equal to maximum number of partitions of a topic among all topics in a cluster.

I have around 60 topics at Kafka cluster. Each topic has single partition only.
Is it possible to achieve scalability/parallelism with Kafka stream for my Kafka cluster?

答:
Do you want to do the same computation over all topics? For this, I would recommend to introduce an extra topic with many partitions that you use to scale out:

// using new 1.0 API
StreamsBuilder builder = new StreamsBuilder():
KStream parallelizedStream = builder
    .stream(/* subscribe to all topics at once*/)
    .through("topic-with-many-partitions");

// apply computation
parallelizedStream...
```

<blockquote>
  <p>Note: You need to create the topic "topic-with-many-partitions" manually before starting your Streams application</p>
</blockquote>

<p>Pro Tip:</p>

<blockquote>
  <p>The topic "topic-with-many-partitions" can have a very short retention time as it's only used for scaling and must not hold data long term.</p>
</blockquote>

<p><strong>Update</strong></p>

<p>If you have 10 topic T1 to T10 with a single partitions each, the program from above will execute as follows (with TN being the dummy topic with 10 partitions):</p>

```T1-0  --+           +--> TN-0   --> T1_1
...   --+--> T0_0 --+--> ...    --> ...
T10-0 --+           +--> TN-10  --> T1_10
```

The first part of your program will only read all 10 input topics and write it back into 10 partitions of TN. Afterwards, you can get up to 10 parallel tasks, each processing one input partition. If you start 10 KafakStreams instances, only one will execute T0_0, and each will alsa one T1_x running.

Body:
Do you want to do the same computation over all topics? For this, I would recommend to introduce an extra topic with many partitions that you use to scale out:

// using new 1.0 API
StreamsBuilder builder = new StreamsBuilder():
KStream parallelizedStream = builder
    .stream(/* subscribe to all topics at once*/)
    .through("topic-with-many-partitions");

// apply computation
parallelizedStream...

Note: You need to create the topic "topic-with-many-partitions" manually before starting your Streams application

Pro Tip:

The topic "topic-with-many-partitions" can have a very short retention time as it's only used for scaling and must not hold data long term.

Update

If you have 10 topic T1 to T10 with a single partitions each, the program from above will execute as follows (with TN being the dummy topic with 10 partitions):

T1-0  --+           +--> TN-0   --> T1_1
...   --+--> T0_0 --+--> ...    --> ...
T10-0 --+           +--> TN-10  --> T1_10

The first part of your program will only read all 10 input topics and write it back into 10 partitions of TN. Afterwards, you can get up to 10 parallel tasks, each processing one input partition. If you start 10 KafakStreams instances, only one will execute T0_0, and each will alsa one T1_x running.


问:
Programmatically exporting BizTalk server configuration
We could programmatically import BizTalk server configuration using the following command :

```<code><BizTalk path>configuration.exe /s config.xml
</code>```

However, how to export the configuration using command line?

答:
You can use BizTalk PowerShell extension to do this. They come on the BizTalk CD as of 2013 I believe. On the BizTalk 2016 CD they are under:
<drive-letter>:\BizTalk Server\MSI\Program Files\SDK\Utilities\PowerShell

Once installed, from Powershell you can navigate the BizTalk server like it's a filesystem:

```<code>PS BizTalk:\> cd .\Applications
PS BizTalk:\Applications> Export-Bindings -Path <my-application-name> -Destination c:\temp\myAppBindings.xml
</code>```

This will export the bindings to a destination of your choosing. You could even set up some kind of scheduled task to run the PS script if desired.

Body:
We could programmatically import BizTalk server configuration using the following command :

<BizTalk path>configuration.exe /s config.xml

However, how to export the configuration using command line?

Body:
You can use BizTalk PowerShell extension to do this. They come on the BizTalk CD as of 2013 I believe. On the BizTalk 2016 CD they are under:
<drive-letter>:\BizTalk Server\MSI\Program Files\SDK\Utilities\PowerShell

Once installed, from Powershell you can navigate the BizTalk server like it's a filesystem:

PS BizTalk:\> cd .\Applications
PS BizTalk:\Applications> Export-Bindings -Path <my-application-name> -Destination c:\temp\myAppBindings.xml

This will export the bindings to a destination of your choosing. You could even set up some kind of scheduled task to run the PS script if desired.


问:
Angular 2 : No NgModule metadata found
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

```<code>compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.
</code>```

and the component doesn't load at all.

Here are my files:

package.json:

```<code>{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}
</code>```

index.html:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">
  </head>
  <body>

    <app>
      ... before angular loads.
    </app>

    <script src="polyfills.bundle.js"></script>
    <script src="vendor.bundle.js"></script>
    <script src="main.bundle.js"></script>

  </body>
</html>
</code>```

main.ts:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

app.ts:

```<code>import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `
    <div>
      <h3>
        Yo, world!
      </h3>
    </div>
    `
})

export class App {}
</code>```

app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};
</code>```

Thanks for your time.

答: I had this error even though I had everything that the answers above suggested in place. A simple edit in the app.module.ts file ( like delete a bracket and put it back) did the trick.

Title: Angular 2 : No NgModule metadata found

Body:
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.

and the component doesn't load at all.

Here are my files:

package.json:

{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}

index.html:

<!DOCTYPE html>

    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">

    <app>
      ... before angular loads.
    </app>

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);

app.ts:

import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `

        Yo, world!

    `
})

export class App {}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};

Thanks for your time.


问:
Excel formula quotation symbol meaning
what do the quotation symbols mean in this equation? I cant find a simple straight answer. </p>

```<code>=IF(K25="","",L24+K25)
</code>```

答: they mean nothing, an empty cell. If k25 is empty, return nothing.</p>

Title: Excel formula quotation symbol meaning

Body:
what do the quotation symbols mean in this equation? I cant find a simple straight answer.

=IF(K25="","",L24+K25)


问:
pythonic way: Iterator chaining and resource management
I find it difficult to articulate smoothly chained iterators and resource management in Python.

It will probably be clearer by examining a concrete example:

I have this little program that works on a bunch of similar, yet different csv files. As they are shared with other co-workers, I need to open and close them frequently. Moreover, I need to transform and filter their content. So I have a lot of different fonctions of this kind:

```<code>def doSomething(fpath):
    with open(fpath) as fh:
        r=csv.reader(fh, delimiter=';')
        s=imap(lambda row: fn(row), r)
        t=ifilter(lambda row: test(row), s)
        for row in t:
            doTheThing(row)
</code>```

That's nice and readable, but, as I said, I have a lot of those and I end up copy-pasting a lot more than I'd wish. But of course I can't refactor the common code into a function returning an iterator:

```<code>def iteratorOver(fpath):
    with open(fpath) as fh:
        r=csv.reader(fh, delimiter=';')
        return r #oops! fh is closed by the time I use it
</code>```

A first step to refactor the code would be to create another 'with-enabled' class:

```<code>def openCsv(fpath):
    class CsvManager(object):
        def __init__(self, fpath):
            self.fh=open(fpath)
        def __enter__(self):
            return csv.reader(self.fh, delimiter=';')
        def __exit__(self, type, value, traceback):
            self.fh.close()
</code>```

and then:

```<code>with openCsv('a_path') as r:
    s=imap(lambda row: fn(row), r)
    t=ifilter(lambda row: test(row), s)
    for row in t:
        doTheThing(row)
</code>```

But I only reduced the boilerplate of each function by one step.

So what is the pythonic way to refactor such a code? My c++ background is getting in the way I think.

答:
You can use generators; these produce an iterable you can then pass to other objects. For example, a generator yielding all the rows in a CSV file:

```<code>def iteratorOver(fpath):
    with open(fpath) as fh:
        r = csv.reader(fh, delimiter=';')
        for row in r:
            yield row
</code>```

Because a generator function pauses whenever you are not iterating over it, the function doesn't exit until the loop is complete and the with statement won't close the file.

You can now use that generator in a filter:

```<code>rows = iteratorOver('some path')
filtered = ifilter(test, rows)
</code>```

etc.

Body:
I find it difficult to articulate smoothly chained iterators and resource management in Python.

It will probably be clearer by examining a concrete example:

I have this little program that works on a bunch of similar, yet different csv files. As they are shared with other co-workers, I need to open and close them frequently. Moreover, I need to transform and filter their content. So I have a lot of different fonctions of this kind:

def doSomething(fpath):
    with open(fpath) as fh:
        r=csv.reader(fh, delimiter=';')
        s=imap(lambda row: fn(row), r)
        t=ifilter(lambda row: test(row), s)
        for row in t:
            doTheThing(row)

That's nice and readable, but, as I said, I have a lot of those and I end up copy-pasting a lot more than I'd wish. But of course I can't refactor the common code into a function returning an iterator:

def iteratorOver(fpath):
    with open(fpath) as fh:
        r=csv.reader(fh, delimiter=';')
        return r #oops! fh is closed by the time I use it

A first step to refactor the code would be to create another 'with-enabled' class:

def openCsv(fpath):
    class CsvManager(object):
        def __init__(self, fpath):
            self.fh=open(fpath)
        def __enter__(self):
            return csv.reader(self.fh, delimiter=';')
        def __exit__(self, type, value, traceback):
            self.fh.close()

and then:

with openCsv('a_path') as r:
    s=imap(lambda row: fn(row), r)
    t=ifilter(lambda row: test(row), s)
    for row in t:
        doTheThing(row)

But I only reduced the boilerplate of each function by one step.

So what is the pythonic way to refactor such a code? My c++ background is getting in the way I think.

Body:
You can use generators; these produce an iterable you can then pass to other objects. For example, a generator yielding all the rows in a CSV file:

def iteratorOver(fpath):
    with open(fpath) as fh:
        r = csv.reader(fh, delimiter=';')
        for row in r:
            yield row

Because a generator function pauses whenever you are not iterating over it, the function doesn't exit until the loop is complete and the with statement won't close the file.

You can now use that generator in a filter:

rows = iteratorOver('some path')
filtered = ifilter(test, rows)

etc.


问:
Have JS auto complete math equations for a calculator app
The issue I am having is that the math is not working as intended. I would like the calculator to auto evaluate the amount if the length of the fullAmount variable length is equal to 3 and then clear the num variable and the fullAmount variable but leave the current number that has been evaluated. So if you put 9 * 1 into the calculator I want it to leave num = [] and fullAmount = [9] but it is currently leaving the fullAmount with [9,*,1] and then adds on to it.

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    console.log(num)
    console.log(fullAmount)
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")
    fullAmount.push(parseInt(num))
    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
      console.log(func)
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] + fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] - fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] * fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] / fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    $("#res").val("")
    console.log(num)
    console.log(fullAmount)
    console.log(func)

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
  </script>
  <script src="calc.js"></script>
  <link rel="stylesheet" type="text/css" href="calc.css">
</head>

<body>
  <div id="calculator-container">
    <form class="show">
      <input type="text" id="res" name="numbers" disabled><br>
    </form>
    <center>
      <div class="calculator-view">
        <table>
          <tr>
            <td>
              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>
            </td>
          </tr>
        </table>
      </div>
</body>

</html></code>```

答:
I made some simple changes. I did not complete the entire calculator because that is your job. I completed one portion, so you can get an idea.

$(document).ready(function() {

  var array = [];

  function getSum(total, num) {
    return parseInt(total) + parseInt(num);
  }

  $('.elem').click(function(e) {

    if(array.length <= 2){

      array.push(e.target.innerText);

      var getTotal = isNaN(getSum(array[0],array[2])) ? array.join(' '):getSum(array[0],array[2]);

      document.getElementById('res').value = getTotal;
    }

    if(e.target.innerText === 'AC'){
        document.getElementById('res').value = '';
    };
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

<!DOCTYPE html>

  <title></title>

  <link rel="stylesheet" type="text/css" href="calc.css">

    <form class="show">
      <input type="text" id="res" name="numbers">

    </form>

              <button id="clear" class="elem" type="button">AC</button>
              <button id="sign" class="elem" type="button">+/-</button>
              <button id="divide" class="elem" type="button">÷</button>

              <button id="seven" class="elem" type="button">7</button>
              <button id="eight" class="elem" type="button">8</button>
              <button id="nine" class="elem" type="button">9</button>
              <button id="multiply" class="elem" type="button">*</button>

              <button id="four" class="elem" type="button">4</button>
              <button id="five" class="elem" type="button">5</button>
              <button id="six" class="elem" type="button">6</button>
              <button id="minus" class="elem" type="button">-</button>

              <button id="one" class="elem" type="button">1</button>
              <button id="two" class="elem" type="button">2</button>
              <button id="three" class="elem" type="button">3</button>

              <button id="zero" class="elem" type="button">0</button>
              <button id="equals" type="button" class="elem">=</button>

```

Body:
The issue I am having is that the math is not working as intended. I would like the calculator to auto evaluate the amount if the length of the fullAmount variable length is equal to 3 and then clear the num variable and the fullAmount variable but leave the current number that has been evaluated. So if you put 9 * 1 into the calculator I want it to leave num = [] and fullAmount = [9] but it is currently leaving the fullAmount with [9,*,1] and then adds on to it.

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    console.log(num)
    console.log(fullAmount)
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")
    fullAmount.push(parseInt(num))
    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
      console.log(func)
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] + fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] - fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] * fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] / fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    $("#res").val("")
    console.log(num)
    console.log(fullAmount)
    console.log(func)

  });
});

<!DOCTYPE html>

  <title></title>

  <link rel="stylesheet" type="text/css" href="calc.css">

    <form class="show">
      <input type="text" id="res" name="numbers" disabled>

    </form>

              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>

              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>

              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>

              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>

              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>

Body:
I made some simple changes. I did not complete the entire calculator because that is your job. I completed one portion, so you can get an idea.

$(document).ready(function() {

  var array = [];

  function getSum(total, num) {
    return parseInt(total) + parseInt(num);
  }

  $('.elem').click(function(e) {

    if(array.length <= 2){

      array.push(e.target.innerText);

      var getTotal = isNaN(getSum(array[0],array[2])) ? array.join(' '):getSum(array[0],array[2]);

      document.getElementById('res').value = getTotal;
    }

    if(e.target.innerText === 'AC'){
        document.getElementById('res').value = '';
    };
  });
});

.as-console-wrapper { max-height: 100% !important; top: 0; }

<!DOCTYPE html>
   <html>

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
  </script>
  <script src="calc.js"></script>
  <link rel="stylesheet" type="text/css" href="calc.css">
</head>

<body>
  <div id="calculator-container">
    <form class="show">
      <input type="text" id="res" name="numbers"><br>
    </form>
    <center>
      <div class="calculator-view">
        <table>
          <tr>
            <td>
              <button id="clear" class="elem" type="button">AC</button>
              <button id="sign" class="elem" type="button">+/-</button>
              <button id="divide" class="elem" type="button">÷</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="seven" class="elem" type="button">7</button>
              <button id="eight" class="elem" type="button">8</button>
              <button id="nine" class="elem" type="button">9</button>
              <button id="multiply" class="elem" type="button">*</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="four" class="elem" type="button">4</button>
              <button id="five" class="elem" type="button">5</button>
              <button id="six" class="elem" type="button">6</button>
              <button id="minus" class="elem" type="button">-</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="one" class="elem" type="button">1</button>
              <button id="two" class="elem" type="button">2</button>
              <button id="three" class="elem" type="button">3</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="zero" class="elem" type="button">0</button>
              <button id="equals" type="button" class="elem">=</button>
            </td>
          </tr>
        </table>
      </div>
</body>

</html>


问:
golang decode JSON request in nested struct and insert in DB as blob
I have a nested struct which I am using to decode JSON request.

```<code>type Service struct {
    ID       string `json:"id,omitempty" db:"id"`
    Name     string `json:"name" db:"name"`
    Contract struct {
        ServiceTime int    `json:"service_time"`
        Region      string `json:"region"`
    } `json:"contract" db:"contract"`
}
</code>```

I am using blob type to store Contract in MySQL. To make it work , I would be needing to create a different struct with Contract as string to insert in DB. Can this be done in better way by using single struct only or is there any other elegant way ?

答:
This depends on what you use to talk to the database, but if you're using database/sql and a driver that provides support for this you can have your Contract type implement the Valuer interface.

```<code>type Service struct {
    ID       string    `json:"id,omitempty" db:"id"`
    Name     string    `json:"name" db:"name"`
    Contract Contract `json:"contract" db:"contract"`
}

type Contract struct {
    ServiceTime int    `json:"service_time"`
    Region      string `json:"region"`
}

func (c *Contract) Value() (driver.Value, error) {
    if c != nil {
        b, err := json.Marshal(c)
        if err != nil {
            return nil, err
        }
        return string(b), nil
    }
    return nil, nil
}
</code>```

And then when you're executing the query just pass in the Service.Contract field and the driver should call the Value method.

```<code>sql := // INSERT INTO ...
svc := // &Service{ ...
db.Exec(sql, svc.ID, svc.Name, svc.Contract)
</code>```

And to be able to retrieve the blob back from db and unmarshal it back into Contract you can have it implement the Scanner interface, again, if a type implements this the driver is expected to call it.

```<code>func (c *Contract) Scan(src interface{}) error {
    var data []byte
    if b, ok := src.([]byte); ok {
        data = b
    } else if s, ok := src.(string); ok {
        data = []byte(s)
    }
    return json.Unmarshal(data, c)
}

// ...

sql := // SELECT * FROM ...
svc := // &Service{ ...
db.QueryRow(sql, 123).Scan(&svc.ID, &svc.Name, &svc.Contract)
</code>```

Body:
I have a nested struct which I am using to decode JSON request.

type Service struct {
    ID       string `json:"id,omitempty" db:"id"`
    Name     string `json:"name" db:"name"`
    Contract struct {
        ServiceTime int    `json:"service_time"`
        Region      string `json:"region"`
    } `json:"contract" db:"contract"`
}

I am using blob type to store Contract in MySQL. To make it work , I would be needing to create a different struct with Contract as string to insert in DB. Can this be done in better way by using single struct only or is there any other elegant way ?

Body:
This depends on what you use to talk to the database, but if you're using database/sql and a driver that provides support for this you can have your Contract type implement the Valuer interface.

type Service struct {
    ID       string    `json:"id,omitempty" db:"id"`
    Name     string    `json:"name" db:"name"`
    Contract Contract `json:"contract" db:"contract"`
}

type Contract struct {
    ServiceTime int    `json:"service_time"`
    Region      string `json:"region"`
}

func (c *Contract) Value() (driver.Value, error) {
    if c != nil {
        b, err := json.Marshal(c)
        if err != nil {
            return nil, err
        }
        return string(b), nil
    }
    return nil, nil
}

And then when you're executing the query just pass in the Service.Contract field and the driver should call the Value method.

sql := // INSERT INTO ...
svc := // &Service{ ...
db.Exec(sql, svc.ID, svc.Name, svc.Contract)

And to be able to retrieve the blob back from db and unmarshal it back into Contract you can have it implement the Scanner interface, again, if a type implements this the driver is expected to call it.

func (c *Contract) Scan(src interface{}) error {
    var data []byte
    if b, ok := src.([]byte); ok {
        data = b
    } else if s, ok := src.(string); ok {
        data = []byte(s)
    }
    return json.Unmarshal(data, c)
}

// ...

sql := // SELECT * FROM ...
svc := // &Service{ ...
db.QueryRow(sql, 123).Scan(&svc.ID, &svc.Name, &svc.Contract)


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答:
This is in response to ctacke's comment on Jon Skeet's answer (It's not long for a comment)

I always thought foreach was pretty
  well known to be slower than a for
  loop since it has to use the iterator.

Actually, no, in this case foreach would be faster.  Index access is bounds checked (ie. i is check to be in range three time in the loop: once in the for() and once each for the two ca[i]s), which makes a for loop slower than foreach.

If the C# compiler detects the specific syntax:

```<code> for(i = 0; i < ca.Length; i++)
</code>```

then it will perform a ad hoc optimization, removing the internal bound-checks, making the for() loop faster.  However, since here we must treat ca[0] as a special case (to prevent a leading space on the output), we can't trigger that optimization.

OwnerDisplayName: Gortok

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok

Body:
This is in response to ctacke's comment on Jon Skeet's answer (It's not long for a comment)

I always thought foreach was pretty
  well known to be slower than a for
  loop since it has to use the iterator.

Actually, no, in this case foreach would be faster.  Index access is bounds checked (ie. i is check to be in range three time in the loop: once in the for() and once each for the two ca[i]s), which makes a for loop slower than foreach.

If the C# compiler detects the specific syntax:

 for(i = 0; i < ca.Length; i++)

then it will perform a ad hoc optimization, removing the internal bound-checks, making the for() loop faster.  However, since here we must treat ca[0] as a special case (to prevent a leading space on the output), we can't trigger that optimization.

OwnerDisplayName: James Curran