问:
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>```

答:
Have you traced the SQL that your second statement produces? It looks like it's going to load all the Users, Accounts, Brokers and Roles without doing any of the joining and filtering that you want. If these tables are large this could take time.

(EDIT: Sorry, I’ve just noticed that you have done this.)

I think that if you want to produce some SQL like your first statement, you're going to have to use linq. It's hard to know exactly what you need without access to your model, but I suspect it's going to look something like:

```<code>var users =
    from user in context.Users
    join acc in Accounts on user.ID equals acc.ClientId
    join broker in Brokers on acc.BrokerId equals broker.brokerid
    join r in Roles on user.id equals r.userid into roles
    from role in roles.DefaultIfEmpty()
    where role.RoleId == 1
    select user;   // or whatever you want to select

return users.ToList();
</code>```

The tricky part is the left outer join, and I'm not in a position to check my syntax at the moment, but I hope this helps.

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

Body:
Have you traced the SQL that your second statement produces? It looks like it's going to load all the Users, Accounts, Brokers and Roles without doing any of the joining and filtering that you want. If these tables are large this could take time.

(EDIT: Sorry, I’ve just noticed that you have done this.)

I think that if you want to produce some SQL like your first statement, you're going to have to use linq. It's hard to know exactly what you need without access to your model, but I suspect it's going to look something like:

var users =
    from user in context.Users
    join acc in Accounts on user.ID equals acc.ClientId
    join broker in Brokers on acc.BrokerId equals broker.brokerid
    join r in Roles on user.id equals r.userid into roles
    from role in roles.DefaultIfEmpty()
    where role.RoleId == 1
    select user;   // or whatever you want to select

return users.ToList();

The tricky part is the left outer join, and I'm not in a position to check my syntax at the moment, but I hope this helps.


来源: stackexchange

问:
Android method onSuccess() of AsyncHttpClient is deprecated. Is there an alternative for this?
```<code>@Override
public void onSuccess(String response) {
    progressDialog.hide();
    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
</code>```

答:
Just Update library to 1.4.9</p>

```<code>compile 'com.loopj.android:android-async-http:1.4.9'

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//code here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just Update library to 1.4.9

compile 'com.loopj.android:android-async-http:1.4.9'

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//code here
}


问:
Sort by or re-order, instead of hiding/showing
I'm trying to refactor my Javascript/Jquery to use a select option and hidden input value in order to sort the divs on the page.

Currently, my JS works but it's hiding all divs whose hidden input has a value of 0. I want to keep the logic, but instead of hiding, just reorder the divs.

So if the user selects Recently_ordered from the select box, then any div whose hidden input has a value of 1 would show first and all with 0 would show after. Basically, all items remain on page but reorder slightly.

here's the working script that currently hides:

```<code><script type="text/javascript">
$(function(){

$('#filterText').on('change', function() {
  var currentVal = $(this).val();

  $(".group-container").show();

  if (currentVal == 'recently_ordered') {
    $('.group-container input[name="reorder"]').each(function (index, value){

        if($(this).val() == "0"){
                $(this).parent('.group-container').hide();
            }
      });
    }
  });
});

</script>
</code>```

And the basic structure of the HTML:

```<code>@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>
</code>```

答:
Grab the .group-container elements as array, sort it according to their reorder value and append them to the DOM in the order of the array.

The snippet is really verbose but should give enough informations to follow the code.

The functions used in this snippet should all have a link to the official documentation or the description in the Mozilla Development Network in the comments.

The "groups" in the DOM have the mentioned hidden input fields and an additional
 element which shows the value of the topseller and reorder fields which should make it easier to follow the changes from the script.

