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

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

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

* ORIGINAL QUESTION *

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

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

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

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

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

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

My objects are defined like this:

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

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

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

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

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

Then seemingly one of these for each user:

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

And also one of these for each user:

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

答:
You are join 3 tables, fetch all data from tables, I think that you don't have any indexed column, and database is on another server

1) filter record because you don't need really all record

2) only select columns that you need, instead of u., a. that returns all columns data

3) add a index column for your database(you should use index column for columns that appear in your where clause most of the time)

and check your query execution time on your database server time to see it is not network latency

Body:
* UPDATE *

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

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

* ORIGINAL QUESTION *

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

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

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

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

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

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

My objects are defined like this:

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

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

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

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

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

Then seemingly one of these for each user:

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

And also one of these for each user:

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


来源: stackexchange

问:
Marklogic - wildcarded search not working for slash (/)
I am using the below xquery for partial  search ,The does not work when the string coming with slash (/) .

The Query should return the URI based on Search.

Xquery:

```<code>cts:search(fn:collection($collectionName),

    cts:and-query((

    cts:element-attribute-value-query(xs:QName("element"),xs:QName("type"),'per'),

    cts:element-value-query(xs:QName("attri"),'*Olliffe Matthew 17/2/3*',("wildcarded","whitespace-sensitive","case-insensitive"))

)))
</code>```

答:
Your code works in MarkLogic 9.0-1.1 console, for me variable $collectionName is "coll1".</p>

```<code>cts:search(fn:collection("coll1"),
                                 cts:and-query((

                                 cts:element-attribute-value-query(xs:QName("element"),xs:QName("type"),'per'),

                                cts:element-value-query(xs:QName("attri"),'*Olliffe Matthew 17/2/3*',("wildcarded","whitespace-sensitive","case-insensitive"))

                        )))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using the below xquery for partial  search ,The does not work when the string coming with slash (/) .

The Query should return the URI based on Search.

Xquery:

cts:search(fn:collection($collectionName),

    cts:and-query((

    cts:element-attribute-value-query(xs:QName("element"),xs:QName("type"),'per'),

    cts:element-value-query(xs:QName("attri"),'*Olliffe Matthew 17/2/3*',("wildcarded","whitespace-sensitive","case-insensitive"))

)))

Body:
Your code works in MarkLogic 9.0-1.1 console, for me variable $collectionName is "coll1".

cts:search(fn:collection("coll1"),
                                 cts:and-query((

                                 cts:element-attribute-value-query(xs:QName("element"),xs:QName("type"),'per'),

                                cts:element-value-query(xs:QName("attri"),'*Olliffe Matthew 17/2/3*',("wildcarded","whitespace-sensitive","case-insensitive"))

                        )))


问:
Laravel CLI fails to create new app due to Cannot use lexical variable $eventName as a parameter name
After successful installation of Laravel's install tool using composer using composer global require "laravel/installer" command, the first attempt to create an application by running laravel new app-name fails with the following output, any advice will be appreciated :)

```<code>Crafting application...
PHP Fatal error:  Cannot use lexical variable $eventName as a parameter name in /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/Emitter.php on line 48
PHP Stack trace:
PHP   1. {main}() /Users/ABN/.composer/vendor/laravel/installer/laravel:0
PHP   2. Symfony\Component\Console\Application->run() /Users/ABN/.composer/vendor/laravel/installer/laravel:13
PHP   3. Symfony\Component\Console\Application->doRun() /Users/ABN/.composer/vendor/symfony/console/Application.php:126
PHP   4. Symfony\Component\Console\Application->doRunCommand() /Users/ABN/.composer/vendor/symfony/console/Application.php:195
PHP   5. Laravel\Installer\Console\NewCommand->run() /Users/ABN/.composer/vendor/symfony/console/Application.php:878
PHP   6. Laravel\Installer\Console\NewCommand->execute() /Users/ABN/.composer/vendor/symfony/console/Command/Command.php:259
PHP   7. Laravel\Installer\Console\NewCommand->download() /Users/ABN/.composer/vendor/laravel/installer/src/NewCommand.php:52
PHP   8. GuzzleHttp\Client->get() /Users/ABN/.composer/vendor/laravel/installer/src/NewCommand.php:125
PHP   9. GuzzleHttp\Client->createRequest() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Client.php:125
PHP  10. GuzzleHttp\Client->getEmitter() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Client.php:115
PHP  11. spl_autoload_call() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/HasEmitterTrait.php:15
PHP  12. Composer\Autoload\ClassLoader->loadClass() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/HasEmitterTrait.php:15
PHP  13. Composer\Autoload\includeFile() /Users/ABN/.composer/vendor/composer/ClassLoader.php:322
</code>```

答:
This is related to Guzzle's PHP 7.x incompatibility and this has been fixed in Guzzle >=5.3.1.

The solution is to upgrade your Guzzle by modifying line in your composer.json file to:

```<code>"guzzlehttp/guzzle": "~5.3.1",
</code>```

or:

```<code>"guzzlehttp/guzzle": "~5.3@stable",
</code>```

Body:
After successful installation of Laravel's install tool using composer using composer global require "laravel/installer" command, the first attempt to create an application by running laravel new app-name fails with the following output, any advice will be appreciated :)

Crafting application...
PHP Fatal error:  Cannot use lexical variable $eventName as a parameter name in /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/Emitter.php on line 48
PHP Stack trace:
PHP   1. {main}() /Users/ABN/.composer/vendor/laravel/installer/laravel:0
PHP   2. Symfony\Component\Console\Application->run() /Users/ABN/.composer/vendor/laravel/installer/laravel:13
PHP   3. Symfony\Component\Console\Application->doRun() /Users/ABN/.composer/vendor/symfony/console/Application.php:126
PHP   4. Symfony\Component\Console\Application->doRunCommand() /Users/ABN/.composer/vendor/symfony/console/Application.php:195
PHP   5. Laravel\Installer\Console\NewCommand->run() /Users/ABN/.composer/vendor/symfony/console/Application.php:878
PHP   6. Laravel\Installer\Console\NewCommand->execute() /Users/ABN/.composer/vendor/symfony/console/Command/Command.php:259
PHP   7. Laravel\Installer\Console\NewCommand->download() /Users/ABN/.composer/vendor/laravel/installer/src/NewCommand.php:52
PHP   8. GuzzleHttp\Client->get() /Users/ABN/.composer/vendor/laravel/installer/src/NewCommand.php:125
PHP   9. GuzzleHttp\Client->createRequest() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Client.php:125
PHP  10. GuzzleHttp\Client->getEmitter() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Client.php:115
PHP  11. spl_autoload_call() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/HasEmitterTrait.php:15
PHP  12. Composer\Autoload\ClassLoader->loadClass() /Users/ABN/.composer/vendor/guzzlehttp/guzzle/src/Event/HasEmitterTrait.php:15
PHP  13. Composer\Autoload\includeFile() /Users/ABN/.composer/vendor/composer/ClassLoader.php:322

Body:
This is related to Guzzle's PHP 7.x incompatibility and this has been fixed in Guzzle >=5.3.1.

The solution is to upgrade your Guzzle by modifying line in your composer.json file to:

"guzzlehttp/guzzle": "~5.3.1",

or:

"guzzlehttp/guzzle": "~5.3@stable",


问:
How to find the pager used by man?
How to find the pager used by man command.</p>

答:
From man man option(snippet below) -P to change pager and default pager is /usr/bin/less

-P  pager
                    Specify which pager to use.   This  option  overrides
                    the  MANPAGER  environment  variable,  which  in turn
                    overrides the PAGER variable.  By default,  man  uses
                    /usr/bin/less -is.

ContentLicense: CC BY-SA 2.5

Title: How to find the pager used by man?


问:
How do I get the full text to show in Unity 3D UI?
I am trying to get the full text to display when entering play mode but its only showing the first few words.

I already set the Horizontal and Vertical overflow to wrap and truncate.

Any help is greatly appreciated.

答:
To show all the text the rect transform should be big enough to contain all the text when using (Wrap, Truncate) settings.

Prese "T" while the text object is selected to see the size of the transform, you can also see in inspector, it is 160w,30h. Which is way too small for a large text. Increase it about 300w,300h and then set paragraph overflow mode horizontal: Wrap, vertical: Overflow. Setting vertical to overflow might result in text going out of the panel but it would give you an idea how tall your panel should be to display all the text in boundary.

You can also use best fit option to size down the text to fit inside the transform boundary.


问:
can't chown /usr/local for homebrew in Mac OS X 10.13 High Sierra
Homebrew needs permissions in /usr/local and since no one else uses my laptop I have always simply done

sudo chown -R $(whoami) $(brew --prefix)

but in High Sierra, this gives

chown: /usr/local: Operation not permitted

What is the fix?

答:
The problem kept occurring... after digging deeper I found that only uninstalling Homebrew and then re-installing it solved this issue.

Uninstalling will remove all your brew packages, you can save the output of brew list in a file first, to have a record of what packages were installed.

Uninstall Homebrew:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
</code>```

