问:
Model Binding on Save isn't returning full List of Nested Objects, maximum of one
Model Binding on Save isn't returning full List of Nested Objects, maximum of one

Trying to understand EditorTemplates, here is a simple example that isn't working at the moment.  The Model isn't returning the full IList
of items, it seems to be returning 1 object each time when there should be 2 in my example.

When I Edit ModelA, the example is:

```<code>- Name: Model A
    List of Model Bs:
        - Name: Model B1
            List of Model Cs:
                - Name: Model C1
                - Name: Model C2
        - Name: Model B2
</code>```

This list shows up properly during Edit, but upon Save, some of the information is "lost", added (not found) below.

```<code>- Name: Model A (in Model)
    List of Model Bs:
        - Name: Model B1 (in Model)
            List of Model Cs:
                - Name: Model C1 (in Model)
                - Name: Model C2 (not found)
        - Name: Model B2 (not found)
</code>```

Basically, on Save, the Model is not returning any more than one object from a list.

Classes:

BaseObject:

```<code>public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Oid { get; set; }

}
</code>```

ModelA, ModelB and ModelC:

```<code>public class ModelA : BaseObject
{
    public string Name { get; set; }
    public virtual IList<ModelB> ModelBs { get; set; }
}

public class ModelB : BaseObject
{
    public string Name { get; set; }

    public Guid? ModelAID { get; set; }

    [ForeignKey("ModelAID")]
    public virtual ModelA ModelA { get; set; }

    public virtual IList<ModelC> ModelCs { get; set; }
}

public class ModelC : BaseObject
{
    public string Name { get; set; }

    public Guid? ModelBID { get; set; }

    [ForeignKey("ModelBID")]
    public virtual ModelB ModelB { get; set; }
}
</code>```

Basic Controller for ModelA, here is the Edit:

```<code>public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    ModelA modelA = db.ModelAs.Find(id);
    if (modelA == null)
    {
        return HttpNotFound();
    }
    return View(modelA);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ModelA modelA)
//Removed: [Bind(Include = "Oid,Name,DateCreated,DateUpdated,DateDeleted,IsDeleted")]
{
    if (ModelState.IsValid) //Break point to review "modelA"
    {
        db.Entry(modelA).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(modelA);
}
</code>```

Views:

Edit.cshtml (for ModelA):

```<code>@model x.Models.Nesting.ModelA

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.EditorForModel(Model)
}
</code>```

Views in Views/Shared/EditorTemplates:

ModelA.cshtml:

```<code>@model x.Models.Nesting.ModelA

<div class="form-horizontal">
    <h4>ModelA</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ModelBs, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.EditorFor(model => model.ModelBs)

            @* Tried the code below as well *@
            @*
            @for (var i = 0; i < Model.ModelBs.Count(); i++)
            {
                @Html.EditorFor(m => m.ModelBs[i])
            }
            *@

        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
</code>```

ModelB.cshtml:

```<code>@model x.Models.Nesting.ModelB
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)
        @Html.HiddenFor(model => model.ModelAID)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ModelCs, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @Html.EditorFor(model => model.ModelCs)

                @* Tried the code below as well *@
                @*
                @foreach(var item in Model.ModelCs)
                {
                    @Html.EditorFor(x => item)
                }
                *@

            </div>
        </div>

    </div>
}
</code>```

ModelC.cshtml:

```<code>@model x.Models.Nesting.ModelC

@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)
        @Html.HiddenFor(model => model.ModelBID)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

    </div>
}
</code>```

As an example from the HTML (when using @Html.EditorFor(model => model.ModelBs)), the binding for both ModelB objects look look like they would be bound properly (but it only returns the first object):

Model B1:

```<code><input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__Oid"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b934">

<input
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__ModelAID"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__Name"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].Name"
    type="text"
    value="Model B1" aria-invalid="false">
</code>```

Model B2:

```<code><input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__Oid"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b936">

<input
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__ModelAID"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__Name"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].Name"
    type="text"
    value="Model B2" aria-invalid="false">
</code>```

When using the for loop in ModelA, looping ModelB (@for (var i = 0; i < Model.ModelBs.Count(); i++) { @Html.EditorFor(m => m.ModelBs[i]) }), the Indexes are Numbers, but still don't return full Models.

Model B1:

```<code><input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_0__Oid" name="ModelBs[0].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b934">

<input
    id="ModelBs_0__ModelAID"
    name="ModelBs[0].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_0__Name" name="ModelBs[0].Name"
    type="text"
    value="Model B1" aria-invalid="false">
</code>```

Model B2:

```<code><input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_1__Oid" name="ModelBs[1].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b936">

<input
    id="ModelBs_1__ModelAID" name="ModelBs[1].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_1__Name" name="ModelBs[1].Name"
    type="text"
    value="Model B 2" aria-invalid="false">
</code>```

POST Form Data:

@Html.EditorFor(...) POST (didn't update ModelBs list of ModelCs):

```<code>__RequestVerificationToken:1PfXHdYtb5eE-j6g4DWBEZiRa0trOL8UvYGKVjL0pxR1qOjQE52be7UB14VaIJRpp5UA1Iz9WXt4g_7LKixKhK7ah7Hjp6hOLmLa1m7XavI1
Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name:Model A1
ModelBs.index:4a481093-9bdd-43ae-b84b-144c576ff346
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelAID:7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].Name:Model B1
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].ModelBID:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].Name:Model C 1
ModelBs.index:a1dd130d-a1f7-47ed-90a2-28055a960c9b
</code>```

For loop POST:

```<code>__RequestVerificationToken:x9hpnm-c1g0Cm9gTnSRjCFIVflziqXqiO3iFkzVpMc33gnNlBoDsvwBHMmRT38sWTCGrFSqCqzcuuBZdXLsXTgX1EbkqUSqPuAtwUrR1XXA1
Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name:Model A1
ModelBs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[0].ModelAID:7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[0].Name:Model B1
ModelBs[0].ModelCs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[0].ModelCs[0].ModelBID:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[0].ModelCs[0].Name:Model C 1
</code>```

EditorFor has ModelBs.index twice (hopeful this leads to a solution), but not in the For.  Something getting cut off> (I double and triple checked that I wasn't missing something further down)

FireFox POST data, looks like the Indexes of 0 and 1 are working to some extent:

```<code>__RequestVerificationToken  qlrlO7Z0_byGZYLGJ6Tbx5Fzmpd0dd6b-JPac4V-f1U-17v06OQr27dYZPh_VmRI3X4nGj7ZAOHtBdERnuZscJlNlgoHAqdeXaNQN04e2qE1
Oid 7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name    Model+A1
ModelBs.index   […]
0   3d003e30-d350-4fb0-becd-f65207b033c4
1   be4e35c3-3fee-4c7f-9ee7-580b6e0c8169
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].Oid   7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelAID  7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].Name  Model+B1
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].Oid    7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].ModelBID   7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].Name   Model+C+1
</code>```

... the mystery continues

答:
The EditorTemplate files (cshtml) for ModelB and ModelC had @using (Html.BeginForm())
{ ... }, removing this resolved the issue, allowing the POST to contain all the information.  Kept the BeginForm on ModelA, that is required.

I figured it out when reviewing the POST information, it showed a(n) .index for the second ModelB, but no associated data, it also has a form tag directly below, everyone knows that many form tags isn't good.

Updated cshtml

ModelB.cshtml:

```<code>@model x.Models.Nesting.ModelB

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)
    @Html.HiddenFor(model => model.ModelAID)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ModelCs, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.EditorFor(model => model.ModelCs)

            @* Tried the code below as well *@
            @*
            @foreach(var item in Model.ModelCs)
            {
                @Html.EditorFor(x => item)
            }
            *@

        </div>
    </div>

</div>
</code>```

ModelC.cshtml:

```<code>@model x.Models.Nesting.ModelC

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)
    @Html.HiddenFor(model => model.ModelBID)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

</div>
</code>```

Body:
Model Binding on Save isn't returning full List of Nested Objects, maximum of one

Trying to understand EditorTemplates, here is a simple example that isn't working at the moment.  The Model isn't returning the full IList
of items, it seems to be returning 1 object each time when there should be 2 in my example.

When I Edit ModelA, the example is:

- Name: Model A
    List of Model Bs:
        - Name: Model B1
            List of Model Cs:
                - Name: Model C1
                - Name: Model C2
        - Name: Model B2

This list shows up properly during Edit, but upon Save, some of the information is "lost", added (not found) below.

- Name: Model A (in Model)
    List of Model Bs:
        - Name: Model B1 (in Model)
            List of Model Cs:
                - Name: Model C1 (in Model)
                - Name: Model C2 (not found)
        - Name: Model B2 (not found)

Basically, on Save, the Model is not returning any more than one object from a list.

Classes:

BaseObject:

public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Oid { get; set; }

}

ModelA, ModelB and ModelC:

public class ModelA : BaseObject
{
    public string Name { get; set; }
    public virtual IList<ModelB> ModelBs { get; set; }
}

public class ModelB : BaseObject
{
    public string Name { get; set; }

    public Guid? ModelAID { get; set; }

    [ForeignKey("ModelAID")]
    public virtual ModelA ModelA { get; set; }

    public virtual IList<ModelC> ModelCs { get; set; }
}

public class ModelC : BaseObject
{
    public string Name { get; set; }

    public Guid? ModelBID { get; set; }

    [ForeignKey("ModelBID")]
    public virtual ModelB ModelB { get; set; }
}

Basic Controller for ModelA, here is the Edit:

public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    ModelA modelA = db.ModelAs.Find(id);
    if (modelA == null)
    {
        return HttpNotFound();
    }
    return View(modelA);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ModelA modelA)
