问:
Entity Framework Core include related data from table by string
I've built a small application that uses data from a SQL Server database of a third party. They have a structure like this to link their objects together:

A table called 'Objecten' that keeps the most common data, like the ObjectId, Unid, Name, Description, ... All these objects have an 'ObjectType' column, which is a VARCHAR/string like: for example 'VRIJ1OBJECT', 'VRIJ2OBJECT', 'HARDWARE'

The related data is stored in a table with these names: 'VRIJ1OBJECTEN', 'VRIJ2OBJECTEN', 'HARDWARE'.

In my (ASP.NET Core) code, I'm using EF Core 2.0. I try to return a (paged) list of objects with some of their related data, but I have no idea how to join on a table using a string name.

So currently, when I'm returning 10 objects for a page, I'm doing 11 queries. 1 to get the 10 objects and 1 for each object to get the related data from the table according to their ObjectType. This takes about 3 seconds, while 1 query only takes about 200ms. The API should be alot faster.

Some code:

```<code>private async Task<(List<ObjectViewModel> objecten, int totaalAantalObjecten)> _getTopDeskObjectenAsync(string q = null, string sort = "Naam-", int take = 0, int skip = 0, string e = null, bool qall = false, string categorie = "", RolstoelZoekenVM rolstoelZoekenVm = null, bool aotCategorie = false, AotZoekenVM aotZoekenVm = null)
{
    var objecten = await _db.Object.Where(o => o.Status != -1).ToListAsync();

    ... (paging, filtering, ...) ...

    var returnObjecten = new List<ObjectViewModel>();
    foreach (var o in objecten){
        returnObjecten.Add(await _dbObjectToViewModelAsync(o));
    }
    return (returnObjecten, totalCount);
}

private async Task<ObjectViewModel> _dbObjectToViewModelAsync(TopDeskDatabase.Object o)
{
    var vrijObject = await GetDbVrijObjectAsync(o);
    return new ObjectViewModel
    {
        ... filling up the VM properties ...
    }
}

// THIS should be done by the SQL Server in the query
public async Task<IVrijobject> GetDbVrijObjectAsync(TopDeskDatabase.Object o)
{
    switch(o.Type.ToLower())
    {
        case "vrij1object":
                return await _db.Vrij1object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij2object":
                return await _db.Vrij2object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij3object":
                return await _db.Vrij3object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij4object":
                return await _db.Vrij4object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij5object":
                return await _db.Vrij5object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "hardware":
                return await _db.Hardware.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "inventaris":
                return await _db.Inventaris.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "telefonie":
                return await _db.Telefonie.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
        }

        throw new InvalidDataException($"Object '{o.RefNaam}' is van type '{o.Type}', welke niet VRIJxOBJECT, INVENTARIS, TELEFONIE of HARDWARE is!");
}
</code>```

答:
You could create a query with LEFT OUTER JOIN for each possible return type, store the resulting objects for each type and then compress the data client side by casting to the IVrijobject.

See the following example with 2 types (Note I created it with EF6, so there might be some changes required for EF Core)

```<code>public class ObjectModel
{
    public int ID { get; set; }

    public int ObjectTypeID { get; set; }

    [StringLength(10)]
    public string ObjectTypeDiscriminator { get; set; }
}

public interface IObjectTypeModel
{
    int ID { get; set; }
    string Data { get; set; }
}

// ObjectTypeDiscriminator = "Type1"
public class ObjectType1Model : IObjectTypeModel
{
    public int ID { get; set; }

    [StringLength(100)]
    public string Data { get; set; }
}

// ObjectTypeDiscriminator = "Type2"
public class ObjectType2Model : IObjectTypeModel
{
    public int ID { get; set; }

    [StringLength(100)]
    public string Data { get; set; }
}

class DbC : DbContext
{
    public DbC()
    {
    }

    public DbSet<ObjectModel> Objects { get; set; }
    public DbSet<ObjectType1Model> Type1Objects { get; set; }
    public DbSet<ObjectType2Model> Type2Objects { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}
</code>```

Test program

```<code>class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<DbC>());

        // initialize some test data
        using (var db = new DbC())
        {
            var t1_1 = db.Type1Objects.Add(new ObjectType1Model { Data = "Object T1 1" });
            var t1_2 = db.Type1Objects.Add(new ObjectType1Model { Data = "Object T1 2" });
            var t2_1 = db.Type2Objects.Add(new ObjectType2Model { Data = "Object T2 1" });
            var t2_2 = db.Type2Objects.Add(new ObjectType2Model { Data = "Object T2 2" });
            db.SaveChanges();
            db.Objects.Add(new ObjectModel { ObjectTypeID = t1_1.ID, ObjectTypeDiscriminator = "Type1" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t1_2.ID, ObjectTypeDiscriminator = "Type1" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t2_1.ID, ObjectTypeDiscriminator = "Type2" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t2_2.ID, ObjectTypeDiscriminator = "Type2" });
            db.SaveChanges();
        }
        // fresh context for query demonstration
        using (var db = new DbC())
        {
            db.Database.Log = x => Console.WriteLine(x);
            var result =
                from o in db.Objects
                join t1 in db.Type1Objects on new { Discriminator = o.ObjectTypeDiscriminator, ObjectTypeID = o.ObjectTypeID } equals new { Discriminator = "Type1", ObjectTypeID = t1.ID } into types1
                join t2 in db.Type2Objects on new { Discriminator = o.ObjectTypeDiscriminator, ObjectTypeID = o.ObjectTypeID } equals new { Discriminator = "Type2", ObjectTypeID = t2.ID } into types2
                from t1 in types1.DefaultIfEmpty()
                from t2 in types2.DefaultIfEmpty()
                select new
                {
                    Obj = o,
                    T1 = t1,
                    T2 = t2,
                };
            foreach (var item in result)
            {
                // only one concrete type will have a non-null value
                var T = (IObjectTypeModel)item.T1 ?? item.T2;
                Console.WriteLine("{0,20}{1,20}", item.Obj.ObjectTypeDiscriminator, T.Data);
            }
        }

        Console.ReadKey();
    }
}
</code>```

Output:

```<code>Opened connection at 06.12.2017 10:25:34 +01:00

SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[ObjectTypeID] AS [ObjectTypeID],
    [Extent1].[ObjectTypeDiscriminator] AS [ObjectTypeDiscriminator],
    [Extent2].[ID] AS [ID1],
    [Extent2].[Data] AS [Data],
    [Extent3].[ID] AS [ID2],
    [Extent3].[Data] AS [Data1]
    FROM   [dbo].[ObjectModels] AS [Extent1]
    LEFT OUTER JOIN [dbo].[ObjectType1Model] AS [Extent2]
        ON ([Extent1].[ObjectTypeDiscriminator] = N'Type1') AND ([Extent1].[ObjectTypeID] = [Extent2].[ID])
    LEFT OUTER JOIN [dbo].[ObjectType2Model] AS [Extent3]
        ON ([Extent1].[ObjectTypeDiscriminator] = N'Type2') AND ([Extent1].[ObjectTypeID] = [Extent3].[ID])

-- Executing at 06.12.2017 10:25:34 +01:00

-- Completed in 6 ms with result: SqlDataReader

               Type1         Object T1 1
               Type1         Object T1 2
               Type2         Object T2 1
               Type2         Object T2 2
Closed connection at 06.12.2017 10:25:34 +01:00
</code>```

As you can see, the generated query will use separate result columns for each object, which might or might not be less efficient than merging the result based on a discriminator (I didn't investigate this aspect). If your Unid is unique enough, then you don't need the Discriminator part of the join condition.

Body:
I've built a small application that uses data from a SQL Server database of a third party. They have a structure like this to link their objects together:

A table called 'Objecten' that keeps the most common data, like the ObjectId, Unid, Name, Description, ... All these objects have an 'ObjectType' column, which is a VARCHAR/string like: for example 'VRIJ1OBJECT', 'VRIJ2OBJECT', 'HARDWARE'

The related data is stored in a table with these names: 'VRIJ1OBJECTEN', 'VRIJ2OBJECTEN', 'HARDWARE'.

In my (ASP.NET Core) code, I'm using EF Core 2.0. I try to return a (paged) list of objects with some of their related data, but I have no idea how to join on a table using a string name.

So currently, when I'm returning 10 objects for a page, I'm doing 11 queries. 1 to get the 10 objects and 1 for each object to get the related data from the table according to their ObjectType. This takes about 3 seconds, while 1 query only takes about 200ms. The API should be alot faster.

Some code:

private async Task<(List<ObjectViewModel> objecten, int totaalAantalObjecten)> _getTopDeskObjectenAsync(string q = null, string sort = "Naam-", int take = 0, int skip = 0, string e = null, bool qall = false, string categorie = "", RolstoelZoekenVM rolstoelZoekenVm = null, bool aotCategorie = false, AotZoekenVM aotZoekenVm = null)
{
    var objecten = await _db.Object.Where(o => o.Status != -1).ToListAsync();

    ... (paging, filtering, ...) ...

    var returnObjecten = new List<ObjectViewModel>();
    foreach (var o in objecten){
        returnObjecten.Add(await _dbObjectToViewModelAsync(o));
    }
    return (returnObjecten, totalCount);
}

private async Task<ObjectViewModel> _dbObjectToViewModelAsync(TopDeskDatabase.Object o)
{
    var vrijObject = await GetDbVrijObjectAsync(o);
    return new ObjectViewModel
    {
        ... filling up the VM properties ...
    }
}

// THIS should be done by the SQL Server in the query
public async Task<IVrijobject> GetDbVrijObjectAsync(TopDeskDatabase.Object o)
{
    switch(o.Type.ToLower())
    {
        case "vrij1object":
                return await _db.Vrij1object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij2object":
                return await _db.Vrij2object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij3object":
                return await _db.Vrij3object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij4object":
                return await _db.Vrij4object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "vrij5object":
                return await _db.Vrij5object.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "hardware":
                return await _db.Hardware.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "inventaris":
                return await _db.Inventaris.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
            case "telefonie":
                return await _db.Telefonie.FirstOrDefaultAsync(d => d.Objectid == o.Unid);
        }

        throw new InvalidDataException($"Object '{o.RefNaam}' is van type '{o.Type}', welke niet VRIJxOBJECT, INVENTARIS, TELEFONIE of HARDWARE is!");
}

Body:
You could create a query with LEFT OUTER JOIN for each possible return type, store the resulting objects for each type and then compress the data client side by casting to the IVrijobject.

See the following example with 2 types (Note I created it with EF6, so there might be some changes required for EF Core)

public class ObjectModel
{
    public int ID { get; set; }

    public int ObjectTypeID { get; set; }

    [StringLength(10)]
    public string ObjectTypeDiscriminator { get; set; }
}

public interface IObjectTypeModel
{
    int ID { get; set; }
    string Data { get; set; }
}

// ObjectTypeDiscriminator = "Type1"
public class ObjectType1Model : IObjectTypeModel
{
    public int ID { get; set; }

    [StringLength(100)]
    public string Data { get; set; }
}

// ObjectTypeDiscriminator = "Type2"
public class ObjectType2Model : IObjectTypeModel
{
    public int ID { get; set; }

    [StringLength(100)]
    public string Data { get; set; }
}

class DbC : DbContext
{
    public DbC()
    {
    }

    public DbSet<ObjectModel> Objects { get; set; }
    public DbSet<ObjectType1Model> Type1Objects { get; set; }
    public DbSet<ObjectType2Model> Type2Objects { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

Test program

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<DbC>());

        // initialize some test data
        using (var db = new DbC())
        {
            var t1_1 = db.Type1Objects.Add(new ObjectType1Model { Data = "Object T1 1" });
            var t1_2 = db.Type1Objects.Add(new ObjectType1Model { Data = "Object T1 2" });
            var t2_1 = db.Type2Objects.Add(new ObjectType2Model { Data = "Object T2 1" });
            var t2_2 = db.Type2Objects.Add(new ObjectType2Model { Data = "Object T2 2" });
            db.SaveChanges();
            db.Objects.Add(new ObjectModel { ObjectTypeID = t1_1.ID, ObjectTypeDiscriminator = "Type1" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t1_2.ID, ObjectTypeDiscriminator = "Type1" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t2_1.ID, ObjectTypeDiscriminator = "Type2" });
            db.Objects.Add(new ObjectModel { ObjectTypeID = t2_2.ID, ObjectTypeDiscriminator = "Type2" });
            db.SaveChanges();
        }
        // fresh context for query demonstration
        using (var db = new DbC())
        {
            db.Database.Log = x => Console.WriteLine(x);
            var result =
                from o in db.Objects
                join t1 in db.Type1Objects on new { Discriminator = o.ObjectTypeDiscriminator, ObjectTypeID = o.ObjectTypeID } equals new { Discriminator = "Type1", ObjectTypeID = t1.ID } into types1
                join t2 in db.Type2Objects on new { Discriminator = o.ObjectTypeDiscriminator, ObjectTypeID = o.ObjectTypeID } equals new { Discriminator = "Type2", ObjectTypeID = t2.ID } into types2
                from t1 in types1.DefaultIfEmpty()
                from t2 in types2.DefaultIfEmpty()
                select new
                {
                    Obj = o,
                    T1 = t1,
                    T2 = t2,
                };
            foreach (var item in result)
            {
                // only one concrete type will have a non-null value
                var T = (IObjectTypeModel)item.T1 ?? item.T2;
                Console.WriteLine("{0,20}{1,20}", item.Obj.ObjectTypeDiscriminator, T.Data);
            }
        }

        Console.ReadKey();
    }
}

