问:
Need to grab a parent value in Linq
I'm using this code to pull a list of email addresses and search them for a specific address, if it's a duplicate then I need to pull the "id" (the value starts with "lead_") which is in the Datam class and/or Contacts

```<code>    var emails = json
        // Enumerate through all data
        .Data
        // Enumerate through all contacts of all data
        .SelectMany(d => d.Contacts)
        // Enumerate through all emails of all contacts
        .SelectMany(c => c.Emails)
        // Get email value
        .Select(e => e.EmailValue)
</code>```

So I have my list of emails, but how do I attach the ID's to them, I assume I need to create an anonymous type?

I've tried this but can't figure out how to go back to the root

JSON:

```<code>{
    "data": [
        {
            "addresses": [],
            "contacts": [
                {
                    "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "date_created": "2017-12-03T05:42:30.737000+00:00",
                    "date_updated": "2017-12-03T05:45:32.227000+00:00",
                    "emails": [
            {
                            "email": "testemail@testemail.com",
                            "type": "office"
                        }
            ],
                    "id": "cont_kH9tcx970T3ZTGKPPP2vh5u3Ha8P9Rjz6gGqflgzwvy",
                    "integration_links": [
                        {
                            "name": "LinkedIn Search",
                            "url": "https://www.linkedin.com/search/results/index/?keywords=Test%20Woodard"
                        }
                    ],
                    "lead_id": "lead_12Rz7R2TrWmwUhCGVTRh8rt6A8hokaXgujSEPlfoWpD",
                    "name": "Test User",
                    "organization_id": "orga_iFnIMLDbvGevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
                    "phones": [
                        {
                            "phone": "+15558675309",
                            "phone_formatted": "+1 555-867-5309",
                            "type": "office"
                        }
                    ],
                    "title": "",
                    "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "urls": []
                }
            ],
            "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "created_by_name": "Test User",
            "custom": {
                "Date Created": "2017-12-03",
                "Initial Service": "Men's Health",
                "Lead Owner": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                "Marketing Source": "Bing"
            },
            "custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K": "Bing",
            "custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B": "Chiropractor",
            "custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3": "2017-12-03",
            "date_created": "2017-12-03T05:42:30.733000+00:00",
            "date_updated": "2017-12-03T05:45:32.234000+00:00",
            "description": "",
            "display_name": "test",
            "html_url": "https://app.close.io/lead/lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpG/",
            "id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
            "integration_links": [
                {
                    "name": "Google Search",
                    "url": "http://google.com/search?q=test"
                }
            ],
            "name": "test",
            "opportunities": [
                {
                    "confidence": 50,
                    "contact_id": null,
                    "contact_name": null,
                    "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "created_by_name": "Test User",
                    "date_created": "2017-12-03T05:44:31.131000+00:00",
                    "date_lost": null,
                    "date_updated": "2017-12-03T05:44:31.131000+00:00",
                    "date_won": null,
                    "id": "oppo_xQ5S1dHMjDWoeUBAigtyiwuwFUkxtbxHURQX5UaL7fT",
                    "integration_links": [],
                    "lead_id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
                    "lead_name": "test",
                    "note": "New Lead",
                    "organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
                    "status_id": "stat_SwQmzqoIqIt20j9YBDxIYem11GyZPGL30G7PdkWYdvG",
                    "status_label": "Chiropractor",
                    "status_type": "active",
                    "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "updated_by_name": "Test User",
                    "user_id": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "user_name": "Test User",
                    "value": 140000,
                    "value_currency": "USD",
                    "value_formatted": "$1,400",
                    "value_period": "one_time"
                }
            ],
            "organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
            "status_id": "stat_auhCEJZNhaUnX9DHdrCaZ5r5mhpqxjfaE1hdwnPz6xx",
            "status_label": "Potential",
            "tasks": [],
            "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "updated_by_name": "Test User",
            "url": null
        }
    ],
    "has_more": false,
    "total_results": 1
}

public partial class Welcome
    {
        [JsonProperty("data")]
        public Datum[] Data { get; set; }

        [JsonProperty("has_more")]
        public bool HasMore { get; set; }

        [JsonProperty("total_results")]
        public long TotalResults { get; set; }
    }
public partial class Datum
    {
        [JsonProperty("addresses")]
        public object[] Addresses { get; set; }

        [JsonProperty("contacts")]
        public Contact[] Contacts { get; set; }

        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("created_by_name")]
        public string CreatedByName { get; set; }

        [JsonProperty("custom")]
        public Custom Custom { get; set; }

        [JsonProperty("custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B")]
        public string CustomInitialService { get; set; }

        [JsonProperty("custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV")]
        public string CustomLeadOwner { get; set; }

        [JsonProperty("custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K")]
        public string CustomMarketingSource { get; set; }

        [JsonProperty("custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3")]
        public string CustomDateCreated { get; set; }
        [JsonProperty("custom.lcf_bzaGzJw0MsgtffSeHDQhYjfBmacMWxCiPM3DlqOlYZQ")]
        public string CustomLocation { get; set; }
        [JsonProperty("custom.lcf_1EE18uGReRLF6xqI45kWA3ijfSWJTe718FSgTiXdyEC")]
        public string CustomStart { get; set; }

        [JsonProperty("custom.lcf_E23dCjch37Zushwm1ZzPm3JXKXKJMZgYEYBjx5oabDF")]
        public string CustomAppointment { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

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

        [JsonProperty("display_name")]
        public string DisplayName { get; set; }

        [JsonProperty("html_url")]
        public string HtmlUrl { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public IntegrationLink[] IntegrationLinks { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("opportunities")]
        public Opportunity[] Opportunities { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("status_id")]
        public string StatusId { get; set; }

        [JsonProperty("status_label")]
        public string StatusLabel { get; set; }

        [JsonProperty("tasks")]
        public object[] Tasks { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("updated_by_name")]
        public string UpdatedByName { get; set; }

        [JsonProperty("url")]
        public object Url { get; set; }
    }
 public partial class Opportunity
    {
        [JsonProperty("confidence")]
        public long Confidence { get; set; }

        [JsonProperty("contact_id")]
        public object ContactId { get; set; }

        [JsonProperty("contact_name")]
        public object ContactName { get; set; }

        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("created_by_name")]
        public string CreatedByName { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_lost")]
        public object DateLost { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

        [JsonProperty("date_won")]
        public object DateWon { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public object[] IntegrationLinks { get; set; }

        [JsonProperty("lead_id")]
        public string LeadId { get; set; }

        [JsonProperty("lead_name")]
        public string LeadName { get; set; }

        [JsonProperty("note")]
        public string Note { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("status_id")]
        public string StatusId { get; set; }

        [JsonProperty("status_label")]
        public string StatusLabel { get; set; }

        [JsonProperty("status_type")]
        public string StatusType { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("updated_by_name")]
        public string UpdatedByName { get; set; }

        [JsonProperty("user_id")]
        public string UserId { get; set; }

        [JsonProperty("user_name")]
        public string UserName { get; set; }

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

        [JsonProperty("value_currency")]
        public string ValueCurrency { get; set; }

        [JsonProperty("value_formatted")]
        public string ValueFormatted { get; set; }

        [JsonProperty("value_period")]
        public string ValuePeriod { get; set; }
    }

    public partial class Custom
    {
        [JsonProperty("Date Created")]
        public string DateCreated { get; set; }

        [JsonProperty("Initial Service")]
        public string InitialService { get; set; }

        [JsonProperty("Lead Owner")]
        public string LeadOwner { get; set; }

        [JsonProperty("Marketing Source")]
        public string MarketingSource { get; set; }

        [JsonProperty("Location")]
        public string Location { get; set; }
    }
    public class Email
    {
        [JsonProperty("email")]
        public string EmailValue { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class Contact
    {
        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

        [JsonProperty("emails")]
        public Email[] Emails { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public IntegrationLink[] IntegrationLinks { get; set; }

        [JsonProperty("lead_id")]
        public string LeadId { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("phones")]
        public Phone[] Phones { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("urls")]
        public object[] Urls { get; set; }
    }
    public partial class Phone
    {
        [JsonProperty("phone_formatted")]
        public string PhoneFormatted { get; set; }

        [JsonProperty("phone")]
        public string PhoneNumber { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class IntegrationLink
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("url")]
        public string Url { get; set; }
    }

    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
    }
</code>```

答:
In cases like this I find the query syntax more convenient than the fluent syntax, precisely because in nested SelectMany queries the outer items are accessible without needing to manually create intermediate anonymous types for passing values into the inner loop.

Thus:

```<code>var query = from d in json.Data
            from c in d.Contacts
            from e in c.Emails
            select new { Email = e.EmailValue, LeadId = c.LeadId };
var emails = query.ToList();
</code>```

This avoids the need to "go up" from the inner item to the outer.

Sample fiddle.

Title: Need to grab a parent value in Linq

Body:
I'm using this code to pull a list of email addresses and search them for a specific address, if it's a duplicate then I need to pull the "id" (the value starts with "lead_") which is in the Datam class and/or Contacts

    var emails = json
        // Enumerate through all data
        .Data
        // Enumerate through all contacts of all data
        .SelectMany(d => d.Contacts)
        // Enumerate through all emails of all contacts
        .SelectMany(c => c.Emails)
        // Get email value
        .Select(e => e.EmailValue)