$(function() {
  $("#filterText").on("change", function() {
    var container = $(".container"),  // get the surrounding container, used for appending the sorted groups
        groups = $(".group-container").get(),  // grab the "groups" and make them a regular array
                                               // .get() -> https://api.jquery.com/get/
        currentVal = this.value;  // the value of the selected option

    groups
      // first we have to sort them in the "correct" order
      // Array.prototype.sort() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
      .sort(function(left, right) {
        var topsellerValueLeft = parseInt(left.querySelector('input[name="topseller"]').value, 10),   // get the value of the topseller field and make it a number
            topsellerValueRight = parseInt(right.querySelector('input[name="topseller"]').value, 10), // get the value of the topseller field and make it a number
            // Element.prototype.querySelector -> https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
            // parseInt() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
            // parseInt($(left).find('input[name="topseller"]').val(), 10)
            // parseInt($(right).find('input[name="topseller"]').val(), 10)
            // would yield the same result, but we don't need two full-blown jQuery objects just to get the value
            reorderValueLeft,
            reorderValueRight;

        // in case of "recently ordered" we sort the groups on their reorder value
        if (currentVal === "recently_ordered") {
          reorderValueLeft = parseInt(left.querySelector('input[name="reorder"]').value, 10);    // get the value of the reorder field and make it a number
          reorderValueRight = parseInt(right.querySelector('input[name="reorder"]').value, 10);  // get the value of the reorder field and make it a number

          // we have to check the reorder value only when the values are different
          if (reorderValueLeft !== reorderValueRight) {
            return reorderValueRight - reorderValueLeft;  // sort descending -> 1 ... 0
          }
        }

        // either we are not supposed to sort the items by their reordered value
        // or they have the same reordered value
        // hence we will then sort them on their topseller value
        // this time in ascending order
        return topsellerValueLeft - topsellerValueRight;
      })
      // now we append the elements to the DOM in the same order as we find them in the array
      // this will "remove" the groups one by one from the DOM and append it at their correct new spot
      // Array.prototype.forEach() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
      .forEach(function(group) {
        container.append(group);  // .append() -> https://api.jquery.com/append/
      });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="filterText">
  <option value="default">default</option>
  <option value="recently_ordered">recently ordered</option>
</select>
<br />
<div class="container">
  <div class="group-container">
    <p>1 | 1</p>
    <input type="hidden" name="topseller" value="1" />
    <input type="hidden" name="reorder" value="1" />
  </div>
  <div class="group-container">
    <p>2 | 0</p>
    <input type="hidden" name="topseller" value="2" />
    <input type="hidden" name="reorder" value="0" />
  </div>
  <div class="group-container">
    <p>3 | 1</p>
    <input type="hidden" name="topseller" value="3" />
    <input type="hidden" name="reorder" value="1" />
  </div>
  <div class="group-container">
    <p>4 | 0</p>
    <input type="hidden" name="topseller" value="4" />
    <input type="hidden" name="reorder" value="0" />
  </div>
</div></code>```

(or on jsfiddle.net)

Body:
I'm trying to refactor my Javascript/Jquery to use a select option and hidden input value in order to sort the divs on the page.

Currently, my JS works but it's hiding all divs whose hidden input has a value of 0. I want to keep the logic, but instead of hiding, just reorder the divs.

So if the user selects Recently_ordered from the select box, then any div whose hidden input has a value of 1 would show first and all with 0 would show after. Basically, all items remain on page but reorder slightly.

here's the working script that currently hides:

And the basic structure of the HTML:

@foreach ($orderFormData->pgroups as $pgroup)

        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>

Body:
Grab the .group-container elements as array, sort it according to their reorder value and append them to the DOM in the order of the array.

The snippet is really verbose but should give enough informations to follow the code.

The functions used in this snippet should all have a link to the official documentation or the description in the Mozilla Development Network in the comments.

The "groups" in the DOM have the mentioned hidden input fields and an additional <p> element which shows the value of the topseller and reorder fields which should make it easier to follow the changes from the script.

$(function() {
  $("#filterText").on("change", function() {
    var container = $(".container"),  // get the surrounding container, used for appending the sorted groups
        groups = $(".group-container").get(),  // grab the "groups" and make them a regular array
                                               // .get() -> https://api.jquery.com/get/
        currentVal = this.value;  // the value of the selected option

    groups
      // first we have to sort them in the "correct" order
      // Array.prototype.sort() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
      .sort(function(left, right) {
        var topsellerValueLeft = parseInt(left.querySelector('input[name="topseller"]').value, 10),   // get the value of the topseller field and make it a number
            topsellerValueRight = parseInt(right.querySelector('input[name="topseller"]').value, 10), // get the value of the topseller field and make it a number
            // Element.prototype.querySelector -> https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
            // parseInt() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
            // parseInt($(left).find('input[name="topseller"]').val(), 10)
            // parseInt($(right).find('input[name="topseller"]').val(), 10)
            // would yield the same result, but we don't need two full-blown jQuery objects just to get the value
            reorderValueLeft,
            reorderValueRight;

        // in case of "recently ordered" we sort the groups on their reorder value
        if (currentVal === "recently_ordered") {
          reorderValueLeft = parseInt(left.querySelector('input[name="reorder"]').value, 10);    // get the value of the reorder field and make it a number
          reorderValueRight = parseInt(right.querySelector('input[name="reorder"]').value, 10);  // get the value of the reorder field and make it a number

          // we have to check the reorder value only when the values are different
          if (reorderValueLeft !== reorderValueRight) {
            return reorderValueRight - reorderValueLeft;  // sort descending -> 1 ... 0
          }
        }

        // either we are not supposed to sort the items by their reordered value
        // or they have the same reordered value
        // hence we will then sort them on their topseller value
        // this time in ascending order
        return topsellerValueLeft - topsellerValueRight;
      })
      // now we append the elements to the DOM in the same order as we find them in the array
      // this will "remove" the groups one by one from the DOM and append it at their correct new spot
      // Array.prototype.forEach() -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
      .forEach(function(group) {
        container.append(group);  // .append() -> https://api.jquery.com/append/
      });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="filterText">
  <option value="default">default</option>
  <option value="recently_ordered">recently ordered</option>
</select>
<br />
<div class="container">
  <div class="group-container">
    <p>1 | 1</p>
    <input type="hidden" name="topseller" value="1" />
    <input type="hidden" name="reorder" value="1" />
  </div>
  <div class="group-container">
    <p>2 | 0</p>
    <input type="hidden" name="topseller" value="2" />
    <input type="hidden" name="reorder" value="0" />
  </div>
  <div class="group-container">
    <p>3 | 1</p>
    <input type="hidden" name="topseller" value="3" />
    <input type="hidden" name="reorder" value="1" />
  </div>
  <div class="group-container">
    <p>4 | 0</p>
    <input type="hidden" name="topseller" value="4" />
    <input type="hidden" name="reorder" value="0" />
  </div>
</div>

(or on jsfiddle.net)


问:
Mysql Select and count number of times in another table
I am trying to get the best SQL sentence for get the data but my sentence need 7 seconds to search and retrieve the data from a table with 9000 records.

```<code> --------------     ---------------
| Table 1      |   | Table 2       |
 --------------     ---------------
| ID           |   |  ID           |
| Ticket Number|   |  ID Relation  |
 --------------    |  Ticket Number|
                    ---------------
</code>```

So Table 1 contains the data of the ticket but 2 o more tickets can be a "grouped ticket" so the relations of this tickets are in the table 2 that contain for the same "ID Relation" every ticket is grouped.

My sentence now is:

```<code>SELECT T1.ID, COUNT(REPEATT2.ID)
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.TicketNumber=T1.TicketNumber
INNER JOIN Table2 REPEATT2ON REPEATT2.IDRelation=T2.IDRelation
GROUP BY T1.ID;
</code>```

So what i am doing is with the 1st "INNER JOIN" i get the "ID Relation" and with the second "INNER JOIN" i get all the files that have that "ID Relation". As i said this sentence needs 7 seconds to get the data for a table with 9000 registers in the Table1.

For example with this values:

```<code>Table 1:
ID, Ticket Number
11   33
12   34
13   35

Table 2:

    ID, ID Relation  Ticket Number
    1   11             33
    2   11             34
    3   12             35
</code>```

So as result i want:

```<code>T1.Ticket Number COUNT(T2.ID Relation)
33                2
34                2
35                1
</code>```

I think i am missing something, if someone that know more about sql can help me will be great.

Thank you.

答:
First if I have understood what you want is the number of ticket in a relation:

```<code>SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation
</code>```

If you want T1.ID then :

```<code>SELECT T1.ID, Count(T2.IDRelation)
FROM Table2
INNER JOIN (
    SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation) T2 ON T2.IDRelation = Table2.IDRelation
INNER JOIN Table1 T1 ON Table2.TicketNumber = T1.TicketNumber
GROUP BY T1.ID
</code>```

But as you are doing INNER JOIN this is quite useless if you want ALL the tickets and count in how much relation they are, here is what you need to do :

```<code>SELECT T1.TicketNumber, Count(T2.IDRelation)
FROM Table1 T1
LEFT JOIN Table2 ON Table2.TicketNumber = T1.TicketNumber
INNER JOIN (SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation) T2 ON T2.IDRelation = Table2.IDRelation
GROUP BY T1.TicketNumber
</code>```

Body:
I am trying to get the best SQL sentence for get the data but my sentence need 7 seconds to search and retrieve the data from a table with 9000 records.

 --------------     ---------------
| Table 1      |   | Table 2       |
 --------------     ---------------
| ID           |   |  ID           |
| Ticket Number|   |  ID Relation  |
 --------------    |  Ticket Number|
                    ---------------

So Table 1 contains the data of the ticket but 2 o more tickets can be a "grouped ticket" so the relations of this tickets are in the table 2 that contain for the same "ID Relation" every ticket is grouped.

My sentence now is:

SELECT T1.ID, COUNT(REPEATT2.ID)
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.TicketNumber=T1.TicketNumber
INNER JOIN Table2 REPEATT2ON REPEATT2.IDRelation=T2.IDRelation
GROUP BY T1.ID;

So what i am doing is with the 1st "INNER JOIN" i get the "ID Relation" and with the second "INNER JOIN" i get all the files that have that "ID Relation". As i said this sentence needs 7 seconds to get the data for a table with 9000 registers in the Table1.

For example with this values:

Table 1:
ID, Ticket Number
11   33
12   34
13   35

Table 2:

    ID, ID Relation  Ticket Number
    1   11             33
    2   11             34
    3   12             35

So as result i want:

T1.Ticket Number COUNT(T2.ID Relation)
33                2
34                2
35                1

I think i am missing something, if someone that know more about sql can help me will be great.

Thank you.

Body:
First if I have understood what you want is the number of ticket in a relation:

SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation

If you want T1.ID then :

SELECT T1.ID, Count(T2.IDRelation)
FROM Table2
INNER JOIN (
    SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation) T2 ON T2.IDRelation = Table2.IDRelation
INNER JOIN Table1 T1 ON Table2.TicketNumber = T1.TicketNumber
GROUP BY T1.ID

But as you are doing INNER JOIN this is quite useless if you want ALL the tickets and count in how much relation they are, here is what you need to do :

SELECT T1.TicketNumber, Count(T2.IDRelation)
FROM Table1 T1
LEFT JOIN Table2 ON Table2.TicketNumber = T1.TicketNumber
INNER JOIN (SELECT IDRelation, Count(TicketNumber)
FROM Table2
GROUP BY IDRelation) T2 ON T2.IDRelation = Table2.IDRelation
GROUP BY T1.TicketNumber


问:
kNN in R using two parameters
Is it possible to train the data in relation to both the trainData$sp and trainData$sex ?

```<code>library(dplyr)
library(caret)
library(e1071)

data(crabs, package = "MASS")
crabs = mutate_if(crabs, is.character, as.factor)
set.seed(1234)
index <- createDataPartition(crabs$sp, p=0.70, list=FALSE)
trainData= crabs[index,]
testData= crabs[-index,]
model_knn1 = knn3(trainData[,4:8], testData$sp, cl=trainData$sp, k=1)
</code>```

In the code above I'm only training the data in relation to the species (trainData$sp).

答:
The solution was to create a column with both values as one and use that :</p>

```<code>crabs$parameter <- paste(crabs$sp , crabs$sex, sep="|")
</code>```

Title: kNN in R using two parameters

Body:
Is it possible to train the data in relation to both the trainData$sp and trainData$sex ?

library(dplyr)
library(caret)
library(e1071)

data(crabs, package = "MASS")
crabs = mutate_if(crabs, is.character, as.factor)
set.seed(1234)
index <- createDataPartition(crabs$sp, p=0.70, list=FALSE)
trainData= crabs[index,]
testData= crabs[-index,]
model_knn1 = knn3(trainData[,4:8], testData$sp, cl=trainData$sp, k=1)

In the code above I'm only training the data in relation to the species (trainData$sp).

Body:
The solution was to create a column with both values as one and use that :

crabs$parameter <- paste(crabs$sp , crabs$sex, sep="|")


问:
How to use strings in emu8086
I need help with strings in emu8086. I have initialized a string:

```<code>str1 db "0neWord"
</code>```

And I have an empty string:

```<code>str2 db ?
</code>```

Now I need to check all letters in str1 and copy to str2, but if the letter in str1 is 0, I need to replace it with O. If not, I need to just copy the letter.

How can I do this?

答:
There are multiple ways to do that.  Here are some examples:

1)   With String Instruction:

```<code>.model small

.data

        str1 db "0neWord$"

        size equ $-str1

        str2 db size dup ('')

.code

main:

        mov ax, @data
        mov ds, ax

        mov cx, size

        cld          ; DF might have been set, but we want lodsb to go forwards
        lea si, str1
        mov ax, 0
        mov bx, 0

     copyStr:

        lodsb  ;str1 to al

        cmp al, '0'
        je alterChar

        mov str2[bx], al
        jmp continue

     alterChar:

        mov str2[bx], 'o'

     continue:

        inc bx

        loop copyStr

        mov str2[bx], '$'

        mov ah, 09h
        lea dx, str2
        int 21h

        mov ah, 04ch
        int 21h

end main
</code>```

2) Without String Instruction:

```<code>.model small

.data

        str1 db "0neWord$"
        str2 db ?

.code

main:

        mov ax, @data
        mov ds, ax

        mov si, 0

        call copyStr

        mov ah, 09h
        lea dx, str2
        int 21h

        mov ah, 04ch
        int 21h

   copyStr proc

        mov bx, 0

      compute:

           mov bl, str1 [si]

           cmp bl, '0'
           je alterChar

           mov str2[si], bl

           jmp continue

        alterChar:

           mov str2 [si], 'o'

        continue:

           inc si

           cmp str1[si], '$'
           je return
           jmp compute

      return:

           mov str2[si], '$'
           ret

   copyStr endp

end main
</code>```

LODSB Instruction you can learn more about string instructions from here

3) With lodsb / stosb and simplified / optimized:

```<code>.model small
.data
        str1 db "0neWord$"
        size equ $-str1

        str2 db size dup ('')

.code
main:
        mov   ax, @data
        mov   ds, ax
        mov   es, ax       ; stosb stores to [es:di]

        mov   si, OFFSET str1
        mov   di, OFFSET str2
        cld          ; make sure stosb/lodsb go forwards

     ; copy SI to DI, including the terminating '$'
     copyStr:           ; do {
        lodsb             ; str1 to al

        cmp   al, '0'
        je    alterChar

     doneAlteration:
        stosb             ; al to str2
        cmp   al, '$'
        jne   copyStr    ; } while(c != '$')

        mov   ah, 09h      ; print implicit-length string
        mov   dx, OFFSET str2
        int   21h

        mov   ah, 04ch     ; exit
        int   21h

     alterChar:
        mov   al, 'o'
        ;jmp   doneAlteration
        stosb
        jmp   copyStr

end main
</code>```

Title: How to use strings in emu8086

Body:
I need help with strings in emu8086. I have initialized a string:

str1 db "0neWord"

And I have an empty string:

str2 db ?

Now I need to check all letters in str1 and copy to str2, but if the letter in str1 is 0, I need to replace it with O. If not, I need to just copy the letter.

How can I do this?

Body:
There are multiple ways to do that.  Here are some examples:

1)   With String Instruction:

.model small

.data

        str1 db "0neWord$"

        size equ $-str1

        str2 db size dup ('')

.code

main:

        mov ax, @data
        mov ds, ax

        mov cx, size

        cld          ; DF might have been set, but we want lodsb to go forwards
        lea si, str1
        mov ax, 0
        mov bx, 0

     copyStr:

        lodsb  ;str1 to al

        cmp al, '0'
        je alterChar

        mov str2[bx], al
        jmp continue

     alterChar:

        mov str2[bx], 'o'

     continue:

        inc bx

        loop copyStr

        mov str2[bx], '$'

        mov ah, 09h
        lea dx, str2
        int 21h

        mov ah, 04ch
        int 21h

end main

2) Without String Instruction:

.model small

.data

        str1 db "0neWord$"
        str2 db ?

.code

main:

        mov ax, @data
        mov ds, ax

        mov si, 0

        call copyStr

        mov ah, 09h
        lea dx, str2
        int 21h

        mov ah, 04ch
        int 21h

   copyStr proc

        mov bx, 0

      compute:

           mov bl, str1 [si]

           cmp bl, '0'
           je alterChar

           mov str2[si], bl

           jmp continue

        alterChar:

           mov str2 [si], 'o'

        continue:

           inc si

           cmp str1[si], '$'
           je return
           jmp compute

      return:

           mov str2[si], '$'
           ret

   copyStr endp

end main

LODSB Instruction you can learn more about string instructions from here

3) With lodsb / stosb and simplified / optimized:

.model small
.data
        str1 db "0neWord$"
        size equ $-str1

        str2 db size dup ('')

.code
main:
        mov   ax, @data
        mov   ds, ax
        mov   es, ax       ; stosb stores to [es:di]

        mov   si, OFFSET str1
        mov   di, OFFSET str2
        cld          ; make sure stosb/lodsb go forwards

     ; copy SI to DI, including the terminating '$'
     copyStr:           ; do {
        lodsb             ; str1 to al

        cmp   al, '0'
        je    alterChar

     doneAlteration:
        stosb             ; al to str2
        cmp   al, '$'
        jne   copyStr    ; } while(c != '$')

        mov   ah, 09h      ; print implicit-length string
        mov   dx, OFFSET str2
        int   21h

        mov   ah, 04ch     ; exit
        int   21h

     alterChar:
        mov   al, 'o'
        ;jmp   doneAlteration
        stosb
        jmp   copyStr

end main


问:
ClickOnce deployed application registry persmission issue
I have developed an application in C# with an option to run at Windows startup implemented using registry (current user hive). When I run my application from VS or from the bin folder, this option works.

When I create ClickOnce installer (to be run from internet) and put it on Codeplex, after the application is installed this option does not work. No exception is thown, it just makes registry write. I suppose there is some kind of a security issue.

I tried to create a ClickOnce installer with the option to be run from a CD/local storage , after the application is installed it works. It just does not work after installing using the ClickOnce web installer (put on CodePlex).

I looked at the Publish settings, there are set to default = full trust. I really do not know what to do now to make the run at startup option work.

答:
Create a second (console) application, that will preform the write, and add it to the references of you original application.

When your user starts the application, check if the registry key is set, if not run the before-mentioned console application with elevated rights. The user will be prompted for administration rights, and the write operation should succeed.

In your main app you have to add the reference to the console app. For easier assembly reference the console app should have at least 1 public class, so that you can get it type and the types assemlby and you thus don't have to use magic strings to get filenames. Example:

```<code> Process.Start(
       new ProcessStartInfo
       {
           Verb = "runas",
           FileName = typeof(SomeClassInOtherAssembly).Assembly.Location,
           UseShellExecute = true,
           CreateNoWindow = true // Optional....
       }).WaitForExit();
</code>```

I also found this nice blog post.

ContentLicense: CC BY-SA 2.5

Body:
Create a second (console) application, that will preform the write, and add it to the references of you original application.

When your user starts the application, check if the registry key is set, if not run the before-mentioned console application with elevated rights. The user will be prompted for administration rights, and the write operation should succeed.

In your main app you have to add the reference to the console app. For easier assembly reference the console app should have at least 1 public class, so that you can get it type and the types assemlby and you thus don't have to use magic strings to get filenames. Example:

 Process.Start(
       new ProcessStartInfo
       {
           Verb = "runas",
           FileName = typeof(SomeClassInOtherAssembly).Assembly.Location,
           UseShellExecute = true,
           CreateNoWindow = true // Optional....
       }).WaitForExit();

I also found this nice blog post.


问:
Exception in thread "main" java.lang.Error: Unresolved compilation
The declared package "" does not match the expected package "src"
I am trying to compile this program and I get the above error.
I imported the project from the downloads folder and copied it to my workspace. Do i need to create a new package ?

What am i doing wrong ?

答: It is happened because your class is not in correct package, you should put your class under defaults package then your issue will be fine; otherwise you should write in top of your class ,your package name for example " mohsen package;"    </p>


问:
Change multiple string in a list
I have a list

```<code>task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
</code>```

the result i want is

```<code>task_list = ['1A1.wakeup', '1A2.brush','2B1.route','2B2.breakfast']
</code>```

I use a for loop:

```<code>new_task_list = task_list[:]
for task in new_task_list:
    task.replace('A', '1A')
    task.replace('B','1B')

In [61]: new_task_list
Out[61]: ['A1.wakeup', 'A2.brush', 'B1.route', 'B2.breakfast']
</code>```

It does not change, What's the problem?

答:
Taking cue from Moses Koledoye's answer

```<code>task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
</code>```

Getting the difference of ascii value of A (=65), B (=66) and 64

```<code>[ str( ord(x[0]) - 64 )+x for x in task_list ]

# ['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']
</code>```

Title: Change multiple string in a list

Body:
I have a list

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']

the result i want is

task_list = ['1A1.wakeup', '1A2.brush','2B1.route','2B2.breakfast']

I use a for loop:

new_task_list = task_list[:]
for task in new_task_list:
    task.replace('A', '1A')
    task.replace('B','1B')

In [61]: new_task_list
Out[61]: ['A1.wakeup', 'A2.brush', 'B1.route', 'B2.breakfast']

It does not change, What's the problem?

Body:
Taking cue from Moses Koledoye's answer

task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']

Getting the difference of ascii value of A (=65), B (=66) and 64

[ str( ord(x[0]) - 64 )+x for x in task_list ]

# ['1A1.wakeup', '1A2.brush', '2B1.route', '2B2.breakfast']


问:
How Can I Detect If One Div Is Outside Another Div?
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }</code>```

     ```

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

答:
You can make a check before changing the child div position, if its new position is outside of where you want it to be, you can skip it.

Something like:

```<code>if (mouse.x > parent_div_width){
    return;
}
else {
   child_div_Xpos = mouse.x
}
</code>```

Body:
I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

        var mousex, mousey;
          function mousepos(e){
            mousex = e.clientX;
            mousey = e.clientY;
            document.getElementById("xy").innerText = mousex + " , " + mousey;
          }
          function testdiv(){
            document.getElementById("testdiv").style.left = mousex;
            document.getElementById("testdiv").style.top = mousey;
            setTimeout(testdiv, 30);
          }

          #city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500;
            width: 500;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }
          #xy{
            color: white;
          }
          #testdiv{
            background-color: white;
            position: absolute;
            width: 100px;
            height: 100px;
          }
          #body{
            background-color: black;
          }

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

Body:
You can make a check before changing the child div position, if its new position is outside of where you want it to be, you can skip it.

Something like:

if (mouse.x > parent_div_width){
    return;
}
else {
   child_div_Xpos = mouse.x
}


问:
How do I resize text inside a table using media queries?
I have this html

```<code><meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/newcss.css"/>
</code>```

...

```<code><table>
  <tbody>
    <tr>
      <td>General Inquiries:</td>
      <td>Email@email.com</td>
    </tr>
    <tr>
      <td>Phone:</td>
      <td>#########</td>
    </tr>
    <tr>
      <td>Mailing address:</td>
      <td>123 Some St. 123 456</td>
    </tr>
  </tbody>
</table>
</code>```

and this css

```<code>table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
}

td {
    padding: 0px 10px;
}

@media (max-width: 730){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}
</code>```

However, when I resize the window to below 730, the font size does not change on any of the elements listed in the media query. Any Ideas?

答:
You simply forgot to add the unit in your max-width statement! Just add px after the number and it will work (click the "View Fullscreen" link below the snippet in order to be able to see the change):

table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
    background: #666; /* added this for the snippet so we can see the text at all */
}

td {
    padding: 0px 10px;
}

@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tbody>
    <tr>
      <td>General Inquiries:</td>
      <td>Email@email.com</td>
    </tr>
    <tr>
      <td>Phone:</td>
      <td>#########</td>
    </tr>
    <tr>
      <td>Mailing address:</td>
      <td>123 Some St. 123 456</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have this html

<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/newcss.css"/>

...

      General Inquiries:
      Email@email.com

      Phone:
      #########

      Mailing address:
      123 Some St. 123 456

and this css

table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
}

td {
    padding: 0px 10px;
}

@media (max-width: 730){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

However, when I resize the window to below 730, the font size does not change on any of the elements listed in the media query. Any Ideas?

Body:
You simply forgot to add the unit in your max-width statement! Just add px after the number and it will work (click the "View Fullscreen" link below the snippet in order to be able to see the change):

table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
    background: #666; /* added this for the snippet so we can see the text at all */
}

td {
    padding: 0px 10px;
}

@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

<table>
  <tbody>
    <tr>
      <td>General Inquiries:</td>
      <td>Email@email.com</td>
    </tr>
    <tr>
      <td>Phone:</td>
      <td>#########</td>
    </tr>
    <tr>
      <td>Mailing address:</td>
      <td>123 Some St. 123 456</td>
    </tr>
  </tbody>
</table>


问:
Mapping objects
Does anyone know about any third party .NET libraries which could map objects between different layers of a project like view and model.</p>

答: Subsonic if you want to interact with a db</p>

Title: Mapping objects


问:
Granting write access for the Authenticated Users to S3 bucket
I want to give read access to all AWS authenticated users to a bucket. Note I don't want my bucket to be publicly available. Old amazon console seems to give that provision which I no longer see -

Old S3 bucket ACL -

New bucket Acl -

How can I achieve old behavior? Can I do it using bucket policies -

Again I don't want

```<code>{
  "Id": "Policy1510826508027",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1510826503866",
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::athakur",
      "Principal": {
        "AWS": [
          "*"
        ]
      }
    }
  ]
}
</code>```

答:
That support is removed in the new s3 console and has to be set via ACL.

You can use the put-bucket-acl api to set the Any Authenticated AWS User as grantee.

The grantee for this is:

<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group"><URI><replaceable>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</replaceable></URI></Grantee>

Refer http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html for more info.

Body:
I want to give read access to all AWS authenticated users to a bucket. Note I don't want my bucket to be publicly available. Old amazon console seems to give that provision which I no longer see -

Old S3 bucket ACL -

New bucket Acl -

How can I achieve old behavior? Can I do it using bucket policies -

Again I don't want

{
  "Id": "Policy1510826508027",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1510826503866",
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::athakur",
      "Principal": {
        "AWS": [
          "*"
        ]
      }
    }
  ]
}


问:
How to rank column accordingly using case_when?
I wanted to create another column (called delayGrade) where the top 10% of values (closest to 0) from another column (averageDelay) get assigned the letter 'A', the next 25% 'B', and the remaining 'C'. I figured I could use a case_when function to do so, but not sure how to go about doing it. Any ideas?</p>

答:
Here is toy data frame and solution:</p>

```<code>library(tidyverse)

df <- tibble(
  averageDelay = rnorm(10)
)

df %>%
  mutate(
    delayGrade = case_when(
      averageDelay < quantile(averageDelay, .1)  ~ "A",
      averageDelay < quantile(averageDelay, .35) ~ "B",
      TRUE                                       ~ "C"
    )
  ) %>%
  arrange(averageDelay) # Not necissary, but improves readability

# A tibble: 10 x 2
   averageDelay delayGrade
          <dbl>      <chr>
 1  -1.57878473          A
 2  -1.00129022          B
 3  -0.34245100          B
 4  -0.08652020          B
 5  -0.05240453          C
 6   0.15732711          C
 7   0.21509389          C
 8   0.34202367          C
 9   0.90296373          C
10   0.90820894          C
</code>```

Body:
Here is toy data frame and solution:

library(tidyverse)

df <- tibble(
  averageDelay = rnorm(10)
)

df %>%
  mutate(
    delayGrade = case_when(
      averageDelay < quantile(averageDelay, .1)  ~ "A",
      averageDelay < quantile(averageDelay, .35) ~ "B",
      TRUE                                       ~ "C"
    )
  ) %>%
  arrange(averageDelay) # Not necissary, but improves readability

# A tibble: 10 x 2
   averageDelay delayGrade
          <dbl>      <chr>
 1  -1.57878473          A
 2  -1.00129022          B
 3  -0.34245100          B
 4  -0.08652020          B
 5  -0.05240453          C
 6   0.15732711          C
 7   0.21509389          C
 8   0.34202367          C
 9   0.90296373          C
10   0.90820894          C


问:
Suppressing anti-forgery X-Frame options header in the global.asax weakens security despite setting X-Frame options in Web.config?
Our MVC5 application contains a partial view that renders a Html.AntiForgeryToken on all pages using the Master.cshtml.

On pages where we render another form, and another Html.AntiForgeryToken, on form submission an exception is thrown:

```<code>Server cannot append header after HTTP headers have been sent.
</code>```

To avoid the exception, within the Global.asax App_Start we can specify:

```<code>AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
</code>```

Our concern here is we're enabling others to embed our website as an iFrame, and enabling 'ClickJacking'?

The above mentioned occurs regardless of us also using Umbraco 7.6.1 which requires we specify within our Web.config:

```<code>    <httpProtocol>
     <customHeaders>
      <remove name="X-Powered-By" />
      <add name="X-Frame-Options" value="SAMEORIGIN" />
     </customHeaders>
    </httpProtocol>
</code>```

Is there an alternative to this contradictive configuration? Are we weakening security?

答:
By suppressing the X-Frame-Options header from Html.AntiForgeryToken, you potentially weaken security by assuming responsibility for applying the X-Frame-Options header.

In your case security is not weakened because you are using the Web.config to apply an X-Frame-Options header with the same value that Html.AntiForgeryToken would apply. Your security is actually stronger than what Html.AntiForgeryToken provides because the X-Frame-Options header will be applied to all responses which includes forms where you neglected to or can't use Html.AntiForgeryToken.

Body:
Our MVC5 application contains a partial view that renders a Html.AntiForgeryToken on all pages using the Master.cshtml.

On pages where we render another form, and another Html.AntiForgeryToken, on form submission an exception is thrown:

Server cannot append header after HTTP headers have been sent.

To avoid the exception, within the Global.asax App_Start we can specify:

AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

Our concern here is we're enabling others to embed our website as an iFrame, and enabling 'ClickJacking'?

The above mentioned occurs regardless of us also using Umbraco 7.6.1 which requires we specify within our Web.config:

    <httpProtocol>
     <customHeaders>
      <remove name="X-Powered-By" />
      <add name="X-Frame-Options" value="SAMEORIGIN" />
     </customHeaders>
    </httpProtocol>

Is there an alternative to this contradictive configuration? Are we weakening security?


问:
Using dplyr `enquo` after calling argument
I have a function that roughly follows this structure:

```<code>TestFunc <- function(dat, point) {
    if (!(point %in% c("NW", "SE", "SW")))
        stop("point must be one of 'SW', 'SE', 'NW'")

    point <- enquo(point)

    return(dat %>% filter(point == !!point))
</code>```

The issue is that I get the following error when I include the check for values:

```<code>Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

The error disappears when I remove the check.  How can I keep both?

答:
Evaluate point so filter can tell the difference between the argument and the data's column

aosmith has a good idea, so I'm putting it in answer form, along with a reproducible example:

```<code>f <- function(dat, point) {
  if (!(point %in% c("NW", "SE", "SW")))
    stop("point must be one of 'SW', 'SE', 'NW'")

  filter(dat, point == !!point)
}

tbl <- tibble(point = c('SE', 'NW'))
f(tbl, 'SE')
f(tbl, 'XX')
</code>```

If you're passing point in as a string, you only need to differentiate the argument point ( = "SE", in this case) and the column dat$point (or tbl$point, depending if you're inside or outside the function). From the dplyr programming doc:

In dplyr (and in tidyeval in general) you use !! to say that you want to unquote an input so that it’s evaluated, not quoted.

You want to evaluate the argument point so that "SE" is passed to filter, that way filter can tell the difference between the column point and the argument SE.

(I also tried using filter(dat, .data$point == point), but the RHS point still refers to the column, not the f argument.)

I hope this example helps with your real code.

Body:
I have a function that roughly follows this structure:

TestFunc <- function(dat, point) {
    if (!(point %in% c("NW", "SE", "SW")))
        stop("point must be one of 'SW', 'SE', 'NW'")

    point <- enquo(point)

    return(dat %>% filter(point == !!point))

The issue is that I get the following error when I include the check for values:

Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

The error disappears when I remove the check.  How can I keep both?

Body:
Evaluate point so filter can tell the difference between the argument and the data's column

aosmith has a good idea, so I'm putting it in answer form, along with a reproducible example:

f <- function(dat, point) {
  if (!(point %in% c("NW", "SE", "SW")))
    stop("point must be one of 'SW', 'SE', 'NW'")

  filter(dat, point == !!point)
}

tbl <- tibble(point = c('SE', 'NW'))
f(tbl, 'SE')
f(tbl, 'XX')

If you're passing point in as a string, you only need to differentiate the argument point ( = "SE", in this case) and the column dat$point (or tbl$point, depending if you're inside or outside the function). From the dplyr programming doc:

In dplyr (and in tidyeval in general) you use !! to say that you want to unquote an input so that it’s evaluated, not quoted.

You want to evaluate the argument point so that "SE" is passed to filter, that way filter can tell the difference between the column point and the argument SE.

(I also tried using filter(dat, .data$point == point), but the RHS point still refers to the column, not the f argument.)

I hope this example helps with your real code.


问:
C - Matrix input function gets runtime error if matrix is bigger than 5x5, but there is no size defined at the code
I'm using this function to read the input matrix:

```<code>void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}
</code>```

And I'm creating the matrix like this:

```<code>scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);
</code>```

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

答:
matriz1 is a double pointer so while allocating memory you should write sizeof(int*). because ** pointer will holds/contains * single pointers.

```<code>int **matriz1 = malloc(v1 * sizeof(int*));
for(i = 0;i < v1; i++){
    matriz1[i] = malloc(v1 * sizeof(int));
}
</code>```

typecasting malloc() is discouraged.

Body:
I'm using this function to read the input matrix:

void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}