//Removed: [Bind(Include = "Oid,Name,DateCreated,DateUpdated,DateDeleted,IsDeleted")]
{
    if (ModelState.IsValid) //Break point to review "modelA"
    {
        db.Entry(modelA).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(modelA);
}

Views:

Edit.cshtml (for ModelA):

@model x.Models.Nesting.ModelA

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.EditorForModel(Model)
}

Views in Views/Shared/EditorTemplates:

ModelA.cshtml:

@model x.Models.Nesting.ModelA

ModelA

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)

        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.ModelBs, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.ModelBs)

            @* Tried the code below as well *@
            @*
            @for (var i = 0; i < Model.ModelBs.Count(); i++)
            {
                @Html.EditorFor(m => m.ModelBs[i])
            }
            *@

            <input type="submit" value="Save" class="btn btn-default" />

ModelB.cshtml:

@model x.Models.Nesting.ModelB
@using (Html.BeginForm())
{

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)
        @Html.HiddenFor(model => model.ModelAID)

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ModelCs, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.ModelCs)

                @* Tried the code below as well *@
                @*
                @foreach(var item in Model.ModelCs)
                {
                    @Html.EditorFor(x => item)
                }
                *@

}

ModelC.cshtml:

@model x.Models.Nesting.ModelC

@using (Html.BeginForm())
{

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)
        @Html.HiddenFor(model => model.ModelBID)

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

}

As an example from the HTML (when using @Html.EditorFor(model => model.ModelBs)), the binding for both ModelB objects look look like they would be bound properly (but it only returns the first object):

Model B1:

<input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__Oid"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b934">

<input
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__ModelAID"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_f1aa613f-96f4-427f-a568-c70556ad2117__Name"
    name="ModelBs[f1aa613f-96f4-427f-a568-c70556ad2117].Name"
    type="text"
    value="Model B1" aria-invalid="false">

Model B2:

<input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__Oid"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b936">

<input
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__ModelAID"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_128318da-af85-46a5-bc0d-71361610d989__Name"
    name="ModelBs[128318da-af85-46a5-bc0d-71361610d989].Name"
    type="text"
    value="Model B2" aria-invalid="false">

When using the for loop in ModelA, looping ModelB (@for (var i = 0; i < Model.ModelBs.Count(); i++) { @Html.EditorFor(m => m.ModelBs[i]) }), the Indexes are Numbers, but still don't return full Models.

Model B1:

<input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_0__Oid" name="ModelBs[0].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b934">

<input
    id="ModelBs_0__ModelAID"
    name="ModelBs[0].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_0__Name" name="ModelBs[0].Name"
    type="text"
    value="Model B1" aria-invalid="false">

Model B2:

<input
    data-val="true" data-val-required="The Oid field is required."
    id="ModelBs_1__Oid" name="ModelBs[1].Oid"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b936">

<input
    id="ModelBs_1__ModelAID" name="ModelBs[1].ModelAID"
    type="hidden"
    value="7e99950b-62c9-e711-afd4-7cb0c2b5b935">

<input
    class="form-control text-box single-line valid"
    id="ModelBs_1__Name" name="ModelBs[1].Name"
    type="text"
    value="Model B 2" aria-invalid="false">

POST Form Data:

@Html.EditorFor(...) POST (didn't update ModelBs list of ModelCs):

__RequestVerificationToken:1PfXHdYtb5eE-j6g4DWBEZiRa0trOL8UvYGKVjL0pxR1qOjQE52be7UB14VaIJRpp5UA1Iz9WXt4g_7LKixKhK7ah7Hjp6hOLmLa1m7XavI1
Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name:Model A1
ModelBs.index:4a481093-9bdd-43ae-b84b-144c576ff346
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelAID:7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].Name:Model B1
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].ModelBID:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[4a481093-9bdd-43ae-b84b-144c576ff346].ModelCs[0].Name:Model C 1
ModelBs.index:a1dd130d-a1f7-47ed-90a2-28055a960c9b

For loop POST:

__RequestVerificationToken:x9hpnm-c1g0Cm9gTnSRjCFIVflziqXqiO3iFkzVpMc33gnNlBoDsvwBHMmRT38sWTCGrFSqCqzcuuBZdXLsXTgX1EbkqUSqPuAtwUrR1XXA1
Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name:Model A1
ModelBs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[0].ModelAID:7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[0].Name:Model B1
ModelBs[0].ModelCs[0].Oid:7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[0].ModelCs[0].ModelBID:7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[0].ModelCs[0].Name:Model C 1

EditorFor has ModelBs.index twice (hopeful this leads to a solution), but not in the For.  Something getting cut off> (I double and triple checked that I wasn't missing something further down)

FireFox POST data, looks like the Indexes of 0 and 1 are working to some extent:

__RequestVerificationToken  qlrlO7Z0_byGZYLGJ6Tbx5Fzmpd0dd6b-JPac4V-f1U-17v06OQr27dYZPh_VmRI3X4nGj7ZAOHtBdERnuZscJlNlgoHAqdeXaNQN04e2qE1
Oid 7e99950b-62c9-e711-afd4-7cb0c2b5b935
Name    Model+A1
ModelBs.index   […]
0   3d003e30-d350-4fb0-becd-f65207b033c4
1   be4e35c3-3fee-4c7f-9ee7-580b6e0c8169
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].Oid   7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelAID  7e99950b-62c9-e711-afd4-7cb0c2b5b935
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].Name  Model+B1
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].Oid    7e99950b-62c9-e711-afd4-7cb0c2b5b936
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].ModelBID   7e99950b-62c9-e711-afd4-7cb0c2b5b934
ModelBs[3d003e30-d350-4fb0-becd-f65207b033c4].ModelCs[0].Name   Model+C+1

... the mystery continues

Body:
The EditorTemplate files (cshtml) for ModelB and ModelC had @using (Html.BeginForm())
{ ... }, removing this resolved the issue, allowing the POST to contain all the information.  Kept the BeginForm on ModelA, that is required.

I figured it out when reviewing the POST information, it showed a(n) .index for the second ModelB, but no associated data, it also has a form tag directly below, everyone knows that many form tags isn't good.

Updated cshtml

ModelB.cshtml:

@model x.Models.Nesting.ModelB

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)
    @Html.HiddenFor(model => model.ModelAID)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ModelCs, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.EditorFor(model => model.ModelCs)

            @* Tried the code below as well *@
            @*
            @foreach(var item in Model.ModelCs)
            {
                @Html.EditorFor(x => item)
            }
            *@

        </div>
    </div>

</div>

ModelC.cshtml:

@model x.Models.Nesting.ModelC

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Oid)
    @Html.HiddenFor(model => model.ModelBID)

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

</div>


来源: stackexchange

问:
Iferror/Index/Match formula that was formerly working now returns all False results despite values existing on target sheet
I wrote a macro some time ago to search for values from one spreadsheet (Data) on another spreadsheet (Sheet1), then pull the value from the cell 2 columns to the left of where the result was found on Sheet1. It was working great, but something seems to have changed(???) and it's now returning all "False" results, despite the fact that the values certainly exist in both spreadsheets.

It searches for the values in Column C on the first worksheet on the second sheet (always called Sheet1)