So I have my list of emails, but how do I attach the ID's to them, I assume I need to create an anonymous type?

I've tried this but can't figure out how to go back to the root

JSON:

{
    "data": [
        {
            "addresses": [],
            "contacts": [
                {
                    "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "date_created": "2017-12-03T05:42:30.737000+00:00",
                    "date_updated": "2017-12-03T05:45:32.227000+00:00",
                    "emails": [
            {
                            "email": "testemail@testemail.com",
                            "type": "office"
                        }
            ],
                    "id": "cont_kH9tcx970T3ZTGKPPP2vh5u3Ha8P9Rjz6gGqflgzwvy",
                    "integration_links": [
                        {
                            "name": "LinkedIn Search",
                            "url": "https://www.linkedin.com/search/results/index/?keywords=Test%20Woodard"
                        }
                    ],
                    "lead_id": "lead_12Rz7R2TrWmwUhCGVTRh8rt6A8hokaXgujSEPlfoWpD",
                    "name": "Test User",
                    "organization_id": "orga_iFnIMLDbvGevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
                    "phones": [
                        {
                            "phone": "+15558675309",
                            "phone_formatted": "+1 555-867-5309",
                            "type": "office"
                        }
                    ],
                    "title": "",
                    "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "urls": []
                }
            ],
            "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "created_by_name": "Test User",
            "custom": {
                "Date Created": "2017-12-03",
                "Initial Service": "Men's Health",
                "Lead Owner": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                "Marketing Source": "Bing"
            },
            "custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K": "Bing",
            "custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B": "Chiropractor",
            "custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3": "2017-12-03",
            "date_created": "2017-12-03T05:42:30.733000+00:00",
            "date_updated": "2017-12-03T05:45:32.234000+00:00",
            "description": "",
            "display_name": "test",
            "html_url": "https://app.close.io/lead/lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpG/",
            "id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
            "integration_links": [
                {
                    "name": "Google Search",
                    "url": "http://google.com/search?q=test"
                }
            ],
            "name": "test",
            "opportunities": [
                {
                    "confidence": 50,
                    "contact_id": null,
                    "contact_name": null,
                    "created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "created_by_name": "Test User",
                    "date_created": "2017-12-03T05:44:31.131000+00:00",
                    "date_lost": null,
                    "date_updated": "2017-12-03T05:44:31.131000+00:00",
                    "date_won": null,
                    "id": "oppo_xQ5S1dHMjDWoeUBAigtyiwuwFUkxtbxHURQX5UaL7fT",
                    "integration_links": [],
                    "lead_id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
                    "lead_name": "test",
                    "note": "New Lead",
                    "organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
                    "status_id": "stat_SwQmzqoIqIt20j9YBDxIYem11GyZPGL30G7PdkWYdvG",
                    "status_label": "Chiropractor",
                    "status_type": "active",
                    "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "updated_by_name": "Test User",
                    "user_id": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
                    "user_name": "Test User",
                    "value": 140000,
                    "value_currency": "USD",
                    "value_formatted": "$1,400",
                    "value_period": "one_time"
                }
            ],
            "organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
            "status_id": "stat_auhCEJZNhaUnX9DHdrCaZ5r5mhpqxjfaE1hdwnPz6xx",
            "status_label": "Potential",
            "tasks": [],
            "updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
            "updated_by_name": "Test User",
            "url": null
        }
    ],
    "has_more": false,
    "total_results": 1
}

public partial class Welcome
    {
        [JsonProperty("data")]
        public Datum[] Data { get; set; }

        [JsonProperty("has_more")]
        public bool HasMore { get; set; }

        [JsonProperty("total_results")]
        public long TotalResults { get; set; }
    }