And I'm creating the matrix like this:

scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

Body:
matriz1 is a double pointer so while allocating memory you should write sizeof(int*). because ** pointer will holds/contains * single pointers.

int **matriz1 = malloc(v1 * sizeof(int*));
for(i = 0;i < v1; i++){
    matriz1[i] = malloc(v1 * sizeof(int));
}

typecasting malloc() is discouraged.


问:
Java 8 Streams FlatMap method example
I have been checking the upcoming Java update, namely: Java 8 or JDK 8. Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code:

```<code>final Stream<Integer>stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
stream.flatMap();
</code>```

the javadocs are

public <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)
      This is an intermediate operation.

I would appreciate if somebody created some simple real-life examples about flatMap, how you could code it in previous java versions Java[6,7] and how you can code the same routines using Java 8.

答:
A very simple example: Split a list of full names to get a list of names, regardless of first or last

```<code> List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);
</code>```

This prints out:

```<code>Barry
Allen
Bruce
Wayne
Clark
Kent
</code>```

Title: Java 8 Streams FlatMap method example

Body:
I have been checking the upcoming Java update, namely: Java 8 or JDK 8. Yes, I am impatient, there's a lot of new stuff, but, there is something I don't understand, some simple code:

final Stream<Integer>stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
stream.flatMap();