I can provide the spreadsheets in question for any testing.
My annotated code is below, any help would be greatly appreciated:

```<code>Sub GroupFileNameFix()
'
' GroupFileNameFix Macro

'define variable types
Dim strFormula As Variant
Dim LastRow As Long

'on Data sheet
With ActiveSheet
' determines last row on spreadsheet and saves value to variable "LastRow"
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   'sets variable "strFormula" as what we want to autofill, grabbing group filenames
strFormula = "=IFERROR(INDEX(Sheet1!RC[-3],(MATCH(RC[1],Sheet1!C[-1],0))),""False"")"
'inserts column "GroupFileName" as column D
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "GroupFileName"
Columns("D:D").EntireColumn.AutoFit
' Fills cell D2 and then autofills column D to end of spreadsheet
Range("D2:D2").Select
.Range("D2:D2").Formula = strFormula
.Range("D2:D" & LastRow).FillDown
End With
'Commit formula to text and replace "png" with "jpg"
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Selection.Replace What:="png", Replacement:="jpg", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

End Sub
</code>```

答:
Based on your code, since you are always putting the formula in the same column, this worked for me. </p>

```<code>With ActiveSheet
 strFormula = "=IFERROR(INDEX(Sheet1!A2,(MATCH(E2,Sheet1!C:C,0))),""False"")"
 'inserts column "GroupFileName" as column D
 Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
 Range("D1").Value = "GroupFileName"
 Columns("D:D").EntireColumn.AutoFit
 ' Fills cell D2 and then autofills column D to end of spreadsheet
 .Range("D2").Formula = strFormula
 .Range("D2:D" & LastRow).FillDown
End With
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wrote a macro some time ago to search for values from one spreadsheet (Data) on another spreadsheet (Sheet1), then pull the value from the cell 2 columns to the left of where the result was found on Sheet1. It was working great, but something seems to have changed(???) and it's now returning all "False" results, despite the fact that the values certainly exist in both spreadsheets.

It searches for the values in Column C on the first worksheet on the second sheet (always called Sheet1)

I can provide the spreadsheets in question for any testing.
My annotated code is below, any help would be greatly appreciated:

Sub GroupFileNameFix()
'
' GroupFileNameFix Macro

'define variable types
Dim strFormula As Variant
Dim LastRow As Long

'on Data sheet
With ActiveSheet
' determines last row on spreadsheet and saves value to variable "LastRow"
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   'sets variable "strFormula" as what we want to autofill, grabbing group filenames
strFormula = "=IFERROR(INDEX(Sheet1!RC[-3],(MATCH(RC[1],Sheet1!C[-1],0))),""False"")"
'inserts column "GroupFileName" as column D
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "GroupFileName"
Columns("D:D").EntireColumn.AutoFit
' Fills cell D2 and then autofills column D to end of spreadsheet
Range("D2:D2").Select
.Range("D2:D2").Formula = strFormula
.Range("D2:D" & LastRow).FillDown
End With
'Commit formula to text and replace "png" with "jpg"
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Selection.Replace What:="png", Replacement:="jpg", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

End Sub

Body:
Based on your code, since you are always putting the formula in the same column, this worked for me.

With ActiveSheet
 strFormula = "=IFERROR(INDEX(Sheet1!A2,(MATCH(E2,Sheet1!C:C,0))),""False"")"
 'inserts column "GroupFileName" as column D
 Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
 Range("D1").Value = "GroupFileName"
 Columns("D:D").EntireColumn.AutoFit
 ' Fills cell D2 and then autofills column D to end of spreadsheet
 .Range("D2").Formula = strFormula
 .Range("D2:D" & LastRow).FillDown
End With


问:
Change the default window font in a Win32 Windows project
I am creating a GUI application using C and Win32 api. I would like to know how we can change the default font of the Main window to thaoma. I am comming from .NET background. In .NET if we change the font of parent control then automatically the child controls inherits that font....
Is there away similar to it or do we need to manually set the font of each control.....

Consider the following code...

```<code>#include <windows.h>