Output:

Opened connection at 06.12.2017 10:25:34 +01:00

SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[ObjectTypeID] AS [ObjectTypeID],
    [Extent1].[ObjectTypeDiscriminator] AS [ObjectTypeDiscriminator],
    [Extent2].[ID] AS [ID1],
    [Extent2].[Data] AS [Data],
    [Extent3].[ID] AS [ID2],
    [Extent3].[Data] AS [Data1]
    FROM   [dbo].[ObjectModels] AS [Extent1]
    LEFT OUTER JOIN [dbo].[ObjectType1Model] AS [Extent2]
        ON ([Extent1].[ObjectTypeDiscriminator] = N'Type1') AND ([Extent1].[ObjectTypeID] = [Extent2].[ID])
    LEFT OUTER JOIN [dbo].[ObjectType2Model] AS [Extent3]
        ON ([Extent1].[ObjectTypeDiscriminator] = N'Type2') AND ([Extent1].[ObjectTypeID] = [Extent3].[ID])

-- Executing at 06.12.2017 10:25:34 +01:00

-- Completed in 6 ms with result: SqlDataReader

               Type1         Object T1 1
               Type1         Object T1 2
               Type2         Object T2 1
               Type2         Object T2 2
Closed connection at 06.12.2017 10:25:34 +01:00

As you can see, the generated query will use separate result columns for each object, which might or might not be less efficient than merging the result based on a discriminator (I didn't investigate this aspect). If your Unid is unique enough, then you don't need the Discriminator part of the join condition.


来源: stackexchange

问:
OpenSSL's DTLSv1_Listen() pauses program at runtime
I'm trying to test with OpenSSL DTLS by making a program that creates a client and server socket to echo strings between the sockets; However, when I try to test out DTLSv1_Listen() function my program seems to pause even when I am not trying connecting or sending data between the sockets. note: I am using a post 1.0.2 OpenSSL which is after DTLSv1_Listen() was rewritten.

Here is my complete C++ winsock specific code:

```<code>#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
//#include <openssl/applink.c>
#include <string>
#pragma comment(lib, "Ws2_32.lib")

struct DTLSStuff { //struct to contain DTLS object instances
    SSL_CTX *ctx;
    SSL *ssl;
    BIO *bio;
};

void DTLSErr() { //DTLS error reporting
    ERR_print_errors_fp(stderr);
    exit(1);
}

int newSocket(sockaddr_in addr) { //creates a socket and returns the file descriptor //TODO expand for multi-platform
    WSADATA wsaData;
    int fd;
    int iResult;

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);                                                     //Initialize Winsock
    if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); exit(1); }

    fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("Unable to create socket"); exit(1); }    //create socket
    printf("New Socket: %i\n", fd);
    if (bind(fd, (struct sockaddr *)&addr, sizeof(sockaddr)) < 0) { printf("bind failed with error %u\n", WSAGetLastError());   exit(1); }

    return fd;                                                                                //file descriptor
}

void InitCTX(SSL_CTX *ctx, bool IsClient) { //Takes a ctx object and initializes it for DTLS communication
    if (IsClient) {
        if(SSL_CTX_use_certificate_chain_file(ctx, "client-cert.pem") < 0) { printf("Failed loading client cert");}
        if(SSL_CTX_use_PrivateKey_file(ctx, "client-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
    }
    else {
        if (SSL_CTX_use_certificate_chain_file(ctx, "server-cert.pem") < 0) { printf("Failed loading client cert"); }
        if (SSL_CTX_use_PrivateKey_file(ctx, "server-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
    }
    //SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cert);    //omitted for testing
    //SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);     //omitted for testing
    //SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);         //omitted for testing
    SSL_CTX_set_read_ahead(ctx, 1);
}

int main() { //creates client and server sockets and DTLS objects. TODO: have client complete handshake with server socket and send a message and have the server echo it back to client socket
    BIO_ADDR *faux_addr = BIO_ADDR_new(); // for DTLSv1_listen(), since we are this is both client and server (meaning client address is known) it is only used to satisfy parameters.
    ERR_load_BIO_strings();
    SSL_load_error_strings();
    SSL_library_init();

    //Set up addresses
    sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(25501);
    client_addr.sin_addr.s_addr = INADDR_ANY;
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(25500);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    //*********CLIENT
    DTLSStuff ClientInf;
    ClientInf.ctx = SSL_CTX_new(DTLSv1_client_method());
    InitCTX(ClientInf.ctx,true);
    int ClientFD = newSocket(client_addr);
    ClientInf.bio = BIO_new_dgram(ClientFD, BIO_NOCLOSE);
    ClientInf.ssl = SSL_new(ClientInf.ctx);
    //SSL_set_options(ClientInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
    SSL_set_bio(ClientInf.ssl, ClientInf.bio, ClientInf.bio);

    //*********SERVER
    DTLSStuff ServerInf;
    ServerInf.ctx = SSL_CTX_new(DTLSv1_server_method());
    InitCTX(ServerInf.ctx,false);
    int ServerFD = newSocket(server_addr);
    ServerInf.bio = BIO_new_dgram(ServerFD, BIO_NOCLOSE);
    ServerInf.ssl = SSL_new(ServerInf.ctx);
    //SSL_set_options(ServerInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
    SSL_set_bio(ServerInf.ssl, ServerInf.bio, ServerInf.bio);

    printf("Listen attempt...\n");
    int ret = DTLSv1_listen(ServerInf.ssl, faux_addr);
    if (ret < 0) { DTLSErr(); }
    printf("this print should occur, but it never does");
    exit(1);
}
</code>```

I expect the results to be as follow:

```<code>NewSocket: 356
NewSocket: 360
Listen attempt...
this print should occur but it never does
</code>```

However when running the program it never prints the last line. The program seems to respond as I am able to cancel the executable by ctrl+c so I am assuming it has not crashed or froze, but aside from that I am at a loss. My understanding is that the method should return 0 if nothing happens, >1 if it heard a clienthello, and <0 if an error occurred.

Also, a somewhat related question: Since DTLSv1_Listen() requires a BIO_ADDR to store the incoming requests address does that mean that separate client and servers programs will both require 2 sockets if they want to be able to both send and listen? Normally UDP clients and servers only need a single socket, but I cannot seem to figure a design to retain this with OpenSSL's DTLS.

I thank you for your time.

答:
I don't see anywhere in your code where you set the socket to be non-blocking. In the default blocking mode when you attempt to read from the socket your program will pause until data has arrived. If you don't want that then make sure your set the appropriate option (I'm not a Windows programmer, but ioctlsocket seems to do the job: https://msdn.microsoft.com/en-us/library/windows/desktop/ms738573(v=vs.85).aspx)

does that mean that separate client and servers programs will both require 2 sockets if they want to be able to both send and listen

When using DTLSv1_listen() you are using the socket in an unconnected state, so you may receive UDP packets from multiple clients. DTLS is connection based so once DTLSv1_listen() returns successfully you are supposed to create a "connected" socket to the client address. So you have one socket for listening for new connections, and one socket per client communicating with your server.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to test with OpenSSL DTLS by making a program that creates a client and server socket to echo strings between the sockets; However, when I try to test out DTLSv1_Listen() function my program seems to pause even when I am not trying connecting or sending data between the sockets. note: I am using a post 1.0.2 OpenSSL which is after DTLSv1_Listen() was rewritten.

Here is my complete C++ winsock specific code:

#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
//#include <openssl/applink.c>
#include <string>
#pragma comment(lib, "Ws2_32.lib")

struct DTLSStuff { //struct to contain DTLS object instances
    SSL_CTX *ctx;
    SSL *ssl;
    BIO *bio;
};

void DTLSErr() { //DTLS error reporting
    ERR_print_errors_fp(stderr);
    exit(1);
}

int newSocket(sockaddr_in addr) { //creates a socket and returns the file descriptor //TODO expand for multi-platform
    WSADATA wsaData;
    int fd;
    int iResult;

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);                                                     //Initialize Winsock
    if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); exit(1); }

    fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { perror("Unable to create socket"); exit(1); }    //create socket
    printf("New Socket: %i\n", fd);
    if (bind(fd, (struct sockaddr *)&addr, sizeof(sockaddr)) < 0) { printf("bind failed with error %u\n", WSAGetLastError());   exit(1); }

    return fd;                                                                                //file descriptor
}