the javadocs are

public <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)
      This is an intermediate operation.

I would appreciate if somebody created some simple real-life examples about flatMap, how you could code it in previous java versions Java[6,7] and how you can code the same routines using Java 8.

Body:
A very simple example: Split a list of full names to get a list of names, regardless of first or last

 List<String> fullNames = Arrays.asList("Barry Allen", "Bruce Wayne", "Clark Kent");

 fullNames.stream()
            .flatMap(fullName -> Pattern.compile(" ").splitAsStream(fullName))
            .forEach(System.out::println);

This prints out:

Barry
Allen
Bruce
Wayne
Clark
Kent

ContentLicense: CC BY-SA 4.0


问:
Spring - JPA OneToMany without setParent on Child object
I have a Parent table that should point to some Childs, Here are my codes:

Parent :

```<code>public class Parent
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> childs;

    public List<Child> getChilds()
    {
        return this.childs;
    }

    public void setChilds(List<Child> childs)
    {
        this.childs = childs;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getId()
    {
        return this.id;
    }
}
</code>```

Child :

```<code>public class Child
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    public void setParent(Parent parent)
    {
        this.parent = parent;
    }

    public Parent getParent()
    {
        return this.parent;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getId()
    {
        return this.id;
    }
}
</code>```

Child table should store parent_id as foreign key, but without setting child.setParent(parent) this column is always null.