#define ID_EDIT 1
#define ID_BUTTON 2

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

  static HWND hwndEdit;
  static HWND hwndButton;
  static int len;
  static TCHAR text[30];

  switch(msg)
  {
    case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

    case WM_DESTROY:
        PostQuitMessage(0);
    break;
  }
  return DefWindowProc(hwnd, msg, wParam, lParam);
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
            LPSTR lpCmdLine, int nCmdShow )
{
  MSG  msg ;
  WNDCLASS wc = {0};
  wc.lpszClassName = TEXT( "Edit Control" );
  wc.hInstance     = hInstance ;
  wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
  wc.lpfnWndProc   = WndProc ;
  wc.hCursor       = LoadCursor(0,IDC_ARROW);

  RegisterClass(&wc);
  CreateWindow( wc.lpszClassName, TEXT("Edit control"),
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                220, 220, 280, 200, 0, 0, hInstance, 0);

  while( GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return (int) msg.wParam;
}
</code>```

How can i change the font of button, textbox in the above program..

Please help me here.......and let me know the general process followed while coding in win32 api....

THanks in advance..

答:
You can set the font of a window by sending it the WM_SETFONT message:

```<code>HWND myButton = CreateWindowEx(/* ... */);
HFONT myFont  = /* ... load font from somewhere ... */

/* Change the button font. */
SendMessage(myButton, WM_SETFONT, WPARAM(myFont), TRUE);
</code>```

This approach gives you a control-by-control control over which fonts you're using, but you only need to do it once per window.

ContentLicense: CC BY-SA 4.0

Body:
I am creating a GUI application using C and Win32 api. I would like to know how we can change the default font of the Main window to thaoma. I am comming from .NET background. In .NET if we change the font of parent control then automatically the child controls inherits that font....
Is there away similar to it or do we need to manually set the font of each control.....

Consider the following code...

#include <windows.h>

#define ID_EDIT 1
#define ID_BUTTON 2

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

  static HWND hwndEdit;
  static HWND hwndButton;
  static int len;
  static TCHAR text[30];

  switch(msg)
  {
    case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

    case WM_DESTROY:
        PostQuitMessage(0);
    break;
  }
  return DefWindowProc(hwnd, msg, wParam, lParam);
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
            LPSTR lpCmdLine, int nCmdShow )
{
  MSG  msg ;
  WNDCLASS wc = {0};
  wc.lpszClassName = TEXT( "Edit Control" );
  wc.hInstance     = hInstance ;
  wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
  wc.lpfnWndProc   = WndProc ;
  wc.hCursor       = LoadCursor(0,IDC_ARROW);

  RegisterClass(&wc);
  CreateWindow( wc.lpszClassName, TEXT("Edit control"),
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                220, 220, 280, 200, 0, 0, hInstance, 0);

  while( GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return (int) msg.wParam;
}

How can i change the font of button, textbox in the above program..

Please help me here.......and let me know the general process followed while coding in win32 api....

THanks in advance..

Body:
You can set the font of a window by sending it the WM_SETFONT message:

HWND myButton = CreateWindowEx(/* ... */);
HFONT myFont  = /* ... load font from somewhere ... */

/* Change the button font. */
SendMessage(myButton, WM_SETFONT, WPARAM(myFont), TRUE);

This approach gives you a control-by-control control over which fonts you're using, but you only need to do it once per window.

ContentLicense: CC BY-SA 2.5


问:
$lookup result shows [object Object]
Using passport with nodejs and mongo/mongoose.

I store attendance records in a collection which use req.user.id as a lookup to tie the attendance records to a registered user.  The key field is called "userId."

In attempting a join, I learned that the _id in the users collection is not of type string.  I've been trying to work around this for quite a bit.  My latest is to try to save the attendance records after converting the req.user.id to ObjectId().  Still, no luck.  It looks like the userId is still saving as string.  How can I get this Join to work?

```<code>router.post('/', ensureAuthenticated, function(req, res){

    var query = { userId: req.user.id };

    var update = {
        userId: new ObjectId(req.user.id),  // This is where I need to save
        response: req.body.inOrOut,
        notes: req.body.notes
    };

    //  Upsert
    var options = { upsert: true };

    // Use mongoose to save via upsert.
    RSVP.findOneAndUpdate( query, update, options, function( err, doc ) {
            if ( err ) throw err;
    });
</code>```

Here is the join:

```<code>RSVP.aggregate([{
        $lookup: {
            from: "users", // collection name in db
            localField: "userId",
            foreignField: "_id",
            as: "user"
        }
    }
    ]).exec( (err, rsvpList) => {
        if (err) throw err;
        console.log(rsvpList);
    });
</code>```

EDIT:

I just realized my mongoose schema for rsvps still had userId as string.  I changed it as follows:

```<code>let mongoose = require('mongoose');
//let ObjectId = require('mongodb').ObjectId;

// RSVP Schema
var RSVPSchema = mongoose.Schema({
    userId: {
        //type: String,
        type: mongoose.Schema.Types.ObjectId,
        index:true
    },
    response: {
        type: String
    },
    notes: {
        type: String
    },
});

var RSVP = module.exports = mongoose.model('RSVP', RSVPSchema);
</code>```

My console.log:

```<code>console.log('rsvp: ' + rsvpList[0].user.toString());
</code>```

It shows [Object object].  I can't tell by this whether my join has worked.  How can I test rsvpList[0].user to see if it contains the joined user?

答:
I was close.  It should have been:</p>

```<code>console.log('rsvp: ' + rsvpList[0].user[0].name);
</code>```

Title: $lookup result shows [object Object]

Body:
Using passport with nodejs and mongo/mongoose.

I store attendance records in a collection which use req.user.id as a lookup to tie the attendance records to a registered user.  The key field is called "userId."

In attempting a join, I learned that the _id in the users collection is not of type string.  I've been trying to work around this for quite a bit.  My latest is to try to save the attendance records after converting the req.user.id to ObjectId().  Still, no luck.  It looks like the userId is still saving as string.  How can I get this Join to work?

router.post('/', ensureAuthenticated, function(req, res){

    var query = { userId: req.user.id };

    var update = {
        userId: new ObjectId(req.user.id),  // This is where I need to save
        response: req.body.inOrOut,
        notes: req.body.notes
    };

    //  Upsert
    var options = { upsert: true };

    // Use mongoose to save via upsert.
    RSVP.findOneAndUpdate( query, update, options, function( err, doc ) {
            if ( err ) throw err;
    });

Here is the join:

RSVP.aggregate([{
        $lookup: {
            from: "users", // collection name in db
            localField: "userId",
            foreignField: "_id",
            as: "user"
        }
    }
    ]).exec( (err, rsvpList) => {
        if (err) throw err;
        console.log(rsvpList);
    });

EDIT:

I just realized my mongoose schema for rsvps still had userId as string.  I changed it as follows:

let mongoose = require('mongoose');
//let ObjectId = require('mongodb').ObjectId;

// RSVP Schema
var RSVPSchema = mongoose.Schema({
    userId: {
        //type: String,
        type: mongoose.Schema.Types.ObjectId,
        index:true
    },
    response: {
        type: String
    },
    notes: {
        type: String
    },
});

var RSVP = module.exports = mongoose.model('RSVP', RSVPSchema);

My console.log:

console.log('rsvp: ' + rsvpList[0].user.toString());

It shows [Object object].  I can't tell by this whether my join has worked.  How can I test rsvpList[0].user to see if it contains the joined user?

Body:
I was close.  It should have been:

console.log('rsvp: ' + rsvpList[0].user[0].name);


问:
django forms: could not get manually added(HTML) nested object fields
I am trying to implement django admin like inline addition of related objects in my app. Totally new to django but I am experienced with ROR and Laravel and happen to be good with ajax, so I don't want to go into nested formsets from django and want to add related objects form using ajax as I would traditionally do in anywhere else. Just be careful about naming of input fields so you can get them on controller side nicely in an array.

In form.html I am simply adding something like this;

```<code><label class="control-label">Name</label>
<input name="items[1][name]" class="form-control"/>
<label class="control-label">Attr</label>
<input name="items[1][attr]" class="form-control"/>
</code>```

This is just an example to give you visual of how my html is generated. I've mutiple items in my form.

Traditional on server side I would get a form object(request input) like this; at-least in Laravel

```<code>[form=> [
"some_attr"=>"val",
"items"=> [
   "1"=> [
       "name"=>"some name",
       "attr"=> "some val"
   ]
]
] ]
</code>```

The main point here is that I would get and array of items in my request on controller side and can iterate over it.

PROBLEM
I am doing everything same as described above but when I am trying to access data from controller side. It doesn't convert items fields to array of objects.
When I print form.data, I get something like this,

```<code><QueryDict: {'csrfmiddlewaretoken': ['C5i6Ge7aQMvoMlHODjwgMziXE7RcIs5F99ibo7YsSZnZKF9z2TdMlwhep8OB668M'], 'some_parent_attr': ['value'], 'status': ['1'], 'items[5][name]': ['some name'], 'items[5][attr]': ['some val'] ....
</code>```

Django does not convert items to array it simply makes it a string key like 'items[5][name]' which cannot be iterated. As I'd have multiple objects with random ids so it is not possible to get all items from this dictionary using there keys.

Is there a way that I don't know about to get it working? Somehow can be formatted as I expect it to? Or this cannot be done this way?

I would really appreciate any guidance/help with this problem.

答:
Python is returning a querydict, that in certain way is similar to a dictionary, if you want to convert it to a dictionary just add this:

```<code>myDict = dict(form.data.iterlists())
</code>```

then you can get your elements accessing with the key, example:

```<code>>>> myDict['items[5][name]'] # Will return
['some name']
</code>```

Body:
I am trying to implement django admin like inline addition of related objects in my app. Totally new to django but I am experienced with ROR and Laravel and happen to be good with ajax, so I don't want to go into nested formsets from django and want to add related objects form using ajax as I would traditionally do in anywhere else. Just be careful about naming of input fields so you can get them on controller side nicely in an array.

In form.html I am simply adding something like this;

Name
<input name="items[1][name]" class="form-control"/>
Attr
<input name="items[1][attr]" class="form-control"/>

This is just an example to give you visual of how my html is generated. I've mutiple items in my form.

Traditional on server side I would get a form object(request input) like this; at-least in Laravel

[form=> [
"some_attr"=>"val",
"items"=> [
   "1"=> [
       "name"=>"some name",
       "attr"=> "some val"
   ]
]
] ]

The main point here is that I would get and array of items in my request on controller side and can iterate over it.

PROBLEM
I am doing everything same as described above but when I am trying to access data from controller side. It doesn't convert items fields to array of objects.
When I print form.data, I get something like this,

<QueryDict: {'csrfmiddlewaretoken': ['C5i6Ge7aQMvoMlHODjwgMziXE7RcIs5F99ibo7YsSZnZKF9z2TdMlwhep8OB668M'], 'some_parent_attr': ['value'], 'status': ['1'], 'items[5][name]': ['some name'], 'items[5][attr]': ['some val'] ....

Django does not convert items to array it simply makes it a string key like 'items[5][name]' which cannot be iterated. As I'd have multiple objects with random ids so it is not possible to get all items from this dictionary using there keys.

Is there a way that I don't know about to get it working? Somehow can be formatted as I expect it to? Or this cannot be done this way?

I would really appreciate any guidance/help with this problem.

Body:
Python is returning a querydict, that in certain way is similar to a dictionary, if you want to convert it to a dictionary just add this:

myDict = dict(form.data.iterlists())

then you can get your elements accessing with the key, example:

>>> myDict['items[5][name]'] # Will return
['some name']


问:
Python 3 Elif Indentation Error
I am working on a simple script in Python, and when I attempt to use an elif statement, it throws an error saying that it expected an indented block. I know this may be something simple, but I have tried everything and I am stuck, so anyone willing to help is welcome. Thank you in advance.

```<code>import math as m

mass = input("Enter the mass of the object (kg)")
i = 0
while i == 0:
  if type(mass)!= type(1.1):
    #mass = input("You have entered an incorrect value, please enter a numerical value.")

  elif type(mass) == type(1.1):
    print("test")
    break
</code>```

The full error message is below:

```<code>Traceback (most recent call last):
  File "python", line 9
    elif type(mass) == type(1.1):
       ^
IndentationError: expected an indented block
</code>```

答: you need to have a code block after the if statement, you cannot have an if statement and directly jump to the elif condition</p>

Title: Python 3 Elif Indentation Error

Body:
I am working on a simple script in Python, and when I attempt to use an elif statement, it throws an error saying that it expected an indented block. I know this may be something simple, but I have tried everything and I am stuck, so anyone willing to help is welcome. Thank you in advance.

import math as m

mass = input("Enter the mass of the object (kg)")
i = 0
while i == 0:
  if type(mass)!= type(1.1):
    #mass = input("You have entered an incorrect value, please enter a numerical value.")

  elif type(mass) == type(1.1):
    print("test")
    break

The full error message is below:

Traceback (most recent call last):
  File "python", line 9
    elif type(mass) == type(1.1):
       ^
IndentationError: expected an indented block


问:
ContactAvailability Lync
I have an application that uses Lync SDK 2013.

My application is linked with my phone, and when i receive a call my precence Lync become Busy (ContactAvilability.Busy) and when i terminate the call, i want to return my presence to its original state (Available or  Do Not Disturb ....).

My question is how can i save my actual state, and return to it when i finish the call ??

```<code>public static void notify(Call call)
        {
            // How to save my current state
            if (call.state == Answer)
            {
                client.Self.BeginPublishContactInformation(
                new Dictionary<PublishableContactInformationType, object>() {
                {    PublishableContactInformationType.Availability, ContactAvailability.Busy }
                }, null, null);
            }
            else
            {
                // where i want to return to my original state
            }
        }
</code>```

Thanks

答:
To save the previous presence:

```<code>_previousPresence = client.Self.Contact.GetContactInformation(new[]
{
    ContactInformationType.Availability,
    ContactInformationType.ActivityId,
    ContactInformationType.CustomActivity
});
</code>```

To restore is a little difficult because of the "Custom" activity which we get only the custom activity localized string but not the custom activity id.  Also there is no way to restore a "unknown" custom activity (i.e. a custom activity presence that is not defined in the custom activities xml file for the client, this can happen where a UCMA endpoint or another client endpoint has custom activities setup not defined on this client). The only way to save and restore the presence exactly in all cases is to use a UCMA application (server or client) which gives you more control over what/how the presence is set i.e. fine grained control over custom activity presence types.

Example of restoring the presence from the Lync Client:

```<code>var publishData = new Dictionary<PublishableContactInformationType, object>
{
    {PublishableContactInformationType.Availability, _previousPresence[ContactInformationType.Availability]},
    {PublishableContactInformationType.ActivityId, _previousPresence[ContactInformationType.ActivityId]}
};

var customId = FindCustomActivityId(client,
    (ContactAvailability)_previousPresence[ContactInformationType.Availability],
    ((List<object>)_previousPresence[ContactInformationType.CustomActivity]).Cast<LocaleString>().ToList());
if (customId != null)
{
    publishData.Add(PublishableContactInformationType.CustomActivityId, customId);
}

await Task.Factory.FromAsync(client.Self.BeginPublishContactInformation(publishData, null, null), client.Self.EndPublishContactInformation);
</code>```

The FindCustomActiviyId is a bit of a "hack" in that it doing a string compare search from the presvious presence information does not give back the custom activity id but only the localized string from the custom activity.

```<code>private static object FindCustomActivityId(Client client, ContactAvailability availability, IReadOnlyCollection<LocaleString> customActivities)
{
    var currentLcid = System.Globalization.CultureInfo.CurrentUICulture.LCID;
    var customStates = client.Self.GetPublishableCustomAvailabilityStates(currentLcid);

    if (customStates == null || !customStates.Any())
    {
        return null;
    }

    var state = customStates.FirstOrDefault(cs => customActivities.Any(ca => cs.Availability == availability && string.Equals(ca.Value, cs.Activity)));

    return state?.Id;
}
</code>```

You may like to also take into account overlapping calls.  i.e. your phone call and a Lync call overlapping.  In these cases the Lync Client presence may already be on the "OnThePhone" busy state. Or if the presence changes to "OnThePhone" while after you answer your other phone system call.

Also you may like to set the busy sub-state to OnThePhone as well so that other Lync Users know you are on a call.  This is what the Lync client is doing for you automatically when you answer a Lync Client call.

```<code>// publish on-the-phone presence
var publishData = new Dictionary<PublishableContactInformationType, object>
{
    {PublishableContactInformationType.Availability, ContactAvailability.Busy},
    {PublishableContactInformationType.ActivityId, "on-the-phone"}
};
await Task.Factory.FromAsync(client.Self.BeginPublishContactInformation(publishData, null, null), client.Self.EndPublishContactInformation);
</code>```

Title: ContactAvailability Lync

Body:
I have an application that uses Lync SDK 2013.

My application is linked with my phone, and when i receive a call my precence Lync become Busy (ContactAvilability.Busy) and when i terminate the call, i want to return my presence to its original state (Available or  Do Not Disturb ....).

My question is how can i save my actual state, and return to it when i finish the call ??

public static void notify(Call call)
        {
            // How to save my current state
            if (call.state == Answer)
            {
                client.Self.BeginPublishContactInformation(
                new Dictionary<PublishableContactInformationType, object>() {
                {    PublishableContactInformationType.Availability, ContactAvailability.Busy }
                }, null, null);
            }
            else
            {
                // where i want to return to my original state
            }
        }

Thanks

Body:
To save the previous presence:

_previousPresence = client.Self.Contact.GetContactInformation(new[]
{
    ContactInformationType.Availability,
    ContactInformationType.ActivityId,
    ContactInformationType.CustomActivity
});

To restore is a little difficult because of the "Custom" activity which we get only the custom activity localized string but not the custom activity id.  Also there is no way to restore a "unknown" custom activity (i.e. a custom activity presence that is not defined in the custom activities xml file for the client, this can happen where a UCMA endpoint or another client endpoint has custom activities setup not defined on this client). The only way to save and restore the presence exactly in all cases is to use a UCMA application (server or client) which gives you more control over what/how the presence is set i.e. fine grained control over custom activity presence types.

Example of restoring the presence from the Lync Client:

var publishData = new Dictionary<PublishableContactInformationType, object>
{
    {PublishableContactInformationType.Availability, _previousPresence[ContactInformationType.Availability]},
    {PublishableContactInformationType.ActivityId, _previousPresence[ContactInformationType.ActivityId]}
};

var customId = FindCustomActivityId(client,
    (ContactAvailability)_previousPresence[ContactInformationType.Availability],
    ((List<object>)_previousPresence[ContactInformationType.CustomActivity]).Cast<LocaleString>().ToList());
if (customId != null)
{
    publishData.Add(PublishableContactInformationType.CustomActivityId, customId);
}

await Task.Factory.FromAsync(client.Self.BeginPublishContactInformation(publishData, null, null), client.Self.EndPublishContactInformation);

The FindCustomActiviyId is a bit of a "hack" in that it doing a string compare search from the presvious presence information does not give back the custom activity id but only the localized string from the custom activity.

private static object FindCustomActivityId(Client client, ContactAvailability availability, IReadOnlyCollection<LocaleString> customActivities)
{
    var currentLcid = System.Globalization.CultureInfo.CurrentUICulture.LCID;
    var customStates = client.Self.GetPublishableCustomAvailabilityStates(currentLcid);

    if (customStates == null || !customStates.Any())
    {
        return null;
    }

    var state = customStates.FirstOrDefault(cs => customActivities.Any(ca => cs.Availability == availability && string.Equals(ca.Value, cs.Activity)));

    return state?.Id;
}

You may like to also take into account overlapping calls.  i.e. your phone call and a Lync call overlapping.  In these cases the Lync Client presence may already be on the "OnThePhone" busy state. Or if the presence changes to "OnThePhone" while after you answer your other phone system call.

Also you may like to set the busy sub-state to OnThePhone as well so that other Lync Users know you are on a call.  This is what the Lync client is doing for you automatically when you answer a Lync Client call.

// publish on-the-phone presence
var publishData = new Dictionary<PublishableContactInformationType, object>
{
    {PublishableContactInformationType.Availability, ContactAvailability.Busy},
    {PublishableContactInformationType.ActivityId, "on-the-phone"}
};
await Task.Factory.FromAsync(client.Self.BeginPublishContactInformation(publishData, null, null), client.Self.EndPublishContactInformation);


问:
Fold with closure that returns a Result
I'm using the regex crate to find some text with this regex:

```<code>lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}
</code>```

I want to find all possible captures and iterate over them:

```<code>FIND_STEPS_RE.captures_iter(script_slice)
</code>```

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]
```

<p>I want to iterate over it, parse the numbers and apply the operation.</p>

<p>I tried:</p>

```let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;
```

<p>where <code>apply_decoding_step</code> is:</p>

```fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}
```

<p>But I got this error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`
</code>```

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

答:
Take a closer look at the type signature for fold:

```<code>fn fold<B, F>(self, init: B, f: F) -> B
 where
    F: FnMut(B, Self::Item) -> B,
{ ... }
</code>```

init has to have the same type as the return value of f. This is also what the compiler tells you in the error message. You could do

```<code>fn apply_decoding_step(sum: Result<i32>, capture: regex::Captures<>) -> Result<i32> {
    match sum {
        Err(_) => sum,
        Ok(s) => {
            let number = parse_number(&capture[2])?;
            match  &capture[1] {
                "+" => Ok(s + number),
                "-" => Ok(s - number),
                "*" => Ok(s * number),
                "/" => Ok(s / number),
                _ => bail!("Unknown step operator"),
           }
       }
    }
}
</code>```

And then call it with an Ok seed:

```<code>.fold(Ok(seed), apply_decoding_step);
</code>```

Now, if any failure occurs, your fold returns an Err.

Title: Fold with closure that returns a Result

Body:
I'm using the regex crate to find some text with this regex:

lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}

I want to find all possible captures and iterate over them:

FIND_STEPS_RE.captures_iter(script_slice)

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]

I want to iterate over it, parse the numbers and apply the operation.

I tried:

let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;

where apply_decoding_step is:

fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}

