问:
C# JSON Deserialization null nested property
I've been struggling to deserialize the following JSON into C#.  The JSON returned from the API has quite a few layers, so maybe I am overlooking something.

The property that is null is MemberStats (inside of the NestedStatEntries class).  Everything else is okay.

JSON:

```<code>{
    "kind": "tm:ltm:pool:members:memberscollectionstats",
    "selfLink": "https://device/mgmt/tm/ltm/pool/myPoolName/members/stats?ver=12.1.2",
    "entries": {
        "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/stats": {
            "nestedStats": {
                "kind": "tm:ltm:pool:members:membersstats",
                "selfLink": "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/stats?ver=12.1.2",
                "entries": {
                    "activeMemberCnt": {
                        "value": 16
                    },
                    "connqAll.ageEdm": {
                        "value": 0
                    },
                    "connqAll.ageEma": {
                        "value": 0
                    },
                    "connqAll.ageHead": {
                        "value": 0
                    },
                    "connqAll.ageMax": {
                        "value": 0
                    },
                    "connqAll.depth": {
                        "value": 0
                    },
                    "connqAll.serviced": {
                        "value": 0
                    },
                    "connq.ageEdm": {
                        "value": 0
                    },
                    "connq.ageEma": {
                        "value": 0
                    },
                    "connq.ageHead": {
                        "value": 0
                    },
                    "connq.ageMax": {
                        "value": 0
                    },
                    "connq.depth": {
                        "value": 0
                    },
                    "connq.serviced": {
                        "value": 0
                    },
                    "curSessions": {
                        "value": 0
                    },
                    "minActiveMembers": {
                        "value": 0
                    },
                    "monitorRule": {
                        "description": "min 1 of /Common/prod-olbtp_https"
                    },
                    "tmName": {
                        "description": "/Common/myPoolName"
                    },
                    "serverside.bitsIn": {
                        "value": 1854170442864
                    },
                    "serverside.bitsOut": {
                        "value": 28010721155520
                    },
                    "serverside.curConns": {
                        "value": 46
                    },
                    "serverside.maxConns": {
                        "value": 350
                    },
                    "serverside.pktsIn": {
                        "value": 1486804119
                    },
                    "serverside.pktsOut": {
                        "value": 2494389460
                    },
                    "serverside.totConns": {
                        "value": 2864936
                    },
                    "status.availabilityState": {
                        "description": "available"
                    },
                    "status.enabledState": {
                        "description": "enabled"
                    },
                    "status.statusReason": {
                        "description": "The pool is available"
                    },
                    "totRequests": {
                        "value": 0
                    },
                    "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/stats": {
                        "nestedStats": {
                            "entries": {
                                "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/~Common~10.10.10.30:443/stats": {
                                    "nestedStats": {
                                        "entries": {
                                            "addr": {
                                                "description": "10.10.10.30"
                                            },
                                            "connq.ageEdm": {
                                                "value": 0
                                            },
                                            "connq.ageEma": {
                                                "value": 0
                                            },
                                            "connq.ageHead": {
                                                "value": 0
                                            },
                                            "connq.ageMax": {
                                                "value": 0
                                            },
                                            "connq.depth": {
                                                "value": 0
                                            },
                                            "connq.serviced": {
                                                "value": 0
                                            },
                                            "curSessions": {
                                                "value": 0
                                            },
                                            "monitorRule": {
                                                "description": "min 1 of /Common/prod-olbtp_https (pool monitor)"
                                            },
                                            "monitorStatus": {
                                                "description": "up"
                                            },
                                            "nodeName": {
                                                "description": "/Common/10.10.10.30"
                                            },
                                            "poolName": {
                                                "description": "/Common/myPoolName"
                                            },
                                            "port": {
                                                "value": 443
                                            },
                                            "serverside.bitsIn": {
                                                "value": 123606959904
                                            },
                                            "serverside.bitsOut": {
                                                "value": 1252550265608
                                            },
                                            "serverside.curConns": {
                                                "value": 4
                                            },
                                            "serverside.maxConns": {
                                                "value": 18
                                            },
                                            "serverside.pktsIn": {
                                                "value": 75556262
                                            },
                                            "serverside.pktsOut": {
                                                "value": 115991280
                                            },
                                            "serverside.totConns": {
                                                "value": 189971
                                            },
                                            "sessionStatus": {
                                                "description": "enabled"
                                            },
                                            "status.availabilityState": {
                                                "description": "available"
                                            },
                                            "status.enabledState": {
                                                "description": "enabled"
                                            },
                                            "status.statusReason": {
                                                "description": "Pool member is available"
                                            },
                                            "totRequests": {
                                                "value": 0
                                            }
                                        }
                                    }
                                },
                                "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/~Common~10.10.10.40:443/stats": {
                                    "nestedStats": {
                                        "entries": {
                                            "addr": {
                                                "description": "10.10.10.40"
                                            },
                                            "connq.ageEdm": {
                                                "value": 0
                                            },
                                            "connq.ageEma": {
                                                "value": 0
                                            },
                                            "connq.ageHead": {
                                                "value": 0
                                            },
                                            "connq.ageMax": {
                                                "value": 0
                                            },
                                            "connq.depth": {
                                                "value": 0
                                            },
                                            "connq.serviced": {
                                                "value": 0
                                            },
                                            "curSessions": {
                                                "value": 0
                                            },
                                            "monitorRule": {
                                                "description": "min 1 of /Common/prod-olbtp_https (pool monitor)"
                                            },
                                            "monitorStatus": {
                                                "description": "up"
                                            },
                                            "nodeName": {
                                                "description": "/Common/10.10.10.40"
                                            },
                                            "poolName": {
                                                "description": "/Common/myPoolName"
                                            },
                                            "port": {
                                                "value": 443
                                            },
                                            "serverside.bitsIn": {
                                                "value": 70383109304
                                            },
                                            "serverside.bitsOut": {
                                                "value": 1114184738168
                                            },
                                            "serverside.curConns": {
                                                "value": 3
                                            },
                                            "serverside.maxConns": {
                                                "value": 32
                                            },
                                            "serverside.pktsIn": {
                                                "value": 58376213
                                            },
                                            "serverside.pktsOut": {
                                                "value": 98729511
                                            },
                                            "serverside.totConns": {
                                                "value": 103410
                                            },
                                            "sessionStatus": {
                                                "description": "enabled"
                                            },
                                            "status.availabilityState": {
                                                "description": "available"
                                            },
                                            "status.enabledState": {
                                                "description": "enabled"
                                            },
                                            "status.statusReason": {
                                                "description": "Pool member is available"
                                            },
                                            "totRequests": {
                                                "value": 0
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

C# Wrapper:

```<code>public class PoolAndMemberStatistics
{
    [JsonProperty("entries")]
    public Dictionary<string, EntriesWrapper> Entries { get; set; }

    [JsonProperty("generation")]
    public long Generation { get; set; }

    [JsonProperty("kind")]
    public string Kind { get; set; }

    [JsonProperty("selfLink")]
    public string SelfLink { get; set; }

    public partial class EntriesWrapper
    {
        [JsonProperty("nestedStats")]
        public NestedStats NestedStats { get; set; }
    }

    public partial class NestedStats
    {
        [JsonProperty("entries")]
        public NestedStatEntries Entries { get; set; }

        [JsonProperty("kind")]
        public string Kind { get; set; }

        [JsonProperty("selfLink")]
        public string SelfLink { get; set; }
    }

    public partial class NestedStatEntries
    {
        [JsonProperty("nestedStats")]
        public Dictionary<string, NestedStats> MemberStats { get; set; }

        [JsonProperty("activeMemberCnt")]
        public Dictionary<string, long> ActiveMemberCnt { get; set; }

        [JsonProperty("connq.ageEdm")]
        public Dictionary<string, long> ConnqAgeEdm { get; set; }

        [JsonProperty("connq.ageEma")]
        public Dictionary<string, long> ConnqAgeEma { get; set; }

        [JsonProperty("connq.ageHead")]
        public Dictionary<string, long> ConnqAgeHead { get; set; }

        [JsonProperty("connq.ageMax")]
        public Dictionary<string, long> ConnqAgeMax { get; set; }

        [JsonProperty("connqAll.ageEdm")]
        public Dictionary<string, long> ConnqAllAgeEdm { get; set; }

        [JsonProperty("connqAll.ageEma")]
        public Dictionary<string, long> ConnqAllAgeEma { get; set; }

        [JsonProperty("connqAll.ageHead")]
        public Dictionary<string, long> ConnqAllAgeHead { get; set; }

        [JsonProperty("connqAll.ageMax")]
        public Dictionary<string, long> ConnqAllAgeMax { get; set; }

        [JsonProperty("connqAll.depth")]
        public Dictionary<string, long> ConnqAllDepth { get; set; }

        [JsonProperty("connqAll.serviced")]
        public Dictionary<string, long> ConnqAllServiced { get; set; }

        [JsonProperty("connq.depth")]
        public Dictionary<string, long> ConnqDepth { get; set; }

        [JsonProperty("connq.serviced")]
        public Dictionary<string, long> ConnqServiced { get; set; }

        [JsonProperty("curSessions")]
        public Dictionary<string, long> CurSessions { get; set; }

        [JsonProperty("minActiveMembers")]
        public Dictionary<string, long> MinActiveMembers { get; set; }

        [JsonProperty("monitorRule")]
        public Dictionary<string, string> MonitorRule { get; set; }

        [JsonProperty("serverside.bitsIn")]
        public Dictionary<string, long> ServersideBitsIn { get; set; }

        [JsonProperty("serverside.bitsOut")]
        public Dictionary<string, long> ServersideBitsOut { get; set; }

        [JsonProperty("serverside.curConns")]
        public Dictionary<string, long> ServersideCurConns { get; set; }

        [JsonProperty("serverside.maxConns")]
        public Dictionary<string, long> ServersideMaxConns { get; set; }

        [JsonProperty("serverside.pktsIn")]
        public Dictionary<string, long> ServersidePktsIn { get; set; }

        [JsonProperty("serverside.pktsOut")]
        public Dictionary<string, long> ServersidePktsOut { get; set; }

        [JsonProperty("serverside.totConns")]
        public Dictionary<string, long> ServersideTotConns { get; set; }

        [JsonProperty("status.availabilityState")]
        public Dictionary<string, string> StatusAvailabilityState { get; set; }

        [JsonProperty("status.enabledState")]
        public Dictionary<string, string> StatusEnabledState { get; set; }

        [JsonProperty("status.statusReason")]
        public Dictionary<string, string> StatusStatusReason { get; set; }

        [JsonProperty("tmName")]
        public Dictionary<string, string> TmName { get; set; }

        [JsonProperty("totRequests")]
        public Dictionary<string, long> TotRequests { get; set; }
    }
}
</code>```

答:
Indeed, this JSON structure does not seem very friendly at first look.  It definitely defies code generation using tools like json2csharp.com.  But on closer inspection it looks like we have a recursive structure here which can be boiled down to two classes.  First, we have a Statistics class, which has a dictionary of Entries (along with a couple of other optional properties).  Secondly, we have an Entry class, which contains either a numeric Value, a string Description or a NestedStats, the latter of which is a Statistics instance.

```<code>class Statistics
{
    [JsonProperty("entries")]
    public Dictionary<string, Entry> Entries { get; set; }

    [JsonProperty("kind")]
    public string Kind { get; set; }

    [JsonProperty("selfLink")]
    public string SelfLink { get; set; }
}