I don't want to call child.setParent(parent) because it will cause performance issue because i should create iterate.

答: Child is the owner of the relationship, so you have to call child.setParent(parent) to properly setup the relationship.

Body:
I have a Parent table that should point to some Childs, Here are my codes:

Parent :

public class Parent
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<Child> childs;

    public List<Child> getChilds()
    {
        return this.childs;
    }

    public void setChilds(List<Child> childs)
    {
        this.childs = childs;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getId()
    {
        return this.id;
    }
}

Child :

public class Child
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    public void setParent(Parent parent)
    {
        this.parent = parent;
    }

    public Parent getParent()
    {
        return this.parent;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getId()
    {
        return this.id;
    }
}

Child table should store parent_id as foreign key, but without setting child.setParent(parent) this column is always null.

I don't want to call child.setParent(parent) because it will cause performance issue because i should create iterate.


问:
Calculate Time Remaining
What's a good algorithm for determining the remaining time for something to complete?  I know how many total lines there are, and how many have completed already, how should I estimate the time remaining?</p>

答:
That really depends on what is being done... lines are not enough unless each individual line takes the same amount of time.

The best way (if your lines are not similar) would probably be to look at logical sections of the code find out how long each section takes on average, then use those average timings to estimate progress.

OwnerDisplayName: Aaron Smith