Then re-install it:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The problem kept occurring... after digging deeper I found that only uninstalling Homebrew and then re-installing it solved this issue.

Uninstalling will remove all your brew packages, you can save the output of brew list in a file first, to have a record of what packages were installed.

Uninstall Homebrew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then re-install it:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


问:
IntelliJ Ruby warning "Cannot resolve properly, was not processed"
I have many lines in my specs that result in this IntelliJ warning:

"Cannot resolve properly, was not processed"

The vast majority of the lines have this format:

```<code>expect(result[:err]).to include('(Check the file permissions.)')
</code>```

If I move the literal string to a separate variable, the warning goes away:

```<code>    msg = '(Check the file permissions.)'
    expect(result[:err]).to include(msg)
</code>```

Is there a way to make this error go away (other than moving all my string literals to variables)?

答:
My guess is that the RubyMine parser thinks that include is the Ruby keyword to include a module and so it emits a warning telling it cannot find the corresponding module.

The only way I found to fix this warning is to use the inclusion alias proposed by the rspec include matcher :

```<code>expect(result[:err]).to inclusion('(Check the file permissions.)')
</code>```

This fixes the warning and the expectation works the same, but sadly the english sentence is bad.

There is also 3 other aliases available, but they don't give better english syntax:

```<code>alias_matcher :a_collection_including, :include
alias_matcher :a_string_including,     :include
alias_matcher :a_hash_including,       :include
alias_matcher :including,              :include
</code>```

These alias definitions can be found here

Maybe by chance this answer could lead someone to a better solution.

Body:
I have many lines in my specs that result in this IntelliJ warning:

"Cannot resolve properly, was not processed"

The vast majority of the lines have this format:

expect(result[:err]).to include('(Check the file permissions.)')

If I move the literal string to a separate variable, the warning goes away:

    msg = '(Check the file permissions.)'
    expect(result[:err]).to include(msg)

Is there a way to make this error go away (other than moving all my string literals to variables)?

Body:
My guess is that the RubyMine parser thinks that include is the Ruby keyword to include a module and so it emits a warning telling it cannot find the corresponding module.

The only way I found to fix this warning is to use the inclusion alias proposed by the rspec include matcher :

expect(result[:err]).to inclusion('(Check the file permissions.)')

This fixes the warning and the expectation works the same, but sadly the english sentence is bad.

There is also 3 other aliases available, but they don't give better english syntax:

alias_matcher :a_collection_including, :include
alias_matcher :a_string_including,     :include
alias_matcher :a_hash_including,       :include
alias_matcher :including,              :include

These alias definitions can be found here

Maybe by chance this answer could lead someone to a better solution.


问:
Conflicting types error message
My little program in ANSII C gives me a "Conflicting Types" error message when I compile it. And I don't know why that is, especially given the fact that I've tested the same situation in a different .c file with no problems whatsoever.

The code is as follows:

```<code>    void search(char *v, Message *l){

    long int max;

    max=countNodes(l);
</code>```