class Entry
{
    [JsonProperty("value")]
    public long Value { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("nestedStats")]
    public Statistics NestedStats { get; set; }
}
</code>```

To the Entry class I would maybe add a read-only EntryType property to indicate which of the three values is populated, but this is optional.

```<code>enum EntryType { Value, Description, NestedStats }

class Entry
{
    ...

    public EntryType EntryType
    {
        get
        {
            if (NestedStats != null) return EntryType.NestedStats;
            if (Description != null) return EntryType.Description;
            return EntryType.Value;
        }
    }
}
</code>```

You can deserialize the whole JSON structure like this:

```<code>Statistics stats = JsonConvert.DeserializeObject<Statistics>(json);
</code>```

(Contrary to what was said in the comments, Json.Net can handle a recursive structure just fine.)

Fiddle: https://dotnetfiddle.net/aB1qbn

Body:
I've been struggling to deserialize the following JSON into C#.  The JSON returned from the API has quite a few layers, so maybe I am overlooking something.

The property that is null is MemberStats (inside of the NestedStatEntries class).  Everything else is okay.

JSON:

{
    "kind": "tm:ltm:pool:members:memberscollectionstats",
    "selfLink": "https://device/mgmt/tm/ltm/pool/myPoolName/members/stats?ver=12.1.2",
    "entries": {
        "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/stats": {
            "nestedStats": {
                "kind": "tm:ltm:pool:members:membersstats",
                "selfLink": "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/stats?ver=12.1.2",
                "entries": {
                    "activeMemberCnt": {
                        "value": 16
                    },
                    "connqAll.ageEdm": {
                        "value": 0
                    },
                    "connqAll.ageEma": {
                        "value": 0
                    },
                    "connqAll.ageHead": {
                        "value": 0
                    },
                    "connqAll.ageMax": {
                        "value": 0
                    },
                    "connqAll.depth": {
                        "value": 0
                    },
                    "connqAll.serviced": {
                        "value": 0
                    },
                    "connq.ageEdm": {
                        "value": 0
                    },
                    "connq.ageEma": {
                        "value": 0
                    },
                    "connq.ageHead": {
                        "value": 0
                    },
                    "connq.ageMax": {
                        "value": 0
                    },
                    "connq.depth": {
                        "value": 0
                    },
                    "connq.serviced": {
                        "value": 0
                    },
                    "curSessions": {
                        "value": 0
                    },
                    "minActiveMembers": {
                        "value": 0
                    },
                    "monitorRule": {
                        "description": "min 1 of /Common/prod-olbtp_https"
                    },
                    "tmName": {
                        "description": "/Common/myPoolName"
                    },
                    "serverside.bitsIn": {
                        "value": 1854170442864
                    },
                    "serverside.bitsOut": {
                        "value": 28010721155520
                    },
                    "serverside.curConns": {
                        "value": 46
                    },
                    "serverside.maxConns": {
                        "value": 350
                    },
                    "serverside.pktsIn": {
                        "value": 1486804119
                    },
                    "serverside.pktsOut": {
                        "value": 2494389460
                    },
                    "serverside.totConns": {
                        "value": 2864936
                    },
                    "status.availabilityState": {
                        "description": "available"
                    },
                    "status.enabledState": {
                        "description": "enabled"
                    },
                    "status.statusReason": {
                        "description": "The pool is available"
                    },
                    "totRequests": {
                        "value": 0
                    },
                    "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/stats": {
                        "nestedStats": {
                            "entries": {
                                "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/~Common~10.10.10.30:443/stats": {
                                    "nestedStats": {
                                        "entries": {
                                            "addr": {
                                                "description": "10.10.10.30"
                                            },
                                            "connq.ageEdm": {
                                                "value": 0
                                            },
                                            "connq.ageEma": {
                                                "value": 0
                                            },
                                            "connq.ageHead": {
                                                "value": 0
                                            },
                                            "connq.ageMax": {
                                                "value": 0
                                            },
                                            "connq.depth": {
                                                "value": 0
                                            },
                                            "connq.serviced": {
                                                "value": 0
                                            },
                                            "curSessions": {
                                                "value": 0
                                            },
                                            "monitorRule": {
                                                "description": "min 1 of /Common/prod-olbtp_https (pool monitor)"
                                            },
                                            "monitorStatus": {
                                                "description": "up"
                                            },
                                            "nodeName": {
                                                "description": "/Common/10.10.10.30"
                                            },
                                            "poolName": {
                                                "description": "/Common/myPoolName"
                                            },
                                            "port": {
                                                "value": 443
                                            },
                                            "serverside.bitsIn": {
                                                "value": 123606959904
                                            },
                                            "serverside.bitsOut": {
                                                "value": 1252550265608
                                            },
                                            "serverside.curConns": {
                                                "value": 4
                                            },
                                            "serverside.maxConns": {
                                                "value": 18
                                            },
                                            "serverside.pktsIn": {
                                                "value": 75556262
                                            },
                                            "serverside.pktsOut": {
                                                "value": 115991280
                                            },
                                            "serverside.totConns": {
                                                "value": 189971
                                            },
                                            "sessionStatus": {
                                                "description": "enabled"
                                            },
                                            "status.availabilityState": {
                                                "description": "available"
                                            },
                                            "status.enabledState": {
                                                "description": "enabled"
                                            },
                                            "status.statusReason": {
                                                "description": "Pool member is available"
                                            },
                                            "totRequests": {
                                                "value": 0
                                            }
                                        }
                                    }
                                },
                                "https://device/mgmt/tm/ltm/pool/myPoolName/members/~Common~myPoolName/members/~Common~10.10.10.40:443/stats": {
                                    "nestedStats": {
                                        "entries": {
                                            "addr": {
                                                "description": "10.10.10.40"
                                            },
                                            "connq.ageEdm": {
                                                "value": 0
                                            },
                                            "connq.ageEma": {
                                                "value": 0
                                            },
                                            "connq.ageHead": {
                                                "value": 0
                                            },
                                            "connq.ageMax": {
                                                "value": 0
                                            },
                                            "connq.depth": {
                                                "value": 0
                                            },
                                            "connq.serviced": {
                                                "value": 0
                                            },
                                            "curSessions": {
                                                "value": 0
                                            },
                                            "monitorRule": {
                                                "description": "min 1 of /Common/prod-olbtp_https (pool monitor)"
                                            },
                                            "monitorStatus": {
                                                "description": "up"
                                            },
                                            "nodeName": {
                                                "description": "/Common/10.10.10.40"
                                            },
                                            "poolName": {
                                                "description": "/Common/myPoolName"
                                            },
                                            "port": {
                                                "value": 443
                                            },
                                            "serverside.bitsIn": {
                                                "value": 70383109304
                                            },
                                            "serverside.bitsOut": {
                                                "value": 1114184738168
                                            },
                                            "serverside.curConns": {
                                                "value": 3
                                            },
                                            "serverside.maxConns": {
                                                "value": 32
                                            },
                                            "serverside.pktsIn": {
                                                "value": 58376213
                                            },
                                            "serverside.pktsOut": {
                                                "value": 98729511
                                            },
                                            "serverside.totConns": {
                                                "value": 103410
                                            },
                                            "sessionStatus": {
                                                "description": "enabled"
                                            },
                                            "status.availabilityState": {
                                                "description": "available"
                                            },
                                            "status.enabledState": {
                                                "description": "enabled"
                                            },
                                            "status.statusReason": {
                                                "description": "Pool member is available"
                                            },
                                            "totRequests": {
                                                "value": 0
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

C# Wrapper:

public class PoolAndMemberStatistics
{
    [JsonProperty("entries")]
    public Dictionary<string, EntriesWrapper> Entries { get; set; }

    [JsonProperty("generation")]
    public long Generation { get; set; }

    [JsonProperty("kind")]
    public string Kind { get; set; }

    [JsonProperty("selfLink")]
    public string SelfLink { get; set; }

    public partial class EntriesWrapper
    {
        [JsonProperty("nestedStats")]
        public NestedStats NestedStats { get; set; }
    }

    public partial class NestedStats
    {
        [JsonProperty("entries")]
        public NestedStatEntries Entries { get; set; }

        [JsonProperty("kind")]
        public string Kind { get; set; }

        [JsonProperty("selfLink")]
        public string SelfLink { get; set; }
    }

    public partial class NestedStatEntries
    {
        [JsonProperty("nestedStats")]
        public Dictionary<string, NestedStats> MemberStats { get; set; }

        [JsonProperty("activeMemberCnt")]
        public Dictionary<string, long> ActiveMemberCnt { get; set; }

        [JsonProperty("connq.ageEdm")]
        public Dictionary<string, long> ConnqAgeEdm { get; set; }

        [JsonProperty("connq.ageEma")]
        public Dictionary<string, long> ConnqAgeEma { get; set; }

        [JsonProperty("connq.ageHead")]
        public Dictionary<string, long> ConnqAgeHead { get; set; }

        [JsonProperty("connq.ageMax")]
        public Dictionary<string, long> ConnqAgeMax { get; set; }

        [JsonProperty("connqAll.ageEdm")]
        public Dictionary<string, long> ConnqAllAgeEdm { get; set; }

        [JsonProperty("connqAll.ageEma")]
        public Dictionary<string, long> ConnqAllAgeEma { get; set; }

        [JsonProperty("connqAll.ageHead")]
        public Dictionary<string, long> ConnqAllAgeHead { get; set; }

        [JsonProperty("connqAll.ageMax")]
        public Dictionary<string, long> ConnqAllAgeMax { get; set; }

        [JsonProperty("connqAll.depth")]
        public Dictionary<string, long> ConnqAllDepth { get; set; }

        [JsonProperty("connqAll.serviced")]
        public Dictionary<string, long> ConnqAllServiced { get; set; }

        [JsonProperty("connq.depth")]
        public Dictionary<string, long> ConnqDepth { get; set; }

        [JsonProperty("connq.serviced")]
        public Dictionary<string, long> ConnqServiced { get; set; }

        [JsonProperty("curSessions")]
        public Dictionary<string, long> CurSessions { get; set; }

        [JsonProperty("minActiveMembers")]
        public Dictionary<string, long> MinActiveMembers { get; set; }

        [JsonProperty("monitorRule")]
        public Dictionary<string, string> MonitorRule { get; set; }

        [JsonProperty("serverside.bitsIn")]
        public Dictionary<string, long> ServersideBitsIn { get; set; }

        [JsonProperty("serverside.bitsOut")]
        public Dictionary<string, long> ServersideBitsOut { get; set; }

        [JsonProperty("serverside.curConns")]
        public Dictionary<string, long> ServersideCurConns { get; set; }

        [JsonProperty("serverside.maxConns")]
        public Dictionary<string, long> ServersideMaxConns { get; set; }

        [JsonProperty("serverside.pktsIn")]
        public Dictionary<string, long> ServersidePktsIn { get; set; }

        [JsonProperty("serverside.pktsOut")]
        public Dictionary<string, long> ServersidePktsOut { get; set; }

        [JsonProperty("serverside.totConns")]
        public Dictionary<string, long> ServersideTotConns { get; set; }

        [JsonProperty("status.availabilityState")]
        public Dictionary<string, string> StatusAvailabilityState { get; set; }

        [JsonProperty("status.enabledState")]
        public Dictionary<string, string> StatusEnabledState { get; set; }

        [JsonProperty("status.statusReason")]
        public Dictionary<string, string> StatusStatusReason { get; set; }

        [JsonProperty("tmName")]
        public Dictionary<string, string> TmName { get; set; }

        [JsonProperty("totRequests")]
        public Dictionary<string, long> TotRequests { get; set; }
    }
}

Body:
Indeed, this JSON structure does not seem very friendly at first look.  It definitely defies code generation using tools like json2csharp.com.  But on closer inspection it looks like we have a recursive structure here which can be boiled down to two classes.  First, we have a Statistics class, which has a dictionary of Entries (along with a couple of other optional properties).  Secondly, we have an Entry class, which contains either a numeric Value, a string Description or a NestedStats, the latter of which is a Statistics instance.

class Statistics
{
    [JsonProperty("entries")]
    public Dictionary<string, Entry> Entries { get; set; }

    [JsonProperty("kind")]
    public string Kind { get; set; }

    [JsonProperty("selfLink")]
    public string SelfLink { get; set; }
}

class Entry
{
    [JsonProperty("value")]
    public long Value { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("nestedStats")]
    public Statistics NestedStats { get; set; }
}

To the Entry class I would maybe add a read-only EntryType property to indicate which of the three values is populated, but this is optional.

enum EntryType { Value, Description, NestedStats }

class Entry
{
    ...

    public EntryType EntryType
    {
        get
        {
            if (NestedStats != null) return EntryType.NestedStats;
            if (Description != null) return EntryType.Description;
            return EntryType.Value;
        }
    }
}

You can deserialize the whole JSON structure like this:

Statistics stats = JsonConvert.DeserializeObject<Statistics>(json);

(Contrary to what was said in the comments, Json.Net can handle a recursive structure just fine.)

Fiddle: https://dotnetfiddle.net/aB1qbn


来源: stackexchange

问:
how to attach a PDF document (from documents directory) to an email
I was wondering how to attach a PDF that I have generated to an email on iPhone/iPad. I have found examples of how to attach a image, but I don't know the mime type for a PDF.

Thanks.

答: The MIME type for a PDF should be application/pdf

ContentLicense: CC BY-SA 2.5


问:
How to create UI and Controls like Apple Music App in Android?
Video Link

I want to create view and animation like Apple Music App available in iOS. But, I want to do it in Android similar to above video link.

Is it possible to create such views in Android? How can I achieve this? How to proceed in this?

Please share any links and references.

This question is already asked but has no answer.

I want to implement something like Apple's new Music app which is synced with iTunes. Bubbles on the move, according to mood we can select a music, genre etc.
  I want this type of gesture with moving bubbles in Android. Can anyone help me out, how to figure out and play with Gestures or Motion Controls of that bubbles anywhere in screen. Also is there any support library if available would be very helpful to implement and move further. The bubbles are to be created randomly by a web service call.

Any suggestion in this will be helpful.

答:
i have used box2d with libGdx to configure the gradle in android studio...
u can refer my project on github which has selectable bubbles in random motion, and u can ask if any doubts...
https://github.com/mohitKejriwal/Bubble-UI-Android</p>

ContentLicense: CC BY-SA 3.0


问:
Is setting a static field via reflection guaranteed to call type initializer?
The following code sets the value of a static field and the initializer (static constructor) is called.

```<code>public class Foo
{
    static Foo()
    {
        Console.WriteLine("Initialized");
    }
    public static string Bar;
}