Title: Calculate Time Remaining


问:
Behavior of mysql_insert_id()
I am using functions from a php library that uses mysql_insert_id() every now and then. Now I've modified a few functions that insert data into tables such that the primary key value is explicitly specified e.g. I insert an a row with ID=300 followed by a row with ID=200 when the table originally had 10 rows. I am wondering if mysql_insert_id will behave as expected i.e. return the value I explicitly specified for the AUTO_INCREMENT PRIMARY KEY column.

答:
Table:

```<code>CREATE TABLE `foo` (
  `id` int(11) NOT NULL auto_increment,
  `value` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`)
) ;
</code>```

Code:

```<code>print phpversion()."\n";
mysql_connect('localhost','user','pass');
mysql_select_db('database');

mysql_query('INSERT INTO `foo` (`id`,`value`) VALUES(100,"bar")');
print var_export(mysql_insert_id())."\n";

mysql_query('INSERT INTO `foo` (`value`) VALUES("zoid")');
print var_export(mysql_insert_id())."\n";

mysql_query('INSERT INTO `foo` (`id`,`value`) VALUES(99,"yargh")');
print var_export(mysql_insert_id())."\n";

$q = mysql_query('SHOW TABLE STATUS LIKE "foo"');
$status = mysql_fetch_assoc($q);
mysql_free_result($q);
print $status['Auto_increment']."\n";