(... This part doesn't matter, I assure you that...)

```<code>    } //end of the "search" function

    long int countNodes(Message *l){

    long int i=0;

    while(l!=NULL){

    i++;
    l=(l->nseg);

    }

    return(i);
    }
</code>```

So, the "countNodes" function determines the number of nodes in "l" (linked list). Then, that number is returned to the "search" function. But the compiler keeps giving me a "Conflicting Types" error message, and I don't know why... I think that everything is fine and well written.

All help is appreciated. Thanks in advance!

答:
Your compiler basically reads your file line by line. So when it reads max=countNodes(l);, it doesn't "know" your countNodes function yet.

You have two options:

put your countNodes function before your search function.

put the prototype of your countNode function before the search function (read about "prototypes in c" if your not familiar with it).

Title: Conflicting types error message

Body:
My little program in ANSII C gives me a "Conflicting Types" error message when I compile it. And I don't know why that is, especially given the fact that I've tested the same situation in a different .c file with no problems whatsoever.

The code is as follows:

    void search(char *v, Message *l){

    long int max;

    max=countNodes(l);

(... This part doesn't matter, I assure you that...)

    } //end of the "search" function

    long int countNodes(Message *l){

    long int i=0;

    while(l!=NULL){

    i++;
    l=(l->nseg);

    }

    return(i);
    }

So, the "countNodes" function determines the number of nodes in "l" (linked list). Then, that number is returned to the "search" function. But the compiler keeps giving me a "Conflicting Types" error message, and I don't know why... I think that everything is fine and well written.

All help is appreciated. Thanks in advance!


问:
Need a cloud hosting for a modular project
I'm searching for an auto-scalable (with parameters) cloud hosting solution for a modular project (rest, web and db) where each module has to scale by it's own and they have to be able to see each other.

If it can be deployed with Docker it will be just perfect.

Any tips?

Thanks for your time

答:
Jelastic PaaS provides auto-clustered solutions deployed with Docker, such as GlassFish cluster, MySQL master-slave replicated databases, WordPress or Magento clusters and many others. They are automatically installed and scaled.

Also, you can run standalone Docker Engine or Swarm cluster with automatic scaling configured by default.


问:
Re-ordering of messages - Artemis
I have to run two instances of the same application that read messages from 'queue-1' and write them back to another queue 'queue-2'.

I need my messages inside the two queues to be ordered by specific property (sequence number) which is initially added to every message by producer. As per documentation, inside queue-1 the order of messages will be preserved as messages are sent by a single producer. But because of having multiple consumers that read, process and send the processed messages to queue-2, the order of messages inside queue-2 might be lost.

So my task is to make sure that messages are delivered to queue-2 in the same order as they were read from queue-1. I have implemented re-sequencer pattern from Apache camel to re-order messages inside queue-2. The re-sequencer works fine but results to data transfer overhead as the camel routes run locally.

Thinking about doing it in a better way, I have three questions:

Does artemis inherently supports re-ordering of messages inside a
queue using a property such as sequence number.

Is it possible to run the routes inside the server? If yes, can you
give an example or give a link to the documentation?

Some artemis features such as divert (split) requires modifying
broker configuration (broker.xml file), is there a way to do them
programmatically and dynamically so I can decide when to start
diverting message? I know this can be accomplished by using camel,
but I want everything to be running in the server.

答:
Does artemis inherently supports re-ordering of messages inside a queue using a property such as sequence number.

No. Camel is really the best solution here in my opinion.

Is it possible to run the routes inside the server? If yes, can you give an example or give a link to the documentation?

You should be able to do the same kind of thing in Artemis as in ActiveMQ 5.x using a web application with a Camel context.  The 5.x doc is here.

Some artemis features such as divert (split) requires modifying broker configuration (broker.xml file), is there a way to do them programatically and dynamically so I can decide when to start diverting message?

You can use the Artemis management methods to create, modify, and delete diverts programmatically (or administratively) at runtime.  However, these modifications will be volatile (i.e. they won't survive a broker restart).

Title: Re-ordering of messages - Artemis


问:
Detecting drop into textarea with Javascript
All I need is to be able to detect when text is dropped into a Textarea.  I then take that text and do stuff with it and clear the textarea.  There may be many of these textareas and very high UI expectations, so polling is a last resort.

For IE, "onfocus" does the trick, since this event is fired after the user drops stuff into the textarea.

For Firefox, I can't find an event that works.  I've tried onmouseup and onchange.. don't know what else to try from there.  I'd hate to have to poll the textarea for content.  Help much appreciated.  Thanks.

Edit:  For clarification, "dropped" means the user selects text (usually) from the page, but it doesn't matter where, drags it, and drops it into the textarea.  This is not the same as Ctrl+V, or right click pasting (which take two different methods of detection, BTW), or (obviously) typing into the textarea.  Specifically, it is the "drop" aspect of drag and drop.  I really don't know how else to phrase it.

I feel this question was stated rather accurately.  To humor me, assume that I meant any of the other operations on a textarea that you all have chosen to share.  If I meant "pasting", don't you think I would have mentioned something about pasting in the title or content of my question?  Same goes for typing in a textarea.  But, perhaps, you all just don't know me well enough to know that I type what I mean, rather than mistakingly typing things only somewhat related to what I mean.

答:
If you want your textarea to react to text being dropped, pasted or typed, your only solution would be a button. Even a timer polling the content will not help you.

You mention that you want the user to be able to type text in the textarea. And you mention that you want to clear the text whenever the event is fired. There is no possible way for the browser to know that the user has finished typing. You must rely on a specific action.

Now for the drop or paste, you can rely on the mouseup and keyup events in order to detect that.

OwnerDisplayName: sam

LastEditorDisplayName: sam

OwnerDisplayName: Vincent Robert


问:
Find last occurrence of character in String?
I want to find the index of the last occurrence of a character in a String. For example if my string is "google.com/program/test" and I want to find the letter /, I want my function to return 18 because that is the last occurrence of / in that string. I have tried to follow Finding index of character in Swift String and have also tried to implement a means to loop through the string and simply find the last index of the String that has my desired character but the advance() function seems to complain about getting an Integer.

```<code>var strCount = 0
var lastSlashIndex = 0
for i in urlAsString {
  if i == "/"{
    if lastSlashIndex < strCount{
      lastSlashIndex = strCount
    }
  }
  strCount++
}

var endOfString = strCount - lastSlash
//Cannot seem to use the advance function to get the remaining substring
var fileName = urlAsString.substringFromIndex(advance(lastSlashIndex, endOfString))
</code>```

Can't seem to figure this out, any help would be appreciated.

EDIT:
This problem is not ment to be specific to just the '/' character. For example, if the string is "abbccd" and I'm looking for the letter 'c', then I want to return the index 4 because that is the last index in which 'c' occurs in.

答:
The following accomplishes this task using an extension that can take a string of your choosing to locate. If it is not available, then you get a nil value back you can handle.

```<code>extension String {
    func lastOccurrenceOfString(string: String) -> String.Index? {
        let characterSet = CharacterSet(charactersIn: string)
        if let range = rangeOfCharacter(from: characterSet, options: .backwards) {
            let offsetBy = distance(from: startIndex, to: range.upperBound)

            return index(startIndex, offsetBy: offsetBy)
        }

        return nil
    }
}
</code>```

And the following shows this in use:

```<code>import UIKit

class ViewController: UIViewController {
    let testString = "google.com/program/test"

    override func viewDidLoad() {
        super.viewDidLoad()

        getIndex(of: "/") // 19
        getIndex(of: ".") // 7
        getIndex(of: "z") // N/A
        getIndex(of: "me") // 21, e appears before m
    }

    func getIndex(of string: String) {

        let slashIndex = testString.lastOccurrenceOfString(string: string)
        print(slashIndex?.encodedOffset ?? "N/A")
    }
}

extension String {
    func lastOccurrenceOfString(string: String) -> String.Index? {
        let characterSet = CharacterSet(charactersIn: string)
        if let range = rangeOfCharacter(from: characterSet, options: .backwards) {
            let offsetBy = distance(from: startIndex, to: range.upperBound)

            return index(startIndex, offsetBy: offsetBy)
        }

        return nil
    }
}
</code>```

Body:
I want to find the index of the last occurrence of a character in a String. For example if my string is "google.com/program/test" and I want to find the letter /, I want my function to return 18 because that is the last occurrence of / in that string. I have tried to follow Finding index of character in Swift String and have also tried to implement a means to loop through the string and simply find the last index of the String that has my desired character but the advance() function seems to complain about getting an Integer.

var strCount = 0
var lastSlashIndex = 0
for i in urlAsString {
  if i == "/"{
    if lastSlashIndex < strCount{
      lastSlashIndex = strCount
    }
  }
  strCount++
}

var endOfString = strCount - lastSlash
//Cannot seem to use the advance function to get the remaining substring
var fileName = urlAsString.substringFromIndex(advance(lastSlashIndex, endOfString))

Can't seem to figure this out, any help would be appreciated.

EDIT:
This problem is not ment to be specific to just the '/' character. For example, if the string is "abbccd" and I'm looking for the letter 'c', then I want to return the index 4 because that is the last index in which 'c' occurs in.

Body:
The following accomplishes this task using an extension that can take a string of your choosing to locate. If it is not available, then you get a nil value back you can handle.

extension String {
    func lastOccurrenceOfString(string: String) -> String.Index? {
        let characterSet = CharacterSet(charactersIn: string)
        if let range = rangeOfCharacter(from: characterSet, options: .backwards) {
            let offsetBy = distance(from: startIndex, to: range.upperBound)

            return index(startIndex, offsetBy: offsetBy)
        }

        return nil
    }
}

And the following shows this in use:

import UIKit

class ViewController: UIViewController {
    let testString = "google.com/program/test"

    override func viewDidLoad() {
        super.viewDidLoad()

        getIndex(of: "/") // 19
        getIndex(of: ".") // 7
        getIndex(of: "z") // N/A
        getIndex(of: "me") // 21, e appears before m
    }

    func getIndex(of string: String) {

        let slashIndex = testString.lastOccurrenceOfString(string: string)
        print(slashIndex?.encodedOffset ?? "N/A")
    }
}

extension String {
    func lastOccurrenceOfString(string: String) -> String.Index? {
        let characterSet = CharacterSet(charactersIn: string)
        if let range = rangeOfCharacter(from: characterSet, options: .backwards) {
            let offsetBy = distance(from: startIndex, to: range.upperBound)

            return index(startIndex, offsetBy: offsetBy)
        }

        return nil
    }
}


问:
Removing referenced entity. Solution, tactics etc
I'm wondering how to solve problem of removing a record from db, that is in relationship with other record. Here's an exemple. Those are two class that represents User and Comment.

```<code>@Entity
public class Comment {
    @Id @GeneratedValue
    @Getter @Setter
    private long id;

    @Getter @Setter
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private User commentAuthor;

    @Getter @Setter
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "article_id")
    private Article associatedArticle;

    @Getter @Setter
    @Column(columnDefinition="DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @Getter @Setter
    @Type(type="text")
    private String commentText;

    public Comment(User author, String text){
        this.commentAuthor = author;
        this.commentText = text;
        this.date = new Date();
    }
}
</code>```

And user class:

```<code>@Entity
public class User {

    @Getter @Setter
    private String username;

    @Getter @Setter
    private String password;

    @Id
    @Getter @Setter
    private String email;

    @Getter @Setter
    private String role;

    @Getter @Setter
    @Column(columnDefinition="DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date registerDate;

    public User(String username, String password, String email){
        this.username = username;
        this.password = BCrypt.hashpw(password, BCrypt.gensalt());
        this.email = email;
        this.registerDate = new Date();
        this.role = "USER";
}

public User(){};
</code>```

As you can see I store information which user added comment. But let's imagine that I want to delete this user. I won't be able to do that if he added comments because I will get SQL error about foreign key etc. I'm pretty sure that it's just bad db design but I'm not sure how to solve this problem. Obviously when deleting user I want to keep his comments and instead of his username just show some info like "User deleted". What is the proper way to do it?

答: You can set  field of comments that is linked to user table to null when user is deleted using syntax like ON DELETE SET NULL. Also you need to allow null for that field</p>

Body:
I'm wondering how to solve problem of removing a record from db, that is in relationship with other record. Here's an exemple. Those are two class that represents User and Comment.

@Entity
public class Comment {
    @Id @GeneratedValue
    @Getter @Setter
    private long id;

    @Getter @Setter
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private User commentAuthor;

    @Getter @Setter
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "article_id")
    private Article associatedArticle;

    @Getter @Setter
    @Column(columnDefinition="DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @Getter @Setter
    @Type(type="text")
    private String commentText;

    public Comment(User author, String text){
        this.commentAuthor = author;
        this.commentText = text;
        this.date = new Date();
    }
}

And user class:

@Entity
public class User {

    @Getter @Setter
    private String username;

    @Getter @Setter
    private String password;

    @Id
    @Getter @Setter
    private String email;

    @Getter @Setter
    private String role;

    @Getter @Setter
    @Column(columnDefinition="DATETIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date registerDate;

    public User(String username, String password, String email){
        this.username = username;
        this.password = BCrypt.hashpw(password, BCrypt.gensalt());
        this.email = email;
        this.registerDate = new Date();
        this.role = "USER";
}

public User(){};

As you can see I store information which user added comment. But let's imagine that I want to delete this user. I won't be able to do that if he added comments because I will get SQL error about foreign key etc. I'm pretty sure that it's just bad db design but I'm not sure how to solve this problem. Obviously when deleting user I want to keep his comments and instead of his username just show some info like "User deleted". What is the proper way to do it?


问:
Getting string input and displaying input with DOS interrupts MASM
In MASM, I created a buffer variable to hold the user string input from keyboard. I am stuck on how to hold the string input into that buffer variable. I don't have any libraries linked like the irvine ones and want to do this with DOS interrupts. So far I have something along the lines of

```<code>            .model small

            .stack 100h

            .data
buff        db  25 dup(0), 10, 13
lbuff       EQU ($ - buff)              ; bytes in a string

            .code
main:
            mov ax, @data
            mov ds, ax

            mov ah, 0Ah         ; doesn't work
            mov buff, ah        ; doesn't seem right
            int 21h

            mov     ax, 4000h       ; display to screen
            mov     bx, 1
            mov     cx, lbuff
            mov     dx, OFFSET buff
            int     21h

            mov ah, 4ch
            int 21h

            end main
</code>```

I assume using 0Ah is correct as it is for reading array of input of buffered characters.

答:
You may follow this code :</p>

```<code>; Problem : input array from user

.MODEL SMALL
.STACK
.DATA
   ARR DB 10 DUB (?)

.CODE
 MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    XOR BX, BX
    MOV CX, 5

    FOR:
      MOV AH, 1
      INT 21H
      MOV ARR[BX], AL
      INC BX
    LOOP FOR

    XOR BX, BX
    MOV CX, 5

    PRINT:
     MOV AX, ARR[BX] ;point to the  current index

     MOV AH, 2       ;output
     MOV DL, AX
     INT 21H

     INC BX           ;move pointer to the next element
    LOOP PRINT       ;loop until done

 MAIN ENDP
</code>```

Body:
In MASM, I created a buffer variable to hold the user string input from keyboard. I am stuck on how to hold the string input into that buffer variable. I don't have any libraries linked like the irvine ones and want to do this with DOS interrupts. So far I have something along the lines of

            .model small

            .stack 100h

            .data
buff        db  25 dup(0), 10, 13
lbuff       EQU ($ - buff)              ; bytes in a string

            .code
main:
            mov ax, @data
            mov ds, ax

            mov ah, 0Ah         ; doesn't work
            mov buff, ah        ; doesn't seem right
            int 21h

            mov     ax, 4000h       ; display to screen
            mov     bx, 1
            mov     cx, lbuff
            mov     dx, OFFSET buff
            int     21h

            mov ah, 4ch
            int 21h

            end main

I assume using 0Ah is correct as it is for reading array of input of buffered characters.

Body:
You may follow this code :

; Problem : input array from user

.MODEL SMALL
.STACK
.DATA
   ARR DB 10 DUB (?)

.CODE
 MAIN PROC
    MOV AX, @DATA
    MOV DS, AX

    XOR BX, BX
    MOV CX, 5

    FOR:
      MOV AH, 1
      INT 21H
      MOV ARR[BX], AL
      INC BX
    LOOP FOR

    XOR BX, BX
    MOV CX, 5

    PRINT:
     MOV AX, ARR[BX] ;point to the  current index

     MOV AH, 2       ;output
     MOV DL, AX
     INT 21H

     INC BX           ;move pointer to the next element
    LOOP PRINT       ;loop until done

 MAIN ENDP


问:
Oracle: Duration of a scheduler Job
I want to know the duration of a scheduler Job, but what I get from the DB is null !</p>

```<code>select LAST_RUN_DURATION from USER_SCHEDULER_JOBS
</code>```

答:
Join the 2 views:</p>

```<code>SELECT l.LOG_ID,l.LOG_DATE,l.JOB_NAME,l.STATUS,dets.RUN_DURATION
FROM ALL_SCHEDULER_JOB_LOG l
JOIN all_scheduler_job_run_details dets  ON l.LOG_ID = dets.LOG_ID
</code>```

Title: Oracle: Duration of a scheduler Job

Body:
I want to know the duration of a scheduler Job, but what I get from the DB is null !

select LAST_RUN_DURATION from USER_SCHEDULER_JOBS

Body:
Join the 2 views:

SELECT l.LOG_ID,l.LOG_DATE,l.JOB_NAME,l.STATUS,dets.RUN_DURATION
FROM ALL_SCHEDULER_JOB_LOG l
JOIN all_scheduler_job_run_details dets  ON l.LOG_ID = dets.LOG_ID


问:
Generic Types and Object in Java
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

```<code>public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}
</code>```

Main.java

```<code>public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}
</code>```

Error Message

```<code>Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
</code>```

答:
Add a generic argument in the method static too, replace Object for a type variable:

```<code>public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<String>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<?> triplet) {
       System.out.println(triplet.a);
       System.out.println(triplet.b);
       System.out.println(triplet.c);
    }

}
</code>```

}

or a valid variant:

```<code>static <A> void printPartsOfTriplet(Triplet<A> triplet) {
    System.out.println(triplet.a);
    System.out.println(triplet.b);
    System.out.println(triplet.c);
}
</code>```

here static  void printPartsOfTriplet(Triplet triplet) you are saying "give me any Triplet, it means a Triple with type A (not given yet), and I will print its values.

here static void printPartsOfTriplet(Triplet<Object> triplet) you are saying give me a Triplet<Object> ( a Triplet of type Object (a fixed type), and I will print its values (each one is an Object)).
 But Object type is not == String type, so, that gives you an error

Title: Generic Types and Object in Java

Body:
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}

Error Message

Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Body:
Add a generic argument in the method static too, replace Object for a type variable:

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<String>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<?> triplet) {
       System.out.println(triplet.a);
       System.out.println(triplet.b);
       System.out.println(triplet.c);
    }

}

}

