问:
Unix domain socket non-blocking operation failed at listen, in C
This program will calculate RTT for non blocking communication for simple IPC program using UNIX domain socket.

I'm having a problem with socket programming where at server-side my socket exit with error at listen(). The blocking version of the code
works fine; I tried to modify it to non-blocking with SOCK_NONBLOCK at
socket(), but it seems to fail at listening:

hafizul96@ubuntu:~/asyntest$ ./Server  [SERVER PROCESS] Socket Created, Process ID : 7334  [SERVER PROCESS] Socket Listening..
  [SERVER PROCESS] Error Accepting **

Client:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>

#define SERV_SOCK_PATH "ipc_unix_sock.server"
#define CLIN_SOCK_PATH "ipc_unix_sock.client"

void Array_Init(int *, int);
void Write_to_File(FILE *, int *, int);

int main(int argc, char *argv[])
{
    struct sockaddr_un serv_addr, cli_addr;
    int client_socket, add_len, rc, array_len, send_bytes, recv_bytes;
    pid_t process_id = getpid();
    clock_t start, end;
    double elapsed = 0.0;
    FILE *cli_arr_recv;
    FILE *cli_arr_send;
    char arr_len[10];
    int *Array_Buff;
    array_len = atoi(argv[1]);
    sprintf(arr_len, "%d", array_len);

    Array_Buff = malloc(sizeof(int)*array_len);
    cli_arr_send = fopen("cli_arr_send.txt","w+");
    cli_arr_recv = fopen("cli_arr_recv.txt","w+");

    memset(&serv_addr, 0, sizeof(struct sockaddr_un));
    memset(&cli_addr, 0, sizeof(struct sockaddr_un));
    memset(Array_Buff, 0, array_len);
    Array_Init(Array_Buff, array_len);
    //Copy arrays to file
    Write_to_File(cli_arr_send, Array_Buff, array_len);

//NON-BLOCKING SOCKET//
    if((client_socket = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0))<0)
    {
        printf("[CLIENT PROCESS] Socket Creation Error\n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[CLIENT PROCESS] Socket Created, Process ID :%d\n", process_id);
        printf("[CLIENT PROCESS] %lubytes Allocated\n", sizeof(int)*array_len);
    }

    cli_addr.sun_family = AF_UNIX;
    strcpy(cli_addr.sun_path, CLIN_SOCK_PATH);
    add_len = sizeof(cli_addr);

    unlink(CLIN_SOCK_PATH);
    if((rc = bind(client_socket, (struct sockaddr*)&cli_addr, add_len ))<0)
    {
        printf("[CLIENT PROCESS] Bind error \n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    serv_addr.sun_family = AF_UNIX;
    strcpy(serv_addr.sun_path, SERV_SOCK_PATH);
    if((rc = connect(client_socket, (struct sockaddr*)&serv_addr, add_len))<0)
    {
        printf("[CLIENT PROCESS] Failed to Connect to Server Process\n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    start = clock();
    if((rc = send(client_socket, arr_len, sizeof(arr_len), 0))<0)
    {
        printf("[CLIENT PROCESS] Failed to Send Array Len to Server Process");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    if((send_bytes = send(client_socket, Array_Buff, sizeof(int)*array_len, 0))<0)
    {
        printf("[CLIENT PROCESS] Failed to Send Array Elements to Server Process");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[CLIENT PROCESS] Total Bytes Sent = %dbytes\n",send_bytes);
        memset(Array_Buff, 0, array_len); //reset buffer
        if((recv_bytes = recv(client_socket, Array_Buff, sizeof(int)*array_len, MSG_WAITALL))<0)
        {
            fclose(cli_arr_recv);
            fclose(cli_arr_send);
            close(client_socket);
            exit(EXIT_FAILURE);
        }
        else
        {
            //Finishes RTT
            end = clock();
            printf("[CLIENT PROCESS] Total Bytes Received Back = %dbytes\n",recv_bytes);
            Write_to_File(cli_arr_recv, Array_Buff, array_len);
        }

    }
    elapsed = (end - start)/(double)CLOCKS_PER_SEC;
    printf("[CLIENT PROCESS] RTT(Round Trip Time) is =  %fs\n", elapsed);
    printf("[CLIENT PROCESS] Program Completed.\n");

    free(Array_Buff);
    fclose(cli_arr_recv);
    fclose(cli_arr_send);
    close(client_socket);
    exit(EXIT_SUCCESS);
}
void Array_Init(int *Array_Buff, int array_len)
{
    unsigned int seed = 184611;
    srand(seed);
    for(int i = 0; i< array_len; i++)
    {
        *(Array_Buff++) = rand() % 999999;
    }
}
void Write_to_File(FILE *outfile, int *Array_Buff, int array_len)
{
    for(int i = 0; i<array_len; i++)
    {
        fprintf(outfile, " %d ", *(Array_Buff++));
    }
    printf("[CLIENT PROCESS] File Write Completed.. \n");
}
</code>```

Server:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SERV_SOCK_PATH "ipc_unix_sock.server"

void Write_to_File(FILE *, int *, int);

int main(int argc, char *argv[])
{
    struct sockaddr_un serv_addr, cli_addr;
    int server_sock, client_sock, add_len, rc, array_len;
    int backlog = 2, recv_bytes = 0, send_bytes = 0;
    pid_t process_id = getpid();
    FILE *serv_file;
    int *Array_Buff;
    char arr_len[10];

    serv_file = fopen("serv_recv_arr.txt","w+");

    /*Making sure that address struct set to zero*/
    memset(&serv_addr, 0, sizeof(struct sockaddr_un));
    memset(&cli_addr, 0, sizeof(struct sockaddr_un));
    memset(arr_len, 0, 10);
//NON-BLOCKING SOCKET TYPE
    if((server_sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0 )
    {
        printf("[SERVER PROCESS] Error Socket\n");
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Socket Created, Process ID : %d\n", process_id);
    }

    serv_addr.sun_family = AF_UNIX;
    strcpy(serv_addr.sun_path, SERV_SOCK_PATH);
    add_len = sizeof(serv_addr);

    unlink(SERV_SOCK_PATH);
    if((rc = bind(server_sock, (struct sockaddr*)&serv_addr, add_len))<0)
    {
    printf("[SERVER PROCESS] Error Binding\n");
    close(server_sock);
    exit(EXIT_FAILURE);
    }

    if((rc = listen(server_sock, backlog)) <0 )
    {
        printf("[SERVER PROCESS] Error Listening\n");
        close(server_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }

    printf("[SERVER PROCESS] Socket Listening..\n");

    if((client_sock = accept(server_sock, (struct sockaddr*)&client_sock, &add_len))<0)
    {
        printf("[SERVER PROCESS] Error Accepting\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }

    add_len = sizeof(cli_addr);
    if((rc = getpeername(client_sock, (struct sockaddr*)&cli_addr, &add_len))<0)
    {
        printf("[SERVER PROCESS] Error Getting Peername\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Client Socket Filepath = %s\n", cli_addr.sun_path);
    }

    printf("[SERVER PROCESS] Waiting to Recv Msg..\n");

    if((rc =  recv(client_sock, arr_len, sizeof(arr_len), MSG_WAITALL))<0)
    {
        printf("[SERVER PROCESS] Error Receiving Msg..\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    printf("[SERVER PROCESS] Array Len Received %s\n", arr_len);
    array_len = atoi(arr_len);
    Array_Buff = malloc(sizeof(int)*array_len);
    printf("[SERVER PROCESS] %lubytes Allocated\n", sizeof(int)*array_len);
    memset(Array_Buff, 0, array_len);

    if((recv_bytes = recv(client_sock, Array_Buff, sizeof(int)*array_len, MSG_WAITALL))<0)
    {
        printf("[SERVER PROCESS] Error Receiving Msg..\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Total Bytes Recv = %dbytes\n",recv_bytes);
        if((send_bytes = send(client_sock, Array_Buff, sizeof(int)*array_len, 0))<0)
        {
            printf("[SERVER PROCESS] Error Sending Back Array\n");
            close(server_sock);
            close(client_sock);
            fclose(serv_file);
            exit(EXIT_FAILURE);
        }
        else
        {
             printf("[SERVER PROCESS] Total Bytes Sent Back = %dbytes\n", send_bytes);
        }

    }
    Write_to_File(serv_file, Array_Buff, array_len);
    printf("[SERVER PROCESS] Program Completed.\n");

    free(Array_Buff);
    close(server_sock);
    close(client_sock);
    exit(EXIT_SUCCESS);
}

void Write_to_File(FILE *outfile, int *Array_Buff, int array_len)
{
    for(int i = 0; i<array_len; i++)
    {
        fprintf(outfile, " %d ", *(Array_Buff++));
    }
    printf("[SERVER PROCESS] File Write Completed.. \n");
    fclose(outfile);
}
</code>```

Does anybody know what the problem is and how to fix it?

答: Because your socket is non-blocking, accept does not wait until a connection happens but it returns EAGAIN or EWOULDBLOCK value. You shall call accept repeatedly until it returns a different value. To avoid consuming 100% of your CPU by those calls, do some  sleep between two calls or use select or poll to wait until your socket is readable.

Body:
This program will calculate RTT for non blocking communication for simple IPC program using UNIX domain socket.

I'm having a problem with socket programming where at server-side my socket exit with error at listen(). The blocking version of the code
works fine; I tried to modify it to non-blocking with SOCK_NONBLOCK at
socket(), but it seems to fail at listening:

hafizul96@ubuntu:~/asyntest$ ./Server  [SERVER PROCESS] Socket Created, Process ID : 7334  [SERVER PROCESS] Socket Listening..
  [SERVER PROCESS] Error Accepting **

Client:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>

#define SERV_SOCK_PATH "ipc_unix_sock.server"
#define CLIN_SOCK_PATH "ipc_unix_sock.client"

void Array_Init(int *, int);
void Write_to_File(FILE *, int *, int);

int main(int argc, char *argv[])
{
    struct sockaddr_un serv_addr, cli_addr;
    int client_socket, add_len, rc, array_len, send_bytes, recv_bytes;
    pid_t process_id = getpid();
    clock_t start, end;
    double elapsed = 0.0;
    FILE *cli_arr_recv;
    FILE *cli_arr_send;
    char arr_len[10];
    int *Array_Buff;
    array_len = atoi(argv[1]);
    sprintf(arr_len, "%d", array_len);

    Array_Buff = malloc(sizeof(int)*array_len);
    cli_arr_send = fopen("cli_arr_send.txt","w+");
    cli_arr_recv = fopen("cli_arr_recv.txt","w+");

    memset(&serv_addr, 0, sizeof(struct sockaddr_un));
    memset(&cli_addr, 0, sizeof(struct sockaddr_un));
    memset(Array_Buff, 0, array_len);
    Array_Init(Array_Buff, array_len);
    //Copy arrays to file
    Write_to_File(cli_arr_send, Array_Buff, array_len);

//NON-BLOCKING SOCKET//
    if((client_socket = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0))<0)
    {
        printf("[CLIENT PROCESS] Socket Creation Error\n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[CLIENT PROCESS] Socket Created, Process ID :%d\n", process_id);
        printf("[CLIENT PROCESS] %lubytes Allocated\n", sizeof(int)*array_len);
    }

    cli_addr.sun_family = AF_UNIX;
    strcpy(cli_addr.sun_path, CLIN_SOCK_PATH);
    add_len = sizeof(cli_addr);

    unlink(CLIN_SOCK_PATH);
    if((rc = bind(client_socket, (struct sockaddr*)&cli_addr, add_len ))<0)
    {
        printf("[CLIENT PROCESS] Bind error \n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    serv_addr.sun_family = AF_UNIX;
    strcpy(serv_addr.sun_path, SERV_SOCK_PATH);
    if((rc = connect(client_socket, (struct sockaddr*)&serv_addr, add_len))<0)
    {
        printf("[CLIENT PROCESS] Failed to Connect to Server Process\n");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    start = clock();
    if((rc = send(client_socket, arr_len, sizeof(arr_len), 0))<0)
    {
        printf("[CLIENT PROCESS] Failed to Send Array Len to Server Process");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    if((send_bytes = send(client_socket, Array_Buff, sizeof(int)*array_len, 0))<0)
    {
        printf("[CLIENT PROCESS] Failed to Send Array Elements to Server Process");
        fclose(cli_arr_recv);
        fclose(cli_arr_send);
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[CLIENT PROCESS] Total Bytes Sent = %dbytes\n",send_bytes);
        memset(Array_Buff, 0, array_len); //reset buffer
        if((recv_bytes = recv(client_socket, Array_Buff, sizeof(int)*array_len, MSG_WAITALL))<0)
        {
            fclose(cli_arr_recv);
            fclose(cli_arr_send);
            close(client_socket);
            exit(EXIT_FAILURE);
        }
        else
        {
            //Finishes RTT
            end = clock();
            printf("[CLIENT PROCESS] Total Bytes Received Back = %dbytes\n",recv_bytes);
            Write_to_File(cli_arr_recv, Array_Buff, array_len);
        }

    }
    elapsed = (end - start)/(double)CLOCKS_PER_SEC;
    printf("[CLIENT PROCESS] RTT(Round Trip Time) is =  %fs\n", elapsed);
    printf("[CLIENT PROCESS] Program Completed.\n");

    free(Array_Buff);
    fclose(cli_arr_recv);
    fclose(cli_arr_send);
    close(client_socket);
    exit(EXIT_SUCCESS);
}
void Array_Init(int *Array_Buff, int array_len)
{
    unsigned int seed = 184611;
    srand(seed);
    for(int i = 0; i< array_len; i++)
    {
        *(Array_Buff++) = rand() % 999999;
    }
}
void Write_to_File(FILE *outfile, int *Array_Buff, int array_len)
{
    for(int i = 0; i<array_len; i++)
    {
        fprintf(outfile, " %d ", *(Array_Buff++));
    }
    printf("[CLIENT PROCESS] File Write Completed.. \n");
}

Server:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SERV_SOCK_PATH "ipc_unix_sock.server"

void Write_to_File(FILE *, int *, int);

int main(int argc, char *argv[])
{
    struct sockaddr_un serv_addr, cli_addr;
    int server_sock, client_sock, add_len, rc, array_len;
    int backlog = 2, recv_bytes = 0, send_bytes = 0;
    pid_t process_id = getpid();
    FILE *serv_file;
    int *Array_Buff;
    char arr_len[10];

    serv_file = fopen("serv_recv_arr.txt","w+");

    /*Making sure that address struct set to zero*/
    memset(&serv_addr, 0, sizeof(struct sockaddr_un));
    memset(&cli_addr, 0, sizeof(struct sockaddr_un));
    memset(arr_len, 0, 10);
//NON-BLOCKING SOCKET TYPE
    if((server_sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0 )
    {
        printf("[SERVER PROCESS] Error Socket\n");
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Socket Created, Process ID : %d\n", process_id);
    }

    serv_addr.sun_family = AF_UNIX;
    strcpy(serv_addr.sun_path, SERV_SOCK_PATH);
    add_len = sizeof(serv_addr);

    unlink(SERV_SOCK_PATH);
    if((rc = bind(server_sock, (struct sockaddr*)&serv_addr, add_len))<0)
    {
    printf("[SERVER PROCESS] Error Binding\n");
    close(server_sock);
    exit(EXIT_FAILURE);
    }

    if((rc = listen(server_sock, backlog)) <0 )
    {
        printf("[SERVER PROCESS] Error Listening\n");
        close(server_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }

    printf("[SERVER PROCESS] Socket Listening..\n");

    if((client_sock = accept(server_sock, (struct sockaddr*)&client_sock, &add_len))<0)
    {
        printf("[SERVER PROCESS] Error Accepting\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }

    add_len = sizeof(cli_addr);
    if((rc = getpeername(client_sock, (struct sockaddr*)&cli_addr, &add_len))<0)
    {
        printf("[SERVER PROCESS] Error Getting Peername\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Client Socket Filepath = %s\n", cli_addr.sun_path);
    }

    printf("[SERVER PROCESS] Waiting to Recv Msg..\n");

    if((rc =  recv(client_sock, arr_len, sizeof(arr_len), MSG_WAITALL))<0)
    {
        printf("[SERVER PROCESS] Error Receiving Msg..\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    printf("[SERVER PROCESS] Array Len Received %s\n", arr_len);
    array_len = atoi(arr_len);
    Array_Buff = malloc(sizeof(int)*array_len);
    printf("[SERVER PROCESS] %lubytes Allocated\n", sizeof(int)*array_len);
    memset(Array_Buff, 0, array_len);

    if((recv_bytes = recv(client_sock, Array_Buff, sizeof(int)*array_len, MSG_WAITALL))<0)
    {
        printf("[SERVER PROCESS] Error Receiving Msg..\n");
        close(server_sock);
        close(client_sock);
        fclose(serv_file);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("[SERVER PROCESS] Total Bytes Recv = %dbytes\n",recv_bytes);
        if((send_bytes = send(client_sock, Array_Buff, sizeof(int)*array_len, 0))<0)
        {
            printf("[SERVER PROCESS] Error Sending Back Array\n");
            close(server_sock);
            close(client_sock);
            fclose(serv_file);
            exit(EXIT_FAILURE);
        }
        else
        {
             printf("[SERVER PROCESS] Total Bytes Sent Back = %dbytes\n", send_bytes);
        }

    }
    Write_to_File(serv_file, Array_Buff, array_len);
    printf("[SERVER PROCESS] Program Completed.\n");

    free(Array_Buff);
    close(server_sock);
    close(client_sock);
    exit(EXIT_SUCCESS);
}

void Write_to_File(FILE *outfile, int *Array_Buff, int array_len)
{
    for(int i = 0; i<array_len; i++)
    {
        fprintf(outfile, " %d ", *(Array_Buff++));
    }
    printf("[SERVER PROCESS] File Write Completed.. \n");
    fclose(outfile);
}

Does anybody know what the problem is and how to fix it?


来源: stackexchange

问:
How I can space the number with PHP command?
I want to code the PHP for spacing the number, example:

$number = "55375911";

So this number should to space to 2-digit and 6-digit, it shows so: "55 3759 11". How I can code this?

Thank you for helping.

答:
You could also use substring (if the number is always the same length):</p>

```<code>$number = "55375911";
$number_f = substr($number, 0, 2) . " " . substr($number, 2, 4) . " " . substr($number, 6, 6);

echo $number_f; // "55 3759 11"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could also use substring (if the number is always the same length):

$number = "55375911";
$number_f = substr($number, 0, 2) . " " . substr($number, 2, 4) . " " . substr($number, 6, 6);

echo $number_f; // "55 3759 11"


问:
Custom Data Types for DataFrame columns when using Spark JDBC
I know I can use a custom dialect for having a correct mapping between my db and spark but how can I create a custom table schema with specific field data types and lengths when I use spark's jdbc.write options? I would like to have granular control over my table schemas when I load a table from spark.

答:
There is a minimal flexibility for writes, implemented by

SPARK-10101 - Spark JDBC writer mapping String to TEXT or VARCHAR

SPARK-10849 - Allow user to specify database column type for data frame fields when writing data to jdbc data sources

but if you want

to have granular control over my table schemas when I load a table from spark.

you might have to implement your own JdbcDialect. It is internal developer API and as far as I can tell it is not plugable so you may need customized Spark binaries (it might be possible to registerDialect but I haven't tried this).


问:
ObjectDisposedException in .NET Core middleware with Entity Framework
I have an API written in .NET Core. I have a token middleware that I'm having some issues with.

If I send a request to the middleware from one client at a time it's fine. If I try to use the middleware by more than one client at a time I get errors.

From what I can tell I think the _userManager doesn't have a new instance created every time a request is made and I think this causes my problem. I seem to either get

System.InvalidOperationException: An attempt was made to use the context while it is being configured

or

System.ObjectDisposedException: Cannot access a disposed object

I'm thinking maybe the UserManager<ApplicationUser> that I'm injecting is a singleton? Maybe both requests are trying to use the same instance of _userManager and the first one disposes it and the second request errors?

I'm sorta new to this so maybe I'm way off base. Maybe _userManager wasn't meant to be used this way or maybe I'm injecting it incorrectly.

Here is some code from the starup.cs and token middleware. Below that are some of the error logs.

Parts of startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddDbContext<ApplicationDbContext>(options =>
     {

options.UseNpgsql(Environment.GetEnvironmentVariable("DbConnString"));
     });

        services.AddIdentity<ApplicationUser, IdentityRole>(o=>
        {
            o.Password.RequireDigit = false;
            o.Password.RequiredLength = 0;
            o.Password.RequireLowercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequireUppercase = false;
            o.SignIn.RequireConfirmedEmail = true;
            o.User.RequireUniqueEmail = true;

        })

                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     ...
      app.UseJWTTokenProviderMiddleware(Options.Create(jwtOptions));

        app.UseAuthentication();
        app.UseMvc();
     ...
 }
</code>```

TokenProviderMiddleware

```<code>public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private TokenProviderOptions _options;
    private UserManager<ApplicationUser> _userManager;
    private readonly ILogger<TokenProviderMiddleware> _logger;
    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, ILogger<TokenProviderMiddleware> logger)
    {
        _next = next;
        _options = options.Value;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;

        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
        {
            await _next(context);
            return;
        }
        if (!context.Request.Method.Equals("POST") || !context.Request.HasFormContentType)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Bad Request");
            return;
        }

        ApplicationUser user = null;
        string refreshToken;
        string accessToken;

        if (context.Request.Form["grant_type"].Equals("refresh_token"))
        {
            refreshToken = context.Request.Form["refresh_token"];
            if(String.IsNullOrEmpty(refreshToken))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token not sent");
                return;
            }

            // Check that the refresh_token is valid
            // I don't like using exceptions for flow control but it's how ValidateToken works
            try
            {
                ValidateRefreshToken(refreshToken);
            }
            catch(SecurityTokenInvalidSignatureException ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            catch(Exception ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            user = await GetUserAsync(context, "from_refresh_token");
            accessToken = await GenerateAccessToken(user);

            var response = new
            {
                access_token = accessToken
            };
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
            return;
        }

private async Task<ApplicationUser> GetUserAsync(HttpContext context, string getUserFrom)
    {
        ApplicationUser user = null;
        if(getUserFrom.Equals("from_username_password"))
        {
            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Username/password not sent");
            }

            user = await _userManager.FindByNameAsync(username);
            var result = _userManager.CheckPasswordAsync(user, password);
            if (result.Result == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password");
            }
            if(!await _userManager.IsEmailConfirmedAsync(user))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Email address not confirmed");
            }

        }

        else if (getUserFrom.Equals("from_refresh_token"))
        {
            JwtSecurityToken decodedRefreshToken = new JwtSecurityTokenHandler().ReadJwtToken(context.Request.Form["refresh_token"]);
            string uid = decodedRefreshToken.Payload.Claims.FirstOrDefault(x => x.Type == "uid").Value;
            user = await _userManager.FindByIdAsync(uid);
        }

        return user;
    }
</code>```

Error logs

```<code>2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": started reading request body.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": started reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": done reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": done reading request body.
2017-12-02 19:45:27.450 -05:00 [Information] Entity Framework Core "2.0.0-rtm-26452" initialized '"ApplicationDbContext"' using provider '"Npgsql.EntityFrameworkCore.PostgreSQL"' with options: "None"
2017-12-02 19:45:27.762 -05:00 [Debug] System.InvalidOperationException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-12-02 19:45:27.762 -05:00 [Debug] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-12-02 19:45:27.763 -05:00 [Error] An unhandled exception has occurred while executing the request
System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.get_UsersSet()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.FindByIdAsync(String userId, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByIdAsync(String userId)
   at MyProject.TokenProviderMiddleware.<GetUserAsync>d__9.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 220
</code>```

```<code>System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AsyncDisposer'.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.AsyncDisposer.Dispose()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<Aggregate_>d__6`3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<GetClaimsAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<GetClaimsAsync>d__103.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.TokenProviderMiddleware.<CreateClaims>d__10.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 239
</code>```

答: If your UserManager is depending on a dbcontext, it should not be a singleton. The dbcontext should be created separately for each request. Make your UserManager transient to manage the dbcontext correctly.</p>

Body:
I have an API written in .NET Core. I have a token middleware that I'm having some issues with.

If I send a request to the middleware from one client at a time it's fine. If I try to use the middleware by more than one client at a time I get errors.

From what I can tell I think the _userManager doesn't have a new instance created every time a request is made and I think this causes my problem. I seem to either get

System.InvalidOperationException: An attempt was made to use the context while it is being configured

or

System.ObjectDisposedException: Cannot access a disposed object

I'm thinking maybe the UserManager<ApplicationUser> that I'm injecting is a singleton? Maybe both requests are trying to use the same instance of _userManager and the first one disposes it and the second request errors?

I'm sorta new to this so maybe I'm way off base. Maybe _userManager wasn't meant to be used this way or maybe I'm injecting it incorrectly.

Here is some code from the starup.cs and token middleware. Below that are some of the error logs.

Parts of startup.cs

public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddDbContext<ApplicationDbContext>(options =>
     {

options.UseNpgsql(Environment.GetEnvironmentVariable("DbConnString"));
     });

        services.AddIdentity<ApplicationUser, IdentityRole>(o=>
        {
            o.Password.RequireDigit = false;
            o.Password.RequiredLength = 0;
            o.Password.RequireLowercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequireUppercase = false;
            o.SignIn.RequireConfirmedEmail = true;
            o.User.RequireUniqueEmail = true;

        })

                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     ...
      app.UseJWTTokenProviderMiddleware(Options.Create(jwtOptions));

        app.UseAuthentication();
        app.UseMvc();
     ...
 }

TokenProviderMiddleware

public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private TokenProviderOptions _options;
    private UserManager<ApplicationUser> _userManager;
    private readonly ILogger<TokenProviderMiddleware> _logger;
    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, ILogger<TokenProviderMiddleware> logger)
    {
        _next = next;
        _options = options.Value;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;

        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
        {
            await _next(context);
            return;
        }
        if (!context.Request.Method.Equals("POST") || !context.Request.HasFormContentType)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Bad Request");
            return;
        }

        ApplicationUser user = null;
        string refreshToken;
        string accessToken;

        if (context.Request.Form["grant_type"].Equals("refresh_token"))
        {
            refreshToken = context.Request.Form["refresh_token"];
            if(String.IsNullOrEmpty(refreshToken))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token not sent");
                return;
            }

            // Check that the refresh_token is valid
            // I don't like using exceptions for flow control but it's how ValidateToken works
            try
            {
                ValidateRefreshToken(refreshToken);
            }
            catch(SecurityTokenInvalidSignatureException ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            catch(Exception ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            user = await GetUserAsync(context, "from_refresh_token");
            accessToken = await GenerateAccessToken(user);

            var response = new
            {
                access_token = accessToken
            };
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
            return;
        }

private async Task<ApplicationUser> GetUserAsync(HttpContext context, string getUserFrom)
    {
        ApplicationUser user = null;
        if(getUserFrom.Equals("from_username_password"))
        {
            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Username/password not sent");
            }

            user = await _userManager.FindByNameAsync(username);
            var result = _userManager.CheckPasswordAsync(user, password);
            if (result.Result == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password");
            }
            if(!await _userManager.IsEmailConfirmedAsync(user))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Email address not confirmed");
            }

        }

        else if (getUserFrom.Equals("from_refresh_token"))
        {
            JwtSecurityToken decodedRefreshToken = new JwtSecurityTokenHandler().ReadJwtToken(context.Request.Form["refresh_token"]);
            string uid = decodedRefreshToken.Payload.Claims.FirstOrDefault(x => x.Type == "uid").Value;
            user = await _userManager.FindByIdAsync(uid);
        }

        return user;
    }

Error logs

2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": started reading request body.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": started reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": done reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": done reading request body.
2017-12-02 19:45:27.450 -05:00 [Information] Entity Framework Core "2.0.0-rtm-26452" initialized '"ApplicationDbContext"' using provider '"Npgsql.EntityFrameworkCore.PostgreSQL"' with options: "None"
2017-12-02 19:45:27.762 -05:00 [Debug] System.InvalidOperationException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-12-02 19:45:27.762 -05:00 [Debug] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-12-02 19:45:27.763 -05:00 [Error] An unhandled exception has occurred while executing the request
System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.get_UsersSet()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.FindByIdAsync(String userId, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByIdAsync(String userId)
   at MyProject.TokenProviderMiddleware.<GetUserAsync>d__9.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 220

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AsyncDisposer'.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.AsyncDisposer.Dispose()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<Aggregate_>d__6`3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<GetClaimsAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<GetClaimsAsync>d__103.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.TokenProviderMiddleware.<CreateClaims>d__10.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 239


问:
Why is using a for loop faster than apply, in computing the norm of all rows/columns of a matrix?
Consider the following

```<code>n <- 10^4
p <- 2
foo <- matrix(runif(p*n), n, p)
</code>```

I would like to compute the norm of each row of the matrix, i.e., to compute sqrt(crossprod(a_i)) where a_i is the i-th row of foo. I can do this with apply, or with a for loop:

```<code>for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
    }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
</code>```

I thought the simpler apply code would be faster, however:

```<code>> microbenchmark(for_loop(foo), use_apply(foo), times = 1000)
Unit: milliseconds
           expr      min       lq     mean   median       uq      max neval
  for_loop(foo) 16.07111 18.87690 24.25369 20.78997 27.66441 179.8374  1000
 use_apply(foo) 24.77948 29.05891 35.98689 31.89625 40.30085 205.1632  1000
</code>```

note that times = 1000 can take quite a bit of time, if you don't have a fast machine you may want to use microbenchmark defaults. Why is apply slower than the for loop code? Is there some function from purrr which would be faster?

EDIT I couldn't believe that crossprod(x) would be so much slower than sum(x*x), so I wanted to check Emmanuel-Lin's results. I get very different timings:

```<code>my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum((x[i,] *x[i,])))
    }
  foo
}

my_apply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r*r)))
}

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
  }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
> microbenchmark(for_loop(foo), my_loop(foo), use_apply(foo), my_apply(foo))
Unit: milliseconds
           expr       min       lq     mean   median       uq       max neval
  for_loop(foo) 16.299758 17.77176 21.59988 19.04428 22.44558 131.33819   100
   my_loop(foo)  9.950813 12.02106 14.43540 12.66142 15.26865  45.42030   100
 use_apply(foo) 25.480019 27.95396 31.98351 29.85244 36.41599  60.88678   100
  my_apply(foo) 13.277354 14.98329 17.60356 15.98103 19.70325  34.07097   100
</code>```

ok, my_apply and my_loop are faster (I still can't believe it! What, is crossprod optimized for slowness? :-/) but not so faster as Emmanuel-lin found. It's probably related to some dimension congruence checks which crossprod performs.

答:
apply is literally an R for-loop if you check the code:

```<code>   #only the for-loop code shown here
   if (length(d.call) < 2L) {
        if (length(dn.call))
            dimnames(newX) <- c(dn.call, list(NULL))
        for (i in 1L:d2) {
            tmp <- forceAndCall(1, FUN, newX[, i], ...)
            if (!is.null(tmp))
                ans[[i]] <- tmp
        }
    }
    else for (i in 1L:d2) {
        tmp <- forceAndCall(1, FUN, array(newX[, i], d.call,
            dn.call), ...)
        if (!is.null(tmp))
            ans[[i]] <- tmp
    }
</code>```

In addition to the above, apply will run a series of checks too, to make sure the arguments you provided were correct. It is the above that make it a bit slower.

However, lapply, sapply and vapply are C-based for-loops and therefore much faster than an R-based for loop.

Body:
Consider the following

n <- 10^4
p <- 2
foo <- matrix(runif(p*n), n, p)

I would like to compute the norm of each row of the matrix, i.e., to compute sqrt(crossprod(a_i)) where a_i is the i-th row of foo. I can do this with apply, or with a for loop:

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
    }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}

I thought the simpler apply code would be faster, however:

> microbenchmark(for_loop(foo), use_apply(foo), times = 1000)
Unit: milliseconds
           expr      min       lq     mean   median       uq      max neval
  for_loop(foo) 16.07111 18.87690 24.25369 20.78997 27.66441 179.8374  1000
 use_apply(foo) 24.77948 29.05891 35.98689 31.89625 40.30085 205.1632  1000

note that times = 1000 can take quite a bit of time, if you don't have a fast machine you may want to use microbenchmark defaults. Why is apply slower than the for loop code? Is there some function from purrr which would be faster?

EDIT I couldn't believe that crossprod(x) would be so much slower than sum(x*x), so I wanted to check Emmanuel-Lin's results. I get very different timings:

my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum((x[i,] *x[i,])))
    }
  foo
}

my_apply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r*r)))
}

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
  }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
> microbenchmark(for_loop(foo), my_loop(foo), use_apply(foo), my_apply(foo))
Unit: milliseconds
           expr       min       lq     mean   median       uq       max neval
  for_loop(foo) 16.299758 17.77176 21.59988 19.04428 22.44558 131.33819   100
   my_loop(foo)  9.950813 12.02106 14.43540 12.66142 15.26865  45.42030   100
 use_apply(foo) 25.480019 27.95396 31.98351 29.85244 36.41599  60.88678   100
  my_apply(foo) 13.277354 14.98329 17.60356 15.98103 19.70325  34.07097   100

ok, my_apply and my_loop are faster (I still can't believe it! What, is crossprod optimized for slowness? :-/) but not so faster as Emmanuel-lin found. It's probably related to some dimension congruence checks which crossprod performs.

Body:
apply is literally an R for-loop if you check the code:

   #only the for-loop code shown here
   if (length(d.call) < 2L) {
        if (length(dn.call))
            dimnames(newX) <- c(dn.call, list(NULL))
        for (i in 1L:d2) {
            tmp <- forceAndCall(1, FUN, newX[, i], ...)
            if (!is.null(tmp))
                ans[[i]] <- tmp
        }
    }
    else for (i in 1L:d2) {
        tmp <- forceAndCall(1, FUN, array(newX[, i], d.call,
            dn.call), ...)
        if (!is.null(tmp))
            ans[[i]] <- tmp
    }

In addition to the above, apply will run a series of checks too, to make sure the arguments you provided were correct. It is the above that make it a bit slower.

However, lapply, sapply and vapply are C-based for-loops and therefore much faster than an R-based for loop.


问:
Give default value using automapper casting two IEnumerables
I have to cast two IEnumerables objects, let's call it Obj1 and Obj2.

To do this, i use automapper to cast directly the two lists, like this:

```<code>config = new MapperConfiguration(cfg => {
            cfg.CreateMap<IEnumerable<Obj1>, IEnumerable<Obj2>>();
        });

        mapper = config.CreateMapper();
</code>```

But i have a problem, because i want to give a default value to all the elements in the Obj2 list. Is there a way to do this keeping the IEnumerable cast?.

The only solution i have in mind is to create the mapper for the element itself and then iterate between all the elements in Obj1 list and cast to type Obj2, like this:

```<code>config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Obj1, Obj2>();
    });

    mapper = config.CreateMapper();
</code>```

And then, in a foreach element in the list of Obj1, cast and add to a list of type Obj2.

I want to do this directly in the mapper configuration, is there a way to do it, keeping the IEnumerable mapping?.

Thanks.

答:
If you have a map for the base objects, you do not need a map for collections of these objects. Instead, set the destination type when you call Map<TDestination>(). See AutoMapper Docs: Lists and Arrays.

```<code>config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Obj1, Obj2>()
        .ForMember(dest => dest.ShouldBeDefaulted,
                   o => o.MapFrom(src => src.ShouldBeDefaulted == null
                        ? TheDefaultValue : src.ShouldBeDefaulted ));
});

var source = new List<Obj1>() { new Obj1("A"), new Obj1("B")};

// tell AutoMapper that the destination should be a collection during call to Map()
Obj2[] dest = mapper.Map<Obj2[]>(source);
Assert.AreEqual(2, dest.Length);
</code>```

Body:
I have to cast two IEnumerables objects, let's call it Obj1 and Obj2.

To do this, i use automapper to cast directly the two lists, like this:

config = new MapperConfiguration(cfg => {
            cfg.CreateMap<IEnumerable<Obj1>, IEnumerable<Obj2>>();
        });

        mapper = config.CreateMapper();

But i have a problem, because i want to give a default value to all the elements in the Obj2 list. Is there a way to do this keeping the IEnumerable cast?.

The only solution i have in mind is to create the mapper for the element itself and then iterate between all the elements in Obj1 list and cast to type Obj2, like this:

config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Obj1, Obj2>();
    });

    mapper = config.CreateMapper();

And then, in a foreach element in the list of Obj1, cast and add to a list of type Obj2.

I want to do this directly in the mapper configuration, is there a way to do it, keeping the IEnumerable mapping?.

Thanks.

Body:
If you have a map for the base objects, you do not need a map for collections of these objects. Instead, set the destination type when you call Map<TDestination>(). See AutoMapper Docs: Lists and Arrays.

config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Obj1, Obj2>()
        .ForMember(dest => dest.ShouldBeDefaulted,
                   o => o.MapFrom(src => src.ShouldBeDefaulted == null
                        ? TheDefaultValue : src.ShouldBeDefaulted ));
});

var source = new List<Obj1>() { new Obj1("A"), new Obj1("B")};

// tell AutoMapper that the destination should be a collection during call to Map()
Obj2[] dest = mapper.Map<Obj2[]>(source);
Assert.AreEqual(2, dest.Length);


问:
Can a browser's "developer tools" help trace where/what click event handler was added?
I've assumed responsibility for maintaining a website where there's a pair of pseudo-buttons (<a tags dressed up like buttons) in the top right corner, for "log in" and "sign up". The client wants to change it for "log in" and "contact us" - the contact us being a different page to the sign up.

No problem, easy fix I thought - I swapped the  to . Pointing to the button on-page shows the correct URL in the status bar, but clicking on the button still goes to the signup page

I thus assumed that there's a click event handler at work doing the nav instead, and I'm trying to find out what that click event code is, or how it came to be attached

Chrome's inspect element doesn't tell me much (maybe it's because I can't understand it) - I switch to the "event listeners" tab after inspecting the button (or anything else in the DOM heirarchy above it), but I just get the same list of event handlers in there (for any DOM element in the hierarchy) and I don't see anything that helps me determine the source code that is run. Chrome says they're linked to all.js - that file is 430kb of minified script, I'm not sure which web library it's from, so "line 13 in all.js" isn't much help. Does anything in the tree under li.sign-up.wide help me get back to the click event handling code?

Edge/IE didn't have much info either.. In these browsers, the event listeners tab is predominantly empty for elements back towards the DOM root, apart from the li holding the a element, which does have a click event listed, but again this just links back to somewhere in all.js - IE does at least tell me it's on line 2 at column 1752, but I have a hard time believing this is the code I want, because as noted all.js is just a mass of minified script.

href="https://i.stack.imgur.com/EQ7AB.png" rel="nofollow noreferrer">

I searched all of the source code (using a standard Find in Files type search) for anything relevant I can think of: bind (the jquery function to bind an event), click (the event bound - seems sometimes jquery.click() is used), signup (the url the user is sent to by the click handler) and I turned up a few things that looked promising:

```<code>    var bindMiniSignup = function () {

        $('#sign-up-widget .sign-up.wide, #sign-up-widget .sign-up.mobile').bind('click',function(){
            Main.ExpandSignUpForm();
            return false;
        });

        $('#sign-up-widget .log-in.wide, #sign-up-widget .log-in.mobile').bind('click',function(){
            Main.ExpandLogInForm();
            return false;
        });
    }
</code>```

These class and ID names surely refer to the element I'm trying to change:

href="https://i.stack.imgur.com/E0Q1Y.png" rel="nofollow noreferrer">

and this function bindMiniSignup is called a few times in various places (document.ready for example) so I was certain it was what I was looking for. Alas, commenting out  the body of the function so the bindings weren't made had no effect on the site; it still behaved as before (cleared cache to make sure the new JS had been loaded)

So my question is; if you were handed the task of finding and changing the PHP or JS file where an element has a click binding, how would you go about finding the code that is called when the element is clicked (or the code that performs the binding)? Is there a way to make the browser break immediately after I click this button, so I can find the actual click handler code running, and hence I can search all the source code for it?

答:
You seem to be on the right track, but jQuery has used on() for a very long time to do event binding.

Additionally, based on the fact that the file that's binding the event is called all.js, you probably need to perform an intermediate compilation or minification step to the source code. This may be the reason your changes aren't having any effect.

Check the project root for any Grunt, Gulp, Webpack, etc. files since they'll indicate what tools were used to do the compilation/pre-processing.

Body:
I've assumed responsibility for maintaining a website where there's a pair of pseudo-buttons (<a tags dressed up like buttons) in the top right corner, for "log in" and "sign up". The client wants to change it for "log in" and "contact us" - the contact us being a different page to the sign up.

No problem, easy fix I thought - I swapped the <a href="/signup" to <a href="/contactus". Pointing to the button on-page shows the correct URL in the status bar, but clicking on the button still goes to the signup page

I thus assumed that there's a click event handler at work doing the nav instead, and I'm trying to find out what that click event code is, or how it came to be attached

Chrome's inspect element doesn't tell me much (maybe it's because I can't understand it) - I switch to the "event listeners" tab after inspecting the button (or anything else in the DOM heirarchy above it), but I just get the same list of event handlers in there (for any DOM element in the hierarchy) and I don't see anything that helps me determine the source code that is run. Chrome says they're linked to all.js - that file is 430kb of minified script, I'm not sure which web library it's from, so "line 13 in all.js" isn't much help. Does anything in the tree under li.sign-up.wide help me get back to the click event handling code?

Edge/IE didn't have much info either.. In these browsers, the event listeners tab is predominantly empty for elements back towards the DOM root, apart from the li holding the a element, which does have a click event listed, but again this just links back to somewhere in all.js - IE does at least tell me it's on line 2 at column 1752, but I have a hard time believing this is the code I want, because as noted all.js is just a mass of minified script.

I searched all of the source code (using a standard Find in Files type search) for anything relevant I can think of: bind (the jquery function to bind an event), click (the event bound - seems sometimes jquery.click() is used), signup (the url the user is sent to by the click handler) and I turned up a few things that looked promising:

    var bindMiniSignup = function () {

        $('#sign-up-widget .sign-up.wide, #sign-up-widget .sign-up.mobile').bind('click',function(){
            Main.ExpandSignUpForm();
            return false;
        });

        $('#sign-up-widget .log-in.wide, #sign-up-widget .log-in.mobile').bind('click',function(){
            Main.ExpandLogInForm();
            return false;
        });
    }

These class and ID names surely refer to the element I'm trying to change:

and this function bindMiniSignup is called a few times in various places (document.ready for example) so I was certain it was what I was looking for. Alas, commenting out  the body of the function so the bindings weren't made had no effect on the site; it still behaved as before (cleared cache to make sure the new JS had been loaded)

So my question is; if you were handed the task of finding and changing the PHP or JS file where an element has a click binding, how would you go about finding the code that is called when the element is clicked (or the code that performs the binding)? Is there a way to make the browser break immediately after I click this button, so I can find the actual click handler code running, and hence I can search all the source code for it?


答:
```<code><?php

$number = "55375911";
$number = str_split($number, 2);
$number=$number[0].' '.$number[1].''.$number[2].' '.$number[3];
echo $number;
</code>```

This code will work for you for this kind of numbers.

The output is :

```<code>55 3759 11
</code>```

Title: How I can space the number with PHP command?

Body:
I want to code the PHP for spacing the number, example:

$number = "55375911";

So this number should to space to 2-digit and 6-digit, it shows so: "55 3759 11". How I can code this?

Thank you for helping.

Body:
<?php

$number = "55375911";
$number = str_split($number, 2);
$number=$number[0].' '.$number[1].''.$number[2].' '.$number[3];
echo $number;

This code will work for you for this kind of numbers.

The output is :

55 3759 11


问:
My function returns String but I can not parse it ? any idea why?
I have craeted a class called db_conn and inside this calass I have the following functions :

```<code>public func login (email : String , password : String ) -> String  {
    var result = ""
    let url = URL(string: API.url_login.rawValue)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "email=\(email)&password=\(password)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("\(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        result = String(responseString!)
        //print("responseString = \(responseString!)")
    }
    task.resume()

    return result
}
</code>```

and then in my login viewController class I try to use it like ==>

```<code> @IBAction func login_button_action(_ sender: UIButton) {

       let email = email_text.text
       let passw0rd = password_text.text

        if (email != "" && passw0rd != ""){
            let db_connect = db_conn()
            if  (db_connect.login(email: email!, password: passw0rd!) == nil ){

                print("it's empty ")

            }else {

                print("not empty \(db_connect.login(email: email!, password: passw0rd!))")

            }

        }else {

            let alert = UIAlertController(title: "Error", message: "Dont leave any of the spaces blank , they all must be filled up , try again ! ", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
</code>```

when I run the project it says that the value for db_connect.login(email: email!, password: passw0rd!) is not empty but it doesnt print it out .
(However in my db_conn calss I can easily print the responseString and I get the returned JSON in String format .
Any idea where am I making my mistake ? And how can I possibly fix it ?

答: Making a network request with URLSession runs asynchronously, which means that iOS put it onto a background thread and continues the current thread immediately before the download is finished. Therefore, when you return result, it's still an empty string. What you probably want to do is pass a completion closure to your login method, and call that with the relevant data when it's finished downloading

Body:
I have craeted a class called db_conn and inside this calass I have the following functions :

public func login (email : String , password : String ) -> String  {
    var result = ""
    let url = URL(string: API.url_login.rawValue)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "email=\(email)&password=\(password)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in

        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("\(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        result = String(responseString!)
        //print("responseString = \(responseString!)")
    }
    task.resume()

    return result
}

and then in my login viewController class I try to use it like ==>

 @IBAction func login_button_action(_ sender: UIButton) {

       let email = email_text.text
       let passw0rd = password_text.text

        if (email != "" && passw0rd != ""){
            let db_connect = db_conn()
            if  (db_connect.login(email: email!, password: passw0rd!) == nil ){

                print("it's empty ")

            }else {

                print("not empty \(db_connect.login(email: email!, password: passw0rd!))")

            }

        }else {

            let alert = UIAlertController(title: "Error", message: "Dont leave any of the spaces blank , they all must be filled up , try again ! ", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }

when I run the project it says that the value for db_connect.login(email: email!, password: passw0rd!) is not empty but it doesnt print it out .
(However in my db_conn calss I can easily print the responseString and I get the returned JSON in String format .
Any idea where am I making my mistake ? And how can I possibly fix it ?


问:
I can't get my header to center the content in it
I'm trying to get everything in my header to get centered in the header table, but I can't figure out how. I managed to get it centered vertically but I can't figure out how to get it centered horizontally. Can you please tell me how to do it? https://fiddle.jshell.net/rgfxs94L/2/</p>

```<code><div id="header">
  <div class="center">
    <div class="header_cells">
      <img onclick="get_page('?page=home');" title="logo" id="logo" src="http://www.rajohan.no/img/logo_small.png">
    </div>
    <div id="main_buttons" class="header_cells">
      <div id="home" class="header_cells">
        <Home>
      </div>
      <div id="cv" class="header_cells">
        <CV>
      </div>
      <div id="nyheter" class="header_cells">
        <Nyheter>
      </div>
      <div id="movie" class="header_cells">
        <Film>
      </div>
      <div id="games" class="header_cells">
        <Spill>
      </div>
      <div id="music" class="header_cells">
        <Musikk>
      </div>
    </div>
    <div class="header_cells">
      <form id="search_form">
        <input type="search" id="search_box" placeholder="Søk...">
      </form>
    </div>
  </div>
</div>

#header {
  border-top: 3px solid #e87f29;
  background-color: #f8f8f8;
  min-width: 100%;
  min-height: 100%;
  position: static;
  border-bottom: 1px solid #e8e8e8;
  display: table;
}

.center {
  text-align: center;
}

.header_cells {
   display: table-cell;
   min-height: 100%;
   min-width: 100%;
   vertical-align: middle;
}

#logo {
  width: auto;
  max-height: 40%;
}
</code>```

答:
Use inline-block instead:

https://fiddle.jshell.net/o4u8per4/

```<code>.header_cells {
   display:inline-block;
   vertical-align: middle;
}
</code>```

Body:
I'm trying to get everything in my header to get centered in the header table, but I can't figure out how. I managed to get it centered vertically but I can't figure out how to get it centered horizontally. Can you please tell me how to do it? https://fiddle.jshell.net/rgfxs94L/2/

        <Home>

        <CV>

        <Nyheter>

        <Film>

        <Spill>

        <Musikk>

      <form id="search_form">
        <input type="search" id="search_box" placeholder="Søk...">
      </form>

#header {
  border-top: 3px solid #e87f29;
  background-color: #f8f8f8;
  min-width: 100%;
  min-height: 100%;
  position: static;
  border-bottom: 1px solid #e8e8e8;
  display: table;
}

.center {
  text-align: center;
}

.header_cells {
   display: table-cell;
   min-height: 100%;
   min-width: 100%;
   vertical-align: middle;
}

#logo {
  width: auto;
  max-height: 40%;
}

Body:
Use inline-block instead:

https://fiddle.jshell.net/o4u8per4/

.header_cells {
   display:inline-block;
   vertical-align: middle;
}


问:
C# string manipulation, why this doesn't work?
```<code>int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}
</code>```

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?

答:
```<code>int i;
for (; i <= 10; i++)  Console.WriteLine("test{0}", i);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and what are correct ways to produce this?


问:
SSIS check if *.csv files exist in a folder
I'm new to SSIS and am learning by the power of Google. I have a package but before it runs, I need to check if any csv exist in a folder.  If they do, then continue, otherwise stop.

I've been watching you tube videos like the below:
https://www.youtube.com/watch?v=qgqyQm6EymU

but this only chekcs for a specific file - I need to check if any csv's exist in a folder regardless of there name - how do I do this?

Thanks.

答:
You can do this in a custom script.

See SSIS Script task to check if file exists in folder or not for the details about hooking up the script task. You don't need the file and fullPath variables, just the folder variable.

Substitute Directory.EnumerateFiles(folder, "*.csv").Any() for File.Exists in the above link.

```<code>Dts.Variables["User::fileExists"].Value = Directory.EnumerateFiles(folder, "*.csv").Any();
</code>```

Body:
You can do this in a custom script.

See SSIS Script task to check if file exists in folder or not for the details about hooking up the script task. You don't need the file and fullPath variables, just the folder variable.

Substitute Directory.EnumerateFiles(folder, "*.csv").Any() for File.Exists in the above link.

Dts.Variables["User::fileExists"].Value = Directory.EnumerateFiles(folder, "*.csv").Any();


问:
How to compare lists of custom classes without defining equals() and hashCode()?
Since defining equals() and hashCode() only for testing purpose is considered as a code smell, I prefer to use ReflectionEquals or custom matchers to compare objects while doing unit testing.

However, I don't know how to use ReflectionEquals or custom matchers in comparing lists of user-defined classes.

For example, how do I assert the following code without defining equals() and hashCode() (maybe only use ReflectionEquals or custom matchers)?

// When
List<Record> actual = sut.findBySomeId();

// Then
List<Record> expected = asList(
    aRecord()...build(),
    aRecord()...build()
);
assertThat(expected, /* how to compare? */);
```

答:
I have also faced this issue in the past and I am totally agree with you that implementing the equals() and hashCode() for only testing purpose is a code smell. I do not use Hamcrest library so I will provide you a custom solution which I successfully use in my projects and as for its usage I am quite pleased with it.

```<code>public static <E, A> void assertListEquals(BiConsumer<E, A> asserter, List<E> expected, List<A> actual) throws AssertionError {
    assertEquals(
            "Lists have different sizes. Expected list: " + expected + ",  actual list: " + actual,
            expected.size(),
            actual.size());

    for (int i = 0; i < expected.size(); i++) {
        try {
            asserter.accept(expected.get(i), actual.get(i));
        } catch (AssertionError e) {
            throw e;
        }
    }
}
</code>```

As you can see, a BiConsumer is used in order to apply the logic for checking the equality of two objects. So this one has to be implemented in the test class. The advantage of it is that you can define the fields of a class you are interested in when comparing two objects.

Lets see the usage of it:
First we have a custom class, f.e.: Person

```<code>public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }
}
</code>```

Then lets see a test method:

```<code>@Test
public void peopleLiveInTheVillage_findPeople_peopleAreFound() throws Exception {
    //Arrange
    List<Person> expectedPeople = Arrays.asList(
            new Person("Lewis", "Smith", 20),
            new Person("Steven", "Richard", 25),
            new Person("Richie", "Rich", 30));

    //Act
    List<Person> actualPeople = sut.findPeople();

    //Assert
    assertListEquals(
            (e, a) -> assertPersonEquals(e, a),
            expectedPeople,
            actualPeople);
}

private void assertPersonEquals(Person expected, Person actual) {
    assertEquals(expected.getFirstName(), actual.getFirstName());
    assertEquals(expected.getLastName(), actual.getLastName());
    assertEquals(expected.getAge(), actual.getAge());
}
</code>```

Since I am a big fan of tests (and TDD) I always write tons of tests so I always make a helper method where I wrap the BiConsumer:

```<code>private void assertPeopleEqual(List<Person> expectedPeople, List<Person> actualPeople) throws AssertionError {
    assertListEquals(
            (e, a) -> assertPersonEqual(e, a),
            expectedPeople,
            actualPeople);
}
</code>```

I hope this helps, cheers!

Body:
I have also faced this issue in the past and I am totally agree with you that implementing the equals() and hashCode() for only testing purpose is a code smell. I do not use Hamcrest library so I will provide you a custom solution which I successfully use in my projects and as for its usage I am quite pleased with it.

public static <E, A> void assertListEquals(BiConsumer<E, A> asserter, List<E> expected, List<A> actual) throws AssertionError {
    assertEquals(
            "Lists have different sizes. Expected list: " + expected + ",  actual list: " + actual,
            expected.size(),
            actual.size());

    for (int i = 0; i < expected.size(); i++) {
        try {
            asserter.accept(expected.get(i), actual.get(i));
        } catch (AssertionError e) {
            throw e;
        }
    }
}

As you can see, a BiConsumer is used in order to apply the logic for checking the equality of two objects. So this one has to be implemented in the test class. The advantage of it is that you can define the fields of a class you are interested in when comparing two objects.

Lets see the usage of it:
First we have a custom class, f.e.: Person

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public int getAge() {
        return age;
    }
}

Then lets see a test method:

@Test
public void peopleLiveInTheVillage_findPeople_peopleAreFound() throws Exception {
    //Arrange
    List<Person> expectedPeople = Arrays.asList(
            new Person("Lewis", "Smith", 20),
            new Person("Steven", "Richard", 25),
            new Person("Richie", "Rich", 30));

    //Act
    List<Person> actualPeople = sut.findPeople();

    //Assert
    assertListEquals(
            (e, a) -> assertPersonEquals(e, a),
            expectedPeople,
            actualPeople);
}

private void assertPersonEquals(Person expected, Person actual) {
    assertEquals(expected.getFirstName(), actual.getFirstName());
    assertEquals(expected.getLastName(), actual.getLastName());
    assertEquals(expected.getAge(), actual.getAge());
}

Since I am a big fan of tests (and TDD) I always write tons of tests so I always make a helper method where I wrap the BiConsumer:

private void assertPeopleEqual(List<Person> expectedPeople, List<Person> actualPeople) throws AssertionError {
    assertListEquals(
            (e, a) -> assertPersonEqual(e, a),
            expectedPeople,
            actualPeople);
}

I hope this helps, cheers!


问:
Firebase Cloud function timeout
I'm using new cloud functions functionality of firebase. For a http type of method, default timeout duration for the method is 60 seconds and I can update it by using google cloud console and from the advanced settings of the method.

However, when I deploy the new version of the method, timeout setting is again 60 seconds and I need to update this field after each deployment of the method.

Any way which I can set the timeout duration per function will be appreciated.

答:
Update your firebase-tools module to at least version 3.15.3, where this bug was fixed for the CLI.  You can always get the latest version like this:</p>

```<code>npm install -g firebase-tools@latest
</code>```

Title: Firebase Cloud function timeout

Body:
Update your firebase-tools module to at least version 3.15.3, where this bug was fixed for the CLI.  You can always get the latest version like this:

npm install -g firebase-tools@latest


问:
Use Results of CTE to Update Another Table
I have the following CTE that does what I want it to do.

```<code>;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID
</code>```

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

```<code>    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate
</code>```

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

```<code>--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate
</code>```

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

答:
CTEs can only be referenced by the immediately-following statement. If you need the results later, you could insert the CTE into a temp table, then select from that temp table and then insert from that temp table:</p>

```<code>;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO #tmp
    FROM   numbering
    GROUP BY SrcID

    SELECT SrcID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   #tmp
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN #tmp
             ON RAW_DATA.SrcID = #tmp.SrcID
             AND RAW_DATA.AsofDate = #tmp.AsofDate
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following CTE that does what I want it to do.

;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

Body:
CTEs can only be referenced by the immediately-following statement. If you need the results later, you could insert the CTE into a temp table, then select from that temp table and then insert from that temp table:

;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO #tmp
    FROM   numbering
    GROUP BY SrcID

    SELECT SrcID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   #tmp
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN #tmp
             ON RAW_DATA.SrcID = #tmp.SrcID
             AND RAW_DATA.AsofDate = #tmp.AsofDate


问:
Two way client server network communication
I am looking at building a client server application in C# using winforms or WPF.  The client application must be a local application because it has to interact with specialised hardware.

The architecture I'm looking for is the client connects to a server port using TCP/IP.  The client will then make requests to the server and the server will send responses to the client.  The client wills stay connected to the server while the user is logged in.

I have looked at web services and as far as I can figure out, WCF extends web services which means there is no way for the server to send a message to the client.

Am I incorrect about WCF?  If not what is the best way to accomplish this?

答: Try reading this article by Juval Lowy which is an excellent discussion of the issues in WCF messaging.  He offers an alternative to duplexing which is his pub-sub framework.  I'm going to have to recommend you buy his WCF book as well.  He is one of the best technical authors I have come accross on any subject.</p>

OwnerDisplayName: John Oxley

OwnerDisplayName: Jimmy McNulty


问:
compare string with startWith in scala
I want to compare a pattern in string

```<code>sealed trait Demo { def value: String }

   object Demo {
  case object TypeAB extends Demo {
    val value = "a:b"
  }
      .......other constants
}
 val test = Option("a:b:c")
val s =test.map(_.startsWith(Demo.TypeAB.value))
</code>```

I want to not use .value in Demo.TypeAB.value
Is there a better approach to achieve the above .I preferred to use startsWith

I tried but it didnot work

```<code> def unapply(arg: Demo): String= arg.value
</code>```

答:
```<code>sealed trait Demo {
  def value: String
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

  implicit def demoToString(demo: Demo): String = demo.value
}
</code>```

You can now write "a:b:c".startsWith(Demo.TypeAB)
Whether it's a good idea to have an implicit Demo to string method in your code, well, I'll leave it up to you :D

Title: compare string with startWith in scala

Body:
I want to compare a pattern in string

sealed trait Demo { def value: String }

   object Demo {
  case object TypeAB extends Demo {
    val value = "a:b"
  }
      .......other constants
}
 val test = Option("a:b:c")
val s =test.map(_.startsWith(Demo.TypeAB.value))

I want to not use .value in Demo.TypeAB.value
Is there a better approach to achieve the above .I preferred to use startsWith

I tried but it didnot work

 def unapply(arg: Demo): String= arg.value

Body:
sealed trait Demo {
  def value: String
}

object Demo {

  case object TypeAB extends Demo {
    val value = "a:b"
  }

  implicit def demoToString(demo: Demo): String = demo.value
}

You can now write "a:b:c".startsWith(Demo.TypeAB)
Whether it's a good idea to have an implicit Demo to string method in your code, well, I'll leave it up to you :D


问:
Python picture grid in loop
I encountered a problem as I tried to fill a tkinter grid with a loop

```<code>i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1
</code>```

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

```<code>folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1
</code>```

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz

答:
I saved the reference of the label instead of the ref of the picture.

```<code>self.image = []
for category in categories:
    self.image.append(PhotoImage(file=category[2]+".png"))
    imageLabel = Label(master, image=self.image[i])
    imageLabel.grid(row=0, column=i)
    i = i + 1
</code>```

this works now!

Title: Python picture grid in loop

Body:
I encountered a problem as I tried to fill a tkinter grid with a loop

i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz

Body:
I saved the reference of the label instead of the ref of the picture.

self.image = []
for category in categories:
    self.image.append(PhotoImage(file=category[2]+".png"))
    imageLabel = Label(master, image=self.image[i])
    imageLabel.grid(row=0, column=i)
    i = i + 1

this works now!


问:
Inter-service communication with Spring Boot and OAuth2
I am working on a micro-service architecture using Spring Boot. We have implemented OAuth2 in a Auth Server.

My question is - If two microservices want to communicate what should be the best way?

As of now, I have discovered below options:

If each microservice is verifying the token then we can pass the same token. But the problem is - in between same token can be expired.

If we use client_credentials grant then there we are having two issues: one is, we need to send the username in next microservice. Another one is, we need to request two times - first for getting the access token, next for actual call.

If we do the token verification in API gateway only (not in microservices) then from the API gateway we need to send the username in every microservices. And microservices implementation needs to be changed to accept that param/header.

Please suggest which option should I pick and if there is any better option please let me know.

Thanks in advance.

答:
I am not an expert on OAuth, but I have done a fair bit of work with microservices. When working with microservices, it is often a good idea to separate your services in such a way that:

They each know as little as possible about the concepts/concerns that they delegate to other services

Their dependency graph is acyclic, whether the services are microservices or part of a well-designed monolith

Take an example of Accounts and Orders. You could have the Accounts service know about users, authentication and authorization, sessions, and contact information. If a user wants to view an order, the accounts service could take all requests, ensure that the user is authorized to do so and then request the order directly from the Orders Service.

The downsides to this approach are:

The Accounts Service must pass all orders data through to the user client, which may result in code duplication and complexity

Changes to the Orders Service API may require changes to the Accounts Service to pass through new data

Upsides are:

The Accounts Service can authenticate with the Orders Service directly using a service-level authentication mechanism like an api token

The Orders Service may live on a private network

Another approach might be to have a third service responsible for identity. The client would make requests directly to the Accounts Service and Orders Service, which would each then ask a third service, let's call it an Identity Service, if a session is valid. If not, it would forward the user to authenticate (sign on) with the Identity Service. Then on each request from the client to the Accounts Service or Orders service, these services would check with the identity service if the session is still valid.

Advantages to this approach are:

The Accounts and Orders Services do not need to know about usernames and passwords

Each service simply provides the data it is responsible for directly to the client

Downsides are:

This architecture is a bit more difficult to set up

A third approach is to implement either of these approaches into a single service. In the case of accounts and orders, I might make an argument that they are very closely related and that splitting them out into separate services may not improve your architecture.

As I said, I am certainly not an expert in OAuth, but I have worked a fair bit with services and microservices.