But I got this error:

error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

Body:
Take a closer look at the type signature for fold:

fn fold<B, F>(self, init: B, f: F) -> B
 where
    F: FnMut(B, Self::Item) -> B,
{ ... }

init has to have the same type as the return value of f. This is also what the compiler tells you in the error message. You could do

fn apply_decoding_step(sum: Result<i32>, capture: regex::Captures<>) -> Result<i32> {
    match sum {
        Err(_) => sum,
        Ok(s) => {
            let number = parse_number(&capture[2])?;
            match  &capture[1] {
                "+" => Ok(s + number),
                "-" => Ok(s - number),
                "*" => Ok(s * number),
                "/" => Ok(s / number),
                _ => bail!("Unknown step operator"),
           }
       }
    }
}

And then call it with an Ok seed:

.fold(Ok(seed), apply_decoding_step);

Now, if any failure occurs, your fold returns an Err.


问:
how to search files and display progress bar in powershell
I am currently coding in Powershell, and I am now looking for a way to display the progress bar while searching the system for documents. I am using Get-ChildItem instead of a loop, since it is much faster and more efficient than a loop. I have already figured out how to use the Get-ChildItem cmdlet, but I need help figuring out how to implement the progress bar into it. Here is an example of the code I am using, so it is easier to understand:

```<code>Set-Variable $Loading 0
Write-Progress -Activity "Collecting Files For Removal..." -CurrentOperation "Collecting User Files..." -PercentComplete $Loading
Get-ChildItem C:\Users\firea\ -Filter *.D11 -ErrorAction SilentlyContinue -Force
</code>```

答:
So, what it sounds like is that you want to show the user a progress bar that displays X% completed, but until you run Get-ChildItem you don't know how many total items there are, so you can't really tell how close to done you are. Let me put this another way.

Say you go out and take a hike. You do a quick search online for local trails, find one, and off you go! You know where the trail starts, and you know that there's a corndog stand at the end of it that you're looking forward to sampling. 12 minutes into your hike your girlfriend calls you and asks you to bring her back a corndog too! Sure, no problem, it might be cold by the time it gets to her, but you can do that. Then she asks how long it'll take,and you realize that you have no idea. You're 12 minutes in, but until you get to that corndog stand you have no idea if it's another 3 minutes along, or 35 minutes along, because you don't know how long the trail is.

Ok, same scenario, but this time you see the zip-line that goes over the trail and take that first. Sure, you don't know what all the details of the trail are, but you get a good idea of about how long it is, and a general idea of the trail. This time when your girlfriend calls you can tell her it'll be about 20 minutes, because you're about 12 minutes in, there's about 4 minutes to the stand, and then another 16 minutes back out to where she's at.

Same idea would be applied to your script. In order to give the user even a rough estimate of progress you have to have a rough idea of what you're looking at. Are you searching 1 folder? Well, there's really no good way to get a rough estimate of one folder, but it shouldn't take that long that you'd need a progress bar. Now if you're searching an entire drive you could use the -directory parameter of Get-ChildItem, find out how many folders there are, and give the user progress based on how many folders you've searched.

Example:

```<code>#Get directory list, silently continue on errors in case script isn't run as an admin and there are system folders
$folders = Get-ChildItem C:\Users -Recurse -Directory -ErrorAction SilentlyContinue
#Loop through folders, checking each for files
$files = For($i = 0; $i -lt $folders.count; $i++)
{
    #Update progress bar for current folder
    Write-Progress -Activity "Collecting Files For Removal..." -CurrentOperation "Collecting User Files..." -PercentComplete (($i+1) / $folders.count * 100) -Status ("Folder {0} of {1}" -f ($i + 1), $folders.count)
    Get-ChildItem $folders[$i].FullName -Filter *.D11 -ea 4
}
</code>```

This example gets all folders under the C:\Users folder. Then it iterates through those folders checking each one for the desired files. For each folder it updates the progress bar. Now it will be a rough estimate, since not all folders will have the same number of files, so some folders will finish faster than others, but it at least gives the user some idea of the progress being made.

Body:
I am currently coding in Powershell, and I am now looking for a way to display the progress bar while searching the system for documents. I am using Get-ChildItem instead of a loop, since it is much faster and more efficient than a loop. I have already figured out how to use the Get-ChildItem cmdlet, but I need help figuring out how to implement the progress bar into it. Here is an example of the code I am using, so it is easier to understand:

Set-Variable $Loading 0
Write-Progress -Activity "Collecting Files For Removal..." -CurrentOperation "Collecting User Files..." -PercentComplete $Loading
Get-ChildItem C:\Users\firea\ -Filter *.D11 -ErrorAction SilentlyContinue -Force

Body:
So, what it sounds like is that you want to show the user a progress bar that displays X% completed, but until you run Get-ChildItem you don't know how many total items there are, so you can't really tell how close to done you are. Let me put this another way.

Say you go out and take a hike. You do a quick search online for local trails, find one, and off you go! You know where the trail starts, and you know that there's a corndog stand at the end of it that you're looking forward to sampling. 12 minutes into your hike your girlfriend calls you and asks you to bring her back a corndog too! Sure, no problem, it might be cold by the time it gets to her, but you can do that. Then she asks how long it'll take,and you realize that you have no idea. You're 12 minutes in, but until you get to that corndog stand you have no idea if it's another 3 minutes along, or 35 minutes along, because you don't know how long the trail is.

Ok, same scenario, but this time you see the zip-line that goes over the trail and take that first. Sure, you don't know what all the details of the trail are, but you get a good idea of about how long it is, and a general idea of the trail. This time when your girlfriend calls you can tell her it'll be about 20 minutes, because you're about 12 minutes in, there's about 4 minutes to the stand, and then another 16 minutes back out to where she's at.

Same idea would be applied to your script. In order to give the user even a rough estimate of progress you have to have a rough idea of what you're looking at. Are you searching 1 folder? Well, there's really no good way to get a rough estimate of one folder, but it shouldn't take that long that you'd need a progress bar. Now if you're searching an entire drive you could use the -directory parameter of Get-ChildItem, find out how many folders there are, and give the user progress based on how many folders you've searched.

Example:

#Get directory list, silently continue on errors in case script isn't run as an admin and there are system folders
$folders = Get-ChildItem C:\Users -Recurse -Directory -ErrorAction SilentlyContinue
#Loop through folders, checking each for files
$files = For($i = 0; $i -lt $folders.count; $i++)
{
    #Update progress bar for current folder
    Write-Progress -Activity "Collecting Files For Removal..." -CurrentOperation "Collecting User Files..." -PercentComplete (($i+1) / $folders.count * 100) -Status ("Folder {0} of {1}" -f ($i + 1), $folders.count)
    Get-ChildItem $folders[$i].FullName -Filter *.D11 -ea 4
}

This example gets all folders under the C:\Users folder. Then it iterates through those folders checking each one for the desired files. For each folder it updates the progress bar. Now it will be a rough estimate, since not all folders will have the same number of files, so some folders will finish faster than others, but it at least gives the user some idea of the progress being made.


问:
Getting a basic materialize CSS dropdown to work
I am trying to use a materialize CSS dropdown, but I am not getting the materialized version to work.

Here is what their example is (I am having this because it requires me to have a code sample to post):