or a valid variant:

static <A> void printPartsOfTriplet(Triplet<A> triplet) {
    System.out.println(triplet.a);
    System.out.println(triplet.b);
    System.out.println(triplet.c);
}

here static <A> void printPartsOfTriplet(Triplet<A> triplet) you are saying "give me any Triplet<A>, it means a Triple with type A (not given yet), and I will print its values.

here static void printPartsOfTriplet(Triplet<Object> triplet) you are saying give me a Triplet<Object> ( a Triplet of type Object (a fixed type), and I will print its values (each one is an Object)).
 But Object type is not == String type, so, that gives you an error


问:
Count based on inner select
I want to do a count based on a sub select statement.

```<code>SELECT MONTH(Received), State, COUNT('id'), SUM(price) FROM Leads GROUP BY MONTH(Received), State
</code>```

That query works and generates something like this

```<code>MONTH(Received)     State   COUNT('id')    SUM(price)
4                   CA      25             35
4                   UT      13             8
</code>```

What I'm trying to count is how many rows had a price > 0

This is the query I tried

```<code>SELECT MONTH(Received), SUM(price), COUNT(`id`), (SELECT COUNT(*) as count FROM Leads WHERE Price > 0) as NumPaidLeads, State FROM Leads GROUP BY MONTH(Received), State
</code>```

But NumPaidLeads Counts the entire column, the price column is numeric type.

What am I doing wrong?

答:
in your case for count the rows  with price > 0 you could use a case</p>