mysql_query('INSERT INTO `foo` (`value`) VALUES("whatever")');
print var_export(mysql_insert_id())."\n";
</code>```

Output:

```<code>5.2.XX-0.dotdeb.1
100
101
99
102
102
</code>```

TL/DR version: it returns the last id, be it auto incremented, or explicitly given.

UPDATE: Added INSERT with id < 100, as suggested by Mchl.

Title: Behavior of mysql_insert_id()

Body:
Table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL auto_increment,
  `value` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`)
) ;

Code:

print phpversion()."\n";
mysql_connect('localhost','user','pass');
mysql_select_db('database');

mysql_query('INSERT INTO `foo` (`id`,`value`) VALUES(100,"bar")');
print var_export(mysql_insert_id())."\n";

mysql_query('INSERT INTO `foo` (`value`) VALUES("zoid")');
print var_export(mysql_insert_id())."\n";

mysql_query('INSERT INTO `foo` (`id`,`value`) VALUES(99,"yargh")');
print var_export(mysql_insert_id())."\n";

$q = mysql_query('SHOW TABLE STATUS LIKE "foo"');
$status = mysql_fetch_assoc($q);
mysql_free_result($q);
print $status['Auto_increment']."\n";

mysql_query('INSERT INTO `foo` (`value`) VALUES("whatever")');
print var_export(mysql_insert_id())."\n";

Output:

5.2.XX-0.dotdeb.1
100
101
99
102
102

TL/DR version: it returns the last id, be it auto incremented, or explicitly given.

UPDATE: Added INSERT with id < 100, as suggested by Mchl.


问:
Vue.js2.0 - vue reactivity confusion
In my project , i have a shoppinglists Array to get displayed. When the component is mounted, the store is populated ( it' conatins only one array for the logged customer, fetched from the API db server... wo any problem)

On dissplay, I get the following message :

```<code>vue.esm.js?efeb:571 [Vue warn]: Property or method "shoppinglists" is not defined on
the instance but referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by initializing the
property.
See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
</code>```

The shoppinglists property is defined as computed ...

```<code>computed: {
  ...mapGetters([ { shoppinglists: 'getShoppingLists' } ])
},
</code>```

And the store contains the shoppinglists array

STATE

```<code>{
 "shoppinglists":
 [{"title":"Groceries","items":[{"text":"Bananas","checked":true},
 {"text":"Apples","checked":false}],"id":1,"userId":1}],
 "isAuthenticated":true,
 "currentUserId":1
 }
</code>```

If I insert a prop declaration in data :

```<code>   data: function () {
  return {
    shoppinglists: []
  }
},
</code>```

the warning disappear, but still theres is no list displayed..

what could be wrong ?
thanks for feedback

not exactly duplicated question, but not far from this one

答:
It looks like you have mixed the two different options for mapGetters().
You can either write it like this:

```<code>import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
</code>```

Which maps this.doneTodosCount to this.$store.doneTodosCount and so on.
Or you could do it this way, which is probably what you want:

```<code>...mapGetters({
  // map `this.doneCount` to `store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})
</code>```

And for your example this becomes:

```<code>computed: {
  ...mapGetters({ shoppinglists: 'getShoppingLists' })
},
</code>```

More documentation and source of the examples are at the bottom of this article.

Title: Vue.js2.0 - vue reactivity confusion

Body:
In my project , i have a shoppinglists Array to get displayed. When the component is mounted, the store is populated ( it' conatins only one array for the logged customer, fetched from the API db server... wo any problem)

On dissplay, I get the following message :

vue.esm.js?efeb:571 [Vue warn]: Property or method "shoppinglists" is not defined on
the instance but referenced during render. Make sure that this property is reactive,
either in the data option, or for class-based components, by initializing the
property.
See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

The shoppinglists property is defined as computed ...

computed: {
  ...mapGetters([ { shoppinglists: 'getShoppingLists' } ])
},

And the store contains the shoppinglists array

STATE

{
 "shoppinglists":
 [{"title":"Groceries","items":[{"text":"Bananas","checked":true},
 {"text":"Apples","checked":false}],"id":1,"userId":1}],
 "isAuthenticated":true,
 "currentUserId":1
 }

If I insert a prop declaration in data :

   data: function () {
  return {
    shoppinglists: []
  }
},

the warning disappear, but still theres is no list displayed..

what could be wrong ?
thanks for feedback

not exactly duplicated question, but not far from this one

Body:
It looks like you have mixed the two different options for mapGetters().
You can either write it like this:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

Which maps this.doneTodosCount to this.$store.doneTodosCount and so on.
Or you could do it this way, which is probably what you want:

...mapGetters({
  // map `this.doneCount` to `store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