public partial class Datum
    {
        [JsonProperty("addresses")]
        public object[] Addresses { get; set; }

        [JsonProperty("contacts")]
        public Contact[] Contacts { get; set; }

        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("created_by_name")]
        public string CreatedByName { get; set; }

        [JsonProperty("custom")]
        public Custom Custom { get; set; }

        [JsonProperty("custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B")]
        public string CustomInitialService { get; set; }

        [JsonProperty("custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV")]
        public string CustomLeadOwner { get; set; }

        [JsonProperty("custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K")]
        public string CustomMarketingSource { get; set; }

        [JsonProperty("custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3")]
        public string CustomDateCreated { get; set; }
        [JsonProperty("custom.lcf_bzaGzJw0MsgtffSeHDQhYjfBmacMWxCiPM3DlqOlYZQ")]
        public string CustomLocation { get; set; }
        [JsonProperty("custom.lcf_1EE18uGReRLF6xqI45kWA3ijfSWJTe718FSgTiXdyEC")]
        public string CustomStart { get; set; }

        [JsonProperty("custom.lcf_E23dCjch37Zushwm1ZzPm3JXKXKJMZgYEYBjx5oabDF")]
        public string CustomAppointment { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

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

        [JsonProperty("display_name")]
        public string DisplayName { get; set; }

        [JsonProperty("html_url")]
        public string HtmlUrl { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public IntegrationLink[] IntegrationLinks { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("opportunities")]
        public Opportunity[] Opportunities { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("status_id")]
        public string StatusId { get; set; }

        [JsonProperty("status_label")]
        public string StatusLabel { get; set; }

        [JsonProperty("tasks")]
        public object[] Tasks { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("updated_by_name")]
        public string UpdatedByName { get; set; }

        [JsonProperty("url")]
        public object Url { get; set; }
    }
 public partial class Opportunity
    {
        [JsonProperty("confidence")]
        public long Confidence { get; set; }

        [JsonProperty("contact_id")]
        public object ContactId { get; set; }

        [JsonProperty("contact_name")]
        public object ContactName { get; set; }

        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("created_by_name")]
        public string CreatedByName { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_lost")]
        public object DateLost { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

        [JsonProperty("date_won")]
        public object DateWon { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public object[] IntegrationLinks { get; set; }

        [JsonProperty("lead_id")]
        public string LeadId { get; set; }

        [JsonProperty("lead_name")]
        public string LeadName { get; set; }

        [JsonProperty("note")]
        public string Note { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("status_id")]
        public string StatusId { get; set; }

        [JsonProperty("status_label")]
        public string StatusLabel { get; set; }

        [JsonProperty("status_type")]
        public string StatusType { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("updated_by_name")]
        public string UpdatedByName { get; set; }

        [JsonProperty("user_id")]
        public string UserId { get; set; }

        [JsonProperty("user_name")]
        public string UserName { get; set; }

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

        [JsonProperty("value_currency")]
        public string ValueCurrency { get; set; }

        [JsonProperty("value_formatted")]
        public string ValueFormatted { get; set; }

        [JsonProperty("value_period")]
        public string ValuePeriod { get; set; }
    }

    public partial class Custom
    {
        [JsonProperty("Date Created")]
        public string DateCreated { get; set; }

        [JsonProperty("Initial Service")]
        public string InitialService { get; set; }

        [JsonProperty("Lead Owner")]
        public string LeadOwner { get; set; }

        [JsonProperty("Marketing Source")]
        public string MarketingSource { get; set; }

        [JsonProperty("Location")]
        public string Location { get; set; }
    }
    public class Email
    {
        [JsonProperty("email")]
        public string EmailValue { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class Contact
    {
        [JsonProperty("created_by")]
        public string CreatedBy { get; set; }

        [JsonProperty("date_created")]
        public string DateCreated { get; set; }

        [JsonProperty("date_updated")]
        public string DateUpdated { get; set; }

        [JsonProperty("emails")]
        public Email[] Emails { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("integration_links")]
        public IntegrationLink[] IntegrationLinks { get; set; }

        [JsonProperty("lead_id")]
        public string LeadId { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("organization_id")]
        public string OrganizationId { get; set; }

        [JsonProperty("phones")]
        public Phone[] Phones { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("updated_by")]
        public string UpdatedBy { get; set; }

        [JsonProperty("urls")]
        public object[] Urls { get; set; }
    }
    public partial class Phone
    {
        [JsonProperty("phone_formatted")]
        public string PhoneFormatted { get; set; }

        [JsonProperty("phone")]
        public string PhoneNumber { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class IntegrationLink
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("url")]
        public string Url { get; set; }
    }

    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
    }

Body:
In cases like this I find the query syntax more convenient than the fluent syntax, precisely because in nested SelectMany queries the outer items are accessible without needing to manually create intermediate anonymous types for passing values into the inner loop.

Thus:

var query = from d in json.Data
            from c in d.Contacts
            from e in c.Emails
            select new { Email = e.EmailValue, LeadId = c.LeadId };
var emails = query.ToList();

This avoids the need to "go up" from the inner item to the outer.

Sample fiddle.


来源: stackexchange

问:
How to remove the gap between navigation icon and toolbar logo?
How can I remove the margin between the navigation icon and toolbar logo.

My toolbar layout

```<code><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/paper9patch"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/toolbarTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">

</android.support.v7.widget.Toolbar>
</code>```

I am inserting logo like this

```<code>   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   toolbar.setContentInsetStartWithNavigation(0);
   getSupportActionBar().setDisplayShowTitleEnabled(false);
   getSupportActionBar().setLogo(R.drawable.sample);
</code>```

my toolbar is looking like this

the logo is almost showing in the middle I want it beside the drawer icon

I searched on stackover flow and all answers tell to use

```<code>app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
</code>```

but its not working . I can say there is no padding for the image it is cropped exactly to edges. If i use tile there is no gap in middle ,the gap appears only when inserted logo.

Is this intended behavior ? Is there any thing else I can do to remove the gap?

Edit : styles i am using

```<code>    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    </style>

   <style name="toolbarTheme" parent="AppTheme">

    <item name="android:textColorPrimary">@color/themeColor</item>
    <item name="android:textColorSecondary">@color/themeColor</item>

    </style>

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

答:
Try this although it not much different from your layout but its works well i have tested it .

```<code> <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:contentInsetLeft="0dp"
                android:contentInsetStart="0dp"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                app:contentInsetStartWithNavigation="0dp"
                android:gravity="center"
                app:popupTheme="@style/AppTheme.PopupOverlay">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>
</code>```

Set up toobar as.

```<code>Toolbar  toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("New");
    getSupportActionBar().setLogo(R.mipmap.ic_launcher);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I remove the margin between the navigation icon and toolbar logo.

My toolbar layout

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/paper9patch"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/toolbarTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">

</android.support.v7.widget.Toolbar>

I am inserting logo like this

   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   toolbar.setContentInsetStartWithNavigation(0);
   getSupportActionBar().setDisplayShowTitleEnabled(false);
   getSupportActionBar().setLogo(R.drawable.sample);

my toolbar is looking like this

the logo is almost showing in the middle I want it beside the drawer icon

I searched on stackover flow and all answers tell to use

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"

but its not working . I can say there is no padding for the image it is cropped exactly to edges. If i use tile there is no gap in middle ,the gap appears only when inserted logo.

Is this intended behavior ? Is there any thing else I can do to remove the gap?

Edit : styles i am using

Body:
Try this although it not much different from your layout but its works well i have tested it .

 <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:contentInsetLeft="0dp"
                android:contentInsetStart="0dp"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                app:contentInsetStartWithNavigation="0dp"
                android:gravity="center"
                app:popupTheme="@style/AppTheme.PopupOverlay">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>

Set up toobar as.

Toolbar  toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("New");
    getSupportActionBar().setLogo(R.mipmap.ic_launcher);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


问:
Do not return the index.hmtl on root url instead return 403 Access is denied
When I enter www.mydomain.com the index.html file is returned.

I do not want that.

On the base url I want to return a 403 Access is denied, how can I do that?

Only when the base url AND further routes/path are appended I want that the

index.html is loaded, because then the frontend can catch the route values

initially for further backend calls.

答:
On the base url I want to return a 403 Access is denied, how can I do that?

Based on your requirement, you could leverage the following url rewrite rule:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
     <rewrite>
      <rules>
          <rule name="Block the request from the root url and return 403" stopProcessing="true">
             <match url="^$" />
             <action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied."/>
                </rule>
      </rules>
  </rewrite>
  </system.webServer>
</configuration>
```

Moreover, you could also remove the index.html document under Application settings > Default documents of your azure web app as follows:

Body:
On the base url I want to return a 403 Access is denied, how can I do that?

Based on your requirement, you could leverage the following url rewrite rule:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
     <rewrite>
      <rules>
          <rule name="Block the request from the root url and return 403" stopProcessing="true">
             <match url="^$" />
             <action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied."/>
                </rule>
      </rules>
  </rewrite>
  </system.webServer>
</configuration>

Moreover, you could also remove the index.html document under Application settings > Default documents of your azure web app as follows:


问:
JButton to open new frame, that is in different class
I am trying to open new frame from my SecondFrame button. The Frame i want is the QueueFrame. However i have put the actionevent but it seems that there is no action when i press the button. This is my Deneme4 class

```<code>    public class Deneme4 extends JFrame {
    public static void main(String a[]) throws FileNotFoundException {
    SecondFrame frame = new SecondFrame();

}}
</code>```

when i do run this my first frame comes up which is the SecondFrame with no problem but in SecondFrame i have b3 and b4 i want each to open different class, for now i tried to open my QueueFrame with b4 but its not doing anything

Second Frame:

```<code>public class SecondFrame extends JFrame {

private JButton b3;
private JButton b4;

public SecondFrame() {

    JFrame secondframe = new JFrame();
    b3 = new JButton("Queue");
    b4 = new JButton("Stack");

    b3.setBounds(150, 100, 180, 100);
    b4.setBounds(150, 300, 180, 100);

    secondframe.add(b3);
    secondframe.add(b4);

    secondframe.setLayout(null);
    secondframe.setSize(500, 750);
    secondframe.setVisible(true);
    secondframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void b4ActionPerformed(ActionEvent e) throws FileNotFoundException{

    QueueFrame queues = new QueueFrame();
    queues.setVisible(true);
    Scanner s = new Scanner(new File("list.txt"));
    Queue queue = new Queue();
    while (s.hasNext()) {
        queue.setMessageOutput((Queue.MessageOutput) queues);
        queue.enqueue(s.nextInt());
    }
    s.close();
    queue.queueSize();
    queue.getHead();
}}
</code>```

答:
How MadProgrammer said... Read, and learn how to write: ActionListener's, cause you can't depends of form editors, is a bad practice.

Well, the only thing that you need to do is write a correct ActionListener, first the name of your class, and after, the name of your method.

```<code>yourButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SecondFrame Sf = new SecondFrame();
Sf.frame();}});
</code>```

Body:
I am trying to open new frame from my SecondFrame button. The Frame i want is the QueueFrame. However i have put the actionevent but it seems that there is no action when i press the button. This is my Deneme4 class

    public class Deneme4 extends JFrame {
    public static void main(String a[]) throws FileNotFoundException {
    SecondFrame frame = new SecondFrame();

}}

when i do run this my first frame comes up which is the SecondFrame with no problem but in SecondFrame i have b3 and b4 i want each to open different class, for now i tried to open my QueueFrame with b4 but its not doing anything

Second Frame:

public class SecondFrame extends JFrame {

private JButton b3;
private JButton b4;

public SecondFrame() {

    JFrame secondframe = new JFrame();
    b3 = new JButton("Queue");
    b4 = new JButton("Stack");

    b3.setBounds(150, 100, 180, 100);
    b4.setBounds(150, 300, 180, 100);

    secondframe.add(b3);
    secondframe.add(b4);

    secondframe.setLayout(null);
    secondframe.setSize(500, 750);
    secondframe.setVisible(true);
    secondframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void b4ActionPerformed(ActionEvent e) throws FileNotFoundException{

    QueueFrame queues = new QueueFrame();
    queues.setVisible(true);
    Scanner s = new Scanner(new File("list.txt"));
    Queue queue = new Queue();
    while (s.hasNext()) {
        queue.setMessageOutput((Queue.MessageOutput) queues);
        queue.enqueue(s.nextInt());
    }
    s.close();
    queue.queueSize();
    queue.getHead();
}}

Body:
How MadProgrammer said... Read, and learn how to write: ActionListener's, cause you can't depends of form editors, is a bad practice.

Well, the only thing that you need to do is write a correct ActionListener, first the name of your class, and after, the name of your method.

yourButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SecondFrame Sf = new SecondFrame();
Sf.frame();}});


问:
Exporting AD Query
Apologies, because I've seen a lot of variations on this. I've spent a ton of time lurking and looking for a solution. I'm new to Powershell and I haven't been able to get this to work. In Powershell it appears to be working, because there's just a blinking space bar after I load the module and I don't get errors (earlier versions got errors that I figured out how to stop popping up); however, when I pipe it out to CSV, there is no data.

What am I doing wrong?

Thank you in advance.

```<code>#Load Active Directory
Import-Module activedirectory
#Load list of computers
$results = @()
$Computer = Get-Content -path 'C:\computers.txt'

#Check each computer in the list
foreach($ComputerName in $Computer)
{
$results += Get-ADComputer -Filter { ComputerName -Like '*$ComputerName*' } -Properties name, samaccountname, lastlogondate

 }

#Export to CSV file
$results | export-csv 'C:\lastlogon.csv'
</code>```

答:
I can see 2 errors in your code

1- Filter has to be a string not a scritpblock

2- Get-ADComputer use the Name or SamAccountName properties, not computername so the correct code should be

```<code>$results += Get-ADComputer -Filter " Name -Like '*$ComputerName*' " -Properties name, samaccountname, lastlogondate
</code>```

Title: Exporting AD Query

Body:
Apologies, because I've seen a lot of variations on this. I've spent a ton of time lurking and looking for a solution. I'm new to Powershell and I haven't been able to get this to work. In Powershell it appears to be working, because there's just a blinking space bar after I load the module and I don't get errors (earlier versions got errors that I figured out how to stop popping up); however, when I pipe it out to CSV, there is no data.

What am I doing wrong?

Thank you in advance.

#Load Active Directory
Import-Module activedirectory
#Load list of computers
$results = @()
$Computer = Get-Content -path 'C:\computers.txt'

#Check each computer in the list
foreach($ComputerName in $Computer)
{
$results += Get-ADComputer -Filter { ComputerName -Like '*$ComputerName*' } -Properties name, samaccountname, lastlogondate

 }

#Export to CSV file
$results | export-csv 'C:\lastlogon.csv'

Body:
I can see 2 errors in your code

1- Filter has to be a string not a scritpblock

2- Get-ADComputer use the Name or SamAccountName properties, not computername so the correct code should be

$results += Get-ADComputer -Filter " Name -Like '*$ComputerName*' " -Properties name, samaccountname, lastlogondate


问:
C equivalent for nested lists (Python)
I am new to C and trying to learn by comparison with Python.

My question is trivial, but I still need some explanations from experts. Here is a Python nested list structure:

```<code>L = [1, [2, [3, 4], 5], 6, [7, 8]]
</code>```

And here is an interesting piece of code (taken from 'Learning Python' by Lutz) to handle nested structures (sum elements):

```<code>def sumtree(L):
    tot = 0
    for x in L:
        if not isinstance(x, list):
            tot += x
        else:
            tot += sumtree(x)
    return tot
</code>```

If I pass L into this function I will get 36, which is a sum of elements in L.
How exactly can nested lists and this particular function be translated into C?

答:
What type is every element of L? It can be a number (an int for example in C), or even a list (it's typical for a list to be implemented with structs in C).

In order to achieve that, you would need a generic list (i.e. that the data of every node is of type void*). Notice that C doesn't provide a list from the standard library, you have to write one (here is an example).

Then, in order to get the sum, you would do something like that:

```<code>int sumtree(struct listnode * L) {
    int tot = 0;
    while (L != NULL) {
        if(L.data /* TODO: check if it is a number*/)
            tot += L.data;
        else /* L.data is a sublist */
            tot = sumtree(L.data);
        list = list->next;
    }
    return tot;
}
</code>```

In order to get the type, you need to follow this answer: How do I check if a variable is of a certain type (compare two types) in C?

However, such nested lists in C are not common, and I would advise you to re-approach the issue.

Title: C equivalent for nested lists (Python)

Body:
I am new to C and trying to learn by comparison with Python.

My question is trivial, but I still need some explanations from experts. Here is a Python nested list structure:

L = [1, [2, [3, 4], 5], 6, [7, 8]]

And here is an interesting piece of code (taken from 'Learning Python' by Lutz) to handle nested structures (sum elements):

def sumtree(L):
    tot = 0
    for x in L:
        if not isinstance(x, list):
            tot += x
        else:
            tot += sumtree(x)
    return tot

If I pass L into this function I will get 36, which is a sum of elements in L.
How exactly can nested lists and this particular function be translated into C?

Body:
What type is every element of L? It can be a number (an int for example in C), or even a list (it's typical for a list to be implemented with structs in C).

In order to achieve that, you would need a generic list (i.e. that the data of every node is of type void*). Notice that C doesn't provide a list from the standard library, you have to write one (here is an example).

Then, in order to get the sum, you would do something like that:

int sumtree(struct listnode * L) {
    int tot = 0;
    while (L != NULL) {
        if(L.data /* TODO: check if it is a number*/)
            tot += L.data;
        else /* L.data is a sublist */
            tot = sumtree(L.data);
        list = list->next;
    }
    return tot;
}

In order to get the type, you need to follow this answer: How do I check if a variable is of a certain type (compare two types) in C?

However, such nested lists in C are not common, and I would advise you to re-approach the issue.


问:
ajax call to controller when value selected from select box
i want to make a ajax call to controller when a value
is selected from select box.

this is my code:

```<code><select class="form-control required"  name="law_name" id="law_name">
    @foreach($law_name as $lawname)
    <option value="{{$lawname->id}}">{{$lawname->law_name}}
    </option>
 @endforeach
 </select>

<script>
    $("#law_name").on('change', function(){
                alert('123');
                $.ajax({
                        type: 'POST',
                        dataType: "json",
                        data: data,
                        url: "{{ URL::to('admin/SubLawController/index') }}",
                        success: function (response) {
                        }
                    });
                });
</script>
</code>```

my script is not running when i change value from select box

答:
following is jquery code for making ajax call on change event of dropdown box,

```<code>$(function() {
     $("#law_name").change(function () {
           alert( $('option:selected', this).text() );
          $.ajax({url: "http://xyz"+ $( this ).text(), success: function(result)
         {
               $("#div1").html(result);
          }});
    });
});
</code>```

Code is in jquery , you have to use xmlhttprequest object for pain javascript.

Body:
i want to make a ajax call to controller when a value
is selected from select box.

this is my code:

<select class="form-control required"  name="law_name" id="law_name">
    @foreach($law_name as $lawname)
    <option value="{{$lawname->id}}">{{$lawname->law_name}}
    </option>
 @endforeach
 </select>

my script is not running when i change value from select box

Body:
following is jquery code for making ajax call on change event of dropdown box,

$(function() {
     $("#law_name").change(function () {
           alert( $('option:selected', this).text() );
          $.ajax({url: "http://xyz"+ $( this ).text(), success: function(result)
         {
               $("#div1").html(result);
          }});
    });
});

Code is in jquery , you have to use xmlhttprequest object for pain javascript.


问:
Firebase Anonymous Data Security
Firebase realtime DB security from a JS app.

I'm allowing a read permission for all password-auth users.
Then, for all other types (only anonymous, per my scheme), I want to allow read for only specific /bundles/.

These are the rules -

```<code>{
    "rules": {
        ".read": "auth != null && auth.provider == 'password'", // working!
        "bundles": {
            "$bundle": {
                ".read": "data.child('anonymous').val() == true", // not working
            }
        },
    }
}
</code>```

And /bundles -

```<code>  "-L-2BbIkAg6J9WPMaJpJ": {
    "anonymous": true,
    "more_data": "data_1"
  },
  "-L-UHBr45eEUHGwsPWqq": {
    "anonymous": false,
    "more_data": "data_2"
  }
</code>```

I expect, when logged-in as anonymous, to see only the first bundle but instead I get an error from FB - "permission_denied at /bundles".

答:
The .read fails because you're trying to access the /bundles location. If instead you query the specific bundle directly, it will pass:

```<code>// read denied
ref.child('bundles').once('value')

// read allowed
ref.child(`bundles/-L-2BbIkAg6J9WPMaJpJ`).once('value')
</code>```

You won't be able to filter data through Firebase rules, as stated in this section of the Firebase docs. I suggest you update the schema and provide a separate node for your anonymous bundles e.g.:

```<code>{
  "rules": {
    ".read": "auth != null && auth.provider == 'password'",
    "anonymousBundles": {
      ".read": "auth != null"
    }
  }
}
</code>```

Title: Firebase Anonymous Data Security

Body:
Firebase realtime DB security from a JS app.

I'm allowing a read permission for all password-auth users.
Then, for all other types (only anonymous, per my scheme), I want to allow read for only specific /bundles/.

These are the rules -

{
    "rules": {
        ".read": "auth != null && auth.provider == 'password'", // working!
        "bundles": {
            "$bundle": {
                ".read": "data.child('anonymous').val() == true", // not working
            }
        },
    }
}

And /bundles -

  "-L-2BbIkAg6J9WPMaJpJ": {
    "anonymous": true,
    "more_data": "data_1"
  },
  "-L-UHBr45eEUHGwsPWqq": {
    "anonymous": false,
    "more_data": "data_2"
  }

I expect, when logged-in as anonymous, to see only the first bundle but instead I get an error from FB - "permission_denied at /bundles".

Body:
The .read fails because you're trying to access the /bundles location. If instead you query the specific bundle directly, it will pass:

// read denied
ref.child('bundles').once('value')

// read allowed
ref.child(`bundles/-L-2BbIkAg6J9WPMaJpJ`).once('value')

You won't be able to filter data through Firebase rules, as stated in this section of the Firebase docs. I suggest you update the schema and provide a separate node for your anonymous bundles e.g.:

{
  "rules": {
    ".read": "auth != null && auth.provider == 'password'",
    "anonymousBundles": {
      ".read": "auth != null"
    }
  }
}


问:
Why did I get the error cannot redeclare block-scoped variable 'name' in TypeScript?
I am trying to declare new variable called name in my typescript code. I have only one line of code.

```<code>var name:string = "John";
</code>```

But got error

```<code>PS D:\TypeScript> tsc test.ts
C:/Users/Users/AppData/Roaming/npm/node_modules/typescript/lib/lib.d.ts(18568,15): error TS2451: Cannot re
declare block-scoped variable 'name'.
test.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'name'.
</code>```

What is the reason behind this error?

答:
To get around this, you can simply have an export statement that exports nothing. In other words, just write

```<code> export {};
</code>```

somewhere at the top-level of your file.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to declare new variable called name in my typescript code. I have only one line of code.

var name:string = "John";

But got error

PS D:\TypeScript> tsc test.ts
C:/Users/Users/AppData/Roaming/npm/node_modules/typescript/lib/lib.d.ts(18568,15): error TS2451: Cannot re
declare block-scoped variable 'name'.
test.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'name'.

What is the reason behind this error?

Body:
To get around this, you can simply have an export statement that exports nothing. In other words, just write

 export {};

somewhere at the top-level of your file.


问:
Lines between all possible points in a plane
I'm trying to draw lines between every point in a plane given the x,y coordinates in an nx2 matrix. So if I have 4 points in the array (named 'A'), there should be 6 connections total. The current code will only give me one line connecting to the next point.</p>

```<code>line(A(:,1),A(:,2))
</code>```

Body:
I'm trying to draw lines between every point in a plane given the x,y coordinates in an nx2 matrix. So if I have 4 points in the array (named 'A'), there should be 6 connections total. The current code will only give me one line connecting to the next point.

line(A(:,1),A(:,2))

Body:
clear all;
A =[0,0; 0,1 ;1,0 ;1,1];
N = max(size(A));
for k = 1:N
 for l = k:N
     line(A(k,:),A(l,:))
 end
end


问:
Allow a user to move a borderless window
I have a form without borders that I would like the user to be able to move. I have not been able to find anything that would allow me to do so.

Is it possible to move a window with the border set to None?

答:
All 'simple' VB answers made my form jump all over the place with multiple screens. So i derived this from same answer in C# and it works like a charm :

```<code>Public Const WM_NCLBUTTONDOWN As Integer = 161
Public Const HT_CAPTION As Integer = 2
</code>```

then

```<code> <DllImport("User32")> Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As Integer) As Integer

End Function

<DllImport("User32")> Private Shared Function ReleaseCapture() As Boolean

End Function
</code>```

and finally

```<code>Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
    If (e.Button = MouseButtons.Left) Then
        ReleaseCapture()
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0)
    End If