static Program()
{
    FieldInfo fld = typeof(Foo).GetField("Bar");
    fld.SetValue(null, ""); // cctor gets called
}
</code>```

Will this always happen; does setting a static field via reflection guarantee the static constructor will run if it hasn't already?

答:
if you access any member of the class, the runtime will invoke the static constructor automatically for you.

Meaning that yes, the static constructor will run if it hasn't already, this is one of the advantages of reflection.

You do not have to initialize it directly, only access it's properties.
this will work as well:

```<code>Type myClass = typeof(MyClass);
myClass.GetField("SomeValue").GetValue(null);
</code>```

If you do want to invoke it explicitly, you can use this:

```<code>myClass.TypeInitializer.Invoke(null, null);
</code>```

Though it is not a good practice and not recommended, I would strongly recommend that you don't do this, however - it violates a type expecting the static constructor to only be executed once.

Body:
The following code sets the value of a static field and the initializer (static constructor) is called.

public class Foo
{
    static Foo()
    {
        Console.WriteLine("Initialized");
    }
    public static string Bar;
}

static Program()
{
    FieldInfo fld = typeof(Foo).GetField("Bar");
    fld.SetValue(null, ""); // cctor gets called
}

Will this always happen; does setting a static field via reflection guarantee the static constructor will run if it hasn't already?

Body:
if you access any member of the class, the runtime will invoke the static constructor automatically for you.

Meaning that yes, the static constructor will run if it hasn't already, this is one of the advantages of reflection.

You do not have to initialize it directly, only access it's properties.
this will work as well:

Type myClass = typeof(MyClass);
myClass.GetField("SomeValue").GetValue(null);

If you do want to invoke it explicitly, you can use this:

myClass.TypeInitializer.Invoke(null, null);

Though it is not a good practice and not recommended, I would strongly recommend that you don't do this, however - it violates a type expecting the static constructor to only be executed once.


问:
Spawning Python Threads at EXACTLY the Same Time?
Right now some friends and I are making a program that generates music using square waves in Python (we're still very early on in development). One of the roadblocks along the way was that we figured that PyAudio will only play one sound at a time, and if you tried to play sounds over each other, e.g. to make a chord, the sounds just overwrite each other. Our current strategy is using threading to get around it, and it almost works, but the timing for when the threads start is very slightly off. Here is a snippet of our code that generates a C major chord:

```<code>import numpy as np
import pyaudio
import math
from scipy import signal
import multiprocessing
from time import time