And for your example this becomes:

computed: {
  ...mapGetters({ shoppinglists: 'getShoppingLists' })
},

More documentation and source of the examples are at the bottom of this article.


答:
I think you forgot the px after the 730, so try

```<code>@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}
</code>```

By the way, if possible, don't insert text inside the  directly, add a  or a
 to wrap the text inside.

Title: How do I resize text inside a table using media queries?

Body:
I think you forgot the px after the 730, so try

@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

By the way, if possible, don't insert text inside the <td> directly, add a <span> or a <p> to wrap the text inside.


问:
How to read a text file into a string variable and strip newlines?
I have a text file that looks like:

```<code>ABC
DEF
</code>```

How can I read the file into a single-line string without newlines, in this case creating a string 'ABCDEF'?

For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.

答:
Have you tried this?</p>

```<code>x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)
</code>```

Body:
I have a text file that looks like:

ABC
DEF

How can I read the file into a single-line string without newlines, in this case creating a string 'ABCDEF'?

For reading the file into a list of lines, but removing the trailing newline character from each line, see How to read a file without newlines?.

Body:
Have you tried this?

x = "yourfilename.txt"
y = open(x, 'r').read()

print(y)


问:
Mariadb-server 10.2. fresh install in debian 8 shows error
I have followed the link for installation .

https://downloads.mariadb.org/mariadb/repositories/#mirror=23Media&distro=Debian&distro_release=jessie--jessie&version=10.2

After adding Repo.list and keys , it started installing .But ended up with the following error message

Unable to set password for the MariaDB "root" user
An error occurred while setting the password for the MariaDB administrative user. This may have happened because the account already has a password, or because of a communication problem with the MariaDB server. You should check the account's password after the package installation.

But Mariadb-10.0 , 10.1 distributions are installing properly and working fine .

答:
The solution given by this link works for me
https://jira.mariadb.org/browse/MDEV-14416

It was a bug with ext3 file system. They fixed it already . The patch will be released in version 10.2.11.But for this above situation please do the following steps [I am doing fresh installation. so no databases inside].

open my.cnf file , find innodb_flush_method = O_DIRECT
  comment it and save .

rm -rf /var/lib/mysql/*

mysql_install_db

systemctl start mariadb.service

mysql -u root [without password]

After entering console , you can set password using the following command

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('pass');


问:
Visual Studio USE LOCAL IIS WEB SERVER issue with IIS 7.5
My Visual Studio 2010 issues following error when I try to map application to use local IIS:

A larger image can be viewed here:

http://img717.imageshack.us/img717/8323/errorvi.jpg

I run VS2010 as administrator and I have installed (I guess) all necessary services and IIS features.

What could be the reason?

答: Ok. Every time when I reinstalled IIS it suddenly started to work. Then, next day issue reoccured. There was an issue with domain group policy, it turned out that some services were getting disabled with PC reset. </p>


问:
Reading the Http POST body content from my web service? (.net 3.5)
Okay, this is driving me nuts. I'm integrating Amazon SNS into a web service I have. Amazon simply sends an HTTP post with a bunch of json content to the url I specify. I just can't access it.

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HandleBounce()
{
    notification = //I need to put the JSON content into here
}
</code>```

Amazon simply access the url (http://test.com/webservice.aspx/HandleBounce). The method is being called correctly. I just need to get the data it's sending in the post. How do I do that?

EDIT:

I originally tried using

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HandleBounce(string json)
{
    notification = //I need to put the JSON content into here
}
</code>```

but when I do this, the method is simply never called at all. At least when I remove the parameter, the method is working.

EDIT 2:

This is from the amazon website as to what request they send to me:

```<code>POST / HTTP/1.1
x-amz-sns-message-type: SubscriptionConfirmation
x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
Content-Length: 1336
Content-Type: text/plain; charset=UTF-8
Host: example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent

{
  "Type" : "SubscriptionConfirmation",
  "MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b",
  "Token" : "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d609c582afbacc99c583a916b9981dd2728f4ae6fdb82efd087cc3b7849e05798d2d2785c03b0879594eeac82c01f235d0e717736",
  "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
  "Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
  "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d609c582afbacc99c583a916b9981dd2728f4ae6fdb82efd087cc3b7849e05798d2d2785c03b0879594eeac82c01f235d0e717736",
  "Timestamp" : "2012-04-26T20:45:04.751Z",
  "SignatureVersion" : "1",
  "Signature" : "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=",
  "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem"
  }
</code>```

答:
Using the following adjustments, I was able to resolve the issue:</p>

```<code>    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void HandleBounce() //This method is called from Amazon Simple Notification Service when we receive a bounce.
    {
        string notification = "";
        using (var stream = new MemoryStream())
        {
            var request = HttpContext.Current.Request;
            request.InputStream.Seek(0, SeekOrigin.Begin);
            request.InputStream.CopyTo(stream);
            notification = Encoding.UTF8.GetString(stream.ToArray());
        }
    }
</code>```

Body:
Okay, this is driving me nuts. I'm integrating Amazon SNS into a web service I have. Amazon simply sends an HTTP post with a bunch of json content to the url I specify. I just can't access it.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HandleBounce()
{
    notification = //I need to put the JSON content into here
}

Amazon simply access the url (http://test.com/webservice.aspx/HandleBounce). The method is being called correctly. I just need to get the data it's sending in the post. How do I do that?

EDIT:

I originally tried using

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HandleBounce(string json)
{
    notification = //I need to put the JSON content into here
}

but when I do this, the method is simply never called at all. At least when I remove the parameter, the method is working.

EDIT 2:

This is from the amazon website as to what request they send to me:

POST / HTTP/1.1
x-amz-sns-message-type: SubscriptionConfirmation
x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b
x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic
Content-Length: 1336
Content-Type: text/plain; charset=UTF-8
Host: example.com
Connection: Keep-Alive
User-Agent: Amazon Simple Notification Service Agent

{
  "Type" : "SubscriptionConfirmation",
  "MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b",
  "Token" : "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d609c582afbacc99c583a916b9981dd2728f4ae6fdb82efd087cc3b7849e05798d2d2785c03b0879594eeac82c01f235d0e717736",
  "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic",
  "Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
  "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:123456789012:MyTopic&Token=2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d609c582afbacc99c583a916b9981dd2728f4ae6fdb82efd087cc3b7849e05798d2d2785c03b0879594eeac82c01f235d0e717736",
  "Timestamp" : "2012-04-26T20:45:04.751Z",
  "SignatureVersion" : "1",
  "Signature" : "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=",
  "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem"
  }

Body:
Using the following adjustments, I was able to resolve the issue:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void HandleBounce() //This method is called from Amazon Simple Notification Service when we receive a bounce.
    {
        string notification = "";
        using (var stream = new MemoryStream())
        {
            var request = HttpContext.Current.Request;
            request.InputStream.Seek(0, SeekOrigin.Begin);
            request.InputStream.CopyTo(stream);
            notification = Encoding.UTF8.GetString(stream.ToArray());
        }
    }