End Sub
</code>```

Body:
All 'simple' VB answers made my form jump all over the place with multiple screens. So i derived this from same answer in C# and it works like a charm :

Public Const WM_NCLBUTTONDOWN As Integer = 161
Public Const HT_CAPTION As Integer = 2

then

 <DllImport("User32")> Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As Integer) As Integer

End Function

<DllImport("User32")> Private Shared Function ReleaseCapture() As Boolean

End Function

and finally

Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
    If (e.Button = MouseButtons.Left) Then
        ReleaseCapture()
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0)
    End If
End Sub


问:
Update Variable On Hashchange
I am trying to have a variable that always matches the hash of the URL on a single page site.

```<code>$(window).on('hashchange', function() {
    var hashTag = window.location.hash;
    $('#btn').click(function(){
        console.log(hashTag)
    });
});
</code>```

Using the code above creates a list of all the past changes rather than the current hash.

```<code>hashTag.last();
</code>```

This didn't work

答:
That is because you are attaching button click event listener again and again. Please move your button event listener outside hashchange event, like below

```<code>var hashTag = "";

$(window).on('hashchange', function() {
    hashTag = window.location.hash;
});

$('#btn').click(function(){
    console.log(hashTag)
});
</code>```

Now, there is permanent event listener attached to button which display value of hashTag variable. And on hashchange value of hashTag variable is updated.

Title: Update Variable On Hashchange

Body:
I am trying to have a variable that always matches the hash of the URL on a single page site.

$(window).on('hashchange', function() {
    var hashTag = window.location.hash;
    $('#btn').click(function(){
        console.log(hashTag)
    });
});

Using the code above creates a list of all the past changes rather than the current hash.

hashTag.last();

This didn't work

Body:
That is because you are attaching button click event listener again and again. Please move your button event listener outside hashchange event, like below

var hashTag = "";

$(window).on('hashchange', function() {
    hashTag = window.location.hash;
});

$('#btn').click(function(){
    console.log(hashTag)
});

Now, there is permanent event listener attached to button which display value of hashTag variable. And on hashchange value of hashTag variable is updated.


问:
How to assign default value to select option
I am working on a project where I need to show select option in the edit field with the value in it.

1) To get all dropdown values I have an API the response is in the screenshot.

2) When I click on Edit I am calling another API where I will get the saved value in API response in which I need to assign MasterData ie File Servers should be defaultly selected in the dropdown:

I am trying to use ng-init to acheive this. Below is my code.

```<code><select ng-if="question.MasterDataCategoryId != null" id="{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData = questionnaireDataEditDefault" class="form-control" style="width: 200px; white-space:pre-wrap;">
                                <option selected="selected"></option>
                                <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>

                            </select>
