问:
Deserializing complex JSON
I am trying to deserialize this JSON:

```<code>{
  "request": {
    "Target": "Affiliate",
    "Format": "json",
    "Service": "HasOffers",
    "Version": "2",
    "NetworkToken": "NETVTxpCN4QxoWuE6D6SCdh67itLvG",
    "Method": "getSignupAnswers",
    "id": "9820",
    "__lc_visitor_id_1040387": "S1501672650.ef9130f70a",
    "optimizelyEndUserId": "oeu1504526823197r0.9821082007049919",
    "optimizelySegments": "{\"3005961667\":\"campaign\",\"3007971800\":\"gc\",\"3016921538\":\"false\"}",
    "optimizelyBuckets": "{\"8910731217\":\"8900223657\"}",
    "_mkto_trk": "id:210-BFY-977&token:_mch-hasoffers.com-1504526823819-68924",
    "__gaTune": "GA1.2.1953499689.1501744456",
    "_hp2_id_1318563364": "{\"userId\":null,\"pageviewId\":\"5080006815314464\",\"sessionId\":\"3328773167767995\",\"identity\":\"23255-2\",\"trackerVersion\":\"3.0\"}",
    "intercom-session-zrjutp6m": "QXAxQTdza0JnNmVPLzNxZDFXSmFjbUQxRnVxQjArcmNmQWxMZzM4NWpSbWt3VXNzemFydG5oVjZYempaUlg3bS0tR0VrYWcwTGpSY3I4cDdsMFB3TndlUT09--5c9d563a96f41049f2703a3121484e9a299b4148",
    "intercom-lou-zrjutp6m": "1"
  },
  "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "140768": {
        "SignupAnswer": {
          "id": "140768",
          "question_id": "1",
          "responder_type": "affiliate",
          "answer": "Individual \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Affiliate Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140770": {
        "SignupAnswer": {
          "id": "140770",
          "question_id": "3",
          "responder_type": "affiliate",
          "answer": "Rugved Agro",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Organisation Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140772": {
        "SignupAnswer": {
          "id": "140772",
          "question_id": "5",
          "responder_type": "affiliate",
          "answer": "9822288117",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Contact Number ",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140774": {
        "SignupAnswer": {
          "id": "140774",
          "question_id": "7",
          "responder_type": "affiliate",
          "answer": "7972274145",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary Contact Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140776": {
        "SignupAnswer": {
          "id": "140776",
          "question_id": "9",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary E-mail Adress",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140778": {
        "SignupAnswer": {
          "id": "140778",
          "question_id": "11",
          "responder_type": "affiliate",
          "answer": "SACHIN RAMLAL AGALE",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payee Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140780": {
        "SignupAnswer": {
          "id": "140780",
          "question_id": "13",
          "responder_type": "affiliate",
          "answer": "Electronic Fund Transfer \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payment Mode",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140782": {
        "SignupAnswer": {
          "id": "140782",
          "question_id": "15",
          "responder_type": "affiliate",
          "answer": "0480104000105996",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Account Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140784": {
        "SignupAnswer": {
          "id": "140784",
          "question_id": "17",
          "responder_type": "affiliate",
          "answer": "IDBI BANK ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140786": {
        "SignupAnswer": {
          "id": "140786",
          "question_id": "19",
          "responder_type": "affiliate",
          "answer": "IBKL0000480",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "IFSC Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140788": {
        "SignupAnswer": {
          "id": "140788",
          "question_id": "21",
          "responder_type": "affiliate",
          "answer": "431259006",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "MICR Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140790": {
        "SignupAnswer": {
          "id": "140790",
          "question_id": "23",
          "responder_type": "affiliate",
          "answer": "Aurangabad ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank City",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140792": {
        "SignupAnswer": {
          "id": "140792",
          "question_id": "25",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "UPLOAD DOCUMENTS\u00a0(If required For Receiving Payments)",
          "type": "affiliate",
          "status": "deleted"
        }
      },
      "140794": {
        "SignupAnswer": {
          "id": "140794",
          "question_id": "27",
          "responder_type": "affiliate",
          "answer": "rugvedagro.blogspot.in",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website URL",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140796": {
        "SignupAnswer": {
          "id": "140796",
          "question_id": "29",
          "responder_type": "affiliate",
          "answer": "Blog\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140798": {
        "SignupAnswer": {
          "id": "140798",
          "question_id": "31",
          "responder_type": "affiliate",
          "answer": "Btw 1000-10000\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Monthly Visits",
          "type": "affiliate",
          "status": "active"
        }
      }
    },
    "errors": [

    ],
    "errorMessage": null
  }
}
</code>```

The classes I have are as follows:

```<code>public class Request
{
    public string Target { get; set; }
    public string Format { get; set; }
    public string Service { get; set; }
    public string Version { get; set; }
    public string NetworkToken { get; set; }
    public string Method { get; set; }
    public string id { get; set; }
    public string __lc_visitor_id_1040387 { get; set; }
    public string optimizelyEndUserId { get; set; }
    public string optimizelySegments { get; set; }
    public string optimizelyBuckets { get; set; }
    public string _mkto_trk { get; set; }
    public string __gaTune { get; set; }
    public string _hp2_id_1318563364 { get; set; }
    [JsonProperty(PropertyName = "intercom-session-zrjutp6m")]
    public string __invalid_name__intercom_session_zrjutp6m { get; set; }
    [JsonProperty(PropertyName = "intercom-lou-zrjutp6m")]
    public string __invalid_name__intercom_lou_zrjutp6m { get; set; }
}
public class SignupAnswer
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class Data
{
    /* I can't code this class */

}

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Data data { get; set; } //I can't code this class
    public List<object> errors { get; set; }
    public object errorMessage { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
    public Response response { get; set; }
}
</code>```

I have already tried it json2csharp. The problem here is the data under node response -> data is dynamic. So I cannot have a fixed class name

答:
I use the special paste option in Visual Studio:

I get this result:

public class Rootobject
{
    public Request request { get; set; }
    public Response response { get; set; }
}

public class Request
{
    public string Target { get; set; }
    public string Format { get; set; }
    public string Service { get; set; }
    public string Version { get; set; }
    public string NetworkToken { get; set; }
    public string Method { get; set; }
    public string id { get; set; }
    public string __lc_visitor_id_1040387 { get; set; }
    public string optimizelyEndUserId { get; set; }
    public string optimizelySegments { get; set; }
    public string optimizelyBuckets { get; set; }
    public string _mkto_trk { get; set; }
    public string __gaTune { get; set; }
    public string _hp2_id_1318563364 { get; set; }
    public string intercomsessionzrjutp6m { get; set; }
    public string intercomlouzrjutp6m { get; set; }
}

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Data data { get; set; }
    public object[] errors { get; set; }
    public object errorMessage { get; set; }
}

public class Data
{
    public _140768 _140768 { get; set; }
    public _140770 _140770 { get; set; }
    public _140772 _140772 { get; set; }
    public _140774 _140774 { get; set; }
    public _140776 _140776 { get; set; }
    public _140778 _140778 { get; set; }
    public _140780 _140780 { get; set; }
    public _140782 _140782 { get; set; }
    public _140784 _140784 { get; set; }
    public _140786 _140786 { get; set; }
    public _140788 _140788 { get; set; }
    public _140790 _140790 { get; set; }
    public _140792 _140792 { get; set; }
    public _140794 _140794 { get; set; }
    public _140796 _140796 { get; set; }
    public _140798 _140798 { get; set; }
}