def noteTest(frequency):
    l = np.linspace(0, 2, 384000, endpoint=False)
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=192000, output=True)
    wave_data = signal.square(2 * math.pi * frequency * l)
    stream.write(wave_data)

def playNotes():
    if __name__ == "__main__":
        multiprocessing.Process(target = noteTest, args = [523.25113060119]).start()
        print(time())
        multiprocessing.Process(target = noteTest, args = [659.25511382575]).start()
        print(time())
        multiprocessing.Process(target = noteTest, args = [783.99087196355]).start()
        print(time())

playNotes()
</code>```

When I look at the output of the program, here are the times it gives:

```<code>1510810518.870557
1510810518.8715587
1510810518.8730626
</code>```

As you can see, the threads are over a thousandth of a second apart. This is surprisingly noticeable, even for just one chord, but we fear that this will become an even bigger problem if we try and make an actual song as the tracks will drift apart and get out of time with each other. Note that all of the computers we tested this with DO have multiple physical cores. Is there any way to make the threads synchronize better, or are we better off finding an alternate solution?

答:
An option is to have a delay in each thread, before playing the sound.  If you have a reasonable idea of the offset involved in starting the threads, you can pass that value in as the delay.

For example, let's say there is 1ms delay between starting threads:

0ms: Start thread 1, with 1ms delay

0ms: Thread 1 starts on new core, waits

1ms: Start thread 2, with no delay

1ms: Thread 1 starts playing after delay

1ms: Thread 2 starts on new core, no delay, and starts playing

Another option, is to have each thread kick off, but wait for a signal from the main process loop to ALL the threads, before they start playing.

Body:
Right now some friends and I are making a program that generates music using square waves in Python (we're still very early on in development). One of the roadblocks along the way was that we figured that PyAudio will only play one sound at a time, and if you tried to play sounds over each other, e.g. to make a chord, the sounds just overwrite each other. Our current strategy is using threading to get around it, and it almost works, but the timing for when the threads start is very slightly off. Here is a snippet of our code that generates a C major chord:

import numpy as np
import pyaudio
import math
from scipy import signal
import multiprocessing
from time import time

def noteTest(frequency):
    l = np.linspace(0, 2, 384000, endpoint=False)
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=192000, output=True)
    wave_data = signal.square(2 * math.pi * frequency * l)
    stream.write(wave_data)

def playNotes():
    if __name__ == "__main__":
        multiprocessing.Process(target = noteTest, args = [523.25113060119]).start()
        print(time())
        multiprocessing.Process(target = noteTest, args = [659.25511382575]).start()
        print(time())
        multiprocessing.Process(target = noteTest, args = [783.99087196355]).start()
        print(time())

playNotes()

When I look at the output of the program, here are the times it gives:

1510810518.870557
1510810518.8715587
1510810518.8730626

As you can see, the threads are over a thousandth of a second apart. This is surprisingly noticeable, even for just one chord, but we fear that this will become an even bigger problem if we try and make an actual song as the tracks will drift apart and get out of time with each other. Note that all of the computers we tested this with DO have multiple physical cores. Is there any way to make the threads synchronize better, or are we better off finding an alternate solution?


问:
Getting consecutive number for each partition in a query
I have this table (sample data):

```<code>CREATE TABLE A
    ([Idx] int, [Title] varchar(50), [Sort] int)
;
INSERT INTO A
    ([Idx], [Title], [Sort])
VALUES
    (6, 'b', 1),
    (6, 'b', 2),
    (6, 'b', 3),

    (4, 'a', 4),
    (4, 'a', 5),
    (4, 'a', 6),

    (7, 'c', 7),
    (7, 'c', 8),
    (7, 'c', 9)
;
</code>```

My query:

```<code>SELECT *
FROM A
ORDER BY Sort
</code>```

Result:

```<code>| Idx | Title | Sort |
|-----|-------|------|
|   6 |     b |    1 |
|   6 |     b |    2 |
|   6 |     b |    3 |
|   4 |     a |    4 |
|   4 |     a |    5 |
|   4 |     a |    6 |
|   7 |     c |    7 |
|   7 |     c |    8 |
|   7 |     c |    9 |
</code>```

I would like to get consecutive number starting from 1 for each partition in the query. (the partition is by Idx)

Expected result:

```<code>| Idx | Title | Sort | N |
|-----|-------|------|---|
|   6 |     b |    1 | 1 |
|   6 |     b |    2 | 1 |
|   6 |     b |    3 | 1 |

|   4 |     a |    4 | 2 |
|   4 |     a |    5 | 2 |
|   4 |     a |    6 | 2 |

|   7 |     c |    7 | 3 |
|   7 |     c |    8 | 3 |
|   7 |     c |    9 | 3 |
</code>```

preferably using ? OVER (PARTITION BY Idx ORDER BY Sort) if possible.

I must also maintain the Sort order!

答:
```<code>;with cte
as
(
select *, row_number()over ( order by idx ) as rwnum,DENSE_RANK() over (Order  by title) as rank
 from #a

)

,cte3
as
(
select c.Idx as idx1,c.Title as title1,c.sort as sort1,c.rwnum,c.rank ,a.Idx ,a.Sort,a.Title
from
cte as c
join #A as a on c.rwnum=a.sort
)

select idx,Title,Sort,rank from cte3
</code>```

Body:
I have this table (sample data):

CREATE TABLE A
    ([Idx] int, [Title] varchar(50), [Sort] int)
;
INSERT INTO A
    ([Idx], [Title], [Sort])
VALUES
    (6, 'b', 1),
    (6, 'b', 2),
    (6, 'b', 3),

    (4, 'a', 4),
    (4, 'a', 5),
    (4, 'a', 6),

    (7, 'c', 7),
    (7, 'c', 8),
    (7, 'c', 9)
;

My query:

SELECT *
FROM A
ORDER BY Sort

Result:

| Idx | Title | Sort |
|-----|-------|------|
|   6 |     b |    1 |
|   6 |     b |    2 |
|   6 |     b |    3 |
|   4 |     a |    4 |
|   4 |     a |    5 |
|   4 |     a |    6 |
|   7 |     c |    7 |
|   7 |     c |    8 |
|   7 |     c |    9 |

I would like to get consecutive number starting from 1 for each partition in the query. (the partition is by Idx)

Expected result:

| Idx | Title | Sort | N |
|-----|-------|------|---|
|   6 |     b |    1 | 1 |
|   6 |     b |    2 | 1 |
|   6 |     b |    3 | 1 |

|   4 |     a |    4 | 2 |
|   4 |     a |    5 | 2 |
|   4 |     a |    6 | 2 |

|   7 |     c |    7 | 3 |
|   7 |     c |    8 | 3 |
|   7 |     c |    9 | 3 |

preferably using ? OVER (PARTITION BY Idx ORDER BY Sort) if possible.

I must also maintain the Sort order!


问:
Complex Arithmetic Expression in Haskell
How can i perform complex arithmetic calculation in haskell ?

Example :

```<code>eval numb(1) = 1
eval (add(numb(1),numb(2))) = 3
eval (add(mult(numb(1),numb(2)),diff(numb(3),numb(4)))) = 1
</code>```

答:
Pretty much just like that, but with some slight syntax tweaks so you're speaking GHC's language.

```<code>data Expr = Numb Int | Add Expr Expr | Diff Expr Expr | Mult Expr Expr