</code>```

Can anyone let me know how to acheive this.

答: After getting response from another API, assign that new value to selected as - $scope.selected = response.value, where response.value will be your real object

Body:
I am working on a project where I need to show select option in the edit field with the value in it.

1) To get all dropdown values I have an API the response is in the screenshot.

2) When I click on Edit I am calling another API where I will get the saved value in API response in which I need to assign MasterData ie File Servers should be defaultly selected in the dropdown:

I am trying to use ng-init to acheive this. Below is my code.

<select ng-if="question.MasterDataCategoryId != null" id="{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData = questionnaireDataEditDefault" class="form-control" style="width: 200px; white-space:pre-wrap;">
                                <option selected="selected"></option>
                                <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>

                            </select>

Can anyone let me know how to acheive this.


问:
Which HTML version should be chosen for a public website
I am currently working on a website. After studying HTML5 and its features I want to go ahead with it. I want to use features like offline storage, data- attribs, simple chat support etc. but because HTML5 is not well-supported yet, I am a bit confused. I have always used XHTML 1.0 transitional until now; should I continue using it or should I use HTML5?

I have seen the web giants like google have completely shifted to HTML5.

答:
HTML5 Features

If you mean the HTML5 features, you must understand what HTML5 really is. I would define it has the culmination of the previous specs as well as newer and richer features. It is made to support existing content (backward compatible) and to support the creation of web applications. What is really awesome is the fact that it does not only stop there. It states for the first time how browsers should deal with error handling.

Now, you need to know that not all features are implemented in browsers. You can take an HTML5 browser test to know what works and what doesn't. That does not mean that they will not work! Most browsers actually allow you to use and style any element you care to invent. The new HTML5 tags have no default style in browsers that do not support them.

The following CSS code would be enough for most browsers:

```<code>section, article, header, footer, nav, aside, hgroup {
  display: block;
}
</code>```

As always, Internet Explorer (IE) has special needs. Only, there is a JavasScript magician who goes by the name of Remy Sharp that has created a JavaScript file that creates each element for IE. So you could add this in your page:

```<code><!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"
  </script>
<![endif]-->
</code>```

By the way, you will have to use JavaScript to be able to test the existence of new HTML5 elements and give an alternate choice to those who have browsers that are not up to speed with certain HTML5 element and attributes. This is why there is this little generic JavaSCript function that you can use to do just that:

```<code>function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if(attribute in test)
    return true;
  else
    return false;
}
</code>```

One last note, I got most of this information from the book HTML5 For Web Designers. Kudos to Jeremy Keith!

HTML5 Doctype

If you mean the new doctype one <!DOCTYPE HTML>, here is what I have to say...

It isn't illegal to use features from previous HTML/XHTML version in HTML5. Note that the new doctype does not have any number associated with it. That is because it is meant to build upon existing specs and to be valid for future versions. Therefore, I say that you go with the new doctype.

You can have a look at the spec on the W3C site. In short the spec says this...

8.1.1 The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy
  reasons. When omitted, browsers tend
  to use a different rendering mode that
  is incompatible with some
  specifications. Including the DOCTYPE
  in a document ensures that the browser
  makes a best-effort attempt at
  following the relevant specifications.

[...]

For the purposes of HTML
  generators that cannot output HTML
  markup with the short DOCTYPE
  "<!DOCTYPE html>", a DOCTYPE legacy
  string may be inserted into the
  DOCTYPE (in the position defined
  above).

ContentLicense: CC BY-SA 2.5

Body:
HTML5 Features

If you mean the HTML5 features, you must understand what HTML5 really is. I would define it has the culmination of the previous specs as well as newer and richer features. It is made to support existing content (backward compatible) and to support the creation of web applications. What is really awesome is the fact that it does not only stop there. It states for the first time how browsers should deal with error handling.

Now, you need to know that not all features are implemented in browsers. You can take an HTML5 browser test to know what works and what doesn't. That does not mean that they will not work! Most browsers actually allow you to use and style any element you care to invent. The new HTML5 tags have no default style in browsers that do not support them.

The following CSS code would be enough for most browsers:

section, article, header, footer, nav, aside, hgroup {
  display: block;
}

As always, Internet Explorer (IE) has special needs. Only, there is a JavasScript magician who goes by the name of Remy Sharp that has created a JavaScript file that creates each element for IE. So you could add this in your page:

<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"
  </script>
<![endif]-->

By the way, you will have to use JavaScript to be able to test the existence of new HTML5 elements and give an alternate choice to those who have browsers that are not up to speed with certain HTML5 element and attributes. This is why there is this little generic JavaSCript function that you can use to do just that:

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if(attribute in test)
    return true;
  else
    return false;
}

One last note, I got most of this information from the book HTML5 For Web Designers. Kudos to Jeremy Keith!

HTML5 Doctype

If you mean the new doctype one <!DOCTYPE HTML>, here is what I have to say...

It isn't illegal to use features from previous HTML/XHTML version in HTML5. Note that the new doctype does not have any number associated with it. That is because it is meant to build upon existing specs and to be valid for future versions. Therefore, I say that you go with the new doctype.

You can have a look at the spec on the W3C site. In short the spec says this...

8.1.1 The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy
  reasons. When omitted, browsers tend
  to use a different rendering mode that
  is incompatible with some
  specifications. Including the DOCTYPE
  in a document ensures that the browser
  makes a best-effort attempt at
  following the relevant specifications.

[...]

For the purposes of HTML
  generators that cannot output HTML
  markup with the short DOCTYPE
  "<!DOCTYPE html>", a DOCTYPE legacy
  string may be inserted into the
  DOCTYPE (in the position defined
  above).


问:
How to read a file from internal storage?
I've just created a file in MainActivity using the code:

```<code>FileOutputStream outputStream = openFileOutput("user", Context.MODE_PRIVATE);
outputStream.close();
</code>```

Now what to use if I want to read the file (noting that the file will be obviously created in the internal storage)?

And is there a way that makes the file reading works as the Scanner function in Java (where the string is being read word by word and line by line)?

答:
This is your solution what I understood from your question,</p>

```<code>FileInputStream fIn = new FileInputStream(new File("FILE_PATH"));