public class _140768
{
    public Signupanswer SignupAnswer { get; set; }
}

public class Signupanswer
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140770
{
    public Signupanswer1 SignupAnswer { get; set; }
}

public class Signupanswer1
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140772
{
    public Signupanswer2 SignupAnswer { get; set; }
}

public class Signupanswer2
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140774
{
    public Signupanswer3 SignupAnswer { get; set; }
}

public class Signupanswer3
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140776
{
    public Signupanswer4 SignupAnswer { get; set; }
}

public class Signupanswer4
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140778
{
    public Signupanswer5 SignupAnswer { get; set; }
}

public class Signupanswer5
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140780
{
    public Signupanswer6 SignupAnswer { get; set; }
}

public class Signupanswer6
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140782
{
    public Signupanswer7 SignupAnswer { get; set; }
}

public class Signupanswer7
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140784
{
    public Signupanswer8 SignupAnswer { get; set; }
}

public class Signupanswer8
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140786
{
    public Signupanswer9 SignupAnswer { get; set; }
}

public class Signupanswer9
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140788
{
    public Signupanswer10 SignupAnswer { get; set; }
}

public class Signupanswer10
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140790
{
    public Signupanswer11 SignupAnswer { get; set; }
}

public class Signupanswer11
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140792
{
    public Signupanswer12 SignupAnswer { get; set; }
}

public class Signupanswer12
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140794
{
    public Signupanswer13 SignupAnswer { get; set; }
}

public class Signupanswer13
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140796
{
    public Signupanswer14 SignupAnswer { get; set; }
}

public class Signupanswer14
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class _140798
{
    public Signupanswer15 SignupAnswer { get; set; }
}