eval :: Expr -> Int
eval (Numb x) = x
eval (Add e e') = eval e + eval e'
eval (Diff e e') = eval e - eval e'
eval (Mult e e') = eval e * eval e'
</code>```

In ghci:

```<code>> eval (Numb 1)
1
> eval (Add (Numb 1) (Numb 2))
3
> eval (Add (Mult (Numb 1) (Numb 2)) (Diff (Numb 3) (Numb 4)))
1
</code>```

Body:
How can i perform complex arithmetic calculation in haskell ?

Example :

eval numb(1) = 1
eval (add(numb(1),numb(2))) = 3
eval (add(mult(numb(1),numb(2)),diff(numb(3),numb(4)))) = 1

Body:
Pretty much just like that, but with some slight syntax tweaks so you're speaking GHC's language.

data Expr = Numb Int | Add Expr Expr | Diff Expr Expr | Mult Expr Expr

eval :: Expr -> Int
eval (Numb x) = x
eval (Add e e') = eval e + eval e'
eval (Diff e e') = eval e - eval e'
eval (Mult e e') = eval e * eval e'

In ghci:

> eval (Numb 1)
1
> eval (Add (Numb 1) (Numb 2))
3
> eval (Add (Mult (Numb 1) (Numb 2)) (Diff (Numb 3) (Numb 4)))
1


问:
Date.getTime() in Java returning different time in different server
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

```<code>public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}
</code>```

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

答:
You need to set the time zone on SimpleDateFormat to be consistent across servers in different regions.  For example:</p>

```<code>public class Test {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        ....
    }

}
</code>```

Body:
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

Body:
You need to set the time zone on SimpleDateFormat to be consistent across servers in different regions.  For example:

public class Test {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        ....
    }

}


问:
How to search for a value in Mysql all tables without specifying the table name and column name?
```<code>SELECT @sqlText = @sqlText + ' SELECT * FROM ' + QUOTENAME(name) + CHAR(13) FROM sys.tables
</code>```

答:
If you are using phpmyadmin do the following steps:

1) select the database

2) Select search from the top links

3) Now you will get text box to enter what to search

4) Select the table in which you want to search.
It will search whole database get the result


问:
Can Gradle handle a build directory structure that does not conform default conventions?
I am working on a java ant+ivy based project that has the following directory structure:

```<code>projectRoot/src
projectRoot/classes
projectRoot/conf
projectRoot/webservices
</code>```

this works perfectly well in ant but I am looking to migrate to gradle.

Is there a way to define a non-maven directory structure in Gradle or should I be looking to mavenize?

答:
Try:

```<code>sourceSets {
    main {
        java {
            srcDirs = ['src/java']
        }
        resources {
            srcDirs = ['src/resources']
        }
    }
}
</code>```

or

```<code>sourceSets {
    main.java.srcDirs += 'src/java'
    main.resources.srcDirs += 'src/resources'
}
</code>```

Body:
I am working on a java ant+ivy based project that has the following directory structure:

projectRoot/src
projectRoot/classes
projectRoot/conf
projectRoot/webservices

this works perfectly well in ant but I am looking to migrate to gradle.

Is there a way to define a non-maven directory structure in Gradle or should I be looking to mavenize?

Body:
Try:

sourceSets {
    main {
        java {
            srcDirs = ['src/java']
        }
        resources {
            srcDirs = ['src/resources']
        }
    }
}

or

sourceSets {
    main.java.srcDirs += 'src/java'
    main.resources.srcDirs += 'src/resources'
}


问:
UIView animate doesn't finish before Label is hidden
My label is disappearing before the animation runs.

The animation should run after a button is pressed and slide out a label and the Button. But when I press the button they are both hidden before the animation can slide them out.

```<code>func nextGame() {

    UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
            NSLog("Animation started")
            self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
            self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
        }, completion: { (finished: Bool) in
            NSLog("Animation stopped")
            self.labelWinningPlayer.isHidden = true
            self.buttonNextGameLabel.isHidden = true
    })

    //sets buttons to start position
    labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
    buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

    //hides buttons that lay under the animated buttons
    for i in 1...9 {

        if let button = view.viewWithTag(i) as? UIButton {
            button.setImage(nil, for: .normal)
        }
    }
    activeGame = true
}

//animation should get started with this button
@IBAction func buttenNextGameAction(_ sender: Any) {
    nextGame()
}