```<code>SELECT MONTH(Received), State,
 sum( case when price > 0 then 1 else 0 END) num_row_with_price, SUM(price)
FROM Leads
GROUP BY MONTH(Received), State
</code>```

Title: Count based on inner select

Body:
I want to do a count based on a sub select statement.

SELECT MONTH(Received), State, COUNT('id'), SUM(price) FROM Leads GROUP BY MONTH(Received), State

That query works and generates something like this

MONTH(Received)     State   COUNT('id')    SUM(price)
4                   CA      25             35
4                   UT      13             8

What I'm trying to count is how many rows had a price > 0

This is the query I tried

SELECT MONTH(Received), SUM(price), COUNT(`id`), (SELECT COUNT(*) as count FROM Leads WHERE Price > 0) as NumPaidLeads, State FROM Leads GROUP BY MONTH(Received), State

But NumPaidLeads Counts the entire column, the price column is numeric type.

What am I doing wrong?

Body:
in your case for count the rows  with price > 0 you could use a case

SELECT MONTH(Received), State,
 sum( case when price > 0 then 1 else 0 END) num_row_with_price, SUM(price)
FROM Leads
GROUP BY MONTH(Received), State


问:
Postgresql and Oracle: update multiple tables from common subquery
Hello i have got 4 tables

first table is menu
have got column:

Id number PK

parent_id number FK to menu.Id

title character varying(250)

softdel boolean default false

second table is page:

id as PK

menu_id as FK to menu.id

page_id as FK to page.id

softdel boolean default false

third table is article:

id as PK and FK to page.id

softdel boolean default set to false

and fourth table article_lang:

partial_id as PK

id as FK to article.id

language character

softdel boolean default set to false

and i need to create update statement when i 'delete' (I mean set softdel true) menu with id for example 200 i also set softdel = false to  all menus which parent_id = 200 and also all pages which menu_id = menus_id and articles which page_id = pages.id and so on....

i need only 1 update statement its possible to do it ??

it would be wonderful if i can create JPA query or EJB query :)

in oracle i write statement :

```<code>update pub_menu pm set softdel = 0 where pm.id in (
with menu_tree(id, parent_id) as (
  select
    t1.id , t1.parent_id
    from menu t1
    where t1.id = 454

    union all
    select
    t2.id , t2.parent_id
      from menu_tree
      join menu t2 on menu_tree.id = t2.parent_id
)
select id from menu_tree

)

update menu_page pmp set softdel = 1 where pmp.menu_id in (
with menu_tree(id, parent_id) as (
  select
    t1.id , t1.parent_id
    from menu t1
    where t1.id = 454

    union all
    select
    t2.id , t2.parent_id
      from menu_tree
      join menu t2 on menu_tree.id = t2.parent_id
)
select id from menu_tree

)
</code>```

its working but i thing that is incorrect to do it like that :/

答:
Oracle doesn't allow any single sql statement to update multiple tables. So regular CTE couldn't help to avoid code duplication in this case.

But this can be worked around by using PL/SQL FOR LOOP IMPLICIT CURSOR like this:

```<code>begin
  for cur in (
    with menu_tree(id, parent_id) as (
        select t1.id, t1.parent_id
        from menu t1 where t1.id = 454
        union all
        select t2.id , t2.parent_id
        from menu_tree
        join menu t2 on menu_tree.id = t2.parent_id
    )
    select id from menu_tree
  ) loop
    update pub_menu pm set softdel = 0 where pm.id = cur.id;
    update menu_page pmp set softdel = 1 where pmp.menu_id = cur.id;
  end loop cur;
end;
</code>```

Body:
Hello i have got 4 tables

first table is menu
have got column:

Id number PK

parent_id number FK to menu.Id

title character varying(250)

softdel boolean default false

second table is page:

id as PK

menu_id as FK to menu.id

page_id as FK to page.id

softdel boolean default false

third table is article:

id as PK and FK to page.id

softdel boolean default set to false

and fourth table article_lang:

partial_id as PK

id as FK to article.id

language character

softdel boolean default set to false

and i need to create update statement when i 'delete' (I mean set softdel true) menu with id for example 200 i also set softdel = false to  all menus which parent_id = 200 and also all pages which menu_id = menus_id and articles which page_id = pages.id and so on....

i need only 1 update statement its possible to do it ??

it would be wonderful if i can create JPA query or EJB query :)

in oracle i write statement :

update pub_menu pm set softdel = 0 where pm.id in (
with menu_tree(id, parent_id) as (
  select
    t1.id , t1.parent_id
    from menu t1
    where t1.id = 454

    union all
    select
    t2.id , t2.parent_id
      from menu_tree
      join menu t2 on menu_tree.id = t2.parent_id
)
select id from menu_tree

)

update menu_page pmp set softdel = 1 where pmp.menu_id in (
with menu_tree(id, parent_id) as (
  select
    t1.id , t1.parent_id
    from menu t1
    where t1.id = 454

    union all
    select
    t2.id , t2.parent_id
      from menu_tree
      join menu t2 on menu_tree.id = t2.parent_id
)
select id from menu_tree

)

its working but i thing that is incorrect to do it like that :/

Body:
Oracle doesn't allow any single sql statement to update multiple tables. So regular CTE couldn't help to avoid code duplication in this case.

But this can be worked around by using PL/SQL FOR LOOP IMPLICIT CURSOR like this:

begin
  for cur in (
    with menu_tree(id, parent_id) as (
        select t1.id, t1.parent_id
        from menu t1 where t1.id = 454
        union all
        select t2.id , t2.parent_id
        from menu_tree
        join menu t2 on menu_tree.id = t2.parent_id
    )
    select id from menu_tree
  ) loop
    update pub_menu pm set softdel = 0 where pm.id = cur.id;
    update menu_page pmp set softdel = 1 where pmp.menu_id = cur.id;
  end loop cur;
end;


问:
Not all data is transfered via Socket
I can't send too large data packets over my setup (currently sending to 127.0.0.1), at about 30kB this functionality starts to fail. For testing I have an application that just starts a Receiver and a Sender, starts two threads, one for the sending, one for receiving, and when both have finished, compares if the sending string is the same as the received string.

```<code>void SenderThread(int count)
{
    messageOut = "";
    messageOut.append(count, 'A');

    sender->sendData(messageOut);
}

void ReceivingThread()
{
    receiver->ReceiveData(message);
}

main()
{
    receiver = new utility::Receiver();
    sender = new utility::Sender();

    receiver->startSocket(9000);
    sender->connectToSocket("127.0.0.1", 9000);
    receiver->accept();

    for (int count = 100; count < 1024 * 1024; count += 100)
    {
        std::thread sendThread(SenderThread, count);
        std::thread recvThread(ReceivingThread);

        sendThread.join();
        recvThread.join();

        printf("Sent data of length %d ", messageOut.length());
        if (message == messageOut)
            printf("successfully.\n");
        else
        {
            printf("not successfully.\n");
            printf("Length of original message: %d, Length of received message: %d.\n", messageOut.length(), message.length());
            break;
        }
    }
    delete receiver;
    delete sender;
}
</code>```

I have following code for my sending socket:

```<code>bool utility::Sender::sendData(const std::string & message)
{
    int numBytes = 0;
    int totalSent = 0;

    // Break condition: send() fails, or whole message was transfered

    while (totalSent < message.length() && send(message.substr(totalSent).c_str(), message.length() - totalSent, numBytes))
    {
        totalSent += numBytes;
    }

    return false;
}

bool utility::Sender::send(const char* pBuffer, int32_t lengthOfBuffer, int32_t &numBytes)
{
    numBytes = ::send(connectSocket, pBuffer, lengthOfBuffer, 0);

    if (numBytes == SOCKET_ERROR)
        return false;

    return true;
}
</code>```

The receiving side:

```<code>bool utility::Receiver::ReceiveData(std::string& message)
{
    int32_t numBytes = 0;

    char data[defaultBufferLength];

    // Set to blocking for the first data package

    u_long iMode = 0;
    ioctlsocket(tcpSocket, FIONBIO, &iMode);

    bool success = receive(data, defaultBufferLength, numBytes);
    message = std::string(data, numBytes);

    // Set to non-blocking for the rest of the journey
    iMode = 1;
    ioctlsocket(tcpSocket, FIONBIO, &iMode);

    while (numBytes == defaultBufferLength && receive(data, defaultBufferLength, numBytes))
    {
        message.append(data, numBytes);
    }

    return success;
}

bool utility::Receiver::receive(char* pBuffer, int32_t lengthOfBuffer, int32_t& numBytes)
{
    int32_t flags = 0;

    numBytes = recv(tcpSocket, pBuffer, lengthOfBuffer, flags);
    if (numBytes == -1)
    {
        numBytes = 0;
        if (errno == EAGAIN || errno == EWOULDBLOCK)
            return false;
        else
            close();
    }

    return true;
}
</code>```

The output I am getting is

```<code>Sent data of length 39200 successfully.
Sent data of length 39300 successfully.
Sent data of length 39400 successfully.
Sent data of length 39500 successfully.
Sent data of length 39600 successfully.
Sent data of length 39700 successfully.
Sent data of length 39800 successfully.
Sent data of length 39900 successfully.
Sent data of length 40000 successfully.
Sent data of length 40100 successfully.
Sent data of length 40200 successfully.
Sent data of length 40300 successfully.
Sent data of length 40400 successfully.
Sent data of length 40500 not successfully.
Length of original message: 40500, Length of received message: 29200.
</code>```

The thing which is the most irritating, and probably the cause of this, is the ::send(...). I can give it 2 MB of char*, and it will just send it in one swoop (but the receiver fails miserably). What can I do about that?

答:
TCP is a byte-oriented protocol, not message oriented.

send does not create a message.  recv does not receive a message.  They work on blocks of bytes, and multiple send calls can be combined at the network layer (for efficiency) or broken into multiple TCP packets.  In practice, even if you turn off Nagle's algorithm, if a frame is lost at the physical layer and TCP has to retry the transmission, the retransmit will include as much data added to the buffer afterward as it can fit in an outgoing datagram.

So you can't rely on any particular mapping between send calls and recv calls.  The only guarantee is that the bytes are delivered to your socket in the same order they were sent.  If boundaries are important, you have to create them yourself.  Length prefixes are popular in combination with TCP, special framing sequences less so.

You do already have a loop for reassembling messages... but you break out of the loop when you see EAGAIN / EWOULDBLOCK or a partly filled buffer, and continue processing.  That's a problem, because you only have a partial message at that point.  You need a way to delay processing until you have a complete message.

Title: Not all data is transfered via Socket

Body:
I can't send too large data packets over my setup (currently sending to 127.0.0.1), at about 30kB this functionality starts to fail. For testing I have an application that just starts a Receiver and a Sender, starts two threads, one for the sending, one for receiving, and when both have finished, compares if the sending string is the same as the received string.

void SenderThread(int count)
{
    messageOut = "";
    messageOut.append(count, 'A');

    sender->sendData(messageOut);
}

void ReceivingThread()
{
    receiver->ReceiveData(message);
}

main()
{
    receiver = new utility::Receiver();
    sender = new utility::Sender();

    receiver->startSocket(9000);
    sender->connectToSocket("127.0.0.1", 9000);
    receiver->accept();

    for (int count = 100; count < 1024 * 1024; count += 100)
    {
        std::thread sendThread(SenderThread, count);
        std::thread recvThread(ReceivingThread);

        sendThread.join();
        recvThread.join();

        printf("Sent data of length %d ", messageOut.length());
        if (message == messageOut)
            printf("successfully.\n");
        else
        {
            printf("not successfully.\n");
            printf("Length of original message: %d, Length of received message: %d.\n", messageOut.length(), message.length());
            break;
        }
    }
    delete receiver;
    delete sender;
}

I have following code for my sending socket:

bool utility::Sender::sendData(const std::string & message)
{
    int numBytes = 0;
    int totalSent = 0;

    // Break condition: send() fails, or whole message was transfered

    while (totalSent < message.length() && send(message.substr(totalSent).c_str(), message.length() - totalSent, numBytes))
    {
        totalSent += numBytes;
    }

    return false;
}

bool utility::Sender::send(const char* pBuffer, int32_t lengthOfBuffer, int32_t &numBytes)
{
    numBytes = ::send(connectSocket, pBuffer, lengthOfBuffer, 0);

    if (numBytes == SOCKET_ERROR)
        return false;

    return true;
}

The receiving side:

bool utility::Receiver::ReceiveData(std::string& message)
{
    int32_t numBytes = 0;

    char data[defaultBufferLength];

    // Set to blocking for the first data package

    u_long iMode = 0;
    ioctlsocket(tcpSocket, FIONBIO, &iMode);

    bool success = receive(data, defaultBufferLength, numBytes);
    message = std::string(data, numBytes);

    // Set to non-blocking for the rest of the journey
    iMode = 1;
    ioctlsocket(tcpSocket, FIONBIO, &iMode);

    while (numBytes == defaultBufferLength && receive(data, defaultBufferLength, numBytes))
    {
        message.append(data, numBytes);
    }

    return success;
}

bool utility::Receiver::receive(char* pBuffer, int32_t lengthOfBuffer, int32_t& numBytes)
{
    int32_t flags = 0;

    numBytes = recv(tcpSocket, pBuffer, lengthOfBuffer, flags);
    if (numBytes == -1)
    {
        numBytes = 0;
        if (errno == EAGAIN || errno == EWOULDBLOCK)
            return false;
        else
            close();
    }

    return true;
}

The output I am getting is

Sent data of length 39200 successfully.
Sent data of length 39300 successfully.
Sent data of length 39400 successfully.
Sent data of length 39500 successfully.
Sent data of length 39600 successfully.
Sent data of length 39700 successfully.
Sent data of length 39800 successfully.
Sent data of length 39900 successfully.
Sent data of length 40000 successfully.
Sent data of length 40100 successfully.
Sent data of length 40200 successfully.
Sent data of length 40300 successfully.
Sent data of length 40400 successfully.
Sent data of length 40500 not successfully.
Length of original message: 40500, Length of received message: 29200.

The thing which is the most irritating, and probably the cause of this, is the ::send(...). I can give it 2 MB of char*, and it will just send it in one swoop (but the receiver fails miserably). What can I do about that?


问:
Do I have to inject the service in the unit test if I cal testBed.get() previously?
I have a service which I'm consuming in my angular 2 unit test.

I call the service in the beforeEach block first with TestBed.get()

Example:

```<code> beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });
</code>```

I then use this service in the unit test like this:

Example:

```<code> it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));
</code>```

Do I need to inject the service in the unit test If called previously, or do I need to just call TestBed.get() and the use it across or should I do both?

答:
As it's explained in this answer, inject and TestBed.get are similar, so it's a matter of style. Some services that are common to all specs can be assigned to variables, while services that are specific to particular specs can be injected only in those specs.

In the case when spec function relies on inject and not local variables, it doesn't have to be necessarily defined in the scope of current describe block and can be reused or moved to some helper function.

It should be noticed that injector instance is created on first inject function or TestBed.get call, the way they are used can alter the results.

Body:
I have a service which I'm consuming in my angular 2 unit test.

I call the service in the beforeEach block first with TestBed.get()

Example:

 beforeEach(() => {
    fixture = TestBed.createComponent(ConfigComponent);
    component = fixture.componentInstance;
    service = TestBed.get(ConfigService);
    fixture.detectChanges();
  });

I then use this service in the unit test like this:

Example:

 it('should do something', inject([ConfigService], (configService) => {
      // code here
 }));

Do I need to inject the service in the unit test If called previously, or do I need to just call TestBed.get() and the use it across or should I do both?


问:
Memory allocation for union in C
I was recently studying union and end up with a confusion even after reading a lot about it.

```<code>#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x);
    return 0;
}
</code>```

What I understood is :

Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. 0 is ASCII value of '\0'. When we do "t.arr[1] = 'G'", arr[] becomes "\0G\0\0". When we print a string using "%s", the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.

What I don't get is second printf statement

Now since arr[] is "\0G\0\0" , the same location is shared with x and y.
So what I think x to be is the following

00000000 01000111 00000000 00000000 ("\0G\0\0")

so t.x should print 4653056.
But what it's printing is 18176.

Where am I going wrong?