```<code>  <div class="input-field col s12">
    <select>
      <option value="" disabled selected>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    <label>Materialize Select</label>
  </div>
</code>```

Here is a fiddle of the example I am trying to get to work, the first is the dropdown using the browser-default and the second is from the reference:

https://jsfiddle.net/msq3g0nk/10/

Here is a link to the doc (choose "select" on the right)

http://materializecss.com/forms.html

Any assistance would be awesome.

答:
You need to initialize the dropdown, as mentioned in the docs.

http://materializecss.com/forms.html#select-initialization

```<code>$(document).ready(function() {
  $('select').material_select();
});
</code>```

Working example: https://jsfiddle.net/msq3g0nk/11/

Body:
I am trying to use a materialize CSS dropdown, but I am not getting the materialized version to work.

Here is what their example is (I am having this because it requires me to have a code sample to post):

    <select>
      <option value="" disabled selected>Choose your option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    Materialize Select

Here is a fiddle of the example I am trying to get to work, the first is the dropdown using the browser-default and the second is from the reference:

https://jsfiddle.net/msq3g0nk/10/

Here is a link to the doc (choose "select" on the right)

http://materializecss.com/forms.html

Any assistance would be awesome.

Body:
You need to initialize the dropdown, as mentioned in the docs.

http://materializecss.com/forms.html#select-initialization

$(document).ready(function() {
  $('select').material_select();
});

Working example: https://jsfiddle.net/msq3g0nk/11/


问:
Downloading a file with Python with a download request url
We're trying to automate the downloading of auto-generated reports from Facebook Ads. When a report is ready to download, we get an email with a download link in the body. We parse the body of the message and get this (redacted) url to download the csv file:

```<code>https://www.facebook.com/ads/manage/download_report.php?act=<account_id>&report_run_id=<run_id>&format=csv&source=email_v2
</code>```

If I put this file into the browser address bar, the file download starts, but when I try to download the content using the python library requests or urllib2:

```<code>import requests
url = 'https://www.facebook.com/ads/manage/download_report.php?act=\
       <account_id>&report_run_id=<run_id>&format=csv&source=email_v2'
r = requests.get(url, allow_redirects=True)
open('test.txt', 'a+').write(r.content)
</code>```

The resultant file is just HTML that contains none of the data I expected, so it's clear that there's no resource attached to this file path.

How can I initiate the download with python?

答:
You need to authenticate to Facebook and use these cookies to download this file. It is not hard to do it but it is worth another question.

You are using open builtin function wrong.

You have to write downloaded file like this:

```<code>import requests
url = 'https://www.facebook.com/ads/manage/download_report.php?act=\
       <account_id>&report_run_id=<run_id>&format=csv&source=email_v2'
r = requests.get(url, allow_redirects=True)
f = open('test.txt', 'a+')
f.write(r.content)
f.close()
</code>```

When working with multiple files, an IOError: [Errno 24] Too many open files exception will be raised if file objects are not deleted.

Quoting from Python documentation:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks

Example:

```<code>with open('test.txt', 'a+') as f:
    f.write(r.content)
    # f.close()  # it is redundant
</code>```

Body:
We're trying to automate the downloading of auto-generated reports from Facebook Ads. When a report is ready to download, we get an email with a download link in the body. We parse the body of the message and get this (redacted) url to download the csv file:

https://www.facebook.com/ads/manage/download_report.php?act=<account_id>&report_run_id=<run_id>&format=csv&source=email_v2

If I put this file into the browser address bar, the file download starts, but when I try to download the content using the python library requests or urllib2:

import requests
url = 'https://www.facebook.com/ads/manage/download_report.php?act=\
       <account_id>&report_run_id=<run_id>&format=csv&source=email_v2'
r = requests.get(url, allow_redirects=True)
open('test.txt', 'a+').write(r.content)

The resultant file is just HTML that contains none of the data I expected, so it's clear that there's no resource attached to this file path.

How can I initiate the download with python?

Body:
You need to authenticate to Facebook and use these cookies to download this file. It is not hard to do it but it is worth another question.

You are using open builtin function wrong.

You have to write downloaded file like this:

import requests
url = 'https://www.facebook.com/ads/manage/download_report.php?act=\
       <account_id>&report_run_id=<run_id>&format=csv&source=email_v2'
r = requests.get(url, allow_redirects=True)
f = open('test.txt', 'a+')
f.write(r.content)
f.close()

When working with multiple files, an IOError: [Errno 24] Too many open files exception will be raised if file objects are not deleted.

Quoting from Python documentation:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks

Example:

with open('test.txt', 'a+') as f:
    f.write(r.content)
    # f.close()  # it is redundant


问:
How to remove unused function parameters in shutil.rmtree
In this question, an answer to how to remove read-only files is presented. It's super effective but requires having unused parameters. In this other question it was asked how to tell pylint that multiple non-adjacent parameters are unused without adding a specific comment (e.g., by using _). Many of the answers were approximately "ZOMG YOU'RE DESIGNING IT WRONG" so I promised I would put up an example where this is needed and out of my control. Here is that example.

```<code>shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
</code>```

The "answer" so that pylint would not complain about action and exc is to

```<code>shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(_action, name, _exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
</code>```

but the new question is, how to do this without having _action or _exc as parameters?

答:
As discussed in the comments, you cannot just ignore action, and exc because rmtree will pass those arguments to the callback. From the python docs:

If onerror is provided, it must be a callable that accepts three
  parameters: function, path, and excinfo.

That being said, you have a couple of options:

You can prefix the callback with a cb_ (see pylint docs on this as well), turning your function into:

```<code>shutil.rmtree(self._temp_dir, onerror=cb_del_rw)

def cb_del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
</code>```

You can use keyword arguments (you could also use *args, but I find this approach more readable):

```<code>shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(**kwargs):
    name = kwargs['name']
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
</code>```

Body:
In this question, an answer to how to remove read-only files is presented. It's super effective but requires having unused parameters. In this other question it was asked how to tell pylint that multiple non-adjacent parameters are unused without adding a specific comment (e.g., by using _). Many of the answers were approximately "ZOMG YOU'RE DESIGNING IT WRONG" so I promised I would put up an example where this is needed and out of my control. Here is that example.

shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

The "answer" so that pylint would not complain about action and exc is to

shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(_action, name, _exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

but the new question is, how to do this without having _action or _exc as parameters?

Body:
As discussed in the comments, you cannot just ignore action, and exc because rmtree will pass those arguments to the callback. From the python docs:

If onerror is provided, it must be a callable that accepts three
  parameters: function, path, and excinfo.

That being said, you have a couple of options:

You can prefix the callback with a cb_ (see pylint docs on this as well), turning your function into:

shutil.rmtree(self._temp_dir, onerror=cb_del_rw)

def cb_del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

You can use keyword arguments (you could also use *args, but I find this approach more readable):

shutil.rmtree(self._temp_dir, onerror=del_rw)

def del_rw(**kwargs):
    name = kwargs['name']
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)


问:
kubernetes node shutdown/crash recovery?
We have a cluster with a master node (foo-1), and two worker nodes (foo-2 and foo-3). We have a pod that was running on foo-3 (as decided by Kubernetes). We purposely shut down foo-3 as an experiment.

My expectation was that Kubernetes would "see" the shutdown, and automatically restart the pod in foo-2. But, it didn't seem to happen. In fact, it seemed to think that the pod was still running on foo-3.

After five minutes of waiting, Kubernetes finally recognized that the cluster node had disappeared, and responded gracefully by restarting the pod on foo-2. Five minutes is too long for us, as this is not a replicated application. How can we make that timeout drastically shorter (like, 10 seconds)? And actually, if the host has a graceful shutdown (like for patching), the effect should be immediate.

答:
There is a --pod-eviction-timeout parameter in kube-controller-manager which is 5m by default:

```<code> --pod-eviction-timeout duration    The grace period for deleting pods on failed nodes. (default 5m0s)
</code>```

You need to modify it if you want to speed up an eviction process.

But if you want to minimize your pod's downtime, when node goes down, you need to modify the following parameters as well:

```<code>kubelet: node-status-update-frequency=4s (default 10s)

kube-controller-manager: node-monitor-period=2s (default 5s)
kube-controller-manager: node-monitor-grace-period=16s (default 40s)
kube-controller-manager: pod-eviction-timeout=30s (default 5m)
</code>```