//slides buttons in
func slideNextGameButtons() {

    labelWinningPlayer.isHidden = false
    buttonNextGameLabel.isHidden = false

    UIView.animate(withDuration: 0.5, animations: {

        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    })
}
</code>```

Here is the NSLog. According to that it's running the full animation...

```<code>2017-11-15 23:26:17.321465 [2442:245232] Animation started
2017-11-15 23:26:20.325137 [2442:245232] Animation stopped
</code>```

Thanks for your help in advance!

答:
set the label and the button's super view clipsToBounds property to true</p>

```<code>UIView.animate(withDuration: 3, delay: 0.0, options: [], animations: {
        NSLog("Animation started")
        self.labelWinningPlayer.center = CGPoint(x: (self.labelWinningPlayer.center.x) * 3, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: (self.buttonNextGameLabel.center.x) * 3, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        NSLog("Animation stopped")
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
    })
</code>```

Body:
My label is disappearing before the animation runs.

The animation should run after a button is pressed and slide out a label and the Button. But when I press the button they are both hidden before the animation can slide them out.

func nextGame() {

    UIView.animate(withDuration: 3, delay: 0.0, options: .allowAnimatedContent, animations: {
            NSLog("Animation started")
            self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
            self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
        }, completion: { (finished: Bool) in
            NSLog("Animation stopped")
            self.labelWinningPlayer.isHidden = true
            self.buttonNextGameLabel.isHidden = true
    })

    //sets buttons to start position
    labelWinningPlayer.center = CGPoint(x: labelWinningPlayer.center.x - 1000, y: labelWinningPlayer.center.y)
    buttonNextGameLabel.center = CGPoint(x: buttonNextGameLabel.center.x - 1000, y: buttonNextGameLabel.center.y)

    //hides buttons that lay under the animated buttons
    for i in 1...9 {

        if let button = view.viewWithTag(i) as? UIButton {
            button.setImage(nil, for: .normal)
        }
    }
    activeGame = true
}

//animation should get started with this button
@IBAction func buttenNextGameAction(_ sender: Any) {
    nextGame()
}

//slides buttons in
func slideNextGameButtons() {

    labelWinningPlayer.isHidden = false
    buttonNextGameLabel.isHidden = false

    UIView.animate(withDuration: 0.5, animations: {

        self.labelWinningPlayer.center = CGPoint(x: self.labelWinningPlayer.center.x + 500, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: self.buttonNextGameLabel.center.x + 500, y: self.buttonNextGameLabel.center.y)
    })
}

Here is the NSLog. According to that it's running the full animation...

2017-11-15 23:26:17.321465 [2442:245232] Animation started
2017-11-15 23:26:20.325137 [2442:245232] Animation stopped

Thanks for your help in advance!

Body:
set the label and the button's super view clipsToBounds property to true

UIView.animate(withDuration: 3, delay: 0.0, options: [], animations: {
        NSLog("Animation started")
        self.labelWinningPlayer.center = CGPoint(x: (self.labelWinningPlayer.center.x) * 3, y: self.labelWinningPlayer.center.y)
        self.buttonNextGameLabel.center = CGPoint(x: (self.buttonNextGameLabel.center.x) * 3, y: self.buttonNextGameLabel.center.y)
    }, completion: { (finished: Bool) in
        NSLog("Animation stopped")
        self.labelWinningPlayer.isHidden = true
        self.buttonNextGameLabel.isHidden = true
    })


问:
Loop over Laravel Collection
```<code>public function showJobCategoryContent($id){

     $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

     // Imagine here i got 5 data

     foreach ($jobsInfoById as $jobInfoById) {
          return  $current=$jobInfoById->created_at;
        //$trialExpires []= $current->addDays(30);
     }
}
</code>```

If i loop it it only show 1 data. How is it possible If use array sign then it will show 1 data.

答:
If you want to get an array of all created_at dates, you don't need a loop.

```<code>public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return $jobsInfoById->pluck('created_at');
}
</code>```

Using the loop:

```<code>public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $dates = [];
    foreach ($jobsInfoById as $jobInfoById) {
        $dates[] = $current = $jobInfoById->created_at;
    }

    return $dates;
}
</code>```

If want to add 30 days to each date:

```<code>public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}
</code>```

Have a look at Laravel collections and how they can be useful: link

Title: Loop over Laravel Collection

Body:
public function showJobCategoryContent($id){

     $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

     // Imagine here i got 5 data

     foreach ($jobsInfoById as $jobInfoById) {
          return  $current=$jobInfoById->created_at;
        //$trialExpires []= $current->addDays(30);
     }
}

If i loop it it only show 1 data. How is it possible If use array sign then it will show 1 data.

Body:
If you want to get an array of all created_at dates, you don't need a loop.

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return $jobsInfoById->pluck('created_at');
}

Using the loop:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $dates = [];
    foreach ($jobsInfoById as $jobInfoById) {
        $dates[] = $current = $jobInfoById->created_at;
    }

    return $dates;
}

If want to add 30 days to each date:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}

Have a look at Laravel collections and how they can be useful: link


问:
Locust login testing on Laravel app
Trying to login to laravel application using Locust.
My code is following:

```<code>from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
  def on_start(self):
    self.login()

  def login(self):
    response = self.client.get("/en/login")
    csrftoken = response.cookies['XSRF-TOKEN']
    session = response.cookies['bitrent_session']
    post_data = {'username': "user@user.com", 'password': '1234', "_token":     csrftoken }
    with self.client.post('/en/login', post_data,
                    catch_response=True) as response:
      print("Code: ", response.status_code)
      print("Content: ", response.content

  @task()
  def index(self):
    self.client.get("/")

class WebsiteUser(HttpLocust):
  task_set = UserBehavior
  min_wait = 5000
  max_wait = 9000
</code>```

However I got error - Code 419 Content The page has expired due to inactivity.
Could anyone advise me how to login to Laravel application using Locust

答:
Found the answer:

Reason is that I'm passing wrong value for _token field.
Instead, if you face same task, you could try following:

```<code>import re
from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
  def on_start(self):
    self.login()

  def login(self):
    response = self.client.get("/en/login")
    print("Content: ", response.content)
    csrftoken = re.search('meta name="csrf-token" content="(.+?)"', response.text).group(1)

    print("token: ", csrftoken)
    post_data = {'username': "user@user.com", 'password': '1234', "_token": csrftoken }
    with self.client.post('/en/login', post_data,
                catch_response=True) as response:
      print("Code: ", response.status_code)
      print("Content: ", response.content)

  @task()
  def index(self):
    self.client.get("/")

class WebsiteUser(HttpLocust):
  task_set = UserBehavior
  min_wait = 5000
  max_wait = 9000
</code>```

Hope that will help someone in future :)

Title: Locust login testing on Laravel app

Body:
Trying to login to laravel application using Locust.
My code is following:

from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
  def on_start(self):
    self.login()

  def login(self):
    response = self.client.get("/en/login")
    csrftoken = response.cookies['XSRF-TOKEN']
    session = response.cookies['bitrent_session']
    post_data = {'username': "user@user.com", 'password': '1234', "_token":     csrftoken }
    with self.client.post('/en/login', post_data,
                    catch_response=True) as response:
      print("Code: ", response.status_code)
      print("Content: ", response.content

  @task()
  def index(self):
    self.client.get("/")

class WebsiteUser(HttpLocust):
  task_set = UserBehavior
  min_wait = 5000
  max_wait = 9000

However I got error - Code 419 Content The page has expired due to inactivity.
Could anyone advise me how to login to Laravel application using Locust

Body:
Found the answer:

Reason is that I'm passing wrong value for _token field.
Instead, if you face same task, you could try following:

import re
from locust import HttpLocust, TaskSet, task

class UserBehavior(TaskSet):
  def on_start(self):
    self.login()

  def login(self):
    response = self.client.get("/en/login")
    print("Content: ", response.content)
    csrftoken = re.search('meta name="csrf-token" content="(.+?)"', response.text).group(1)

    print("token: ", csrftoken)
    post_data = {'username': "user@user.com", 'password': '1234', "_token": csrftoken }
    with self.client.post('/en/login', post_data,
                catch_response=True) as response:
      print("Code: ", response.status_code)
      print("Content: ", response.content)

  @task()
  def index(self):
    self.client.get("/")

class WebsiteUser(HttpLocust):
  task_set = UserBehavior
  min_wait = 5000
  max_wait = 9000

Hope that will help someone in future :)


问:
Removing max and min elements of array from mean calculation
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

```<code>a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])
</code>```

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

```<code>#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]
</code>```

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

```<code>mean1=f.mean(axis=0)
</code>```

but it did not work.

答:
A python list has a remove method.

With a utility function we could remove the min and max elements from a row:

```<code>def foo(i,j,k):
    il = i.tolist()
    il.remove(j)
    il.remove(k)
    return il

In [230]: [foo(i,j,k) for i,j,k in zip(a,b,c)]
Out[230]: [[4, 5], [2, 5], [3, 9]]
</code>```

This could be turned back into an array with np.array(...).  Note that this removed just one of the 9 in the last row.  If it had removed both, the last list would have just 1 value, and the result could not be turned back into a 2d array.

I'm sure we could come up with a pure-array method, possibly useing argmax and argmin instead of max and min.  But I think the list approach is a better starting point for a Python beginner.

An array masking approach

```<code>In [232]: bi = np.argmax(a,1)
In [233]: ci = np.argmin(a,1)
In [234]: bi
Out[234]: array([3, 1, 1], dtype=int32)
In [235]: ci
Out[235]: array([0, 3, 3], dtype=int32)

In [243]: mask = np.ones_like(a, bool)
In [244]: mask[np.arange(3),bi]=False
In [245]: mask[np.arange(3),ci]=False
In [246]: mask
Out[246]:
array([[False,  True,  True, False],
       [ True, False,  True, False],
       [ True, False,  True, False]], dtype=bool)

In [247]: a[mask]
Out[247]: array([4, 5, 2, 5, 3, 9])
In [248]: _.reshape(3,-1)
Out[248]:
array([[4, 5],
       [2, 5],
       [3, 9]])
</code>```

Again this is better if we just delete one max and one min from each row.

Another masking approach:

```<code>In [257]: (a!=b[:,None]) & (a!=c[:,None])
Out[257]:
array([[False,  True,  True, False],
       [ True, False,  True, False],
       [ True, False, False, False]], dtype=bool)