BufferedReader bufferedReader = new BufferedReader(
  new InputStreamReader(fIn));

String str = bufferedReader.readLine();
</code>```

Body:
I've just created a file in MainActivity using the code:

FileOutputStream outputStream = openFileOutput("user", Context.MODE_PRIVATE);
outputStream.close();

Now what to use if I want to read the file (noting that the file will be obviously created in the internal storage)?

And is there a way that makes the file reading works as the Scanner function in Java (where the string is being read word by word and line by line)?

Body:
This is your solution what I understood from your question,

FileInputStream fIn = new FileInputStream(new File("FILE_PATH"));

BufferedReader bufferedReader = new BufferedReader(
  new InputStreamReader(fIn));

String str = bufferedReader.readLine();


问:
Searching fast for a file in a large directory in Python
I would like to search for a file in Python, however, the directory where I am looking for a file consists of many subdirectories and hundreds of thousands or even millions of files. So far I have used the following code, but it is very slow. Is there a faster way to find a file?</p>

```<code>for root, dirs, files in os.walk(search_dir):
    for name in files:
        if desired_filename==name:
            ...
</code>```

答:
If glob("**/filename") approach suggested by @Shadow doesn't work out well, you may want to build an index for the directory you work with:

```<code>import pickle
from collections import defaultdict

# run this once
index = defaultdict(str)
for path_to_file, file_name in walk(search_dir):
    index[file_name] += '{};'.format(path_to_file)
pickle.dump(index, 'index.bin')

# load index
index = pickle.load('index.bin')

# run this to get semicolon-separated list of paths that end with the file
paths = index['my_file.txt']
for path in paths.split(';')[:-1]:
    # do stuff with the file
</code>```

"Hundreds of thousands" of files isn't that large amount and will take around 10-100 Mb in RAM, depending on path length. I'm using defaultdict(str) to keep memory usage short and predictable, but you can also try defaultdict(list) or defaultdict(tuple).

To get an idea of execution speed of this approach, you can try this:

```<code>>>> d = {
    'file_{}.csv'.format(i): '/home/user/data/{};/home/user/backup;'.format(i)
    for i in range(500000)
}
>>> d['file_4021.csv']
'/home/user/data/4021;/home/user/backup;'
</code>```

Body:
I would like to search for a file in Python, however, the directory where I am looking for a file consists of many subdirectories and hundreds of thousands or even millions of files. So far I have used the following code, but it is very slow. Is there a faster way to find a file?

for root, dirs, files in os.walk(search_dir):
    for name in files:
        if desired_filename==name:
            ...

Body:
If glob("**/filename") approach suggested by @Shadow doesn't work out well, you may want to build an index for the directory you work with:

import pickle
from collections import defaultdict

# run this once
index = defaultdict(str)
for path_to_file, file_name in walk(search_dir):
    index[file_name] += '{};'.format(path_to_file)
pickle.dump(index, 'index.bin')

# load index
index = pickle.load('index.bin')

# run this to get semicolon-separated list of paths that end with the file
paths = index['my_file.txt']
for path in paths.split(';')[:-1]:
    # do stuff with the file

"Hundreds of thousands" of files isn't that large amount and will take around 10-100 Mb in RAM, depending on path length. I'm using defaultdict(str) to keep memory usage short and predictable, but you can also try defaultdict(list) or defaultdict(tuple).

To get an idea of execution speed of this approach, you can try this:

>>> d = {
    'file_{}.csv'.format(i): '/home/user/data/{};/home/user/backup;'.format(i)
    for i in range(500000)
}
>>> d['file_4021.csv']
'/home/user/data/4021;/home/user/backup;'


问:
JQuery append filters out html like tags?
I would like to append below line of text to the select html tag using JQuery:

"<option selected=true value="-1"><new></option>"

The problem is in <new>. This substring is filtered out completely by append function. I know this is not legal html tag, and probably it filters it just of this reason. Can I force JQuery somehow to interpret <new> as substring? Because <new> is not meant as html tag, but only to point out to the user that this is not the value in the list, but a selection to make a new entry on the list.

答:
take a look at this post :
How to display HTML tags as plain text

it shows you how to print special characters like < and > in between your code.

you should replace  < by < and > by >

Body:
take a look at this post :
How to display HTML tags as plain text

it shows you how to print special characters like < and > in between your code.

you should replace  < by &lt; and > by &gt;


问:
CodeIgniter and Grocery CRUD
Just a question to clarify things.
I have just started using CodeIgniter with Grocery CRUD, searching around i have found books and code examples for CodeIgniter but extremely little to find about Grocery CRUD, and for a "newbe" the Grocery Crud website and examples are not very easy to understand.
so, the question is:
What is the difference between these? i have read in the CodeIgniter documentation that it also have a CRUD....
Am I right to presume that Grocery Crud is a "plug-in" to CodeIgniter? so i could create the whole website with user management etc. in CodeIgniter and use Grocery Crud as a plugin where needed?

Is there any better places to get Grocery CRUD tutorials and code examples?
does any books exist about Grocery CRUD?

I am a "newbe" so please be gentle.

Thanks for any answers and pointers.

答:
Sorry to disappoint you but there ain't any book availed for GroceryCrud.
As for examples, the ones given on the site under documentation are as brief as required. Rest, many examples are shared in the documentation. If you looking for something like a cookbook, there ain't anything yet available. Many solutions that you may require are already put up inside grocerycrud forum. Users have been curiously asking for solutions and maximum of the issues are all resolved.

You can surely look around for the solutions inside the forum. If you still have queries, you can freely ask up in there, someone or the other must be answering in.

Title: CodeIgniter and Grocery CRUD


问:
CSS Transition with greensock
Is there any way to change the border color with greensock from top to down.
It's the simple line div and want to change its color from top to down, e.g.:

.line {
  position: relative;
  border: 1px solid #c3ced8;
  width: 0;
  height: 50px;
  display: block;
  content: '';
  z-index: 1;
  top: -19px;
  margin: 0;
  left: 5.3px;
  margin-bottom: -30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line"></div></code>```

Want to change its border color from top to down with greensock lib.

答:
You can do it with the border-image: linear-gradient(), e.g.:

.line {
  position: relative;
  border: 1px solid;
  width: 0;
  height: 50px;
  display: block;
  content: '';
  z-index: 1;
  top: -19px;
  margin: 0;
  left: 5.3px;
  margin-bottom: -30px;
  -webkit-border-image: -webkit-linear-gradient(#f00, #00f) 1;
  -o-border-image: -o-linear-gradient(#f00, #00f) 1;
  border-image: linear-gradient(to bottom, #f00, #00f) 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="line"></div></code>```

Title: CSS Transition with greensock

Body:
Is there any way to change the border color with greensock from top to down.
It's the simple line div and want to change its color from top to down, e.g.:

.line {
  position: relative;
  border: 1px solid #c3ced8;
  width: 0;
  height: 50px;
  display: block;
  content: '';
  z-index: 1;
  top: -19px;
  margin: 0;
  left: 5.3px;
  margin-bottom: -30px;
}

Want to change its border color from top to down with greensock lib.

Body:
You can do it with the border-image: linear-gradient(), e.g.:

.line {
  position: relative;
  border: 1px solid;
  width: 0;
  height: 50px;
  display: block;
  content: '';
  z-index: 1;
  top: -19px;
  margin: 0;
  left: 5.3px;
  margin-bottom: -30px;
  -webkit-border-image: -webkit-linear-gradient(#f00, #00f) 1;
  -o-border-image: -o-linear-gradient(#f00, #00f) 1;
  border-image: linear-gradient(to bottom, #f00, #00f) 1;
}

<div class="line"></div>


问:
AngularDart ngFor with input change
Tasks structure like: <Map<String,String>>[{'_tasknumber':'123'}]

Repository

```<code>@Component(
    template: '''
    <div *ngFor="let task of tasks">
                <label for="fileInput">
                    <material-button>
                        Add image
                    </material-button>
                </label>

          id: {{task['_tasknumber']}}

          <input type="file"
                id="fileInput"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>
    </div>
    ''')
</code>```

In function uploadFilesForTask I just print taskId value:

```<code>Future<Null> uploadFilesForTask(
      List<File> files, String taskId) async {
    print(taskId);
}
</code>```

When I press "Add image" button I every time get id of first task in list of  tasks.

When I press input button "Choose files" I get right id what I need.

How I can get right id of task by "Add image" button?

pubspec.yaml:

```<code>environment:
  sdk: '>=1.24.2'

dependencies:
  angular: '^4.0.0'
  angular_forms: '^1.0.0'
  angular_router: '^1.0.2'
  angular_components: '^0.8.0'
</code>```

答:
I use not unique label for attribute.

Not right:

```<code><label for="fileInput">
                    <material-button>
                        Add image
                    </material-button>
                </label>

          <input type="file"
                id="fileInput"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>
</code>```

Right:

```<code><label [attr.for]="task['_tasknumber']">
                    <material-button>
                        Add image
                    </material-button>
                </label>

          <input type="file"
                [attr.id]="task['_tasknumber']"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>
</code>```

Title: AngularDart ngFor with input change

Body:
Tasks structure like: <Map<String,String>>[{'_tasknumber':'123'}]

Repository

@Component(
    template: '''

                    <material-button>
                        Add image
                    </material-button>

          id: {{task['_tasknumber']}}

          <input type="file"
                id="fileInput"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>

    ''')

In function uploadFilesForTask I just print taskId value:

Future<Null> uploadFilesForTask(
      List<File> files, String taskId) async {
    print(taskId);
}

When I press "Add image" button I every time get id of first task in list of  tasks.

When I press input button "Choose files" I get right id what I need.

How I can get right id of task by "Add image" button?

pubspec.yaml:

environment:
  sdk: '>=1.24.2'

dependencies:
  angular: '^4.0.0'
  angular_forms: '^1.0.0'
  angular_router: '^1.0.2'
  angular_components: '^0.8.0'

Body:
I use not unique label for attribute.

Not right:

<label for="fileInput">
                    <material-button>
                        Add image
                    </material-button>
                </label>

          <input type="file"
                id="fileInput"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>

Right:

<label [attr.for]="task['_tasknumber']">
                    <material-button>
                        Add image
                    </material-button>
                </label>

          <input type="file"
                [attr.id]="task['_tasknumber']"
                multiple
                #fileInput
                (change)="uploadFilesForTask(fileInput.files, task['_tasknumber'])"/>


问:
Store ssh connections in rails
I have a rails app that needs to communicate with a couple of servers through ssh. I'm using the Net::SSH library and it works great. I would like however to be able to cache/store the ssh connections somehow between requests (something like OpenSSH multiplexing).

So, i can't store them in a key-value store like Memcached or Redis (because ssh connections are not serializable).

I don't want to store them in a session because they are meant to be used by all users (and besides i think it needs to be serializable also).

I managed to get this working with class variables and initiliazer constants. I know that class variables don't replicate between servers (in production), and i'm pretty certain initializer constants also don't. Something like:

initializer:

```<code>SSH = {}
</code>```

model:

```<code>class Server
    def connection
        require 'net/ssh'
        SSH[name] ||= Net::SSH.start(ip, "root", :password => password)
    end
end
</code>```

OpenSSH multiplexing would be great but i'm not sure if i could do that through the Net::SSH ruby library (i'm back to storing the master connection somewhere).

Are there any other solutions? Or if not, which one is the least evil of them all?

答:
Perhaps rather than trying to share sockets across requests which is bound to end up causing pain and suffering you could delegate to a background processor of some kind? You could set up an ssh tunnel and use DRb to talk across it as if it was just a local network daemon, or any of the large number of networked asynchronous job handling daemons.

http://ruby-toolbox.com/categories/queueing.html

Title: Store ssh connections in rails

Body:
I have a rails app that needs to communicate with a couple of servers through ssh. I'm using the Net::SSH library and it works great. I would like however to be able to cache/store the ssh connections somehow between requests (something like OpenSSH multiplexing).

So, i can't store them in a key-value store like Memcached or Redis (because ssh connections are not serializable).

I don't want to store them in a session because they are meant to be used by all users (and besides i think it needs to be serializable also).

I managed to get this working with class variables and initiliazer constants. I know that class variables don't replicate between servers (in production), and i'm pretty certain initializer constants also don't. Something like:

initializer:

SSH = {}

model:

class Server
    def connection
        require 'net/ssh'
        SSH[name] ||= Net::SSH.start(ip, "root", :password => password)
    end
end

OpenSSH multiplexing would be great but i'm not sure if i could do that through the Net::SSH ruby library (i'm back to storing the master connection somewhere).

Are there any other solutions? Or if not, which one is the least evil of them all?


问:
Angular 2.0.1 Router EmptyError: no elements in sequence
I'm having trouble getting Angular 2 routing to work. I am using Angular 2 and Webpack. In the Angular 2 webpack starter, I noticed they had webpack generating their html and their links, but I was hoping I would not have to webpack my html files.

Here's my app.routes.ts...

```<code>import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from "./home/home.component";
import { ScheduleComponent } from "./schedule/schedule.component";
import { PageNotFoundComponent } from "./PageNotFoundComponent";

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'schedule', component: ScheduleComponent },
    { path: '**', component: PageNotFoundComponent }
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

Here's my @NgModule code...

```<code>@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        routing ],
    declarations: [
        AppComponent,
        AppBanner,
        AppLogin,
        HomeComponent,
        ScheduleComponent,
        PageNotFoundComponent
    ],
    bootstrap: [ AppComponent ],
    providers: [
        ApplicationState,
        appRoutingProviders
    ]
})
export class AppModule { }
</code>```

Here is the schedule component...

```<code>import { Component } from '@angular/core';

@Component({
    template: `
    <div>Schedule</div>
    `
})
export class ScheduleComponent {

}
</code>```

And here's my HTML where I tried to add my routes...

```<code><a [routerLink]=" ['/schedule'] ">Schedule</a>
</code>```

I know this is a lot of code, but here is my webpack build as well. As you can see, the webpack task does not touch my HTML pages, so this webpack code may be irrelevant...

```<code>module.exports = {
    entry: {
        'polyfills': __dirname + '/src/polyfills.ts',
        'vendor': __dirname + '/src/vendor.ts',
        'app': __dirname + '/src/main.ts'
    },

    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/src/bundle/',
        publicPath: '/',
        sourceMapFilename: __dirname + '/src/bundle/[name].bundle.map.js'
    },

    resolve: {
        extensions: ['', '.ts', '.js'],
        alias: { 'rxjs': 'rxjs-es' }
    },

    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            },
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader']
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract("style-loader", "css-loader")
            },
            { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file?name=/fonts/[name].[ext]" },
            { test: /\.(woff|woff2)$/, loader:"url?prefix=font/&limit=5000&name=/fonts/[name].[ext]" },
            { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream&name=/fonts/[name].[ext]" },
            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml&name=/fonts/[name].[ext]" }
        ]
    },

    plugins: [
        new ExtractTextPlugin('css/[name].css')
    ]
}
</code>```

Unfortunately, when I click on the Schedule link, I just get an error. Here's the detailed error info from zone...

```<code>Unhandled Promise rejection: no elements in sequence ; Zone: angular ;
Task: Promise.then ; Value: Error: no elements in sequence(…)
EmptyError: no elements in sequence
</code>```

Any tips? What is the problem here?

答:
This bug is due to the last version of Angular's Router. Please remove revert back angular version or add pathMatch: 'full' to your routes.

```<code>export const userRoutes = [
    { path: 'profile', component: ProfileComponent, pathMatch: 'full' },
    { path: 'login', component: LoginComponent, pathMatch: 'full' }
];

export const appRoutes = [
    { path: '', redirectTo: '/events', pathMatch: 'full' },
    { path: 'user', loadChildren: './user/user.module#UserModule' }
];
</code>```

You can find the issue here

Body:
I'm having trouble getting Angular 2 routing to work. I am using Angular 2 and Webpack. In the Angular 2 webpack starter, I noticed they had webpack generating their html and their links, but I was hoping I would not have to webpack my html files.

Here's my app.routes.ts...

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from "./home/home.component";
import { ScheduleComponent } from "./schedule/schedule.component";
import { PageNotFoundComponent } from "./PageNotFoundComponent";

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'schedule', component: ScheduleComponent },
    { path: '**', component: PageNotFoundComponent }
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Here's my @NgModule code...

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        routing ],
    declarations: [
        AppComponent,
        AppBanner,
        AppLogin,
        HomeComponent,
        ScheduleComponent,
        PageNotFoundComponent
    ],
    bootstrap: [ AppComponent ],
    providers: [
        ApplicationState,
        appRoutingProviders
    ]
})
export class AppModule { }

Here is the schedule component...

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

@Component({
    template: `