void InitCTX(SSL_CTX *ctx, bool IsClient) { //Takes a ctx object and initializes it for DTLS communication
    if (IsClient) {
        if(SSL_CTX_use_certificate_chain_file(ctx, "client-cert.pem") < 0) { printf("Failed loading client cert");}
        if(SSL_CTX_use_PrivateKey_file(ctx, "client-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
    }
    else {
        if (SSL_CTX_use_certificate_chain_file(ctx, "server-cert.pem") < 0) { printf("Failed loading client cert"); }
        if (SSL_CTX_use_PrivateKey_file(ctx, "server-key.pem", SSL_FILETYPE_PEM) < 0) { printf("Failed loading client key"); }
    }
    //SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cert);    //omitted for testing
    //SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);     //omitted for testing
    //SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);         //omitted for testing
    SSL_CTX_set_read_ahead(ctx, 1);
}

int main() { //creates client and server sockets and DTLS objects. TODO: have client complete handshake with server socket and send a message and have the server echo it back to client socket
    BIO_ADDR *faux_addr = BIO_ADDR_new(); // for DTLSv1_listen(), since we are this is both client and server (meaning client address is known) it is only used to satisfy parameters.
    ERR_load_BIO_strings();
    SSL_load_error_strings();
    SSL_library_init();

    //Set up addresses
    sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(25501);
    client_addr.sin_addr.s_addr = INADDR_ANY;
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(25500);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    //*********CLIENT
    DTLSStuff ClientInf;
    ClientInf.ctx = SSL_CTX_new(DTLSv1_client_method());
    InitCTX(ClientInf.ctx,true);
    int ClientFD = newSocket(client_addr);
    ClientInf.bio = BIO_new_dgram(ClientFD, BIO_NOCLOSE);
    ClientInf.ssl = SSL_new(ClientInf.ctx);
    //SSL_set_options(ClientInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
    SSL_set_bio(ClientInf.ssl, ClientInf.bio, ClientInf.bio);

    //*********SERVER
    DTLSStuff ServerInf;
    ServerInf.ctx = SSL_CTX_new(DTLSv1_server_method());
    InitCTX(ServerInf.ctx,false);
    int ServerFD = newSocket(server_addr);
    ServerInf.bio = BIO_new_dgram(ServerFD, BIO_NOCLOSE);
    ServerInf.ssl = SSL_new(ServerInf.ctx);
    //SSL_set_options(ServerInf.ssl, SSL_OP_COOKIE_EXCHANGE); //omitted for testing
    SSL_set_bio(ServerInf.ssl, ServerInf.bio, ServerInf.bio);

    printf("Listen attempt...\n");
    int ret = DTLSv1_listen(ServerInf.ssl, faux_addr);
    if (ret < 0) { DTLSErr(); }
    printf("this print should occur, but it never does");
    exit(1);
}

I expect the results to be as follow:

NewSocket: 356
NewSocket: 360
Listen attempt...
this print should occur but it never does

However when running the program it never prints the last line. The program seems to respond as I am able to cancel the executable by ctrl+c so I am assuming it has not crashed or froze, but aside from that I am at a loss. My understanding is that the method should return 0 if nothing happens, >1 if it heard a clienthello, and <0 if an error occurred.

Also, a somewhat related question: Since DTLSv1_Listen() requires a BIO_ADDR to store the incoming requests address does that mean that separate client and servers programs will both require 2 sockets if they want to be able to both send and listen? Normally UDP clients and servers only need a single socket, but I cannot seem to figure a design to retain this with OpenSSL's DTLS.

I thank you for your time.


问:
explicit instantiation of static variable of a template class in different translation units
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

```<code>template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;
</code>```

Source.cpp

```<code>#include "Header.h"
template<> int Foo<int>::count = 5;
</code>```

main.cpp

```<code>#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}
</code>```

the output on xcode8.3.3 is:

```<code> 7
 7
</code>```

whereas the output on Visual Studio 2015 is:

```<code>2
2
</code>```

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.

答:
gcc complains about double instances:

```<code>/tmp/ccUEOg7s.o:(.bss._ZN3FooIiE5countE[_ZN3FooIiE5countE]+0x0): multiple definition of `Foo<int>::count'
/tmp/ccG7CO9C.o:(.data+0x0): first defined here
</code>```

So having two instances and a linker which is not able to see this, any result can be the effect.

It is simply a failure to have two instances of your variable here, independent if it is a templated instance or not. You have to remove one of them.

If using C++17 you can have the var inline in the header.

Body:
I was working with a template class that contains a static variable. The structure of code is as follows.

Header.h

template<class T> class Foo
{
public:
    static int count;
    Foo() {
        count++;
    }
    void printCount() {
        cout << count << endl;
    }
};
template<class T> int Foo<T>::count;

Source.cpp

#include "Header.h"
template<> int Foo<int>::count = 5;

main.cpp

#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
    Foo<int> obj1;
    Foo<int> obj2;
    obj1.printCount();
    obj2.printCount();
    return 0;
}

the output on xcode8.3.3 is:

 7
 7

whereas the output on Visual Studio 2015 is:

2
2

i.e. the specific instantiation overrides the generic instantiation in xcode8.3.3 but not in Visual Studio 2015.
Could someone explain this difference in behavior?
Thanks in advance.

Body:
gcc complains about double instances:

/tmp/ccUEOg7s.o:(.bss._ZN3FooIiE5countE[_ZN3FooIiE5countE]+0x0): multiple definition of `Foo<int>::count'
/tmp/ccG7CO9C.o:(.data+0x0): first defined here

So having two instances and a linker which is not able to see this, any result can be the effect.

It is simply a failure to have two instances of your variable here, independent if it is a templated instance or not. You have to remove one of them.

If using C++17 you can have the var inline in the header.


问:
Analyzing spikes in performance measurement
I have a set of  C++ functions which does some image processing related operation. Generally I see that the final output is delivered in 5-6ms time range. I am measuring the time taken using QueryPerformanceCounter Win32 API. But when running in a continuous loop with 100 images, I see that the performance spikes up to 20ms for some images. My question is how do I go about analyzing such issues. Basically I want to determine whether the spikes are caused due to some delay in this code or whether some other task started running inside the CPU because of which this operation took time. I have tried using GetThreadTimes API to see how much time my thread spent inside CPU but am unable to conclude based on those numbers. What is the standard way to go about troubleshooting these types of issues?

答:
Reason behind sudden spikes during processing could be any of IO, interrupt, scheduled processes etc.

It is very common to see such spikes considering such low latency/processing time operations. IMO you can consider them because of any of the above mentioned reasons (There could be more). Simplest solution is run same experiment with more inputs multiple times and take the average for final consideration.

To answer your question about checking/confirming source of the spike you can try following,

Check variation in images - already ruled out as per your comment

Monitor resource utilization during processing. Check if any resource is choking (% util is simplest way to check and SAR/NMON utility on linux is best with minimal overhead)

Reserve few CPU's on system (CPU Affinity) for your experiment which are dedicated only for your program and no OS task will run on them. Taskset is simplest utility to try out. More details are here.

Run the experiment with this setting and check behavior.


问:
Get current user in ApplicationRecord Model and perform a query in has_many
I've a model Post with lot of relationships, the one I want to focus on is

```<code>has_many :grid_notifications, :dependent=>:destroy
</code>```

I'm using jbuilder to return data to Backbone.js layer, so when I fetch posts as_json method is called

```<code>  def as_json(opts=nil)
  out={
    ...
    notifications: self.grid_notifications,
    ...
  }
  end
</code>```

I defined views following jBuilder docs

views/posts/index.json.jbuilder

```<code>json.array! @posts, partial: 'posts/post', as: :post
</code>```

and related partial  views/posts/_post.json.jbuilder

```<code>json.extract! post, ...other values... , :grid_notifications
</code>```

In this way, foreach Post it returns all the GridNotifications, no matter which is the current user.
So, I'd like to perform query related to Post model to return GridNotifications of current user and not of all users, so has_many statement become

```<code>has_many :grid_notifications, -> { where user_id: user.id }, :dependent=>:destroy
</code>```

But in this way I get the following error:

Showing .../app/views/posts/index.json.jbuilder where line #1 raised:
undefined local variable or method `user' for #

So, how I've to define _post.json.jbuilder or ?

答:
Use scope in model Post

```<code>scope :user_grid_notifications, -> (user) { includes(:grid_notifications).where(grid_notifications: {user_id: user.id}) }
</code>```

and then

```<code>notifications: self.user_grid_notifications(current_user)
</code>```

Body:
I've a model Post with lot of relationships, the one I want to focus on is

has_many :grid_notifications, :dependent=>:destroy

I'm using jbuilder to return data to Backbone.js layer, so when I fetch posts as_json method is called

  def as_json(opts=nil)
  out={
    ...
    notifications: self.grid_notifications,
    ...
  }
  end

I defined views following jBuilder docs

views/posts/index.json.jbuilder

json.array! @posts, partial: 'posts/post', as: :post

and related partial  views/posts/_post.json.jbuilder

json.extract! post, ...other values... , :grid_notifications

In this way, foreach Post it returns all the GridNotifications, no matter which is the current user.
So, I'd like to perform query related to Post model to return GridNotifications of current user and not of all users, so has_many statement become

has_many :grid_notifications, -> { where user_id: user.id }, :dependent=>:destroy

But in this way I get the following error:

Showing .../app/views/posts/index.json.jbuilder where line #1 raised:
undefined local variable or method `user' for #

So, how I've to define _post.json.jbuilder or ?

Body:
Use scope in model Post

scope :user_grid_notifications, -> (user) { includes(:grid_notifications).where(grid_notifications: {user_id: user.id}) }

and then

notifications: self.user_grid_notifications(current_user)


问:
Creating an instance from String in Java
If I have 2 classes, "A" and "B", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

```<code>public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}
</code>```

Thanks!

Joel

答:
You may take a look at Reflection:</p>

```<code>import java.awt.Rectangle;

public class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If I have 2 classes, "A" and "B", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}

Thanks!

Joel

Body:
You may take a look at Reflection:

import java.awt.Rectangle;

public class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}


问:
Get anonymous users with Cloud Functions for Firebase
I am using Cloud Functions to manage the database and the auth in my project. I followed the example https://github.com/firebase/functions-samples/tree/master/delete-unused-accounts-cron to delete inactive users in my app. I want to get only the anonymous users that were inactive for some time. I don't know to make the query to the identity toolkit to filter only the correct ones. Does anybody help?

Thanks!

答:
You can use the Admin SDK listUsers API to list all users and then inspect if the account has no provider data (assuming you don't use custom authentication)/no emails and inspect the metadata lastSignInTime. However, as Firebase sessions are indefinite, that does not guarantee the account is inactive:
Listing users: https://firebase.google.com/docs/auth/admin/manage-users#list_all_users

User record metadata which contains last sign in time: https://firebase.google.com/docs/reference/admin/node/admin.auth.UserRecord#metadata


问:
laravel - inserting id from one table to another right after submitting a form
Since I'm new in Laravel (started using this framework 2 weeks ago), I'm having a hard time inserting an id from one table to another right after submitting a form.

The scenario is that I have a form and what I wanted is that the id (p_id) of the newly submitted data from the 1st table (packages table) will be inserted to the 2nd table (itineraries table). Below are the codes of my controller and my model:

Controller

```<code>public function store(Request $request){
    request()->validate([
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);
    Packages::create($request->all());
    Itinerary::create($request->all());
    return redirect()->route('Agent.Packages');
}
</code>```

Itinerary Model

```<code>class Itinerary extends Model{
   public $fillable = [
       'noOfDays',
       'day',
       'time',
       'destination',
       ];
}
</code>```

答:
The create method returns the saved model instance.

```<code>$package = Packages::create($request->all());
</code>```

After that you can use it to populate the Itinerary table however you want.

```<code>$itinerary =  new Itinerary();
$itinerary->package_id = $package->id;
// Populate other fields
$itinerary->save();
</code>```

Since you're new to Laravel, I would propose to use the ->save() method to populate it. In my opinion, it's clearer in telling what you want to do in the code.

Body:
Since I'm new in Laravel (started using this framework 2 weeks ago), I'm having a hard time inserting an id from one table to another right after submitting a form.

The scenario is that I have a form and what I wanted is that the id (p_id) of the newly submitted data from the 1st table (packages table) will be inserted to the 2nd table (itineraries table). Below are the codes of my controller and my model:

Controller

public function store(Request $request){
    request()->validate([
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);
    Packages::create($request->all());
    Itinerary::create($request->all());
    return redirect()->route('Agent.Packages');
}

Itinerary Model

class Itinerary extends Model{
   public $fillable = [
       'noOfDays',
       'day',
       'time',
       'destination',
       ];
}

Body:
The create method returns the saved model instance.

$package = Packages::create($request->all());

After that you can use it to populate the Itinerary table however you want.

$itinerary =  new Itinerary();
$itinerary->package_id = $package->id;
// Populate other fields
$itinerary->save();

Since you're new to Laravel, I would propose to use the ->save() method to populate it. In my opinion, it's clearer in telling what you want to do in the code.


问:
Symfony3 404 NotFoundHttpException
I am developing with Symfony3, and now my problem is "404 error" when trying to access "http://localhost:8000/auth page"

dev.log

```<code>[2016-04-18 18:30:14] request.ERROR: Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "GuideBundle\Entity\MedicalStaff object not found." at D:\Elya\КПИ\6 семестр\TSPP\mg\vendor\sensio\framework-extra-bundle\Request\ParamConverter\DoctrineParamConverter.php line 66  []
</code>```

It worked before (I don't remember what I had done to fail it).
My routing.yml

```<code>auth:
    path: /auth
    defaults: {_controller: GuideBundle:Security:login}
</code>```

SecurityController.php

```<code> class SecurityController extends Controller
    {
        /**
         * @Route("/auth", name="auth")
         */
        public function loginAction(Request $request)
        {
            //Here is the code, If I comment It nothing changes and I don't use here any MedicalStaff object
        }

    }
</code>```

MedicalStaff.php is in GuideBundle\Entity folder

```<code>namespace GuideBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MedicalStaff
 *
 * @ORM\Table(name="medical_staff")
 * @ORM\Entity(repositoryClass="GuideBundle\Repository\MedicalStaffRepository")
 */
class MedicalStaff
{
    //here are methods and properties
}
</code>```

Can anyone say what can cause such type of problem?

答:
This YML

```<code>auth:
    path: /auth
    defaults: {_controller: GuideBundle:Security:login}
</code>```

Will conflict with your annotation

```<code>class SecurityController extends Controller
{
    /**
     * @Route("/auth", name="auth")
     */
    public function loginAction(Request $request)
    {
        //Here is the code, If I comment It nothing changes and I don't use here any MedicalStaff object
    }

}
</code>```

Use one and not both, check your config to see which you SHOULD be using.

Title: Symfony3 404 NotFoundHttpException

Body:
I am developing with Symfony3, and now my problem is "404 error" when trying to access "http://localhost:8000/auth page"

dev.log

[2016-04-18 18:30:14] request.ERROR: Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "GuideBundle\Entity\MedicalStaff object not found." at D:\Elya\КПИ\6 семестр\TSPP\mg\vendor\sensio\framework-extra-bundle\Request\ParamConverter\DoctrineParamConverter.php line 66  []

It worked before (I don't remember what I had done to fail it).
My routing.yml

auth:
    path: /auth
    defaults: {_controller: GuideBundle:Security:login}

SecurityController.php

 class SecurityController extends Controller
    {
        /**
         * @Route("/auth", name="auth")
         */
        public function loginAction(Request $request)
        {
            //Here is the code, If I comment It nothing changes and I don't use here any MedicalStaff object
        }

    }

MedicalStaff.php is in GuideBundle\Entity folder

namespace GuideBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MedicalStaff
 *
 * @ORM\Table(name="medical_staff")
 * @ORM\Entity(repositoryClass="GuideBundle\Repository\MedicalStaffRepository")
 */
class MedicalStaff
{
    //here are methods and properties
}

Can anyone say what can cause such type of problem?

Body:
This YML

auth:
    path: /auth
    defaults: {_controller: GuideBundle:Security:login}

Will conflict with your annotation

class SecurityController extends Controller
{
    /**
     * @Route("/auth", name="auth")
     */
    public function loginAction(Request $request)
    {
        //Here is the code, If I comment It nothing changes and I don't use here any MedicalStaff object
    }

}

Use one and not both, check your config to see which you SHOULD be using.


问:
How to draw a chain network map
I want a central warehouse-customer supply chain network. I am trying to plot 394 cities with connecting lines. But I received an error message. I am using the following code.
Note that my data frame contains latitude, longitude of the cities. Origin is a same place, whereas a destination changes every row.</p>

```<code>map <-get_map(location='united states', zoom=4, maptype = "satellite",
             source='google',color='color')
p <- ggmap(map)

    for(i in 2:nrow(x))

    {
      plot_data <-as.data.frame(rbind(c(unique(x$Origin),as.numeric(unique(x$LAT.x)),as.numeric(unique(x$LONG.x))),
                                       c(x$Destination[i],x$LAT.y[i],x$LONG.y[i])))

      colnames(plot_data) <- c("Place","Lat","Long")
      plot_data$Lat <- as.numeric(as.character(plot_data$Lat))
      plot_data$Long <- as.numeric(as.character(plot_data$Long))

      p <- p + geom_point(data=plot_data, aes(x=Long, y=Lat),color="blue",size=3)
      p <- p + geom_path(data=plot_data, aes(x=Long, y=Lat), color="red", size=1)

      }
</code>```

答:
I leave a demonstration showing how I usually handle this kind of task. I borrowed a data set from the maps package. There is long/lat information for world cities. I subsetted some of the data focusing on the US. I added two columns to this object. One is for long and the other is for lat for a starting point of lines. In this case, I randomly chose Denver. I used great circle to get lines between Denver and destination cities. Then, I converted the data to data.frame so that ggplot can draw a map using fortify().

```<code>library(ggmap)
library(maps)
library(dplyr)
library(ggplot2)
library(geosphere)

data(world.cities)

mymap <- get_map(location = "texas", maptype = "watercolor", source = "stamen", zoom = 4)

foo <- world.cities %>%
       filter(pop >= 500000 & country.etc == "USA") %>%
       mutate(start_long = -104.9903,
              start_lat = 39.7392) %>%
       do(fortify(as(gcIntermediate(.[,c("start_long", "start_lat")],
                                    .[,c("long", "lat")],
                                    100,
                                    breakAtDateLine = FALSE,
                                    addStartEnd = TRUE,
                                    sp = TRUE), "SpatialLinesDataFrame")))

g <- ggmap(mymap) +
     geom_path(data = foo, aes(x = long, y = lat, group = id), color = "red")
</code>```

Title: How to draw a chain network map

Body:
I want a central warehouse-customer supply chain network. I am trying to plot 394 cities with connecting lines. But I received an error message. I am using the following code.
Note that my data frame contains latitude, longitude of the cities. Origin is a same place, whereas a destination changes every row.

map <-get_map(location='united states', zoom=4, maptype = "satellite",
             source='google',color='color')
p <- ggmap(map)

    for(i in 2:nrow(x))

    {
      plot_data <-as.data.frame(rbind(c(unique(x$Origin),as.numeric(unique(x$LAT.x)),as.numeric(unique(x$LONG.x))),
                                       c(x$Destination[i],x$LAT.y[i],x$LONG.y[i])))

      colnames(plot_data) <- c("Place","Lat","Long")
      plot_data$Lat <- as.numeric(as.character(plot_data$Lat))
      plot_data$Long <- as.numeric(as.character(plot_data$Long))

      p <- p + geom_point(data=plot_data, aes(x=Long, y=Lat),color="blue",size=3)
      p <- p + geom_path(data=plot_data, aes(x=Long, y=Lat), color="red", size=1)

      }

Body:
I leave a demonstration showing how I usually handle this kind of task. I borrowed a data set from the maps package. There is long/lat information for world cities. I subsetted some of the data focusing on the US. I added two columns to this object. One is for long and the other is for lat for a starting point of lines. In this case, I randomly chose Denver. I used great circle to get lines between Denver and destination cities. Then, I converted the data to data.frame so that ggplot can draw a map using fortify().

library(ggmap)
library(maps)
library(dplyr)
library(ggplot2)
library(geosphere)

data(world.cities)

mymap <- get_map(location = "texas", maptype = "watercolor", source = "stamen", zoom = 4)

foo <- world.cities %>%
       filter(pop >= 500000 & country.etc == "USA") %>%
       mutate(start_long = -104.9903,
              start_lat = 39.7392) %>%
       do(fortify(as(gcIntermediate(.[,c("start_long", "start_lat")],
                                    .[,c("long", "lat")],
                                    100,
                                    breakAtDateLine = FALSE,
                                    addStartEnd = TRUE,
                                    sp = TRUE), "SpatialLinesDataFrame")))

g <- ggmap(mymap) +
     geom_path(data = foo, aes(x = long, y = lat, group = id), color = "red")


问:
Java can't connect to MySQL if password contain % symbol
Here is my connection URL:

```<code>jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%u16*!ypK@WrUQbr
</code>```

When i call

```<code>DriverManager.getConnection()
</code>```

with current URL i'm catching exception:

```<code>ava.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u1"
</code>```

If connection URL not contain % everything works.

i have found some info about this issue, and there recommend to do next conversion :

```<code>replaceAll("%(?![0-9a-fA-F]{2})", "%25")
</code>```

With this conversion i have error:

```<code>Access denied for user(incorrect password)
</code>```

Can somebody help to convert url correctly?

答:
I have tried as "Carlos Heuberger" recommended,
call getConnection(String url, String user, String password)

In this style it works, and from my view looks more clear instead of build one huge URL with all parameters included

Body:
Here is my connection URL:

jdbc:mysql://mydbhost:3306/mydatabase?user=username&password=%u16*!ypK@WrUQbr

When i call

DriverManager.getConnection()

with current URL i'm catching exception:

ava.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u1"

If connection URL not contain % everything works.

i have found some info about this issue, and there recommend to do next conversion :

replaceAll("%(?![0-9a-fA-F]{2})", "%25")

With this conversion i have error:

Access denied for user(incorrect password)

Can somebody help to convert url correctly?


问:
event when user check some checkbox
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

```<code><td id='checkbox_val_to_reveal'>

    <div class="form-group">
        <label>Status</label>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
    </div>

</td>

<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</code>```

JS

```<code><script>
//  $("#checkbox_val_to_reveal .flat").change(function() {

    $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
        alert("RRR");

    if ($(this).val() === "3" && $(this).is(":checked")) {
        $(".reveal_div_by_checkbox_val").show();
    } else {
        $(".reveal_div_by_checkbox_val").hide();
    }
    });
</script>
</code>```

答:
My suggestion

$(function(){
  $("input[type='checkbox'][value=3]").on("click",function() {
      $(".reveal_div_by_checkbox_val").toggle(this.checked);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.reveal_div_by_checkbox_val { display: none }</code>```

  Status

<input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved

<input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA

<input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply

Ticket Cause

```
</div>
</div>
</p>

<p>Better - use a data attribute:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function(){
  $("input[type='checkbox']").on("click",function() {
    var divId = $(this).attr("data-div");
    if (divId) {
      $("#"+divId).toggle(this.checked);
    }
  });
});</code>```

#ticket-cause { display: none }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td id='checkbox_val_to_reveal'>

<div class="form-group">
  <label>Status</label>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' data-div="ticket-cause" class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
</div>

</td>

<div id='ticket-cause'>
    <p><label class="title">Ticket Cause</label><br />
</div></code>```

Title: event when user check some checkbox

Body:
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

        Status

<input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved

<input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA

<input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply

Ticket Cause

JS

Body:
My suggestion

$(function(){
  $("input[type='checkbox'][value=3]").on("click",function() {
      $(".reveal_div_by_checkbox_val").toggle(this.checked);
  });
});

.reveal_div_by_checkbox_val { display: none }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td id='checkbox_val_to_reveal'>

<div class="form-group">
  <label>Status</label>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
</div>

</td>

<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>

Better - use a data attribute:

$(function(){
  $("input[type='checkbox']").on("click",function() {
    var divId = $(this).attr("data-div");
    if (divId) {
      $("#"+divId).toggle(this.checked);
    }
  });
});

#ticket-cause { display: none }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td id='checkbox_val_to_reveal'>

<div class="form-group">
  <label>Status</label>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
  <div class='checkbox'><label><input type='checkbox' data-div="ticket-cause" class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
  <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
</div>

</td>

<div id='ticket-cause'>
    <p><label class="title">Ticket Cause</label><br />
</div>


问:
How to change chart's width to fill up div using angular2-highcharts when hide/open left side nav menu?
How to change chart's width to fill up div when hide/open left side nav menu using angular2-highcharts??

I tried to use style="display:block; width: 100% !important;" as recommended on most resources I found, but it didn't help.

Here is an example of using chart inside mat-sidenav-container and mat-sidenav-content:

Html

```<code>`<mat-sidenav-container class="sidenavContainer">
  <mat-sidenav #sideNav opened="true" mode="side" class="filters-viewer-sidenav">
    mat-sidenav
  </mat-sidenav>
  <mat-sidenav-content>
    mat-sidenav-content
    <button (click)="sideNav.toggle()">
      mat-sidenav-button
    </button>
    <div style="width: 100%; height: 100%">
      <chart [options]="options"  style="display:block; width: 100% !important;"></chart>
    </div>
  </mat-sidenav-content>
</mat-sidenav-container>`
</code>```

css

```<code>`html, body, mat-sidenav-container, .chart-wrapper {
  margin: 0;
  width: 100%;
  height: 100%;
}
.sidenav {
  width: 240px;
  height: 100%;
  box-shadow: 3px 0 6px rgba(0,0,0,.24);
}`
</code>```

Added also screenshot: after I close left side nav menu, chart width stays the same.
still_same_chart_width_size

答:
One of the solution was to delay rendering of the chart. I used ngAfterViewInit() lifecycle hook:</p>

```<code>    ngAfterViewInit() {
     setTimeout(() => {
      if(this.chart) {
        this.chart.reflow();
      }
     },100);
    }
</code>```

Body:
How to change chart's width to fill up div when hide/open left side nav menu using angular2-highcharts??

I tried to use style="display:block; width: 100% !important;" as recommended on most resources I found, but it didn't help.

Here is an example of using chart inside mat-sidenav-container and mat-sidenav-content:

Html

`<mat-sidenav-container class="sidenavContainer">
  <mat-sidenav #sideNav opened="true" mode="side" class="filters-viewer-sidenav">
    mat-sidenav
  </mat-sidenav>
  <mat-sidenav-content>
    mat-sidenav-content
    <button (click)="sideNav.toggle()">
      mat-sidenav-button
    </button>

      <chart [options]="options"  style="display:block; width: 100% !important;"></chart>

  </mat-sidenav-content>
</mat-sidenav-container>`

css

`html, body, mat-sidenav-container, .chart-wrapper {
  margin: 0;
  width: 100%;
  height: 100%;
}
.sidenav {
  width: 240px;
  height: 100%;
  box-shadow: 3px 0 6px rgba(0,0,0,.24);
}`

Added also screenshot: after I close left side nav menu, chart width stays the same.
still_same_chart_width_size

Body:
One of the solution was to delay rendering of the chart. I used ngAfterViewInit() lifecycle hook:

    ngAfterViewInit() {
     setTimeout(() => {
      if(this.chart) {
        this.chart.reflow();
      }
     },100);
    }