public class Signupanswer15
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}
```

Title: Deserializing complex JSON

Body:
I am trying to deserialize this JSON:

{
  "request": {
    "Target": "Affiliate",
    "Format": "json",
    "Service": "HasOffers",
    "Version": "2",
    "NetworkToken": "NETVTxpCN4QxoWuE6D6SCdh67itLvG",
    "Method": "getSignupAnswers",
    "id": "9820",
    "__lc_visitor_id_1040387": "S1501672650.ef9130f70a",
    "optimizelyEndUserId": "oeu1504526823197r0.9821082007049919",
    "optimizelySegments": "{\"3005961667\":\"campaign\",\"3007971800\":\"gc\",\"3016921538\":\"false\"}",
    "optimizelyBuckets": "{\"8910731217\":\"8900223657\"}",
    "_mkto_trk": "id:210-BFY-977&token:_mch-hasoffers.com-1504526823819-68924",
    "__gaTune": "GA1.2.1953499689.1501744456",
    "_hp2_id_1318563364": "{\"userId\":null,\"pageviewId\":\"5080006815314464\",\"sessionId\":\"3328773167767995\",\"identity\":\"23255-2\",\"trackerVersion\":\"3.0\"}",
    "intercom-session-zrjutp6m": "QXAxQTdza0JnNmVPLzNxZDFXSmFjbUQxRnVxQjArcmNmQWxMZzM4NWpSbWt3VXNzemFydG5oVjZYempaUlg3bS0tR0VrYWcwTGpSY3I4cDdsMFB3TndlUT09--5c9d563a96f41049f2703a3121484e9a299b4148",
    "intercom-lou-zrjutp6m": "1"
  },
  "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "140768": {
        "SignupAnswer": {
          "id": "140768",
          "question_id": "1",
          "responder_type": "affiliate",
          "answer": "Individual \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Affiliate Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140770": {
        "SignupAnswer": {
          "id": "140770",
          "question_id": "3",
          "responder_type": "affiliate",
          "answer": "Rugved Agro",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Organisation Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140772": {
        "SignupAnswer": {
          "id": "140772",
          "question_id": "5",
          "responder_type": "affiliate",
          "answer": "9822288117",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Contact Number ",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140774": {
        "SignupAnswer": {
          "id": "140774",
          "question_id": "7",
          "responder_type": "affiliate",
          "answer": "7972274145",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary Contact Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140776": {
        "SignupAnswer": {
          "id": "140776",
          "question_id": "9",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary E-mail Adress",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140778": {
        "SignupAnswer": {
          "id": "140778",
          "question_id": "11",
          "responder_type": "affiliate",
          "answer": "SACHIN RAMLAL AGALE",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payee Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140780": {
        "SignupAnswer": {
          "id": "140780",
          "question_id": "13",
          "responder_type": "affiliate",
          "answer": "Electronic Fund Transfer \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payment Mode",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140782": {
        "SignupAnswer": {
          "id": "140782",
          "question_id": "15",
          "responder_type": "affiliate",
          "answer": "0480104000105996",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Account Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140784": {
        "SignupAnswer": {
          "id": "140784",
          "question_id": "17",
          "responder_type": "affiliate",
          "answer": "IDBI BANK ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140786": {
        "SignupAnswer": {
          "id": "140786",
          "question_id": "19",
          "responder_type": "affiliate",
          "answer": "IBKL0000480",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "IFSC Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140788": {
        "SignupAnswer": {
          "id": "140788",
          "question_id": "21",
          "responder_type": "affiliate",
          "answer": "431259006",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "MICR Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140790": {
        "SignupAnswer": {
          "id": "140790",
          "question_id": "23",
          "responder_type": "affiliate",
          "answer": "Aurangabad ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank City",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140792": {
        "SignupAnswer": {
          "id": "140792",
          "question_id": "25",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "UPLOAD DOCUMENTS\u00a0(If required For Receiving Payments)",
          "type": "affiliate",
          "status": "deleted"
        }
      },
      "140794": {
        "SignupAnswer": {
          "id": "140794",
          "question_id": "27",
          "responder_type": "affiliate",
          "answer": "rugvedagro.blogspot.in",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website URL",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140796": {
        "SignupAnswer": {
          "id": "140796",
          "question_id": "29",
          "responder_type": "affiliate",
          "answer": "Blog\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140798": {
        "SignupAnswer": {
          "id": "140798",
          "question_id": "31",
          "responder_type": "affiliate",
          "answer": "Btw 1000-10000\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Monthly Visits",
          "type": "affiliate",
          "status": "active"
        }
      }
    },
    "errors": [

    ],
    "errorMessage": null
  }
}

The classes I have are as follows:

public class Request
{
    public string Target { get; set; }
    public string Format { get; set; }
    public string Service { get; set; }
    public string Version { get; set; }
    public string NetworkToken { get; set; }
    public string Method { get; set; }
    public string id { get; set; }
    public string __lc_visitor_id_1040387 { get; set; }
    public string optimizelyEndUserId { get; set; }
    public string optimizelySegments { get; set; }
    public string optimizelyBuckets { get; set; }
    public string _mkto_trk { get; set; }
    public string __gaTune { get; set; }
    public string _hp2_id_1318563364 { get; set; }
    [JsonProperty(PropertyName = "intercom-session-zrjutp6m")]
    public string __invalid_name__intercom_session_zrjutp6m { get; set; }
    [JsonProperty(PropertyName = "intercom-lou-zrjutp6m")]
    public string __invalid_name__intercom_lou_zrjutp6m { get; set; }
}
public class SignupAnswer
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class Data
{
    /* I can't code this class */

}

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Data data { get; set; } //I can't code this class
    public List<object> errors { get; set; }
    public object errorMessage { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
    public Response response { get; set; }
}

I have already tried it json2csharp. The problem here is the data under node response -> data is dynamic. So I cannot have a fixed class name


来源: stackexchange

问:
How to properly import RxJS by patching?
I have an Angular project and I need to use Observables from RxJS with a few selection of operators.

This is what the documentation says:

To import only what you need by patching (this is useful for size-sensitive bundling):

```<code>import { Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

Observable.of(1,2,3).map(x => x + '!!!'); // etc
</code>```

And this is what I'm doing in my app component:

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private testObservable: Observable<string> = Observable.of(1,2,3).map(x => x + '!!!');

  constructor() { }

  ngOnInit() {

    this.testObservable.subscribe((str: string) => {

      console.log(str);

    });

  }

}
</code>```

This is where I get confused. When I delete the second and third import (of and map), the Observable's operators still work!

I was under the impression that using the import 'rxjs/add/operator/*'; would only add the operators I need and skip importing the rest of them. However, I can see that all the operators (static and instance) are members of the Observable class and get imported through the first import statement.

My questions are:

How can I properly import only the parts I need and exclude the rest?

What's the point of using import 'rxjs/add/operator/*'; if all operators are already a member of the Observable class?

答:
You're importing map somewhere else, too, not just in your component. Try not importing something exotic, say, bufferToggle. It will throw error. Map is imported and patched all over, perhaps even from Angular itself.

So, importing specific operators still makes sense. import * would suck, but import just map reduces your bundle size.

ContentLicense: CC BY-SA 3.0

Body:
I have an Angular project and I need to use Observables from RxJS with a few selection of operators.

This is what the documentation says:

To import only what you need by patching (this is useful for size-sensitive bundling):

import { Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

Observable.of(1,2,3).map(x => x + '!!!'); // etc

And this is what I'm doing in my app component:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private testObservable: Observable<string> = Observable.of(1,2,3).map(x => x + '!!!');

  constructor() { }

  ngOnInit() {

    this.testObservable.subscribe((str: string) => {

      console.log(str);

    });

  }

}

This is where I get confused. When I delete the second and third import (of and map), the Observable's operators still work!

I was under the impression that using the import 'rxjs/add/operator/*'; would only add the operators I need and skip importing the rest of them. However, I can see that all the operators (static and instance) are members of the Observable class and get imported through the first import statement.

My questions are:

How can I properly import only the parts I need and exclude the rest?

What's the point of using import 'rxjs/add/operator/*'; if all operators are already a member of the Observable class?


问:
Custom view with button like behavior on click/touch
I have created a custom View which I usually attach an onClickListener to. I'd like to have some button like behavior: if it is pressed, it should alter its appearance which is defined in the onDraw() method. However, this code does not work:

```<code>//In my custom View:

@Override
protected void onDraw(Canvas canvas)
{

    boolean pressed = isPressed();
    //draw depending on the value of pressed
}

//when creating the view:
MyView.setClickable(true);
</code>```

pressed always has the value false. What's wrong?

Thanks a lot!

答:
Your fault is you are not implementing click or touch event for your custom view. There is no click event for view. You can use touch event instead, so below code should work for you:

```<code>myView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:

    break;
    case MotionEvent.ACTION_UP:

    break;
    case MotionEvent.ACTION_MOVE:

    break;
    }

    return true;
}

});
</code>```

In this code use action_up for click and it will work for you.

ContentLicense: CC BY-SA 2.5

Body:
I have created a custom View which I usually attach an onClickListener to. I'd like to have some button like behavior: if it is pressed, it should alter its appearance which is defined in the onDraw() method. However, this code does not work:

//In my custom View:

@Override
protected void onDraw(Canvas canvas)
{

    boolean pressed = isPressed();
    //draw depending on the value of pressed
}

//when creating the view:
MyView.setClickable(true);

pressed always has the value false. What's wrong?

Thanks a lot!

Body:
Your fault is you are not implementing click or touch event for your custom view. There is no click event for view. You can use touch event instead, so below code should work for you:

myView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:

    break;
    case MotionEvent.ACTION_UP:

    break;
    case MotionEvent.ACTION_MOVE:

    break;
    }

    return true;
}

});

In this code use action_up for click and it will work for you.

ContentLicense: CC BY-SA 4.0


问:
Where set name of fields in belongsToMany?
I have three models: Post, List and PostList (Pivot).
I DB I have three tables: post (post_id, ...), list(list_id, ...), post_list(post_id, glist_id(In fact it's id of list)).

I have such code:

Post -

```<code>public function list()
{
    return $this->belongsToMany(List::class, 'post_list');
}
</code>```

List -

```<code>public function stories()

{
    return $this->belongsToMany(Post::class, 'post_list');
}
</code>```

PostList

```<code>   public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function list()
    {
        return $this->belongsTo(list::class);
    }
</code>```

With such code Laravel try find glist_id in PostList.

In which part of relations I must set that column in table PostList not default list_id, but glist_id?

答:
Per the documentation:

The third argument is the foreign key name of the model on which you
  are defining the relationship, while the fourth argument is the
  foreign key name of the model that you are joining to.

So in your case, this would be:

```<code>public function list()
{
    return $this->belongsToMany(List::class, 'post_list', 'post_id', 'glist_id');
}

public function stories()
{
    return $this->belongsToMany(Post::class, 'post_list', 'glist_id', 'post_id');
}
</code>```

Body:
I have three models: Post, List and PostList (Pivot).
I DB I have three tables: post (post_id, ...), list(list_id, ...), post_list(post_id, glist_id(In fact it's id of list)).

I have such code:

Post -

public function list()
{
    return $this->belongsToMany(List::class, 'post_list');
}

List -

public function stories()

{
    return $this->belongsToMany(Post::class, 'post_list');
}

PostList

   public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function list()
    {
        return $this->belongsTo(list::class);
    }

With such code Laravel try find glist_id in PostList.

In which part of relations I must set that column in table PostList not default list_id, but glist_id?

Body:
Per the documentation:

The third argument is the foreign key name of the model on which you
  are defining the relationship, while the fourth argument is the
  foreign key name of the model that you are joining to.

So in your case, this would be:

public function list()
{
    return $this->belongsToMany(List::class, 'post_list', 'post_id', 'glist_id');
}

public function stories()
{
    return $this->belongsToMany(Post::class, 'post_list', 'glist_id', 'post_id');
}


问:
Kotlin Intent error
I have the following code and am getting an error with the Intent. It is because of the this I am fairly certain.

```<code>listView.onItemClickListener = object : OnItemClickListener {
            override
            fun onItemClick(parent: AdapterView<*>, view: View,
                            position: Int, id: Long) {
                val intent = Intent(this, MyActivity::class.java)
                startActivity(intent)
            }

        }
</code>```

答: Yes you can change it to getappicationcontext or declare global context and assign this to context.</p>

Title: Kotlin Intent error

Body:
I have the following code and am getting an error with the Intent. It is because of the this I am fairly certain.

listView.onItemClickListener = object : OnItemClickListener {
            override
            fun onItemClick(parent: AdapterView<*>, view: View,
                            position: Int, id: Long) {
                val intent = Intent(this, MyActivity::class.java)
                startActivity(intent)
            }

        }


问:
Angular 4 HttpModule How to Return a File From Get Request
I have a REST API that if I query directly in the browser, it returns a JSON or CSV file to download. I want to do the same thing with the Angular HttpModule.

My get request is simple (it has a query string param to indicate which file format to return):

```<code>public Submit(request: Request) {
  ...
  return this.http.get(url).subscribe(response => {
    //What here
  });
}
</code>```

The response content-type is application/octet-stream. I've tried processing the response as a blob, which doesn't work. How can I just pass through the response from the server to the browser and let it download the file? This method is part of a service that is being called by a component that is responding to a button click

```<code>onClick() {
    this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}
</code>```

答:
You have to add

```<code>{ responseType: ResponseContentType.Blob }
</code>```

and then map response to blob.

```<code>return this.http.get(url, { responseType: ResponseContentType.Blob })
    .map(r => r.blob())
    .subscribe(response => {

    });
</code>```

Next you can download this file using fileSaver.js.

Body:
I have a REST API that if I query directly in the browser, it returns a JSON or CSV file to download. I want to do the same thing with the Angular HttpModule.

My get request is simple (it has a query string param to indicate which file format to return):

public Submit(request: Request) {
  ...
  return this.http.get(url).subscribe(response => {
    //What here
  });
}

The response content-type is application/octet-stream. I've tried processing the response as a blob, which doesn't work. How can I just pass through the response from the server to the browser and let it download the file? This method is part of a service that is being called by a component that is responding to a button click

onClick() {
    this._requestService.Submit(request); //This gets the Subscription response from the service, but I want it to let the broswer download the file
}

Body:
You have to add

{ responseType: ResponseContentType.Blob }

and then map response to blob.

return this.http.get(url, { responseType: ResponseContentType.Blob })
    .map(r => r.blob())
    .subscribe(response => {

    });

Next you can download this file using fileSaver.js.


问:
Prime number function in R
I am trying to create a function to test if a given integer is a prime number, I tried using the following:

```<code>tpn <- function(prime.num){

    if(prime.num==2){
        print("PRIME")
    } else {

    if(prime.num%%(2:(prime.num-1))!=0){
        print("PRIME")

    } else {
        print("NOT PRIME")

}}}
</code>```

This doesn't work, although I cant understand why. I am checking to see if the given number can be divided by any of the integers up to this number with no remainders. If it cant, then the number is prime.

Another solution I found was:

```<code>tpn <- function(pn){

    if(sum(pn/1:pn==pn%/%1:pn)==2)
            print("prime")

}
</code>```

This works. Although, I cant get my head around what sum(pn/1:pn == pn%/%1:pn) == 2 is actually testing for.

答:
Here is one more method to find prime number using simple concept</p>

```<code>is.prime <- function(n){
 if (n == 2){  # finds the square root of number and assign to var 'i'
  print('number is prime')
 }
 else if (n > 2){
 i <- sqrt(n)   # finds the square root of number and assign to var 'i'
 i <- round(i, digits = 1) # if square root generates decimals, round it to one place
 vec <- c(2:i) #creating vector to load numbers from 2 to 'i'
 d <- n %% (vec) #dividing each number generated by vector by the input number 'n'
 if ( 0 %in% d){ # check to see if any of the result of division is 0
  print('number is not prime') #if any of the result of division is 0, number is not prime
 }
 else{
   print('number is prime')
 }
 }
}

is.prime(2)
[1] "number is prime"

is.prime(131) #calling the function with the desired number
[1] "number is prime"

is.prime(237)
[1] "number is not prime"
</code>```

Title: Prime number function in R

Body:
I am trying to create a function to test if a given integer is a prime number, I tried using the following:

tpn <- function(prime.num){

    if(prime.num==2){
        print("PRIME")
    } else {

    if(prime.num%%(2:(prime.num-1))!=0){
        print("PRIME")

    } else {
        print("NOT PRIME")

}}}

This doesn't work, although I cant understand why. I am checking to see if the given number can be divided by any of the integers up to this number with no remainders. If it cant, then the number is prime.

Another solution I found was:

tpn <- function(pn){

    if(sum(pn/1:pn==pn%/%1:pn)==2)
            print("prime")

}

This works. Although, I cant get my head around what sum(pn/1:pn == pn%/%1:pn) == 2 is actually testing for.

Body:
Here is one more method to find prime number using simple concept

is.prime <- function(n){
 if (n == 2){  # finds the square root of number and assign to var 'i'
  print('number is prime')
 }
 else if (n > 2){
 i <- sqrt(n)   # finds the square root of number and assign to var 'i'
 i <- round(i, digits = 1) # if square root generates decimals, round it to one place
 vec <- c(2:i) #creating vector to load numbers from 2 to 'i'
 d <- n %% (vec) #dividing each number generated by vector by the input number 'n'
 if ( 0 %in% d){ # check to see if any of the result of division is 0
  print('number is not prime') #if any of the result of division is 0, number is not prime
 }
 else{
   print('number is prime')
 }
 }
}

is.prime(2)
[1] "number is prime"

is.prime(131) #calling the function with the desired number
[1] "number is prime"

is.prime(237)
[1] "number is not prime"


问:
Laravel - Unable to Dump Query Result
I want to get the result of query just like on this example.

I have tried like the example given but I did not get any output. May I know what I am doing wrong?

Below are the example:

AppServiceProvider.php

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use DB;
use Event;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (env('APP_ENV') === 'local') {
            DB::connection()->enableQueryLog();
            Event::listen('kernel.handled', function ($request, $response) {
                if ($request->has('sql-debug')) {
                    $queries = DB::getQueryLog();
                    dd($queries);
                }
            });
        }

        Schema::defaultStringLength(191);
    }
}
</code>```

SeasonRecord.php

```<code>public function index()
{
    $cars = User::where('id', 3)
    ->get();

    // return view('seasonRecord', compact('cars'));
}
</code>```

Web.php

```<code>Route::get('/record', 'SeasonRecord@index');
</code>```

On my .env file the APP_ENV is set to local

For the url I wrote http://127.0.0.1:8000/record?sql-debug=1 but no result is shown.

答:
No more kernel.handled from Laravel version 5.4. Change set

Please try below code

```<code>...
Event::listen(\Illuminate\Foundation\Http\Events\RequestHandled::class, function ($event) {
    if ($event->request->has('sql-debug')) {
        $queries = DB::getQueryLog();
        dd($queries);
    }
});
...
</code>```

Title: Laravel - Unable to Dump Query Result

Body:
I want to get the result of query just like on this example.

I have tried like the example given but I did not get any output. May I know what I am doing wrong?

Below are the example:

AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use DB;
use Event;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (env('APP_ENV') === 'local') {
            DB::connection()->enableQueryLog();
            Event::listen('kernel.handled', function ($request, $response) {
                if ($request->has('sql-debug')) {
                    $queries = DB::getQueryLog();
                    dd($queries);
                }
            });
        }

        Schema::defaultStringLength(191);
    }
}

SeasonRecord.php

public function index()
{
    $cars = User::where('id', 3)
    ->get();

    // return view('seasonRecord', compact('cars'));
}

Web.php

Route::get('/record', 'SeasonRecord@index');

On my .env file the APP_ENV is set to local

For the url I wrote http://127.0.0.1:8000/record?sql-debug=1 but no result is shown.

Body:
No more kernel.handled from Laravel version 5.4. Change set

Please try below code

...
Event::listen(\Illuminate\Foundation\Http\Events\RequestHandled::class, function ($event) {
    if ($event->request->has('sql-debug')) {
        $queries = DB::getQueryLog();
        dd($queries);
    }
});
...


问:
child node is treated as grand child node when trying to structure
I am using django-mptt library for the category. I could show the list of categories in template but I wanted to indent it properly so user can know which is a main category and which one is sub-category and etc. The way i tried to structure is

```<code>{% recursetree nodes %}
  <li class="node">
    <a href="/category/{{ node.get_absolute_url }}"
      class="{% if not node.is_leaf_node and not node.is_root_node and node.is_child_node %} child_parent {% elif node.is_leaf_node and not node.is_root_node %}leaf_node{% endif %}">
      {{ node.name }}
      {% if node.is_root_node %}
        <span class="badge">{{ node.get_count_children }}</span>
      {% endif %}
    </a>
      {% if not node.is_leaf_node %}
          <ul class="children">
            <li>{{ children }}</li>
          </ul>
      {% endif %}
  </li>
{% endrecursetree %}
</code>```

This yields the following design of category

Here Dressing Table is a child of Bedroom Items like Bed and Almirah not a child of Bed. How could i fix this? I know the problem is here

```<code><a href="/category/{{ node.get_absolute_url }}"
class="{% if not node.is_leaf_node and not node.is_root_node and node.is_child_node %} child_parent {% elif node.is_leaf_node and not node.is_root_node %}leaf_node{% endif %}">
</code>```

but could not fix this issue

Not the dressing table in the screenshot

答:
According to you updated answer.

Dinning Set, Kitchen Rack, and Kitchen Setup(Modular Kitchen) are supposed to be cyan since they are second level.
If my understanding is correct.

Here is my hacked solution. If anybody found the better one please raise.

Add extra method to the Model instance

I have to add nodes to the context. (This would be an optional if you are using Django2.0 like mine)

Use the instance method in the template

models.py

```<code>from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True,
                            on_delete=models.CASCADE)

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return f'{self.name}'

    def is_second_node(self):
        return True if (self.get_ancestors().count() == 1) else False
</code>```

views.py

```<code>from django.views.generic import ListView

from genres.models import Genre

class GenreListView(ListView):
    model = Genre
    template_name = 'genre_list.html'

    def get_context_data(self, *, object_list=None, **kwargs):
        """Get the context for this view."""
        queryset = object_list if object_list is not None else self.object_list
        page_size = self.get_paginate_by(queryset)
        context_object_name = self.get_context_object_name(queryset)
        if page_size:
            paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
            context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
            }
        else:
            context = {
                'paginator': None,
                'page_obj': None,
                'is_paginated': False,
                'object_list': queryset
            }
        if context_object_name is not None:
            context[context_object_name] = queryset
        context.update(kwargs)
        context['nodes'] = context.get('object_list')
        return super().get_context_data(**context)
</code>```

genre_list.html

```<code><!DOCTYPE html>
{% load mptt_tags %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Genre ListView</title>
</head>
<style>
    .root {color: purple}
    .child{color: cyan}
    .leaf {color: gray}
</style>
<body>
    {% recursetree nodes %}
    <div class="
        {% if node.is_root_node %}
        root
        {% elif node.is_child_node and not node.is_leaf_node or node.is_second_node%}
        child
        {% elif node.is_leaf_node and not node.is_root_node%}
        leaf
        {%endif%}">
        {{node.name}}
        {{node.is_second_node}}
    </div>
    {% if not node.is_leaf_node%}
    <ul>{{children}}</ul>
    {% endif %}

    {% endrecursetree %}
</ul>
</body>
</html>
</code>```

Body:
I am using django-mptt library for the category. I could show the list of categories in template but I wanted to indent it properly so user can know which is a main category and which one is sub-category and etc. The way i tried to structure is

{% recursetree nodes %}

      {{ node.name }}
      {% if node.is_root_node %}
        {{ node.get_count_children }}
      {% endif %}

      {% if not node.is_leaf_node %}

{{ children }}

      {% endif %}

{% endrecursetree %}

This yields the following design of category

Here Dressing Table is a child of Bedroom Items like Bed and Almirah not a child of Bed. How could i fix this? I know the problem is here

but could not fix this issue

Not the dressing table in the screenshot

Body:
According to you updated answer.

Dinning Set, Kitchen Rack, and Kitchen Setup(Modular Kitchen) are supposed to be cyan since they are second level.
If my understanding is correct.

Here is my hacked solution. If anybody found the better one please raise.

Add extra method to the Model instance

I have to add nodes to the context. (This would be an optional if you are using Django2.0 like mine)

Use the instance method in the template

models.py

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True,
                            on_delete=models.CASCADE)

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return f'{self.name}'

    def is_second_node(self):
        return True if (self.get_ancestors().count() == 1) else False

views.py

from django.views.generic import ListView

from genres.models import Genre

class GenreListView(ListView):
    model = Genre
    template_name = 'genre_list.html'

    def get_context_data(self, *, object_list=None, **kwargs):
        """Get the context for this view."""
        queryset = object_list if object_list is not None else self.object_list
        page_size = self.get_paginate_by(queryset)
        context_object_name = self.get_context_object_name(queryset)
        if page_size:
            paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
            context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
            }
        else:
            context = {
                'paginator': None,
                'page_obj': None,
                'is_paginated': False,
                'object_list': queryset
            }
        if context_object_name is not None:
            context[context_object_name] = queryset
        context.update(kwargs)
        context['nodes'] = context.get('object_list')
        return super().get_context_data(**context)

genre_list.html

<!DOCTYPE html>
{% load mptt_tags %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Genre ListView</title>
</head>
<style>
    .root {color: purple}
    .child{color: cyan}
    .leaf {color: gray}
</style>
<body>
    {% recursetree nodes %}
    <div class="
        {% if node.is_root_node %}
        root
        {% elif node.is_child_node and not node.is_leaf_node or node.is_second_node%}
        child
        {% elif node.is_leaf_node and not node.is_root_node%}
        leaf
        {%endif%}">
        {{node.name}}
        {{node.is_second_node}}
    </div>
    {% if not node.is_leaf_node%}
    <ul>{{children}}</ul>
    {% endif %}

    {% endrecursetree %}
</ul>
</body>
</html>


问:
NLP: Qualitatively "positive" vs "negative" sentence
I need your help in determining the best approach for analyzing industry-specific sentences (i.e. movie reviews) for "positive" vs "negative". I've seen libraries such as OpenNLP before, but it's too low-level - it just gives me the basic sentence composition; what I need is a higher-level structure:
- hopefully with wordlists
- hopefully trainable on my set of data

Thanks!

答:
Some approaches to sentiment analysis use strategies popular on other text classification tasks. The most common being transforming your film review into a word vector, and feeding it into a classifier algorithm as training data. Most popular data mining packages can help you here. You could have a look at this tutorial on sentiment classification illustrating how to do an experiment using the open source RapidMiner toolkit.

Incidentally, there is a good data set made available for research purposes related to detecting opinion on film reviews. It is based on IMDB user reviews, and you can check many related research work on the area and how they use the data set.

Its worth bearing in mind that the effectiveness of these methods can only be judged from a statistical viewpoint, so you can pretty much assume there will be misclassifications and cases where opinion is hard to detect. As already noticed in this thread, detecting things like irony and sarcasm can be very difficult indeed.

OwnerDisplayName: Alex

OwnerDisplayName: Bohana


问:
Excel - comparing a single value to splits/totals for that value
I have a sheet that tracks deliveries of a material in 30,000-40,000lb values.  On a "Delivered amounts" tab, I have:

```<code>Ticket 12345:  41250
Ticket 23456:  42200
Ticket 34567:  43000
</code>```

On a separate tab, I say whether or not these entries have been billed and
they may be split up.  So we may see Ticket 34567 used twice, with values of 21500 and 21500.

I'm wrestling with how to go about comparing all of these split entries to the original total.  If a table contains

```<code>Ticket 23456:  21100
Ticket 23456:  21100
Ticket 34567:  21500
Ticket 34567:  21500
Ticket 34567:  10000
</code>```

Then it would look up each ticket entry, sum up the values and give a response of "Ticket 23456 matches the total and has been properly billed" and "Ticket 34567 has been over-billed, please recheck your figures."   Not with that specific text, but just a way to compare the split and totaled amounts to what the original value should be.

答:
Create a pivot table from the data in the split table and then use a formula to compare with the original values.

Change the formula in D3 to something like

```<code>=IF(SUMIFS(J:J,I:I,B3)<C3,"underpaid","overpaid")
</code>```

Edit: second thought: this can be done totally without the pivot table. Use the formula

```<code>=IF(SUMIFS(G:G,F:F,B3)<C3,"underpaid","overpaid")
</code>```

Body:
I have a sheet that tracks deliveries of a material in 30,000-40,000lb values.  On a "Delivered amounts" tab, I have:

Ticket 12345:  41250
Ticket 23456:  42200
Ticket 34567:  43000

On a separate tab, I say whether or not these entries have been billed and
they may be split up.  So we may see Ticket 34567 used twice, with values of 21500 and 21500.

I'm wrestling with how to go about comparing all of these split entries to the original total.  If a table contains

Ticket 23456:  21100
Ticket 23456:  21100
Ticket 34567:  21500
Ticket 34567:  21500
Ticket 34567:  10000

Then it would look up each ticket entry, sum up the values and give a response of "Ticket 23456 matches the total and has been properly billed" and "Ticket 34567 has been over-billed, please recheck your figures."   Not with that specific text, but just a way to compare the split and totaled amounts to what the original value should be.

Body:
Create a pivot table from the data in the split table and then use a formula to compare with the original values.

Change the formula in D3 to something like

=IF(SUMIFS(J:J,I:I,B3)<C3,"underpaid","overpaid")

Edit: second thought: this can be done totally without the pivot table. Use the formula

=IF(SUMIFS(G:G,F:F,B3)<C3,"underpaid","overpaid")


问:
How to pass in my meat, rice and beans value, from my Burrito class to the meat class, rice class, and beans class respectively?
I have four classes, I am trying to pass in my meat value, rice value and beans value to their respective classes, and return their value through the Burrito class. I have battled with this for two days but no visible progress, any idea on what to do, apologies for any grammatical error. Below is the first three classes, According to the instructions given am not suppose to touch any line in the first three classes, all my code modifications should be in the Burrito class.

```<code>class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False
</code>```

Here is the class were am suppose to pass in value from and return value from as well.

```<code>class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)

    def set_meat(self, meat):
        self.set_value(meat)

    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False

    def set_rice(self, rice):
        self.set_value(rice)

    def set_beans(self, beans):
        self.set_value(beans)

    def get_meat(self):
        self.meat_v = Meat()
        return self.meat_v.value

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        self.rice_v = Rice()
        return self.rice_v.value

    def get_beans(self):
        self.beans_v = Beans()
        return self.beans_v.value
</code>```

Here is the line am using to test my code:

```<code>newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)
</code>```

This is the error line am getting:

```<code><__main__.Meat object at 0x7fa5ad8bccf8>
</code>```

Am expecting it to print

```<code>pork
</code>```

答:
Thanks everyone for the effort i appreciate all the pointers i got from your codes. @BoarGules thanks for pointing me to a whole new idea in python as am a beginner. I will research further into python properties and see what arsenal it adds to my tool kit for future challenges. I ended up writing the working code by drawing inspiration from everyone here. First of all the first three classes which is not meant to be touched:

```<code>class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False
</code>```

My working Burrito class:

```<code>class Burrito:
    def __init__ (self, meat, to_go, rice, beans, extra_meat = False, guacamole = False, cheese = False, pico = False, corn = False):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)
        self.set_extra_meat(extra_meat)
        self.set_guacamole(guacamole)
        self.set_cheese(cheese)
        self.set_pico(pico)
        self.set_corn(corn)
    def set_meat(self, meat):
        self.meat.set_value(meat)
    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False
    def set_rice(self, rice):
        self.rice.set_value(rice)
    def set_beans(self, beans):
        self.beans.set_value(beans)
    def set_extra_meat(self, extra_meat):
        extra_meat_list = [True, False]
        if extra_meat in extra_meat_list:
            self.extra_meat = extra_meat
        else:
            self.extra_meat = False
    def set_guacamole(self, guacamole):
        guacamole_list = [True, False]
        if guacamole in guacamole_list:
            self.guacamole = guacamole
        else:
            self.guacamole = False
    def set_cheese(self, cheese):
        cheese_list = [True, False]
        if cheese in cheese_list:
            self.cheese = cheese
        else:
            self.cheese = False
    def set_pico(self, pico):
        pico_list = [True, False]
        if pico in pico_list:
            self.pico = pico
        else:
            self.pico = False
    def set_corn(self, corn):
        corn_list = [True, False]
        if corn in corn_list:
            self.corn = corn
        else:
            self.corn = False

    def get_cost(self):
        cost = 5
        if self.meat.get_value() == "chicken" or self.meat.get_value() == "pork" or self.meat.get_value() == "tofu":
            cost += 1
        if self.meat.get_value() == "steak":
            cost += 1.50
        if self.extra_meat == True and not self.meat.get_value() == False:
            cost += 1
        if self.guacamole == True:
            cost += 0.75
        return cost

    def get_meat(self):
        return self.meat.get_value()

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        return self.rice.get_value()

    def get_beans(self):
        return self.beans.get_value()

    def get_extra_meat(self):
        return self.extra_meat

    def get_guacamole(self):
        return self.guacamole

    def get_cheese(self):
        return self.cheese

    def get_pico(self):
        return self.pico

    def get_corn(self):
        return self.corn
</code>```

To get the meat, rice and beans instance of the Burrito class to communicate with the three classes above, I need to call their class getters and setters into the Burrito class getters and setters. Example to send a meat instance from Burrito class to Meat class i simply write my setter for the meat method in Burrito like this:

```<code>def set_meat(self, meat):
        self.meat.set_value(meat)
</code>```

As seen in Burrito class above. Same applies to beans and rice.

Now to call values back from them, i simply call their respective class getters into my Burrito class getters. Example using the meat once more:

```<code>def get_meat(self):
        return self.meat.get_value()
</code>```

Same applies to the rice and the beans class as seen in the Burrito class above:

For  the curious minds, this is a little way of testing it :

```<code>newburrito = Burrito("pork", True, "brown", "pinto", True, True)
print (newburrito.meat.get_value())
</code>```

Thanks once more and apologies for any grammatical error. I hope my explanations were clear enough.
Note please i decided to post my entire code for clarity as against the select code i posted when i was asking my question.

Body:
I have four classes, I am trying to pass in my meat value, rice value and beans value to their respective classes, and return their value through the Burrito class. I have battled with this for two days but no visible progress, any idea on what to do, apologies for any grammatical error. Below is the first three classes, According to the instructions given am not suppose to touch any line in the first three classes, all my code modifications should be in the Burrito class.

class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False

Here is the class were am suppose to pass in value from and return value from as well.

class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)

    def set_meat(self, meat):
        self.set_value(meat)

    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False

    def set_rice(self, rice):
        self.set_value(rice)

    def set_beans(self, beans):
        self.set_value(beans)

    def get_meat(self):
        self.meat_v = Meat()
        return self.meat_v.value

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        self.rice_v = Rice()
        return self.rice_v.value

    def get_beans(self):
        self.beans_v = Beans()
        return self.beans_v.value

Here is the line am using to test my code:

newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)

This is the error line am getting:

<__main__.Meat object at 0x7fa5ad8bccf8>

Am expecting it to print

pork

Body:
Thanks everyone for the effort i appreciate all the pointers i got from your codes. @BoarGules thanks for pointing me to a whole new idea in python as am a beginner. I will research further into python properties and see what arsenal it adds to my tool kit for future challenges. I ended up writing the working code by drawing inspiration from everyone here. First of all the first three classes which is not meant to be touched:

class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False

My working Burrito class:

class Burrito:
    def __init__ (self, meat, to_go, rice, beans, extra_meat = False, guacamole = False, cheese = False, pico = False, corn = False):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)
        self.set_extra_meat(extra_meat)
        self.set_guacamole(guacamole)
        self.set_cheese(cheese)
        self.set_pico(pico)
        self.set_corn(corn)
    def set_meat(self, meat):
        self.meat.set_value(meat)
    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False
    def set_rice(self, rice):
        self.rice.set_value(rice)
    def set_beans(self, beans):
        self.beans.set_value(beans)
    def set_extra_meat(self, extra_meat):
        extra_meat_list = [True, False]
        if extra_meat in extra_meat_list:
            self.extra_meat = extra_meat
        else:
            self.extra_meat = False
    def set_guacamole(self, guacamole):
        guacamole_list = [True, False]
        if guacamole in guacamole_list:
            self.guacamole = guacamole
        else:
            self.guacamole = False
    def set_cheese(self, cheese):
        cheese_list = [True, False]
        if cheese in cheese_list:
            self.cheese = cheese
        else:
            self.cheese = False
    def set_pico(self, pico):
        pico_list = [True, False]
        if pico in pico_list:
            self.pico = pico
        else:
            self.pico = False
    def set_corn(self, corn):
        corn_list = [True, False]
        if corn in corn_list:
            self.corn = corn
        else:
            self.corn = False

    def get_cost(self):
        cost = 5
        if self.meat.get_value() == "chicken" or self.meat.get_value() == "pork" or self.meat.get_value() == "tofu":
            cost += 1
        if self.meat.get_value() == "steak":
            cost += 1.50
        if self.extra_meat == True and not self.meat.get_value() == False:
            cost += 1
        if self.guacamole == True:
            cost += 0.75
        return cost

    def get_meat(self):
        return self.meat.get_value()

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        return self.rice.get_value()

    def get_beans(self):
        return self.beans.get_value()

    def get_extra_meat(self):
        return self.extra_meat

    def get_guacamole(self):
        return self.guacamole

    def get_cheese(self):
        return self.cheese

    def get_pico(self):
        return self.pico

    def get_corn(self):
        return self.corn

To get the meat, rice and beans instance of the Burrito class to communicate with the three classes above, I need to call their class getters and setters into the Burrito class getters and setters. Example to send a meat instance from Burrito class to Meat class i simply write my setter for the meat method in Burrito like this:

def set_meat(self, meat):
        self.meat.set_value(meat)

As seen in Burrito class above. Same applies to beans and rice.

Now to call values back from them, i simply call their respective class getters into my Burrito class getters. Example using the meat once more:

def get_meat(self):
        return self.meat.get_value()

Same applies to the rice and the beans class as seen in the Burrito class above:

For  the curious minds, this is a little way of testing it :

newburrito = Burrito("pork", True, "brown", "pinto", True, True)
print (newburrito.meat.get_value())

Thanks once more and apologies for any grammatical error. I hope my explanations were clear enough.
Note please i decided to post my entire code for clarity as against the select code i posted when i was asking my question.


问:
Unable to configure 'IApplicationBuilder UseOwin'
As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.

I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.

Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.

Note:
I am using dotnetcore 2.0 with Visual Studio 2017

Error

I am getting following error.

return owinAppBuilder.Build,
  Task>>(); TypeLoadException: Could not load type
  'System.Security.Cryptography.DpapiDataProtector' from assembly
  'System.Security, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

My attempt

```<code>    app.UseOwin(setup => setup(next =>
    {
        var owinAppBuilder = new AppBuilder();

        var aspNetCoreLifetime =
            (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));

        new AppProperties(owinAppBuilder.Properties)
        {
            OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
            DefaultApp = next,
            AppName = "test"
        };

        // Only required if CORS is used, configure it as you wish
        var corsPolicy = new System.Web.Cors.CorsPolicy
        {

            AllowAnyHeader = true,
            AllowAnyMethod = true,
            AllowAnyOrigin = true,
            SupportsCredentials = true
        };

        //corsPolicy.GetType()
        //      .GetProperty(nameof(corsPolicy.ExposedHeaders))
        //      .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());

        owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context => Task.FromResult(corsPolicy)
            }
        });

        PublicClientId = "self";

        OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
            Provider = new MyServiceProvider(PublicClientId),

            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            AllowInsecureHttp = true,
            RefreshTokenProvider = new MyRefreshTokenProvider(),
        };

        owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
        //owinAppBuilder.UseTus(context => new DefaultTusConfiguration
        //{
        //    // Excluded for brevity, use the same configuration as you would normally do
        //});

        return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
    }));
</code>```

答:
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:

Package 'Microsoft.Owin 3.1.0' was restored using
  '.NETFramework,Version=v4.6.1' instead of the project target framework
  '.NETCoreApp,Version=v2.0'. This package may not be fully compatible
  with your project.

There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).

So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.

If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change

```<code><TargetFramework>netcoreapp2.0</TargetFramework>
</code>```

To some .NET framework version that supports .NET Standard 2.0, for example:

```<code><TargetFramework>net47</TargetFramework>
</code>```

Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.

That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.

Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).

Body:
As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.

I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.

Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.

Note:
I am using dotnetcore 2.0 with Visual Studio 2017

Error

I am getting following error.

return owinAppBuilder.Build,
  Task>>(); TypeLoadException: Could not load type
  'System.Security.Cryptography.DpapiDataProtector' from assembly
  'System.Security, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'.

My attempt

    app.UseOwin(setup => setup(next =>
    {
        var owinAppBuilder = new AppBuilder();

        var aspNetCoreLifetime =
            (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));

        new AppProperties(owinAppBuilder.Properties)
        {
            OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
            DefaultApp = next,
            AppName = "test"
        };

        // Only required if CORS is used, configure it as you wish
        var corsPolicy = new System.Web.Cors.CorsPolicy
        {

            AllowAnyHeader = true,
            AllowAnyMethod = true,
            AllowAnyOrigin = true,
            SupportsCredentials = true
        };

        //corsPolicy.GetType()
        //      .GetProperty(nameof(corsPolicy.ExposedHeaders))
        //      .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());

        owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context => Task.FromResult(corsPolicy)
            }
        });

        PublicClientId = "self";

        OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
            Provider = new MyServiceProvider(PublicClientId),

            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            AllowInsecureHttp = true,
            RefreshTokenProvider = new MyRefreshTokenProvider(),
        };

        owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
        //owinAppBuilder.UseTus(context => new DefaultTusConfiguration
        //{
        //    // Excluded for brevity, use the same configuration as you would normally do
        //});

        return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
    }));

Body:
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:

Package 'Microsoft.Owin 3.1.0' was restored using
  '.NETFramework,Version=v4.6.1' instead of the project target framework
  '.NETCoreApp,Version=v2.0'. This package may not be fully compatible
  with your project.

There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).

So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.

If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change

<TargetFramework>netcoreapp2.0</TargetFramework>

To some .NET framework version that supports .NET Standard 2.0, for example:

<TargetFramework>net47</TargetFramework>

Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.

That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.

Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).


问:
What innerHTML internally does to the DOM?
Consider the snippet-

```<code><html >
    <script>
        function  test(){

            function getPosition(parent, descendant) {
                return parent.compareDocumentPosition(descendant);
            }
            var p = document.getElementById("myPara");
            console.log(getPosition(document, p));          // 20

            console.log(document.body.innerHTML);

            document.body.innerHTML += "<p>It's clobberin' time!</p>";
            console.log(getPosition(document, p));          // 37 WHY?

            console.log(document.getElementById("myPara") === p); // false WHY?
        }

    </script>
    <body>
        <p id="myPara">Its a paragraph</p>
        <button onclick="test()">Press Me!</button>
    </body>
</html>
</code>```

The document.body.innerHTMLbefore the assignation prints

```<code>"
        <p id="myPara">Its a paragraph</p>
        <button onclick="test()">Press Me!</button>

"
</code>```

on the console.

2 questions here-

Why is console.log(getPosition(document, p));          // 37 WHY?
The element
It's clobberin' time!
 was appended to the
innerHTML but why did it messed the position of the element
identified by myPara.

Secondly, console.log(document.getElementById("myPara") === p); //    false, WHY?

答:
I don't usually see .innerHTML += often. I suppose that can add on to whatever is already in the element... The .innerHTML is meant to change the contents of whatever object/element it is fed to in the DOM if it is set as an rvalue '='.

Its false because it's more than just an empty element and you're using === which means type and value.

Body:
Consider the snippet-

Its a paragraph

        <button onclick="test()">Press Me!</button>

The document.body.innerHTMLbefore the assignation prints

"

Its a paragraph

        <button onclick="test()">Press Me!</button>

"

on the console.

2 questions here-

Why is console.log(getPosition(document, p));          // 37 WHY?
The element
It's clobberin' time!
 was appended to the
innerHTML but why did it messed the position of the element
identified by myPara.

Secondly, console.log(document.getElementById("myPara") === p); //    false, WHY?


问:
Angular 4 RXJS Observable .interval() Doesn't Work In Background
I have a simple timer observable which is subscribed to when a timer starts in my app. It works well, but if another browser tab is selected then the timer stops until the app's tab is selected again.

```<code>public timer = Observable
  .interval(100)
</code>```

Is there a way I can keep the observable running while the tab is in the background?

Update

I looked briefly into running this as a Web Worker, but soon started reading about difficulties of integrating Web Workers into Angular projects.

So for the time being I'm using the simple solution of getting the start time of my timer and subtracting that from the current time to get the timer run duration. This way the timer will correct itself when when the tab becomes active again.

I did want the page title to display the timer count so that it can be seen just by looking at the tab, so I'd still like to find a better solution to this problem.

答:
Tabs in the background of Chrome are heavily restricted in the amount of things performancewise they can do. See this blogpost of the Chrome team: https://developers.google.com/web/updates/2017/03/background_tabs

Shipping in Chrome 57, budget-based timer throttling is a further
  extension of the timer alignment mechanism, placing an additional
  limit on background timer CPU usage. It operates as follows:

Each background tab has a time budget (in seconds) for running timers in the background.

A page is subjected to time budget limitations after 10 seconds in the background.

A timer task is allowed to run only when the time budget is non-negative.

After a timer has executed, its run time is subtracted from the budget.

The budget continuously regenerates with time (currently set to a rate of 0.01 seconds per second). Note that this budget regeneration
  rate can be tweaked as Chrome collects more data about throttling
  behavior.

So running a timer ever 100msec in the background will not work dramatically slowed down due to the budget restriction in cpu cycles.

Body:
I have a simple timer observable which is subscribed to when a timer starts in my app. It works well, but if another browser tab is selected then the timer stops until the app's tab is selected again.

public timer = Observable
  .interval(100)

Is there a way I can keep the observable running while the tab is in the background?

Update

I looked briefly into running this as a Web Worker, but soon started reading about difficulties of integrating Web Workers into Angular projects.

So for the time being I'm using the simple solution of getting the start time of my timer and subtracting that from the current time to get the timer run duration. This way the timer will correct itself when when the tab becomes active again.

I did want the page title to display the timer count so that it can be seen just by looking at the tab, so I'd still like to find a better solution to this problem.


问:
Dynamic Programming: top down versus bottom up comparison
Can you point me to some dynamic programming problem statements where bottom up is more beneficial than top down? (i.e. simple DP works more naturally but memoization would be harder to implement?)

I find recursion with memoization much easier, and want to solve problems where bottom up is a better/perhaps only feasible approach.

I understand that theoretically both are equivalent, so even something like ease of implementation would count as a benefit.

答:
Two things to consider when deciding which algorithm to use

Time Complexity. Both approaches have the same time complexity in general, but because for loop is cheaper than recursive function calls, bottom-up can be faster if measured in machine time.

Space Complexity. (without considering extra call stack allocations during top-down) Usually both approaches need to build a table for all sub-solutions, but bottom-up is following a topological order, its cost of auxiliary space can be sometimes reduced to the size of problem's immediate dependencies. For example: fibonacci(n) = fibonacci(n-1) + fibonacci(n-2), we only need to store the past two calculations

That being said, bottom-up is not always the best choice, I will try to illustrate with examples:

(mentioned by @Nikunj Banka) top-down only solves sub-problems used by your solution whereas bottom-up might waste time on redundant sub-problems. A silly example would be 0-1 knapsack with 1 item...run time difference is O(1) vs O(weight)

you might need to perform extra work to get topological order for bottm-up. In Longest Increasing Path in Matrix, if we want to do sub-problems after their dependencies, we would have to sort all entries of the matrix in descending order, that's extra nmlog(nm) pre-processing time before DP