Is this technically undefined or is it due to some silly mistake or am I missing some concept??

答:
tl;dr: endianity!

When printf reads the data from the memory pointed at by your union, it looks at the endianity of your system and reads the data stored in little endian.
So, instead of printing the data as it is stored in memory (0x00470000) it gets the number 0x00004700, which correlates to 18176, like you get.

Code example:

```<code>#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x); // prints 18176

    t.x = 0;
    t.arr[2] = 'G';
    printf("%d\n",t.x); // prints 4653056
    return 0;
}
</code>```

Or in Python:

```<code>import struct

union_data = "\x00G\x00\x00"
print struct.unpack("<I", a)[0] # This is little endian. Prints 18176
print struct.nupack(">I", a)[0] # This is big endian. Prints 4653056
</code>```

Bonus! You can also use the function htonl to convert integers read as little endian to big endian. See more at the docs.

Title: Memory allocation for union in C

Body:
I was recently studying union and end up with a confusion even after reading a lot about it.

#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x);
    return 0;
}

What I understood is :

Since x and arr[4] share the same memory, when we set x = 0, all characters of arr are set as 0. 0 is ASCII value of '\0'. When we do "t.arr[1] = 'G'", arr[] becomes "\0G\0\0". When we print a string using "%s", the printf function starts from the first character and keeps printing till it finds a \0. Since the first character itself is \0, nothing is printed.

What I don't get is second printf statement

Now since arr[] is "\0G\0\0" , the same location is shared with x and y.
So what I think x to be is the following

00000000 01000111 00000000 00000000 ("\0G\0\0")

so t.x should print 4653056.
But what it's printing is 18176.

Where am I going wrong?

Is this technically undefined or is it due to some silly mistake or am I missing some concept??

Body:
tl;dr: endianity!

When printf reads the data from the memory pointed at by your union, it looks at the endianity of your system and reads the data stored in little endian.
So, instead of printing the data as it is stored in memory (0x00470000) it gets the number 0x00004700, which correlates to 18176, like you get.

Code example:

#include<stdio.h>
union test
{
    int x;
    char arr[4];
    int y;
};

int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s\n", t.arr);
    printf("%d\n",t.x); // prints 18176

    t.x = 0;
    t.arr[2] = 'G';
    printf("%d\n",t.x); // prints 4653056
    return 0;
}

Or in Python:

import struct

union_data = "\x00G\x00\x00"
print struct.unpack("<I", a)[0] # This is little endian. Prints 18176
print struct.nupack(">I", a)[0] # This is big endian. Prints 4653056

Bonus! You can also use the function htonl to convert integers read as little endian to big endian. See more at the docs.


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

答:
```<code>task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
task_list = [w.replace('A', '1A') for w in task_list]
task_list = [w.replace('B', '2B') for w in task_list]
</code>```

Then, you will get

```<code>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:
task_list = ['A1.wakeup', 'A2.brush','B1.route','B2.breakfast']
task_list = [w.replace('A', '1A') for w in task_list]
task_list = [w.replace('B', '2B') for w in task_list]

Then, you will get

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


问:
Don't MIME types like images or PDF files need to be base64 or otherwise encoded?
Don't MIME types like images or PDF files need to be base64 or otherwise encoded
when wanting to send them or upload them over HTTP, since they could potentialy contain control characters?

Don't binary data need a separate tratment from the textual ones, or could I even transfer a text file as binary data (application/octet-stream) and let the receiving application decide how to handle it?

答:
HTTP request doesn't need any transfer encoding. Properly constructed HTTP POST request with multipart/form-data would include Content-Type for each section through every boundary. Don't need to think about it as MIME message. Server/application, this HTTP request addressed to, will handle each boundary content according to content headers and in particular Content-Type. The small example of HTTP POST payload may look like ...

```<code>POST /my_page HTTP/1.1
Content-Type: multipart/form-data; boundary=MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF

--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="field1"

content of this input field
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="html_content"

<p><em>Dear customer</em>,</p>
<p>Please review the attached.</p>
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="file0"; filename="sample.txt"
Content-Type: text/plain

Plain text file content.
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="file1"; filename="sample.docx"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document

PK     ! ß¤ÒlZ      [Content_Types].xml ¢(
l"%3÷Þ3VÆƒÑÚšl  µw%ë=–“^i7+Ù×ä-d&á”0ÞAÉ6€l4¼½L60#µÃ’ÍS
Oœ£œƒXø Ž*•V$z3„ü3à÷½Þ—Þ%p)Oµ^ “²×5}nH"dÙsÓXg•L„
    Á  8
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF--
</code>```

Body:
HTTP request doesn't need any transfer encoding. Properly constructed HTTP POST request with multipart/form-data would include Content-Type for each section through every boundary. Don't need to think about it as MIME message. Server/application, this HTTP request addressed to, will handle each boundary content according to content headers and in particular Content-Type. The small example of HTTP POST payload may look like ...

POST /my_page HTTP/1.1
Content-Type: multipart/form-data; boundary=MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF

--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="field1"

content of this input field
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="html_content"

<p><em>Dear customer</em>,</p>
<p>Please review the attached.</p>
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="file0"; filename="sample.txt"
Content-Type: text/plain

Plain text file content.
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF
Content-Disposition: form-data; name="file1"; filename="sample.docx"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document

PK     ! ß¤ÒlZ      [Content_Types].xml ¢(
l"%3÷Þ3VÆƒÑÚšl  µw%ë=–“^i7+Ù×ä-d&á”0ÞAÉ6€l4¼½L60#µÃ’ÍS
Oœ£œƒXø Ž*•V$z3„ü3à÷½Þ—Þ%p)Oµ^ “²×5}nH"dÙsÓXg•L„
    Á  8
--MNZ2WM28FYlZX3miY-6E9iytpT0UfW-uzlOvF--


问:
What values do I specify for clientid and secret for `OpenID Connect - Get a token`?
I would like to use the REST API to retrieve the IAM token which you can retrieve using the `bx iam oauth-tokens' command:

```<code>$ bx login --apikey @myapikey.json
$ bx iam oauth-tokens
IAM token:  Bearer ****
UAA token:  Bearer ****
</code>```

By setting BLUEMIX_TRACE=true, I can see that there is a call to https://iam.ng.bluemix.net/oidc/token.

I've found the docs for the token service provide the following information:

Authorization
  Authorization Token used for the request. The supported
  token type is a basic auth token containing a clientid and secret. If
  the token is omitted, a default client configuration will be used
  which can only interact with Api Keys.'

```<code>var options = {
  "method": "POST",
  "hostname": "localhost",
  "port": "443",
  "path": "//oidc/token",
  "headers": {
    "authorization": "string",
    "accept": "application/json",
    "content-type": "application/x-www-form-urlencoded"
  }
};
</code>```

What should I be setting for clientid and secret?  Do I need to obtain these values from another API call?

答:
The recommended way is to omit the authorization header. So this call should work (please note that I am using the global endpoint iam.bluemix.net for best availability, and also the new context path /identity/token):

curl -d "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=<your API key>" https://iam.bluemix.net/identity/token

Body:
I would like to use the REST API to retrieve the IAM token which you can retrieve using the `bx iam oauth-tokens' command:

$ bx login --apikey @myapikey.json
$ bx iam oauth-tokens
IAM token:  Bearer ****
UAA token:  Bearer ****

By setting BLUEMIX_TRACE=true, I can see that there is a call to https://iam.ng.bluemix.net/oidc/token.

I've found the docs for the token service provide the following information:

Authorization
  Authorization Token used for the request. The supported
  token type is a basic auth token containing a clientid and secret. If
  the token is omitted, a default client configuration will be used
  which can only interact with Api Keys.'

var options = {
  "method": "POST",
  "hostname": "localhost",
  "port": "443",
  "path": "//oidc/token",
  "headers": {
    "authorization": "string",
    "accept": "application/json",
    "content-type": "application/x-www-form-urlencoded"
  }
};

What should I be setting for clientid and secret?  Do I need to obtain these values from another API call?


问:
putRecords into a Kinesis Stream by hitting a HTTP Endpoint?
I want to add data to Kinesis Stream by Hitting an HTTP Endpoint, specifying some headers and data.

I know its possible via API Gateway -> AWS Service Proxy -> Kinesis Stream.
I dont want to use API Gateway.

Also I dont want to use the KPL Library.

The task is to provide an Endpoint to a Tibco Service and Tibco Service is going to ingest data into the stream.

Architecture Changes are welcome.!

答:
The Kinesis API endpoints is what you're looking for.

However, handling the authentication and signing of the requests is going to be much work, which is already done for you in the AWS CLI and SDKs.

If possible, use those to submit your Kinesis data.

If this is not possible, you will need to create your own endpoint to receive the more "basic" request, and convert that into an AWS authenticated request. That's either done using the API gateway (which you state you do not want to do), or you host your own web server on an EC2 instance.

AWS has provided many tools to make things easy for you. Either use them, or roll your own.


问:
Unitary test PHP & Mocks
I am trying to code a test class but this is the first time I'm doing it, so I'm a little lost with the exemple I've got from class.

Here is my Exchange Class :

```<code><?php