Schedule

    `
})
export class ScheduleComponent {

}

And here's my HTML where I tried to add my routes...

Schedule

I know this is a lot of code, but here is my webpack build as well. As you can see, the webpack task does not touch my HTML pages, so this webpack code may be irrelevant...

module.exports = {
    entry: {
        'polyfills': __dirname + '/src/polyfills.ts',
        'vendor': __dirname + '/src/vendor.ts',
        'app': __dirname + '/src/main.ts'
    },

    output: {
        filename: '[name].bundle.js',
        path: __dirname + '/src/bundle/',
        publicPath: '/',
        sourceMapFilename: __dirname + '/src/bundle/[name].bundle.map.js'
    },

    resolve: {
        extensions: ['', '.ts', '.js'],
        alias: { 'rxjs': 'rxjs-es' }
    },

    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015']
                }
            },
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader']
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract("style-loader", "css-loader")
            },
            { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file?name=/fonts/[name].[ext]" },
            { test: /\.(woff|woff2)$/, loader:"url?prefix=font/&limit=5000&name=/fonts/[name].[ext]" },
            { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream&name=/fonts/[name].[ext]" },
            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml&name=/fonts/[name].[ext]" }
        ]
    },

    plugins: [
        new ExtractTextPlugin('css/[name].css')
    ]
}

Unfortunately, when I click on the Schedule link, I just get an error. Here's the detailed error info from zone...

Unhandled Promise rejection: no elements in sequence ; Zone: angular ;
Task: Promise.then ; Value: Error: no elements in sequence(…)
EmptyError: no elements in sequence

Any tips? What is the problem here?

Body:
This bug is due to the last version of Angular's Router. Please remove revert back angular version or add pathMatch: 'full' to your routes.

export const userRoutes = [
    { path: 'profile', component: ProfileComponent, pathMatch: 'full' },
    { path: 'login', component: LoginComponent, pathMatch: 'full' }
];

export const appRoutes = [
    { path: '', redirectTo: '/events', pathMatch: 'full' },
    { path: 'user', loadChildren: './user/user.module#UserModule' }
];

You can find the issue here


问:
Does Laravel-Excel has native method of PHP Excel?
I want to use Laravel-Excel, but my concern is which can I use native PHP-Excel method or not, as I have read the documentation. Laravel-Excel is run on of PHP-Excel. </p>

答:
From Laravel-Excel github page:

An eloquent way of importing and exporting Excel and CSV files for Laravel with the power of PHPExcel

So yes, this package is just a wrapper around the PHPExcel package but it adds conveniences for a laravel project as it follows Laravel's own Eloquent model.


问:
getting coreml running in objective-C
I'm having trouble creating a very simple example of using Apple's CoreML in Objective-C. I have already created a model file using python which works rather simply now:

```<code>coreml_model_svm = coremltools.models.MLModel("svm.mlmodel")
test_x = [1.0 for x in range(160)]
predictions_coreml_svm = coreml_model_svm.predict({"input":test_x})
</code>```

I would like to reproduce the above three lines in Objective-C. I know that my data has to be an MLMultiArray and the model needs to be loaded into MLModel. I've been trying to find some info on the syntax, but it seems I don't understand how the documentation works, and all the examples are in Swift. Here's my code so far. Commenting the MLMultiArray leads to an uncaught exception for initializing the MLModel. When not commenting the MLMultiArray I get no known class method for selector 'initWithShape:dataType:error'.

```<code>#import <Foundation/Foundation.h>
#import <CoreML/CoreML.h>

//clang -framework Foundation coremltest.m -o coremltest
int main (int argc, const char * argv[])
{
        NSLog(@"start");

        NSArray * shape = [[NSArray alloc]  init];
        MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
        NSError * error = nil;

        MLMultiArray * input =  [MLMultiArray initWithShape:(NSArray*) shape
                             dataType:(MLMultiArrayDataType ) dataType
                        error:(NSError **) error];

        MLModel * mymodel = [[MLModel init] initWithContentsOfFile:@"svm.mlmodel"];

        return 0;
}
</code>```

I would appreciate any help with this.

答:
First of all you need to import the your model class, in your case svm (would be better Svm starting with upper case letter):

```<code>#import "svm.h"
</code>```

This class definition contains all the informations you need for the inputs and outputs and the method definitions.
You could find this specification in the automatically generated class description by clicking on the small arrow just next the class name when you choose the mlmodel file on the left. In this class description

In your case the input is a MLMultiArray with 160 Double elements as a vector. So first define the dimensions with the shape array

```<code>NSArray *shape = @[@1, @160];
</code>```

Then define the MLMultiArray which will be your svmModelInput for the prediction process (defined by XCode automatically again):

```<code>    MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
    NSError *error = nil;

    MLMultiArray *theMultiArray =  [[MLMultiArray alloc] initWithShape:(NSArray*)shape
                                          dataType:(MLMultiArrayDataType)dataType
                                             error:&error] ;

    for (int i = 0; i < 160; i++) {
         [theMultiArray setObject:[NSNumber numberWithDouble:1.0] atIndexedSubscript:(NSInteger)i];
    }
</code>```

The used

initWithShape

is an MLMultiArray method by Apple. I filled the array with "1" just for  test, but you have to replace it later with your real input of course.

No need to get your model, just instantiate your svm then run the

predictionFromInput:

method which is from the class built by the XCode again:

```<code>        svm *mySvm = [[svm alloc] init];

        svmOutput * svmModelOutput = [(svm *)mySvm predictionFromInput:theMultiArray error:&error];
        NSLog(@"SVM Model output = %lld -- %@", svmModelOutput.classLabel, svmModelOutput.classProbability );

           if (!error)
           {
               NSLog(@"svm finished without error");
           }
           else
           {
               NSLog(@"Error: %@", error.localizedDescription);
           }
</code>```

As you print out the svmModelOutput (created by XCode for you) you can check the predicted classLabel as an Integer and the probabilities for all the labels, like this:

```<code>2017-12-04 07:32:45.765015+0100 CoreML_test[2634:877638] SVM Model output = 2 -- {
    11 = "0.002656571278812773";
    3 = "0.2121030282896462";
    10 = "0.004570897664662783";
    2 = "0.5825387375626612";
    9 = "0.02911120023388797";
    4 = "0.1690195649703292";
}
</code>```

Title: getting coreml running in objective-C

Body:
I'm having trouble creating a very simple example of using Apple's CoreML in Objective-C. I have already created a model file using python which works rather simply now:

coreml_model_svm = coremltools.models.MLModel("svm.mlmodel")
test_x = [1.0 for x in range(160)]
predictions_coreml_svm = coreml_model_svm.predict({"input":test_x})

I would like to reproduce the above three lines in Objective-C. I know that my data has to be an MLMultiArray and the model needs to be loaded into MLModel. I've been trying to find some info on the syntax, but it seems I don't understand how the documentation works, and all the examples are in Swift. Here's my code so far. Commenting the MLMultiArray leads to an uncaught exception for initializing the MLModel. When not commenting the MLMultiArray I get no known class method for selector 'initWithShape:dataType:error'.

#import <Foundation/Foundation.h>
#import <CoreML/CoreML.h>

//clang -framework Foundation coremltest.m -o coremltest
int main (int argc, const char * argv[])
{
        NSLog(@"start");

        NSArray * shape = [[NSArray alloc]  init];
        MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
        NSError * error = nil;

        MLMultiArray * input =  [MLMultiArray initWithShape:(NSArray*) shape
                             dataType:(MLMultiArrayDataType ) dataType
                        error:(NSError **) error];

        MLModel * mymodel = [[MLModel init] initWithContentsOfFile:@"svm.mlmodel"];

        return 0;
}

I would appreciate any help with this.

Body:
First of all you need to import the your model class, in your case svm (would be better Svm starting with upper case letter):

#import "svm.h"

This class definition contains all the informations you need for the inputs and outputs and the method definitions.
You could find this specification in the automatically generated class description by clicking on the small arrow just next the class name when you choose the mlmodel file on the left. In this class description

In your case the input is a MLMultiArray with 160 Double elements as a vector. So first define the dimensions with the shape array

NSArray *shape = @[@1, @160];

Then define the MLMultiArray which will be your svmModelInput for the prediction process (defined by XCode automatically again):

    MLMultiArrayDataType dataType = MLMultiArrayDataTypeDouble;
    NSError *error = nil;

    MLMultiArray *theMultiArray =  [[MLMultiArray alloc] initWithShape:(NSArray*)shape
                                          dataType:(MLMultiArrayDataType)dataType
                                             error:&error] ;

    for (int i = 0; i < 160; i++) {
         [theMultiArray setObject:[NSNumber numberWithDouble:1.0] atIndexedSubscript:(NSInteger)i];
    }

The used

initWithShape

is an MLMultiArray method by Apple. I filled the array with "1" just for  test, but you have to replace it later with your real input of course.

No need to get your model, just instantiate your svm then run the

predictionFromInput:

method which is from the class built by the XCode again:

        svm *mySvm = [[svm alloc] init];

        svmOutput * svmModelOutput = [(svm *)mySvm predictionFromInput:theMultiArray error:&error];
        NSLog(@"SVM Model output = %lld -- %@", svmModelOutput.classLabel, svmModelOutput.classProbability );

           if (!error)
           {
               NSLog(@"svm finished without error");
           }
           else
           {
               NSLog(@"Error: %@", error.localizedDescription);
           }

As you print out the svmModelOutput (created by XCode for you) you can check the predicted classLabel as an Integer and the probabilities for all the labels, like this:

2017-12-04 07:32:45.765015+0100 CoreML_test[2634:877638] SVM Model output = 2 -- {
    11 = "0.002656571278812773";
    3 = "0.2121030282896462";
    10 = "0.004570897664662783";
    2 = "0.5825387375626612";
    9 = "0.02911120023388797";
    4 = "0.1690195649703292";
}