In [258]: a[(a!=b[:,None]) & (a!=c[:,None])]
Out[258]: array([4, 5, 2, 5, 3])
</code>```

This does remove all '9's in the last row.  But it does not preserve the row split.

This preserves the row structure, and allows variable lengths:

```<code>In [259]: mask=(a!=b[:,None]) & (a!=c[:,None])
In [260]: [i[j] for i,j in zip(a, mask)]
Out[260]: [array([4, 5]), array([2, 5]), array([3])]
</code>```

Body:
I am hoping to delete the highest number and the lowest number from the array 3*4. Let's say, the data looks like this:

a=np.array([[1,4,5,10],[2,6,5,0],[3,9,9,0]])

so I expected to see the result like this:
    deleted_data=[4,5],[2,5],[3]

Could you advise me how to delete the max and min from each array?

to do so, I did like this (UPDATE):

#to find out the max / min values:
b = np.max(a,1) #max
c = np.min(a,1) #min

#creating dataset after deleting max & min
d=(a!=b[:,None]) & (a!=c[:,None])
f=[i[j] for i,j in zip(a, d)]

output: [array([8, 7, 7, 9, 9, 8]), array([8, 7, 8, 6, 8, 8]), array([9, 8, 9, 9, 8]), array([6, 7, 7, 6, 6, 7]), array([7, 7, 7, 7, 6])]

Now I am not sure how to calculate the mean of the list objects?
I would like to calculate the mean of each array, so I have tried this:

mean1=f.mean(axis=0)

but it did not work.

Body:
A python list has a remove method.

With a utility function we could remove the min and max elements from a row:

def foo(i,j,k):
    il = i.tolist()
    il.remove(j)
    il.remove(k)
    return il

In [230]: [foo(i,j,k) for i,j,k in zip(a,b,c)]
Out[230]: [[4, 5], [2, 5], [3, 9]]

This could be turned back into an array with np.array(...).  Note that this removed just one of the 9 in the last row.  If it had removed both, the last list would have just 1 value, and the result could not be turned back into a 2d array.

I'm sure we could come up with a pure-array method, possibly useing argmax and argmin instead of max and min.  But I think the list approach is a better starting point for a Python beginner.

An array masking approach

In [232]: bi = np.argmax(a,1)
In [233]: ci = np.argmin(a,1)
In [234]: bi
Out[234]: array([3, 1, 1], dtype=int32)
In [235]: ci
Out[235]: array([0, 3, 3], dtype=int32)

In [243]: mask = np.ones_like(a, bool)
In [244]: mask[np.arange(3),bi]=False
In [245]: mask[np.arange(3),ci]=False
In [246]: mask
Out[246]:
array([[False,  True,  True, False],
       [ True, False,  True, False],
       [ True, False,  True, False]], dtype=bool)

In [247]: a[mask]
Out[247]: array([4, 5, 2, 5, 3, 9])
In [248]: _.reshape(3,-1)
Out[248]:
array([[4, 5],
       [2, 5],
       [3, 9]])

Again this is better if we just delete one max and one min from each row.

Another masking approach:

In [257]: (a!=b[:,None]) & (a!=c[:,None])
Out[257]:
array([[False,  True,  True, False],
       [ True, False,  True, False],
       [ True, False, False, False]], dtype=bool)
In [258]: a[(a!=b[:,None]) & (a!=c[:,None])]
Out[258]: array([4, 5, 2, 5, 3])

This does remove all '9's in the last row.  But it does not preserve the row split.

This preserves the row structure, and allows variable lengths:

In [259]: mask=(a!=b[:,None]) & (a!=c[:,None])
In [260]: [i[j] for i,j in zip(a, mask)]
Out[260]: [array([4, 5]), array([2, 5]), array([3])]


问:
configuring WCF with <services> tag
I am trying to solve a WCF error found in my previous question. Basically, the error is:

The maximum string content length quota (8192) has been exceeded while reading XML data.

And someone suggested to use a services tag in my web.config to resolve my issue.

Now, I am facing a different problem. I can’t figure out how am I suppose to configure the services tag in my web.config to work correctly on my server. I always get the following error when I try to use the services tag:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

Here is my web.config with the services tag added:

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding
      name="BasicHttpBinding_Service1"
      closeTimeout="00:01:00"
      openTimeout="00:01:00"
      receiveTimeout="00:10:00"
      sendTimeout="00:01:00"
      allowCookies="false"
      bypassProxyOnLocal="false"
      hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536"
      maxBufferPoolSize="524288"
      maxReceivedMessageSize="65536"
      messageEncoding="Text"
      textEncoding="utf-8"
      transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas
        maxDepth="32"
        maxStringContentLength="10000"
        maxArrayLength="16384"
        maxBytesPerRead="4096"
        maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint
    address="http://localhost:53931/WCF/Service1.svc"
    binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_Service1"
    contract="ServiceReference.Service1"
    name="BasicHttpBinding_Service1" />
</client>
<behaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<!--PROBLEM SOMEWHERE IN THE SERVICES TAG-->
<services>
  <service
    behaviorConfiguration="NewBehavior"
    name="AspPersonalWebsite.ServiceReference">
    <endpoint
      address="http://localhost:53931/WCF/Service1.svc"
      binding="basicHttpBinding"
      contract="ServiceReference.Service1"
      bindingConfiguration="BasicHttpBinding_Service1" />
  </service>
</services>
</code>```

Please note that by removing the services tag everything works fine, but then I will not be able to resolve my original problem posted on my previous question.

so could someone please tell me if I am doing something wrong on my web.config, specifically in my services tag?!

答:
Okay, let's tackle this:

First, you need to define a custom basicHttpBinding binding configuration with some custom settings:

```<code><bindings>
  <basicHttpBinding>
    <binding name="LargeSettings"
             maxBufferSize="524288"
             maxBufferPoolSize="524288"
             maxReceivedMessageSize="6553600">
        <readerQuotas maxDepth="32" maxStringContentLength="100000"
                      maxArrayLength="16384" maxBytesPerRead="4096"
                      maxNameTableCharCount="16384" />
      <security mode="None" />
    </binding>
  </basicHttpBinding>
</bindings>
</code>```

This section needs to be in both your server-side's web.config, as well as your client side's config.

Secondly, on the server-side, you need to have a <services> tag that defines your service and its endpoints and their configuration:

```<code><services>
   <service name="YourNamespace.YourClassName"
            behaviorConfiguration="ServiceWithMetadata">
      <endpoint name="Default"
                address="http://localhost:53931/WCF/Service1.svc"
                binding="basicHttpBinding"
                bindingConfiguration="LargeSettings"
                contract="YourNamespace.IServiceContract" />
   </service>
</services>
<behaviors>
   <serviceBehaviors>
      <behavior name="ServiceWithMetadata">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
   </serviceBehaviors>
</behaviors>
</code>```

Points to check:

your service name must be the fully qualified name (YourNamespace.YourClassName) of your service class - the class that implements your service contract

your service contract in the endpoint must also be the fully qualified name of your service contract  (YourNamespace.IYourServiceContract)

the behaviorConfiguration of your <service> tag must reference and match exactly to the name= attribute as defined in your <behaviors> section

And thirdly, on the client side, you need something like this:

```<code><client>
  <endpoint name="Default"
            address="http://localhost:53931/WCF/Service1.svc"
            binding="basicHttpBinding"
            bindingConfiguration="LargeSettings"
            contract="ServiceReference.IYourService" />
</client>
</code>```

You need to reference the endpoint defined in your service's definition on the server side, you need to use the same binding and binding configuration, and you need to use the service contract as defined in your service reference.

Title: configuring WCF with <services> tag

Body:
I am trying to solve a WCF error found in my previous question. Basically, the error is:

The maximum string content length quota (8192) has been exceeded while reading XML data.

And someone suggested to use a services tag in my web.config to resolve my issue.

Now, I am facing a different problem. I can’t figure out how am I suppose to configure the services tag in my web.config to work correctly on my server. I always get the following error when I try to use the services tag:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

Here is my web.config with the services tag added:

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding
      name="BasicHttpBinding_Service1"
      closeTimeout="00:01:00"
      openTimeout="00:01:00"
      receiveTimeout="00:10:00"
      sendTimeout="00:01:00"
      allowCookies="false"
      bypassProxyOnLocal="false"
      hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536"
      maxBufferPoolSize="524288"
      maxReceivedMessageSize="65536"
      messageEncoding="Text"
      textEncoding="utf-8"
      transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas
        maxDepth="32"
        maxStringContentLength="10000"
        maxArrayLength="16384"
        maxBytesPerRead="4096"
        maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint
    address="http://localhost:53931/WCF/Service1.svc"
    binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_Service1"
    contract="ServiceReference.Service1"
    name="BasicHttpBinding_Service1" />
</client>
<behaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>

<services>
  <service
    behaviorConfiguration="NewBehavior"
    name="AspPersonalWebsite.ServiceReference">
    <endpoint
      address="http://localhost:53931/WCF/Service1.svc"
      binding="basicHttpBinding"
      contract="ServiceReference.Service1"
      bindingConfiguration="BasicHttpBinding_Service1" />
  </service>
</services>

Please note that by removing the services tag everything works fine, but then I will not be able to resolve my original problem posted on my previous question.

so could someone please tell me if I am doing something wrong on my web.config, specifically in my services tag?!

Body:
Okay, let's tackle this:

First, you need to define a custom basicHttpBinding binding configuration with some custom settings:

<bindings>
  <basicHttpBinding>
    <binding name="LargeSettings"
             maxBufferSize="524288"
             maxBufferPoolSize="524288"
             maxReceivedMessageSize="6553600">
        <readerQuotas maxDepth="32" maxStringContentLength="100000"
                      maxArrayLength="16384" maxBytesPerRead="4096"
                      maxNameTableCharCount="16384" />
      <security mode="None" />
    </binding>
  </basicHttpBinding>
</bindings>

This section needs to be in both your server-side's web.config, as well as your client side's config.

Secondly, on the server-side, you need to have a <services> tag that defines your service and its endpoints and their configuration:

<services>
   <service name="YourNamespace.YourClassName"
            behaviorConfiguration="ServiceWithMetadata">
      <endpoint name="Default"
                address="http://localhost:53931/WCF/Service1.svc"
                binding="basicHttpBinding"
                bindingConfiguration="LargeSettings"
                contract="YourNamespace.IServiceContract" />
   </service>
</services>
<behaviors>
   <serviceBehaviors>
      <behavior name="ServiceWithMetadata">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
   </serviceBehaviors>