//require 'User.php';
require 'Product.php';
require 'EmailSender.php';
require 'DatabaseConnection.php';

class Exchange{

private $dateDebut;
private $dateFin;
private $receiver;
private $product;
private $owner;
private $emailSender;
private $dbConnexion;

function __construct($dateDebut, $dateFin, $receiver, $product, $owner)
{
    $this->dateDebut = $dateDebut;
    $this->dateFin = $dateFin;
    $this->receiver = $receiver;
    $this->product = $product;
    $this->owner = $owner;
    $this->emailSender = new EmailSender();
    $this->dbConnexion = new DatabaseConnection();
}

public function save($dateDebut, $dateFin)
{

    if($this->owner->isValid()){
        $checkOwner = true;
    }

    if($this->receiver->isValid()){
        $checkReceiver = true;
    }

    if($this->product->isValid()){
        $checkProduct = true;
    }

    if(!empty($dateDebut) && $dateDebut > date("Y-m-d")){
        $checkDateDebut = true;
    }

    if(!empty($dateFin) && $dateFin > date("Y-m-d") && $dateFin > $dateDebut){
        $checkDateFin = true;
    }

    if($checkProduct == true && $checkReceiver == true && $checkOwner == true && $checkDateFin == true && $checkDateDebut == true){

            if($this->receiver->age < 19){
                $this->emailSender->sendMail($this->receiver->getEmail(), "Moins de 18 ans");
            }

            // enregistrer en base
            return 12;
    }
    else{
        return false;
    }

}

// Liste des setters

public function setDateDebut($dateDebut)
{
    $this->dateDebut = $dateDebut;
}

public function setDateFin($dateFin)
{
    $this->dateFin = $dateFin;
}

public function setReceiver($receiver)
{
    $this->receiver = $receiver;
}

public function setProduct($product)
{
    $this->product = $product;
}

public function setOwner($owner)
{
    $this->owner = $owner;
}

public function setEmailSender($emailSender)
{
    $this->emailSender = $emailSender;
}

public function setDBConnexion($dbConnexion)
{
    $this->dbConnexion = $dbConnexion;
}

// Liste des getters

public function getDateDebut()
{
    return $this->dateDebut;
}

public function getDateFin()
{
    return $this->dateFin;
}

public function getReceiver()
{
    return $this->receiver;
}

public function getProduct()
{
    return $this->product;
}

public function getOwner()
{
    return $this->owner;
}

public function getEmailSender()
{
    return $this->emailSender;
}

public function getDBConnexion()
{
    return $this->dbConnexion;
}

}

?>
</code>```

And here is my "Test" class I tried to do.

```<code><?php
</code>```

require 'Exchange.php';

```<code>class ExchangeTest extends PHPUnit_Framework_TestCase{

    private $exchange;

    public function testSave()
    {
        $result = $this->exchange->save("2017-11-18", "2017-11-20");
        $this->assertEquals($result, 12);
    }
}
</code>```

Any help with unitary test will be nice, thanks, I've got the error that the function data is null yet.

答:
It looks like you've defined a property which you haven't populated, so when you go to use it there's no object there to run methods on and it errors out.

In most unit test scenarios you want each test to be as self-contained as possible to avoid one test causing a cascade failure in another. Making this a local variable should fix the problem:

```<code>public function testSave()
{
  $exchange = new Exchange(...);

  $result = $this->exchange->save("2017-11-18", "2017-11-20");
  $this->assertEquals($result, 12);
}
</code>```

You my want to create an exchange() factory method of some kind that properly initializes the Exchange instance to avoid having to repeat a lot of boilerplate inside of each test.

Title: Unitary test PHP & Mocks

Body:
I am trying to code a test class but this is the first time I'm doing it, so I'm a little lost with the exemple I've got from class.

Here is my Exchange Class :

<?php

//require 'User.php';
require 'Product.php';
require 'EmailSender.php';
require 'DatabaseConnection.php';

class Exchange{

private $dateDebut;
private $dateFin;
private $receiver;
private $product;
private $owner;
private $emailSender;
private $dbConnexion;

function __construct($dateDebut, $dateFin, $receiver, $product, $owner)
{
    $this->dateDebut = $dateDebut;
    $this->dateFin = $dateFin;
    $this->receiver = $receiver;
    $this->product = $product;
    $this->owner = $owner;
    $this->emailSender = new EmailSender();
    $this->dbConnexion = new DatabaseConnection();
}

public function save($dateDebut, $dateFin)
{

    if($this->owner->isValid()){
        $checkOwner = true;
    }

    if($this->receiver->isValid()){
        $checkReceiver = true;
    }

    if($this->product->isValid()){
        $checkProduct = true;
    }

    if(!empty($dateDebut) && $dateDebut > date("Y-m-d")){
        $checkDateDebut = true;
    }

    if(!empty($dateFin) && $dateFin > date("Y-m-d") && $dateFin > $dateDebut){
        $checkDateFin = true;
    }

    if($checkProduct == true && $checkReceiver == true && $checkOwner == true && $checkDateFin == true && $checkDateDebut == true){

            if($this->receiver->age < 19){
                $this->emailSender->sendMail($this->receiver->getEmail(), "Moins de 18 ans");
            }

            // enregistrer en base
            return 12;
    }
    else{
        return false;
    }

}

// Liste des setters

public function setDateDebut($dateDebut)
{
    $this->dateDebut = $dateDebut;
}

public function setDateFin($dateFin)
{
    $this->dateFin = $dateFin;
}

public function setReceiver($receiver)
{
    $this->receiver = $receiver;
}

public function setProduct($product)
{
    $this->product = $product;
}

public function setOwner($owner)
{
    $this->owner = $owner;
}

public function setEmailSender($emailSender)
{
    $this->emailSender = $emailSender;
}

public function setDBConnexion($dbConnexion)
{
    $this->dbConnexion = $dbConnexion;
}

// Liste des getters

public function getDateDebut()
{
    return $this->dateDebut;
}

public function getDateFin()
{
    return $this->dateFin;
}

public function getReceiver()
{
    return $this->receiver;
}

public function getProduct()
{
    return $this->product;
}

public function getOwner()
{
    return $this->owner;
}

public function getEmailSender()
{
    return $this->emailSender;
}

public function getDBConnexion()
{
    return $this->dbConnexion;
}

}

?>

And here is my "Test" class I tried to do.

<?php

require 'Exchange.php';

class ExchangeTest extends PHPUnit_Framework_TestCase{

    private $exchange;

    public function testSave()
    {
        $result = $this->exchange->save("2017-11-18", "2017-11-20");
        $this->assertEquals($result, 12);
    }
}

Any help with unitary test will be nice, thanks, I've got the error that the function data is null yet.

Body:
It looks like you've defined a property which you haven't populated, so when you go to use it there's no object there to run methods on and it errors out.

In most unit test scenarios you want each test to be as self-contained as possible to avoid one test causing a cascade failure in another. Making this a local variable should fix the problem:

public function testSave()
{
  $exchange = new Exchange(...);

  $result = $this->exchange->save("2017-11-18", "2017-11-20");
  $this->assertEquals($result, 12);
}

You my want to create an exchange() factory method of some kind that properly initializes the Exchange instance to avoid having to repeat a lot of boilerplate inside of each test.