And, of course, you can always have your deployments with replica 2 and service will be up even if one node goes down.

Body:
There is a --pod-eviction-timeout parameter in kube-controller-manager which is 5m by default:

 --pod-eviction-timeout duration    The grace period for deleting pods on failed nodes. (default 5m0s)

You need to modify it if you want to speed up an eviction process.

But if you want to minimize your pod's downtime, when node goes down, you need to modify the following parameters as well:

kubelet: node-status-update-frequency=4s (default 10s)

kube-controller-manager: node-monitor-period=2s (default 5s)
kube-controller-manager: node-monitor-grace-period=16s (default 40s)
kube-controller-manager: pod-eviction-timeout=30s (default 5m)

And, of course, you can always have your deployments with replica 2 and service will be up even if one node goes down.


问:
bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)
I have a xml file with data like below

```<code><temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

```<code>sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml
</code>```

output : 20

desired output: 50

I appreciate the help. Thank you

答:
You can try</p>

```<code>cut -sd '"' -f 4 my.xml
</code>```

Body:
I have a xml file with data like below

<temp>

</temp>

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml

output : 20

desired output: 50

I appreciate the help. Thank you

Body:
You can try

cut -sd '"' -f 4 my.xml


问:
Flexdashboard can't find input/session
I have been using Shiny/Flexdashboard for a couple of days and out of nowhere all of my code stopped working and I just get session or input not found errors. I tried re-installing RStudio and R and all the packages, but it didn't work.

When running my code I get something like this:

```<code>Warning: Error in dropNulls: objeto 'session' não encontrado
Stack trace (innermost first):
    117: dropNulls
    116: updateSelectizeInput
    115: eval
    114: eval
    113: withVisible
    112: withCallingHandlers
    111: handle
    110: timing_fn
    109: evaluate_call
    108: evaluate::evaluate
    107: evaluate
    106: in_dir
    105: block_exec
    104: call_block
    103: process_group.block
    102: process_group
    101: withCallingHandlers
    100: process_file
     99: knitr::knit
     98: <Anonymous>
     97: do.call
     96: contextFunc
     95: .getReactiveEnvironment()$runWith
     94: shiny::maskReactiveContext
     93: <reactive>
     82: doc
     81: shiny::renderUI
     80: func
     79: origRenderFunc
     78: output$__reactivedoc__
      3: <Anonymous>
      2: do.call
      1: rmarkdown::run
Warning: Error in %in%: objeto 'input' não encontrado
Stack trace (innermost first):
    73: %in%
    72: [.data.frame
    71: [ [<text>#13]
    70: <reactive:sliderDatMP> [<text>#13]
    59: sliderDatMP
    58: observerFunc [<text>#36]
     3: <Anonymous>
     2: do.call
     1: rmarkdown::run
ERROR: [on_request_read] connection reset by peer
</code>```

But it's not just in my code, I can try to run the simple Old faithul example on the flexdashboard website and the same thing happens.

Screenshot of what I get running the Old faithul

I have absolutely no idea what happened, it was working just fine the whole week and now nothing works. All help would be appreciated.

答:
Identified as issue with rmarkdown. Solution from within R: </p>

```<code>devtools::install_github("rstudio/rmarkdown")
</code>```

Title: Flexdashboard can't find input/session

Body:
I have been using Shiny/Flexdashboard for a couple of days and out of nowhere all of my code stopped working and I just get session or input not found errors. I tried re-installing RStudio and R and all the packages, but it didn't work.

When running my code I get something like this:

Warning: Error in dropNulls: objeto 'session' não encontrado
Stack trace (innermost first):
    117: dropNulls
    116: updateSelectizeInput
    115: eval
    114: eval
    113: withVisible
    112: withCallingHandlers
    111: handle
    110: timing_fn
    109: evaluate_call
    108: evaluate::evaluate
    107: evaluate
    106: in_dir
    105: block_exec
    104: call_block
    103: process_group.block
    102: process_group
    101: withCallingHandlers
    100: process_file
     99: knitr::knit
     98: <Anonymous>
     97: do.call
     96: contextFunc
     95: .getReactiveEnvironment()$runWith
     94: shiny::maskReactiveContext
     93: <reactive>
     82: doc
     81: shiny::renderUI
     80: func
     79: origRenderFunc
     78: output$__reactivedoc__
      3: <Anonymous>
      2: do.call
      1: rmarkdown::run
Warning: Error in %in%: objeto 'input' não encontrado
Stack trace (innermost first):
    73: %in%
    72: [.data.frame
    71: [ [<text>#13]
    70: <reactive:sliderDatMP> [<text>#13]
    59: sliderDatMP
    58: observerFunc [<text>#36]
     3: <Anonymous>
     2: do.call
     1: rmarkdown::run
ERROR: [on_request_read] connection reset by peer

But it's not just in my code, I can try to run the simple Old faithul example on the flexdashboard website and the same thing happens.

Screenshot of what I get running the Old faithul

I have absolutely no idea what happened, it was working just fine the whole week and now nothing works. All help would be appreciated.

Body:
Identified as issue with rmarkdown. Solution from within R:

devtools::install_github("rstudio/rmarkdown")


问:
Using strtok() to store numeric values in a 2D array
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

```<code>int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}
</code>```

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

答:
there are multiple issues here.

First j=0 must be done after fgets or it's never reset.

Second, the biggest error is that when you do strtok(line," ") you're initializing strtok state machine, and you must loop using NULL as first argument until strtok returns NULL, but you're not doing that: you're looping on both calls. AS an improvement, pass multiple choices as a separator: linefeed, tabulation, and space.

So the second time the string is already tokenized and the loop ends, but with only the first item.

Also, you have to store the value of j for each line, else you lose track of how many elements there are on each line (since it's variable). In the code below, I'm using the first position to store the size, then come the items.

My fix proposal (tested & works on your data):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    const char *spaces = "\n\t ";
    int myArray[240][30];
    char line[240];
    char *token;
    int i, n, j;
    FILE *fp;
    fp=fopen("array_list.txt", "rt");
    i = 0;
    while(fgets(line, sizeof(line), fp))
    {
        j = 1;
        token = strtok(line, spaces);  // initialize line tokens
        while(token)  // won't enter if the line is empty, and stops when no more tokens
        {
            n = atoi(token);  // strtol + error checking would be better
            myArray[i][j] = n;
            j++;
            printf("%d ", myArray[i][j]);
            token = strtok(NULL, spaces);  // next token
        }
        myArray[i][0] = j;  // use first array position to store the size

        printf("\n");
        i++;
    }
    return 0;
}
</code>```

the program is still missing a few things:

protecting against "too many elements for array". If you have too many elements in your text file (too many lines / too many items in one line) you can corrupt your memory. Check i & j & abort if they're going past the limits.

atoi has no error checking, so entering "whatever" leads to a 0 value. strtol allows error checking.

Body:
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

Body:
there are multiple issues here.

First j=0 must be done after fgets or it's never reset.

Second, the biggest error is that when you do strtok(line," ") you're initializing strtok state machine, and you must loop using NULL as first argument until strtok returns NULL, but you're not doing that: you're looping on both calls. AS an improvement, pass multiple choices as a separator: linefeed, tabulation, and space.

So the second time the string is already tokenized and the loop ends, but with only the first item.

Also, you have to store the value of j for each line, else you lose track of how many elements there are on each line (since it's variable). In the code below, I'm using the first position to store the size, then come the items.

My fix proposal (tested & works on your data):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    const char *spaces = "\n\t ";
    int myArray[240][30];
    char line[240];
    char *token;
    int i, n, j;
    FILE *fp;
    fp=fopen("array_list.txt", "rt");
    i = 0;
    while(fgets(line, sizeof(line), fp))
    {
        j = 1;
        token = strtok(line, spaces);  // initialize line tokens
        while(token)  // won't enter if the line is empty, and stops when no more tokens
        {
            n = atoi(token);  // strtol + error checking would be better
            myArray[i][j] = n;
            j++;
            printf("%d ", myArray[i][j]);
            token = strtok(NULL, spaces);  // next token
        }
        myArray[i][0] = j;  // use first array position to store the size

        printf("\n");
        i++;
    }
    return 0;
}

the program is still missing a few things:

protecting against "too many elements for array". If you have too many elements in your text file (too many lines / too many items in one line) you can corrupt your memory. Check i & j & abort if they're going past the limits.

atoi has no error checking, so entering "whatever" leads to a 0 value. strtol allows error checking.