</behaviors>

Points to check:

your service name must be the fully qualified name (YourNamespace.YourClassName) of your service class - the class that implements your service contract

your service contract in the endpoint must also be the fully qualified name of your service contract  (YourNamespace.IYourServiceContract)

the behaviorConfiguration of your <service> tag must reference and match exactly to the name= attribute as defined in your <behaviors> section

And thirdly, on the client side, you need something like this:

<client>
  <endpoint name="Default"
            address="http://localhost:53931/WCF/Service1.svc"
            binding="basicHttpBinding"
            bindingConfiguration="LargeSettings"
            contract="ServiceReference.IYourService" />
</client>

You need to reference the endpoint defined in your service's definition on the server side, you need to use the same binding and binding configuration, and you need to use the service contract as defined in your service reference.


问:
PySpark MongoDB append all elements of an array from DataFrame
I have a MongoDB collection that looks something like this:

```<code>{
    "_id" : { "customerName" : "Bob",  "customerPhone" : "123-456-7890"},
    "purchases": ["A", "B", "C", "D"]
}
</code>```

Basically the _id is a pair of unique key about the customer and the purchases are the array of the items that the customer has bought.

I also have a PySpark DataFrame that I would like to push into this collection where it contains information that I would like to update this particular document.

```<code>df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append") \
                .option("spark.mongodb.output.uri", "mongodb://localhost:27017/customer.purchases").save()
</code>```

The problem is that if I am updating this document where I want to add new purchases for Bob it would only append the non-existing ones in purchases instead of appending all.

As a result what I ended up doing right now is that I would just have to call rdd.collect() to turn the whole thing into a list and not using the schema to convert it to DataFrame. Then insert everything one by one while checking if the key exists; which makes this part slow and requires a lot of memory when the query for RDD gets large.

For versions:

PySpark: 2.2
MongoDB: 3.0.15
Mongo Spark Connector: 2.2.1

Does anyone if there is anything that I can do to append all element in the array to MongoDB collection using dataframe?
Also, if there is anything that I am missing or other things that I should do please let me know.
Thanks!

答:
You need to change the data models or schema of your documents. The important part here being the _id key field. The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

In your case, the value of _id field is mutable, in fact this is what you're trying to update. As a suggestion, you may want to change this to:

```<code>{ "_id" : <unique identifier>
  "customerName" : "Bob",
  "customerPhone" : "123-456-7890",
  "purchases": ["A", "B", "C", "D"]
}
</code>```

You may utilise the default _id value of ObjectId as a unique identifier.

Once you have a unique identifier on _id field, let's talk about update operation. Since MongoDB Spark Connector v1.1+ (currently version 2.2), if a Dataframe contains an _id field during write, the data will be upsert-ed. Which means any existing documents with the same _id value will be updated and new documents without existing _id value in the collection will be inserted.

Bonus rounds:

You need to find a better schema as well for purchases field. Having an array length of undefined length may create issues in the future. i.e. Bob made 1000 purchases in a year.

Please update your MongoDB server version (version 3.0.x is from 2015), the current stable version is 3.4, with 3.6 being released in the next month.

Body:
I have a MongoDB collection that looks something like this:

{
    "_id" : { "customerName" : "Bob",  "customerPhone" : "123-456-7890"},
    "purchases": ["A", "B", "C", "D"]
}

Basically the _id is a pair of unique key about the customer and the purchases are the array of the items that the customer has bought.

I also have a PySpark DataFrame that I would like to push into this collection where it contains information that I would like to update this particular document.

df.write.format("com.mongodb.spark.sql.DefaultSource").mode("append") \
                .option("spark.mongodb.output.uri", "mongodb://localhost:27017/customer.purchases").save()

The problem is that if I am updating this document where I want to add new purchases for Bob it would only append the non-existing ones in purchases instead of appending all.

As a result what I ended up doing right now is that I would just have to call rdd.collect() to turn the whole thing into a list and not using the schema to convert it to DataFrame. Then insert everything one by one while checking if the key exists; which makes this part slow and requires a lot of memory when the query for RDD gets large.

For versions:

PySpark: 2.2
MongoDB: 3.0.15
Mongo Spark Connector: 2.2.1

Does anyone if there is anything that I can do to append all element in the array to MongoDB collection using dataframe?
Also, if there is anything that I am missing or other things that I should do please let me know.
Thanks!

Body:
You need to change the data models or schema of your documents. The important part here being the _id key field. The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

In your case, the value of _id field is mutable, in fact this is what you're trying to update. As a suggestion, you may want to change this to:

{ "_id" : <unique identifier>
  "customerName" : "Bob",
  "customerPhone" : "123-456-7890",
  "purchases": ["A", "B", "C", "D"]
}

You may utilise the default _id value of ObjectId as a unique identifier.

Once you have a unique identifier on _id field, let's talk about update operation. Since MongoDB Spark Connector v1.1+ (currently version 2.2), if a Dataframe contains an _id field during write, the data will be upsert-ed. Which means any existing documents with the same _id value will be updated and new documents without existing _id value in the collection will be inserted.

Bonus rounds:

You need to find a better schema as well for purchases field. Having an array length of undefined length may create issues in the future. i.e. Bob made 1000 purchases in a year.

Please update your MongoDB server version (version 3.0.x is from 2015), the current stable version is 3.4, with 3.6 being released in the next month.


问:
How to track and show mouse position in unity 3d
I have a questions with Unity 3d:  How do you get the current mouse position on a Canvas object in Unity 3D? Currently I'm trying to create a mouse tracker on the Unity 3D, so if you move the mouse on the canvas, there will be a small text below the mouse showing the current position of the mouse.</p>

答:
You can get mouse position from Input class
for complete example</p>

```<code>using UnityEngine;
using UnityEngine.UI;

public class TrackMouse : MonoBehaviour
{
    public Text text;
    //get reference to the RectTransform component
    private RectTransform rectTransform;

    void Start ()
    {
        rectTransform = text.GetComponent<RectTransform>();

        //Set the anchor to Left Below Corner
        rectTransform.anchorMin = new Vector2(0,0);
        rectTransform.anchorMax = new Vector2(0,0);
    }

    void Update ()
    {
        //update the position of the text
        rectTransform.anchoredPosition3D = Input.mousePosition;
        //display position info on the text
        text.text = Input.mousePosition.ToString();
    }
}
</code>```

Body:
You can get mouse position from Input class
for complete example

using UnityEngine;
using UnityEngine.UI;

public class TrackMouse : MonoBehaviour
{
    public Text text;
    //get reference to the RectTransform component
    private RectTransform rectTransform;

    void Start ()
    {
        rectTransform = text.GetComponent<RectTransform>();

        //Set the anchor to Left Below Corner
        rectTransform.anchorMin = new Vector2(0,0);
        rectTransform.anchorMax = new Vector2(0,0);
    }

    void Update ()
    {
        //update the position of the text
        rectTransform.anchoredPosition3D = Input.mousePosition;
        //display position info on the text
        text.text = Input.mousePosition.ToString();
    }
}


问:
Aligning a text and line parallel

There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">Sections</div><hr/></div></code>```

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

答:
Another way..

You can do it using jquery also. ( Since there is no jquery tag in your question, take this as a secondary choice.)

```<code>$("hr").each(function() {
  var abtwidth = $(this).parent().find(".about").width();
  var hrwidth = 300 - abtwidth;
  $(this).css('width',hrwidth);
});
</code>```

FIDDLE

Title: Aligning a text and line parallel

Body:
There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}

Chapter

Learning Objectives

Pages

Sections

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

Body:
Another way..

You can do it using jquery also. ( Since there is no jquery tag in your question, take this as a secondary choice.)

$("hr").each(function() {
  var abtwidth = $(this).parent().find(".about").width();
  var hrwidth = 300 - abtwidth;
  $(this).css('width',hrwidth);
});

FIDDLE


问:
VS 2008 Designer not executing default constructor anymore?
I just tested which type of code is executed by the WinForms Designer in VS 2008.
It seems that the designer is not executing the default constructor anymore.
I added a simple thing like this.Text = "foo"; nothing is changed in the designer.

Did I miss a change between VS 2005/2008? (or SP1)

tia

答:
I placed several statements (setting the background, MessageBox.Show, File.WriteAllText,...) into the constructor including System.Diagnostics.Debugger.Break(), but nothing causes any type of response...

Not to misunderstand me, it is the behavior I'd like to have, but I know I had problems in VS 2005 regarding this issue, and I don't find any info about the fact that there is a change in the Winforms Designer.

Using the .NET reflector I don't see any additional constructors, but maybe the designer is creating one on-demand, ...

OwnerDisplayName: Martin Moser

LastEditorDisplayName: Fabian Steeg