问:
Upload file in angular2: Body (FormData) empty
I'm trying to upload a picture with Angular2 to my REST Service (Loopback).
The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.

Here's a simplified service method that sends the POST request:

```<code>public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}
</code>```

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.

In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:

Data before Request

But in the request, the body is an empty object {}:

Request

I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.

I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?

答:
From this How to inspect FormData? SO answer and this MDN documentation outputing FormData in the console just results in a {}.

FormData can directly be used in a for ... of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries()).

Body:
I'm trying to upload a picture with Angular2 to my REST Service (Loopback).
The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.

Here's a simplified service method that sends the POST request:

public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.

In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:

Data before Request

But in the request, the body is an empty object {}:

Request

I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.

I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?


来源: stackexchange

问:
orderByChild() is not working in Firebase Database
Here is the firebase data structure.

Here I want to select all the node with value "stop" and delete them. I write this code but this is not working.

```<code>final Map<String, Object> map = new HashMap<String, Object>();
Query numberQuery = reference.child("numbers").orderByChild("stop");
numberQuery.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
      if (dataSnapshot.exists()){
       for (DataSnapshot eachDataSnapShot : dataSnapshot.getChildren()) {
              map.put("/numbers/"+eachDataSnapShot.getKey(), null);
           }
       }
     }
   @Override
   public void onCancelled(DatabaseError databaseError) {

     }
    });

    reference.updateChildren(map);
</code>```

Actually, I did not get how to use query in firebase document. If there is any other method (without using query) tell me.

答:
you can use orderByValue() and it will sort it this way :

Children with a null value for the specified child key come first.

Children with a value of false for the specified child key come next. If multiple children have a value of false, they are sorted
lexicographically by key.

Children with a value of true for the specified child key come next. If multiple children have a value of true, they are sorted
lexicographically by key.

Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the
specified child node, they are sorted by key.

Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the
specified child node, they are ordered lexicographically by key.

Objects come last and are sorted lexicographically by key in ascending order.

check this

ContentLicense: CC BY-SA 3.0

Body:
Here is the firebase data structure.

Here I want to select all the node with value "stop" and delete them. I write this code but this is not working.

final Map<String, Object> map = new HashMap<String, Object>();
Query numberQuery = reference.child("numbers").orderByChild("stop");
numberQuery.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
      if (dataSnapshot.exists()){
       for (DataSnapshot eachDataSnapShot : dataSnapshot.getChildren()) {
              map.put("/numbers/"+eachDataSnapShot.getKey(), null);
           }
       }
     }
   @Override
   public void onCancelled(DatabaseError databaseError) {

     }
    });

    reference.updateChildren(map);

Actually, I did not get how to use query in firebase document. If there is any other method (without using query) tell me.


问:
Argument out of range for 9th and 10th items in gridview
I'm getting an argument out of range exception in the row rowdatabound event when clicking the edit button, but only for the 9th and 10th items, regardless of the data (same for any page).

The error occurs here.

```<code>DropDownList DropDownList_QuantityType = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_QuantityType");
</code>```

This is the rowdatabound event.

```<code>protected void GridView_BidItemTypeTables_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            DropDownList DropDownList_QuantityType = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_QuantityType");
            DropDownList_QuantityType.SelectedValue = GridView_BidItemTypeTables.DataKeys[e.Row.RowIndex].Values[1].ToString();
            DropDownList DropDownList_FHWA = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_FHWA");
            DropDownList_FHWA.SelectedValue = GridView_BidItemTypeTables.DataKeys[e.Row.RowIndex].Values[2].ToString();
        }
    }
</code>```

PageSize is set to 10, so I do not understand why the [8] and [9] item would be an argument out of range exception.

I attempted changing PageSize to 8, and all 8 items worked fine. When I changed PageSize to 11, the last 3 items failed instead of the last 2.

Here is the view in the aspx page.

```<code><asp:View ID="View_BidItemTypeTables" runat="server">
        <div>
            <div style="width: 100%; overflow-x: scroll; overflow-y: auto;">
                <asp:GridView ID="GridView_BidItemTypeTables" runat="server" AutoGenerateColumns="false" EmptyDataText="No Records" DataKeyNames="GUID, QuantityTypeGuid,FHWA" AllowPaging="true" PageSize="10"
                    CssClass="gridview" Width="50%" BorderColor="Black" BorderWidth="1px" BorderStyle="Solid" OnRowCancelingEdit="GridView_BidItemTypeTables_RowCancelingEdit" OnRowEditing="GridView_BidItemTypeTables_RowEditing" OnRowUpdating="GridView_BidItemTypeTables_RowUpdating" OnRowDataBound="GridView_BidItemTypeTables_RowDataBound" OnPageIndexChanging="GridView_BidItemTypeTables_PageIndexChanging" OnRowCommand="GridView_BidItemTypeTables_RowCommand">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="Button_EditTypeTables" runat="server" CommandName="Edit" Text="Edit" Visible="true" CommandArgument="<%# Container.DataItemIndex %>" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:Button ID="Button_SaveTypeTables" runat="server" CommandName="Update" Text="Save" Visible="true" OnClick="Button_SaveTypeTables_Click" CausesValidation="true" ValidationGroup="ValidationFailed" /><asp:Button ID="Button_CancelTypeTables" runat="server" CommandName="Cancel" Text="Cancel" Visible="true" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Code">
                            <ItemTemplate>
                                <asp:Label ID="Label_Code" Text='<%# Bind("Code") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Code" Text='<%# Bind("Code") %>' runat="server" />
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_Code" runat="server" ErrorMessage="Code is Required." ControlToValidate="TextBox_Code" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                                <asp:CustomValidator runat="server" ID="CustomValidator_CodeGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxCodeValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Description">
                            <ItemTemplate>
                                <asp:Label ID="Label_Description" Text='<%# Bind("Description") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Description" Text='<%# Bind("Description") %>' runat="server" />
                                <asp:CustomValidator runat="server" ID="CustomValidator_DescriptionGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxDescriptionValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="QuantityType">
                            <ItemTemplate><%# Eval("QuantityType.Code") %></ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownList_QuantityType" AppendDataBoundItems="True" DataSourceID="ObjectDataSource_QuantityType" DataTextField="Code" DataValueField="Guid" runat="server">
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_QuantityType" runat="server" ErrorMessage="QuantityType is Required." ControlToValidate="DropDownList_QuantityType" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Unit">
                            <ItemTemplate>
                                <asp:Label ID="Label_Unit" Text='<%# Bind("Unit") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Unit" Text='<%# Bind("Unit") %>' runat="server" />
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_Unit" runat="server" ErrorMessage="Unit is Required." ControlToValidate="TextBox_Unit" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                                <asp:CustomValidator runat="server" ID="CustomValidator_UnitGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="UnitPrice">
                            <ItemTemplate>
                                <asp:Label ID="Label_UnitPrice" Text='<%# Bind("UnitPrice") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_UnitPrice" Text='<%# Bind("UnitPrice") %>' runat="server" MaxLength="9"/>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitPrice" runat="server" ErrorMessage="Unit Price is Required." ControlToValidate="TextBox_UnitPrice" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                                <asp:RegularExpressionValidator ID="RegularExpressionValidator_UnitPrice" runat="server" CssClass="failureNotification" ErrorMessage="Unit Price is in incorrect format or exceeds (999999.99)." ControlToValidate="TextBox_UnitPrice" Display="Dynamic" ValidationGroup="ValidationFailed" ValidationExpression="^\d{0,6}(\.\d{1,2})?$" SetFocusOnError="true">*</asp:RegularExpressionValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="FHWA">
                            <ItemTemplate>
                                <asp:Label ID="Label_FHWA" Text='<%# Bind("FHWA") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownList_FHWA" AppendDataBoundItems="True" runat="server">
                                    <asp:ListItem Value="" Selected="true">Select FHWA</asp:ListItem>
                                    <asp:ListItem Value="Y">Y</asp:ListItem>
                                    <asp:ListItem Value="N">N</asp:ListItem>
                                </asp:DropDownList><asp:RequiredFieldValidator ID="RequiredFieldValidator_FHWA" runat="server" ErrorMessage="FHWA is Required." ControlToValidate="DropDownList_FHWA" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="IsActive">
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox_IsActive" Checked='<%# Bind("IsActive") %>' runat="server" Enabled="False" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:CheckBox ID="CheckBox_IsActive" Checked='<%# Bind("IsActive") %>' runat="server" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
            <br />
            <br />
            <asp:Panel ID="Panel_AddBidItemTypeTables" runat="server" Visible="false">
                <table width="35%">
                    <tr>
                        <td>Code:</td>
                        <td>
                            <asp:TextBox ID="TextBox_CodeBidItemTypeTables" runat="server"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_CodeBidItemTypeTables" runat="server" ErrorMessage="Code is Required." ControlToValidate="TextBox_CodeBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification"  SetFocusOnError="true">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_CodeBidItemTypeTables" ControlToValidate="TextBox_CodeBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxCodeValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>Description:</td>
                        <td>
                            <asp:TextBox ID="TextBox_DescriptionBidItemTypeTables" runat="server" ClientIDMode="Static"></asp:TextBox>
                            <asp:CustomValidator runat="server" ID="CustomValidator_DescriptionBidItemTypeTables" ControlToValidate="TextBox_DescriptionBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxDescriptionValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>Quantity Type:</td>
                        <td>
                            <asp:DropDownList ID="DropDownList_QuantityTypeBidItemTypeTables" AppendDataBoundItems="True" DataSourceID="ObjectDataSource_QuantityType" DataTextField="Code" DataValueField="Guid" runat="server">
                                <asp:ListItem Value="" Selected="true">Select QuantityType</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator_QuantityTypeBidItemTypeTables" runat="server" Enabled="false" ErrorMessage="Quantity Type is Required." ControlToValidate="DropDownList_QuantityTypeBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>Unit:</td>
                        <td>
                            <asp:TextBox ID="TextBox_UnitBidItemTypeTables" runat="server"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitBidItemTypeTables" runat="server" ErrorMessage="Unit is Required." ControlToValidate="TextBox_UnitBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_UnitBidItemTypeTables" ControlToValidate="TextBox_UnitBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>UnitPrice:</td>
                        <td>
                            <asp:TextBox ID="TextBox_UnitPriceBidItemTypeTables" runat="server" MaxLength="9"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitPriceBidItemTypeTables" runat="server" ErrorMessage="Unit Price is Required." ControlToValidate="TextBox_UnitPriceBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_UnitPriceBidItemTypeTables" ControlToValidate="TextBox_UnitPriceBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitPriceValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>FHWA:</td>
                        <td>
                            <asp:DropDownList ID="DropDownList_FHWABidItemTypeTables" AppendDataBoundItems="True" runat="server">
                                <asp:ListItem Value="" Selected="true">Select FHWA</asp:ListItem>
                                <asp:ListItem Value="Y">Y</asp:ListItem>
                                <asp:ListItem Value="N">N</asp:ListItem>
                            </asp:DropDownList>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_FHWABidItemTypeTables" runat="server" Enabled="false" ErrorMessage="FHWA is Required." ControlToValidate="DropDownList_FHWABidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                        </td>
                        <td>
                            <asp:Button ID="Button_AddBidItemTypeTables" runat="server" Text="Add" CausesValidation="true" ValidationGroup="ValidationFailed" OnClick="Button_AddBidItemTypeTables_Click" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>
        </div>
    </asp:View>
</code>```

Anyone experience similar issue before?

答: Try e.Row.FindControl instead of e.Row.Cells[e.Row.RowIndex].FindControl.

Body:
I'm getting an argument out of range exception in the row rowdatabound event when clicking the edit button, but only for the 9th and 10th items, regardless of the data (same for any page).

The error occurs here.

DropDownList DropDownList_QuantityType = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_QuantityType");

This is the rowdatabound event.

protected void GridView_BidItemTypeTables_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            DropDownList DropDownList_QuantityType = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_QuantityType");
            DropDownList_QuantityType.SelectedValue = GridView_BidItemTypeTables.DataKeys[e.Row.RowIndex].Values[1].ToString();
            DropDownList DropDownList_FHWA = (DropDownList)e.Row.Cells[e.Row.RowIndex].FindControl("DropDownList_FHWA");
            DropDownList_FHWA.SelectedValue = GridView_BidItemTypeTables.DataKeys[e.Row.RowIndex].Values[2].ToString();
        }
    }

PageSize is set to 10, so I do not understand why the [8] and [9] item would be an argument out of range exception.

I attempted changing PageSize to 8, and all 8 items worked fine. When I changed PageSize to 11, the last 3 items failed instead of the last 2.

Here is the view in the aspx page.

<asp:View ID="View_BidItemTypeTables" runat="server">

                <asp:GridView ID="GridView_BidItemTypeTables" runat="server" AutoGenerateColumns="false" EmptyDataText="No Records" DataKeyNames="GUID, QuantityTypeGuid,FHWA" AllowPaging="true" PageSize="10"
                    CssClass="gridview" Width="50%" BorderColor="Black" BorderWidth="1px" BorderStyle="Solid" OnRowCancelingEdit="GridView_BidItemTypeTables_RowCancelingEdit" OnRowEditing="GridView_BidItemTypeTables_RowEditing" OnRowUpdating="GridView_BidItemTypeTables_RowUpdating" OnRowDataBound="GridView_BidItemTypeTables_RowDataBound" OnPageIndexChanging="GridView_BidItemTypeTables_PageIndexChanging" OnRowCommand="GridView_BidItemTypeTables_RowCommand">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="Button_EditTypeTables" runat="server" CommandName="Edit" Text="Edit" Visible="true" CommandArgument="<%# Container.DataItemIndex %>" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:Button ID="Button_SaveTypeTables" runat="server" CommandName="Update" Text="Save" Visible="true" OnClick="Button_SaveTypeTables_Click" CausesValidation="true" ValidationGroup="ValidationFailed" /><asp:Button ID="Button_CancelTypeTables" runat="server" CommandName="Cancel" Text="Cancel" Visible="true" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Code">
                            <ItemTemplate>
                                <asp:Label ID="Label_Code" Text='<%# Bind("Code") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Code" Text='<%# Bind("Code") %>' runat="server" />
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_Code" runat="server" ErrorMessage="Code is Required." ControlToValidate="TextBox_Code" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                                <asp:CustomValidator runat="server" ID="CustomValidator_CodeGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxCodeValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Description">
                            <ItemTemplate>
                                <asp:Label ID="Label_Description" Text='<%# Bind("Description") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Description" Text='<%# Bind("Description") %>' runat="server" />
                                <asp:CustomValidator runat="server" ID="CustomValidator_DescriptionGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxDescriptionValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="QuantityType">
                            <ItemTemplate><%# Eval("QuantityType.Code") %></ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownList_QuantityType" AppendDataBoundItems="True" DataSourceID="ObjectDataSource_QuantityType" DataTextField="Code" DataValueField="Guid" runat="server">
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_QuantityType" runat="server" ErrorMessage="QuantityType is Required." ControlToValidate="DropDownList_QuantityType" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Unit">
                            <ItemTemplate>
                                <asp:Label ID="Label_Unit" Text='<%# Bind("Unit") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_Unit" Text='<%# Bind("Unit") %>' runat="server" />
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_Unit" runat="server" ErrorMessage="Unit is Required." ControlToValidate="TextBox_Unit" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                                <asp:CustomValidator runat="server" ID="CustomValidator_UnitGrid" ControlToValidate="TextBox_Code" ClientIDMode="Static" ValidationGroup = "ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitValidatorBidItem_Grid" SetFocusOnError="true">*</asp:CustomValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="UnitPrice">
                            <ItemTemplate>
                                <asp:Label ID="Label_UnitPrice" Text='<%# Bind("UnitPrice") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox_UnitPrice" Text='<%# Bind("UnitPrice") %>' runat="server" MaxLength="9"/>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitPrice" runat="server" ErrorMessage="Unit Price is Required." ControlToValidate="TextBox_UnitPrice" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                                <asp:RegularExpressionValidator ID="RegularExpressionValidator_UnitPrice" runat="server" CssClass="failureNotification" ErrorMessage="Unit Price is in incorrect format or exceeds (999999.99)." ControlToValidate="TextBox_UnitPrice" Display="Dynamic" ValidationGroup="ValidationFailed" ValidationExpression="^\d{0,6}(\.\d{1,2})?$" SetFocusOnError="true">*</asp:RegularExpressionValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="FHWA">
                            <ItemTemplate>
                                <asp:Label ID="Label_FHWA" Text='<%# Bind("FHWA") %>' runat="server" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="DropDownList_FHWA" AppendDataBoundItems="True" runat="server">
                                    <asp:ListItem Value="" Selected="true">Select FHWA</asp:ListItem>
                                    <asp:ListItem Value="Y">Y</asp:ListItem>
                                    <asp:ListItem Value="N">N</asp:ListItem>
                                </asp:DropDownList><asp:RequiredFieldValidator ID="RequiredFieldValidator_FHWA" runat="server" ErrorMessage="FHWA is Required." ControlToValidate="DropDownList_FHWA" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            </EditItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="IsActive">
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox_IsActive" Checked='<%# Bind("IsActive") %>' runat="server" Enabled="False" />
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:CheckBox ID="CheckBox_IsActive" Checked='<%# Bind("IsActive") %>' runat="server" />
                            </EditItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

            <asp:Panel ID="Panel_AddBidItemTypeTables" runat="server" Visible="false">

                        Code:

                            <asp:TextBox ID="TextBox_CodeBidItemTypeTables" runat="server"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_CodeBidItemTypeTables" runat="server" ErrorMessage="Code is Required." ControlToValidate="TextBox_CodeBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification"  SetFocusOnError="true">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_CodeBidItemTypeTables" ControlToValidate="TextBox_CodeBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxCodeValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>

                        Description:

                            <asp:TextBox ID="TextBox_DescriptionBidItemTypeTables" runat="server" ClientIDMode="Static"></asp:TextBox>
                            <asp:CustomValidator runat="server" ID="CustomValidator_DescriptionBidItemTypeTables" ControlToValidate="TextBox_DescriptionBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxDescriptionValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>

                        Quantity Type:

                            <asp:DropDownList ID="DropDownList_QuantityTypeBidItemTypeTables" AppendDataBoundItems="True" DataSourceID="ObjectDataSource_QuantityType" DataTextField="Code" DataValueField="Guid" runat="server">
                                <asp:ListItem Value="" Selected="true">Select QuantityType</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator_QuantityTypeBidItemTypeTables" runat="server" Enabled="false" ErrorMessage="Quantity Type is Required." ControlToValidate="DropDownList_QuantityTypeBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification" SetFocusOnError="true">*</asp:RequiredFieldValidator>

                        Unit:

                            <asp:TextBox ID="TextBox_UnitBidItemTypeTables" runat="server"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitBidItemTypeTables" runat="server" ErrorMessage="Unit is Required." ControlToValidate="TextBox_UnitBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_UnitBidItemTypeTables" ControlToValidate="TextBox_UnitBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>

                        UnitPrice:

                            <asp:TextBox ID="TextBox_UnitPriceBidItemTypeTables" runat="server" MaxLength="9"></asp:TextBox>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_UnitPriceBidItemTypeTables" runat="server" ErrorMessage="Unit Price is Required." ControlToValidate="TextBox_UnitPriceBidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" Enabled="false" CssClass="failureNotification">*</asp:RequiredFieldValidator>
                            <asp:CustomValidator runat="server" ID="CustomValidator_UnitPriceBidItemTypeTables" ControlToValidate="TextBox_UnitPriceBidItemTypeTables" ClientIDMode="Static" ValidationGroup="ValidationFailed" Display="Dynamic" Enabled="true" CssClass="failureNotification" OnServerValidate="TextBoxUnitPriceValidatorBidItem" SetFocusOnError="true">*</asp:CustomValidator>

                        FHWA:

                            <asp:DropDownList ID="DropDownList_FHWABidItemTypeTables" AppendDataBoundItems="True" runat="server">
                                <asp:ListItem Value="" Selected="true">Select FHWA</asp:ListItem>
                                <asp:ListItem Value="Y">Y</asp:ListItem>
                                <asp:ListItem Value="N">N</asp:ListItem>
                            </asp:DropDownList>
                           <asp:RequiredFieldValidator ID="RequiredFieldValidator_FHWABidItemTypeTables" runat="server" Enabled="false" ErrorMessage="FHWA is Required." ControlToValidate="DropDownList_FHWABidItemTypeTables" Display="Dynamic" ValidationGroup="ValidationFailed" CssClass="failureNotification">*</asp:RequiredFieldValidator>

                            <asp:Button ID="Button_AddBidItemTypeTables" runat="server" Text="Add" CausesValidation="true" ValidationGroup="ValidationFailed" OnClick="Button_AddBidItemTypeTables_Click" />

            </asp:Panel>

    </asp:View>

Anyone experience similar issue before?


问:
Restrict assignment of property to a set of constants in C#
Say I had a property

```<code>public string RestrictedString {get; set;}
</code>```

and I had a few static constant strings defined

```<code>public const string String1 = "First String";
public const string String2 = "Second String";
</code>```

is there a way to only allow RestrictedString to be assigned to String1 or String2?

答:
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

```<code>using System;
using System.ComponentModel;
using System.Reflection;

public static class Program
{
    public const string String1 = "First String";
    public const string String2 = "Second String";
    public enum RestrictedStrings
    {
        [Description("First String")]
        String1,
        [Description("Second String")]
        String2
    }

    public static string GetDescription(Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return en.ToString();
        }

    public static void Main()
    {
        string description = Program.GetDescription(Program.RestrictedStrings.String1);
        Console.WriteLine(description);
    }
}

// Output: First String
</code>```

Hopefully this helps.

Body:
Say I had a property

public string RestrictedString {get; set;}

and I had a few static constant strings defined

public const string String1 = "First String";
public const string String2 = "Second String";

is there a way to only allow RestrictedString to be assigned to String1 or String2?

Body:
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

using System;
using System.ComponentModel;
using System.Reflection;

public static class Program
{
    public const string String1 = "First String";
    public const string String2 = "Second String";
    public enum RestrictedStrings
    {
        [Description("First String")]
        String1,
        [Description("Second String")]
        String2
    }

    public static string GetDescription(Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return en.ToString();
        }

    public static void Main()
    {
        string description = Program.GetDescription(Program.RestrictedStrings.String1);
        Console.WriteLine(description);
    }
}

// Output: First String

Hopefully this helps.


问:
Gradle build finished with 22 warnings(s)
I'm working in Android Studio, I finished my app and I generated signed APK, but when i install it the app stops unfortunately.

When i want to clean the project it shows 22 warnings in a file named R.java and this 22 lines can't be deleted because the file generally can't be edited.
In the log event, the system says that this warnings are some stings which haven't no translation.
I tried also to use my phone instead of android emulator in order to test the app but i encounter the same problem and the app crashes.
Can i solve this with stack trace and how ?this is my build gradle
My main activity here

答:
Add the following line to build.gradle:

```<code>android {
buildTypes {
    release {
        lintOptions {
            disable 'MissingTranslation'
        }
    }
}
</code>```

}

Hope it will help you...

Body:
Add the following line to build.gradle:

android {
buildTypes {
    release {
        lintOptions {
            disable 'MissingTranslation'
        }
    }
}

}

Hope it will help you...


问:
m2eclipse: Eclipse is running in a JRE, but a JDK is required
I have a problem with m2eclipse (0.10.0) together with eclipse galileo (Build id: 20090920-1017).

I always get the error message:"Eclipse is running in a JRE, but a JDK is required". I have tried several things, but nothing works. The error message is still there. Here are the things I have tried:

In Window>Preferences>Java>Installed JREs I checked JDK1.6.0_20. DOES NOT WORK

In Window>Preferences>Java>Installed JREs I removed all JREs. Only the checked JDK1.6.0_20 is still there. DOES NOT WORK

In Window>Preferences>Java>Installed JREs>Execution Environments I choosed JavaSE-1.6 and checked JDK1.6.0_20[perfect match]. DOES NOT WORK.

In Preferences of the eclipse desktop start icon I added the -vm parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin). DOES NOT WORK.

I added the clean parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin -clean). DOES NOT WORK.

I added the -vm parameter to the eclipse.ini file with a carriage return after -vm and C:/Programme/Java/jdk1.6.0_20/bin/javaw.exe in a new line. DOES NOT WORK.

After doing all these things I removed the m2eclipse plugin and installed it once again.  DOES NOT WORK.

New ideas I have tried:

In Preferences of the eclipse desktop start icon I put the executable at the end (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe). DOES NOT WORK.

I changed in eclipse.ini the slashes to backslashes. DOES NOT WORK.

Here is my eclipse.ini file:

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
</code>```

Is anyone out there who have other ideas? Any help is appreciated.

Thank You very much.
GernoK

答:
Put these lines at the beginning of the eclipse.ini file:

```<code>-vm
G:/dev/jdk1.6.0_19/bin/javaw.exe
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a problem with m2eclipse (0.10.0) together with eclipse galileo (Build id: 20090920-1017).

I always get the error message:"Eclipse is running in a JRE, but a JDK is required". I have tried several things, but nothing works. The error message is still there. Here are the things I have tried:

In Window>Preferences>Java>Installed JREs I checked JDK1.6.0_20. DOES NOT WORK

In Window>Preferences>Java>Installed JREs I removed all JREs. Only the checked JDK1.6.0_20 is still there. DOES NOT WORK

In Window>Preferences>Java>Installed JREs>Execution Environments I choosed JavaSE-1.6 and checked JDK1.6.0_20[perfect match]. DOES NOT WORK.

In Preferences of the eclipse desktop start icon I added the -vm parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin). DOES NOT WORK.

I added the clean parameter (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin -clean). DOES NOT WORK.

I added the -vm parameter to the eclipse.ini file with a carriage return after -vm and C:/Programme/Java/jdk1.6.0_20/bin/javaw.exe in a new line. DOES NOT WORK.

After doing all these things I removed the m2eclipse plugin and installed it once again.  DOES NOT WORK.

New ideas I have tried:

In Preferences of the eclipse desktop start icon I put the executable at the end (C:\Programme\eclipse_galileo\eclipse\eclipse.exe -vm C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe). DOES NOT WORK.

I changed in eclipse.ini the slashes to backslashes. DOES NOT WORK.

Here is my eclipse.ini file:

-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
C:\Programme\Java\jdk1.6.0_20\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

Is anyone out there who have other ideas? Any help is appreciated.

Thank You very much.
GernoK

Body:
Put these lines at the beginning of the eclipse.ini file:

-vm
G:/dev/jdk1.6.0_19/bin/javaw.exe


问:
How to pass arguments to .exe file calling form php?
I am trying to call a .exe file in php with arguments

    I use this to run .exe

```<code>$answer = shell_exec("calu.exe");
echo $answer."</br>";
</code>```

This Shows result:

Now how to pass argument like entering symbol

when i run this .exe file from commad line it ask Enter Symbol and the Enter two Number.
Enter symbol

Enter Number

I want to do same from Php and print result .

 How can i do so ?

答:
You said that Dos Calculator was a program of your own, written either in Python or in Batch.

What I would suggest then is to modify your program in order to handle command line arguments.

Some little snippets about how to handle command line arguments.
This will store your first argument, casted as a number, in b.

In Batch:

```<code>Set b=%1
</code>```

In Python:

```<code>import sys
b = int(sys.argv[1]) # Index 0 is the name of your program
</code>```

Then in php, you can call the your program with arguments like this:

```<code>$answer = shell_exec("calu.exe" . $first_number . " " . $second_number);
</code>```

Body:
I am trying to call a .exe file in php with arguments

    I use this to run .exe

$answer = shell_exec("calu.exe");
echo $answer."
";

This Shows result:

Now how to pass argument like entering symbol

when i run this .exe file from commad line it ask Enter Symbol and the Enter two Number.
Enter symbol

Enter Number

I want to do same from Php and print result .

 How can i do so ?

Body:
You said that Dos Calculator was a program of your own, written either in Python or in Batch.

What I would suggest then is to modify your program in order to handle command line arguments.

Some little snippets about how to handle command line arguments.
This will store your first argument, casted as a number, in b.

In Batch:

Set b=%1

In Python:

import sys
b = int(sys.argv[1]) # Index 0 is the name of your program

Then in php, you can call the your program with arguments like this:

$answer = shell_exec("calu.exe" . $first_number . " " . $second_number);


问:
How to solve Timeout FeignClient
My application is getting below error when consuming a service that performs queries in SQL Server using FeignClient.

ERROR:

Exception in thread "pool-10-thread-14" feign.RetryableException: Read timed out executing GET
  http://127.0.0.1:8876/processoData/search/buscaProcessoPorCliente?cliente=ELEKTRO+-+TRABALHISTA&estado=SP

My Consumer Service:

```<code>@FeignClient(url="http://127.0.0.1:8876")
public interface ProcessoConsumer {

@RequestMapping(method = RequestMethod.GET, value = "/processoData/search/buscaProcessoPorCliente?cliente={cliente}&estado={estado}")
public PagedResources<ProcessoDTO> buscaProcessoClienteEstado(@PathVariable("cliente") String cliente, @PathVariable("estado") String estado);

}
</code>```

My YML:

```<code>server:
  port: 8874

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  client:
  serviceUrl:
    defaultZone: ${vcap.services.eureka-service.credentials.uri:http://xxx.xx.xxx.xx:8764}/eureka/
  instance:
    preferIpAddress: true

ribbon:
  eureka:
    enabled: true

spring:
  application:
    name: MyApplication
  data:
    mongodb:
      host: xxx.xx.xxx.xx
      port: 27017
      uri: mongodb://xxx.xx.xxx.xx/recortesExtrator
      repositories.enabled: true
    solr:
      host: http://xxx.xx.xxx.xx:8983/solr
      repositories.enabled: true
</code>```

Anyone know how to solve this?

Thanks.

答:
just ran into this issue as well. As suggested by @spencergibb here is the workaround I'm using. See the link

Add these in the application.properties.

```<code># Disable Hystrix timeout globally (for all services)
hystrix.command.default.execution.timeout.enabled: false

# Increase the Hystrix timeout to 60s (globally)
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
</code>```

Add this in the Java configuration class.

```<code>import feign.Request;

@Configuration
@EnableDiscoveryClient
@EnableFeignClients(basePackageClasses = { ServiceFeignClient.class })
@ComponentScan(basePackageClasses = { ServiceFeignClient.class })
public class FeignConfig {

    /**
     * Method to create a bean to increase the timeout value,
     * It is used to overcome the Retryable exception while invoking the feign client.
     * @param env,
     *            An {@link ConfigurableEnvironment}
     * @return A {@link Request}
     */
    @Bean
    public static Request.Options requestOptions(ConfigurableEnvironment env) {
        int ribbonReadTimeout = env.getProperty("ribbon.ReadTimeout", int.class, 70000);
        int ribbonConnectionTimeout = env.getProperty("ribbon.ConnectTimeout", int.class, 60000);

        return new Request.Options(ribbonConnectionTimeout, ribbonReadTimeout);
    }
}
</code>```

Title: How to solve Timeout FeignClient

Body:
My application is getting below error when consuming a service that performs queries in SQL Server using FeignClient.

ERROR:

Exception in thread "pool-10-thread-14" feign.RetryableException: Read timed out executing GET
  http://127.0.0.1:8876/processoData/search/buscaProcessoPorCliente?cliente=ELEKTRO+-+TRABALHISTA&estado=SP

My Consumer Service:

@FeignClient(url="http://127.0.0.1:8876")
public interface ProcessoConsumer {

@RequestMapping(method = RequestMethod.GET, value = "/processoData/search/buscaProcessoPorCliente?cliente={cliente}&estado={estado}")
public PagedResources<ProcessoDTO> buscaProcessoClienteEstado(@PathVariable("cliente") String cliente, @PathVariable("estado") String estado);

}

My YML:

server:
  port: 8874

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  client:
  serviceUrl:
    defaultZone: ${vcap.services.eureka-service.credentials.uri:http://xxx.xx.xxx.xx:8764}/eureka/
  instance:
    preferIpAddress: true

ribbon:
  eureka:
    enabled: true

spring:
  application:
    name: MyApplication
  data:
    mongodb:
      host: xxx.xx.xxx.xx
      port: 27017
      uri: mongodb://xxx.xx.xxx.xx/recortesExtrator
      repositories.enabled: true
    solr:
      host: http://xxx.xx.xxx.xx:8983/solr
      repositories.enabled: true

Anyone know how to solve this?

Thanks.

Body:
just ran into this issue as well. As suggested by @spencergibb here is the workaround I'm using. See the link

Add these in the application.properties.

# Disable Hystrix timeout globally (for all services)
hystrix.command.default.execution.timeout.enabled: false

# Increase the Hystrix timeout to 60s (globally)
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000

Add this in the Java configuration class.

import feign.Request;

@Configuration
@EnableDiscoveryClient
@EnableFeignClients(basePackageClasses = { ServiceFeignClient.class })
@ComponentScan(basePackageClasses = { ServiceFeignClient.class })
public class FeignConfig {

    /**
     * Method to create a bean to increase the timeout value,
     * It is used to overcome the Retryable exception while invoking the feign client.
     * @param env,
     *            An {@link ConfigurableEnvironment}
     * @return A {@link Request}
     */
    @Bean
    public static Request.Options requestOptions(ConfigurableEnvironment env) {
        int ribbonReadTimeout = env.getProperty("ribbon.ReadTimeout", int.class, 70000);
        int ribbonConnectionTimeout = env.getProperty("ribbon.ConnectTimeout", int.class, 60000);

        return new Request.Options(ribbonConnectionTimeout, ribbonReadTimeout);
    }
}


问:
I want google pie chart to show pieSliceText to be rounded whole number
I am using Google Pie Chart, I want to display round percentage value but it is not showing like that. Anyone, suggest me an idea to show rounded percentage value. My code looks like</p>

```<code> google.setOnLoadCallback(drawChart);
                    function drawChart() {
 var data = google.visualization.arrayToDataTable([
                            ['Members', 'Total Members'],
                            ['Members', 23],
                            ['Total Members', 41 - 23]
                        ]);
                    var options = {
                            width: 150,
                            height: 150,
                            chartArea: {
                                width: 150,
                                height: 150,
                                left: 10},
                            legend: {position: 'none'},
                            tooltip: {trigger: 'none'},
                            colors: ['#FEC240', '#FFFFFF'],
                            pieSliceText: 'percentage',
                            pieSliceTextStyle: {
                                bold: true,
                                fontSize: 16,
                                color: 'black'
                            },
                            enableInteractivity: false,
                            pieSliceBorderColor: "#DFE0E1"

                        };
var chart = new
google.visualization.PieChart(document.getElementById('checkpie'));
chart.draw(data, options);

<div id="checkpie" ></div>
</code>```

答:
there isn't a standard option for setting the format of the percentage shown on the slices

as such, need to calculate the percentage manually,

use option --> pieSliceText: 'value' -- to show formatted value on slices

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Members', 'Total Members'],
    ['Members', 23],
    ['Total Members', 41 - 23]
  ]);

  // find total to calc % manually
  var totalData = google.visualization.data.group(
    data,
    [{column: 0, modifier: function () {return 'total'}, type:'string'}],
    [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
  );

  // number formatter
  var formatPercent = new google.visualization.NumberFormat({
    pattern: '0%'
  });

  // set formatted value for each row
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    var calcPercent = data.getValue(i, 1) / totalData.getValue(0, 1);
    data.setFormattedValue(i, 1, formatPercent.formatValue(calcPercent));
  }

  var options = {
    width: 150,
    height: 150,
    chartArea: {
      width: 150,
      height: 150,
      left: 10
    },
    legend: {position: 'none'},
    tooltip: {trigger: 'none'},
    colors: ['#FEC240', '#FFFFFF'],
    pieSliceText: 'value',  // <-- show formatted value on slices
    pieSliceTextStyle: {
      bold: true,
      fontSize: 16,
      color: 'black'
    },
    enableInteractivity: false,
    pieSliceBorderColor: "#DFE0E1"
  };
  var chart = new google.visualization.PieChart(document.getElementById('checkpie'));
  chart.draw(data, options);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="checkpie"></div></code>```

Body:
I am using Google Pie Chart, I want to display round percentage value but it is not showing like that. Anyone, suggest me an idea to show rounded percentage value. My code looks like

 google.setOnLoadCallback(drawChart);
                    function drawChart() {
 var data = google.visualization.arrayToDataTable([
                            ['Members', 'Total Members'],
                            ['Members', 23],
                            ['Total Members', 41 - 23]
                        ]);
                    var options = {
                            width: 150,
                            height: 150,
                            chartArea: {
                                width: 150,
                                height: 150,
                                left: 10},
                            legend: {position: 'none'},
                            tooltip: {trigger: 'none'},
                            colors: ['#FEC240', '#FFFFFF'],
                            pieSliceText: 'percentage',
                            pieSliceTextStyle: {
                                bold: true,
                                fontSize: 16,
                                color: 'black'
                            },
                            enableInteractivity: false,
                            pieSliceBorderColor: "#DFE0E1"

                        };
var chart = new
google.visualization.PieChart(document.getElementById('checkpie'));
chart.draw(data, options);

Body:
there isn't a standard option for setting the format of the percentage shown on the slices

as such, need to calculate the percentage manually,

use option --> pieSliceText: 'value' -- to show formatted value on slices

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Members', 'Total Members'],
    ['Members', 23],
    ['Total Members', 41 - 23]
  ]);

  // find total to calc % manually
  var totalData = google.visualization.data.group(
    data,
    [{column: 0, modifier: function () {return 'total'}, type:'string'}],
    [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
  );

  // number formatter
  var formatPercent = new google.visualization.NumberFormat({
    pattern: '0%'
  });

  // set formatted value for each row
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    var calcPercent = data.getValue(i, 1) / totalData.getValue(0, 1);
    data.setFormattedValue(i, 1, formatPercent.formatValue(calcPercent));
  }

  var options = {
    width: 150,
    height: 150,
    chartArea: {
      width: 150,
      height: 150,
      left: 10
    },
    legend: {position: 'none'},
    tooltip: {trigger: 'none'},
    colors: ['#FEC240', '#FFFFFF'],
    pieSliceText: 'value',  // <-- show formatted value on slices
    pieSliceTextStyle: {
      bold: true,
      fontSize: 16,
      color: 'black'
    },
    enableInteractivity: false,
    pieSliceBorderColor: "#DFE0E1"
  };
  var chart = new google.visualization.PieChart(document.getElementById('checkpie'));
  chart.draw(data, options);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="checkpie"></div>


问:
Is there a way of using my .vimrc when doing a git commit?
I have made my .vimrc fitting my needs in a quite cool way and I'm already really used to it. That's why I get always confused when my different shortcut and bindings don't work as they do in the git commit vim.

Is there a way that this will use my normal vim config? Why is this even different from the normal vim? Does that not use my local vim editor?

I have already set vim as standard editor according to this question.

Thanks!

Update

I use Mac OS X Sierra.

:version inside the git vim returns the right file '$HOME/.vimrc'.

Update 2

I'm actually using Neovim. But I set VISUAL to 'nvim' and it still doesn't work.

答:
It's probably some unusual system setting, path variable or alias interfering with this. To make Git explicitly pick up a certain editor (Neovim in your case), do the following:

```<code>git config --global core.editor "$(which nvim)"
</code>```

This assumes you are using a Bash-compatible shell and that running nvim directly opens the editor with the configuration you want and are used to.

It works by setting the global Git configuration to use the absolute path to the nvim binary that gets picked up in your PATH.

Body:
It's probably some unusual system setting, path variable or alias interfering with this. To make Git explicitly pick up a certain editor (Neovim in your case), do the following:

git config --global core.editor "$(which nvim)"

This assumes you are using a Bash-compatible shell and that running nvim directly opens the editor with the configuration you want and are used to.

It works by setting the global Git configuration to use the absolute path to the nvim binary that gets picked up in your PATH.

ContentLicense: CC BY-SA 4.0


问:
passing an array as an index to another array?
alright so I'm writing some code used for image processing and most of it is converted from some old matlab code for the same process. At the point I'm at now(the final step in the process) I need to pass an array as an index to another array.

a bit of background: I'm separating the images in to RGB bands or mask. earlier in the code I took all the images(as numpy arrays) and took a median along along the 3rd dimension. I'm trying to pass the RGB mask as arguments so I can get the median along those pixel values, and have 0's in place of the RB pixels.

The code in Matlab to do this is pretty straightforward:

```<code>finalMedGreen_ROI(exp_i+1) = median(median(EXPMedian_ROI(GMask_ROI)));
</code>```

where GMask_ROI is an array that is a region of interest of the raw image data, and EXPMedian_ROI is the Median of all the raw image data).

I tried to replicate this in python:

```<code>self.final_median_green_roi[image+1] = np.median(np.median(self.exposure_median_roi(self.green_mask_roi)))
</code>```

and I got this error:

```<code>TypeError: 'numpy.ndarray' object is not callable
</code>```

I tried to simply pass both arrays as arguments in np.median. here's the thing, self.green_mask_roi is an array of boolean values(true for green pixels, false for everything else. when I ran this:

```<code>self.final_median_green_roi[0,1] = np.median(np.median(self.dark_median_roi,self.green_mask_roi))
</code>```

I got this error:

```<code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I'm not sure if it's suggesting those for the boolean array or the numeric median array and I'd rather get it right simply for the fact that I'm new to image processing and I'm unlikely to catch the mistake. any suggestions?

答:
Use numpy's builtin mask arrays:

```<code>...  =np.median(np.median(np.ma.masked_array(self.dark_median_roi, self.green_mask_roi)))
</code>```

This creates a new array by making a mask of the 2nd parameter, self.green_mask_roi, and applying it to the 1st, self.dark_median_roi, so that you get an array that has all of the original elements of self.dark_median_roi that are also present in self.green_mask_roi.

Body:
alright so I'm writing some code used for image processing and most of it is converted from some old matlab code for the same process. At the point I'm at now(the final step in the process) I need to pass an array as an index to another array.

a bit of background: I'm separating the images in to RGB bands or mask. earlier in the code I took all the images(as numpy arrays) and took a median along along the 3rd dimension. I'm trying to pass the RGB mask as arguments so I can get the median along those pixel values, and have 0's in place of the RB pixels.

The code in Matlab to do this is pretty straightforward:

finalMedGreen_ROI(exp_i+1) = median(median(EXPMedian_ROI(GMask_ROI)));

where GMask_ROI is an array that is a region of interest of the raw image data, and EXPMedian_ROI is the Median of all the raw image data).

I tried to replicate this in python:

self.final_median_green_roi[image+1] = np.median(np.median(self.exposure_median_roi(self.green_mask_roi)))

and I got this error:

TypeError: 'numpy.ndarray' object is not callable

I tried to simply pass both arrays as arguments in np.median. here's the thing, self.green_mask_roi is an array of boolean values(true for green pixels, false for everything else. when I ran this:

self.final_median_green_roi[0,1] = np.median(np.median(self.dark_median_roi,self.green_mask_roi))

I got this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I'm not sure if it's suggesting those for the boolean array or the numeric median array and I'd rather get it right simply for the fact that I'm new to image processing and I'm unlikely to catch the mistake. any suggestions?

Body:
Use numpy's builtin mask arrays:

...  =np.median(np.median(np.ma.masked_array(self.dark_median_roi, self.green_mask_roi)))

This creates a new array by making a mask of the 2nd parameter, self.green_mask_roi, and applying it to the 1st, self.dark_median_roi, so that you get an array that has all of the original elements of self.dark_median_roi that are also present in self.green_mask_roi.


问:
PHP performance question
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

```<code>if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
</code>```

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

答:
For separation of concerns, it might be viable to let the client browser add functions for logged in users. Meaning you send out one static version of the website, and Javascript checks client-side for the presence of a login cookie. If it's present the few additional GUI elements or permissable links are displayed.

The obvious pitfall being that JS disabled browsers would not see anything. Unless you decorate elements with CSS .optional-func and disable/enable that:

```<code>if (!document.cookies.match(/login/)) { $(".user-funcs").hide(); }
</code>```

Title: PHP performance question

Body:
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

Body:
For separation of concerns, it might be viable to let the client browser add functions for logged in users. Meaning you send out one static version of the website, and Javascript checks client-side for the presence of a login cookie. If it's present the few additional GUI elements or permissable links are displayed.

The obvious pitfall being that JS disabled browsers would not see anything. Unless you decorate elements with CSS .optional-func and disable/enable that:

if (!document.cookies.match(/login/)) { $(".user-funcs").hide(); }


问:
Retrieve data from web service with ws addressing
I have a web service on a client site from which I need to report.

Locally, I mimicked the service using the provided wsdls and have been able to report on these. However, now pointing at the client site I am unable to access the data as the service requires ws addressing headers to be included.

The webservice is expecting the below:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:add="http://www.w3.org/2005/08/addressing" xmlns:ns="CustomerNamespace" xmlns:sch="Schema.xsd">
   <soapenv:Header>
      <add:From>
         <add:Address>Something</add:Address>
         <add:ReferenceParameters>
            <ns:TransactionGroupID>SomeOtherThing</ns:TransactionGroupID>
            <ns:SenderID>911</ns:SenderID>
         </add:ReferenceParameters>
      </add:From>
      <add:Action>Request</add:Action>
      <add:MessageID>TestGUID</add:MessageID>
   </soapenv:Header>
   <soapenv:Body>
      <sch:Request>
         <sch:SearchCustomerSystem>SystemXYZ</sch:SearchCustomerSystem>
          <sch:ServiceID>999999999999</sch:ServiceID>
      </sch:Request>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

At present, I ccan get SSRS to produce the below:

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>
</code>```

Other than creating a custom data extension (which I would rather avoid), is there a way of getting the ws addressing headers into the request?

答:
The following snippet is the part of our WSDL that may be helpful if you have ability to change your WSDL. You will likely only need a bit of the namespaces, particularly the "addressing" related items. The "wsaw" namespace is the one used on our Action attributes that live on wsdl:input attributes under path of wsdl:portType -> wsdl:operation.</p>

```<code>  <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="OurTargetNamespaceHere" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" name="OurServiceNameHere" targetNamespace="OurTargetNamespaceHere">
  <wsp:Policy wsu:Id="OurCustomPolicy_policy">
    <wsp:ExactlyOne>
      <wsp:All>
        <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
          <wsp:Policy>
            <sp:TransportToken>
              <wsp:Policy>
                <sp:HttpsToken RequireClientCertificate="false"/>
              </wsp:Policy>
            </sp:TransportToken>
            <sp:AlgorithmSuite>
              <wsp:Policy>
                <sp:Basic256/>
              </wsp:Policy>
            </sp:AlgorithmSuite>
            <sp:Layout>
              <wsp:Policy>
                <sp:Strict/>
              </wsp:Policy>
            </sp:Layout>
          </wsp:Policy>
        </sp:TransportBinding>
      </wsp:All>
    </wsp:ExactlyOne>
  </wsp:Policy>
</code>```

Body:
I have a web service on a client site from which I need to report.

Locally, I mimicked the service using the provided wsdls and have been able to report on these. However, now pointing at the client site I am unable to access the data as the service requires ws addressing headers to be included.

The webservice is expecting the below:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:add="http://www.w3.org/2005/08/addressing" xmlns:ns="CustomerNamespace" xmlns:sch="Schema.xsd">
   <soapenv:Header>
      <add:From>
         <add:Address>Something</add:Address>
         <add:ReferenceParameters>
            <ns:TransactionGroupID>SomeOtherThing</ns:TransactionGroupID>
            <ns:SenderID>911</ns:SenderID>
         </add:ReferenceParameters>
      </add:From>
      <add:Action>Request</add:Action>
      <add:MessageID>TestGUID</add:MessageID>
   </soapenv:Header>
   <soapenv:Body>
      <sch:Request>
         <sch:SearchCustomerSystem>SystemXYZ</sch:SearchCustomerSystem>
          <sch:ServiceID>999999999999</sch:ServiceID>
      </sch:Request>
   </soapenv:Body>
</soapenv:Envelope>

At present, I ccan get SSRS to produce the below:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>

Other than creating a custom data extension (which I would rather avoid), is there a way of getting the ws addressing headers into the request?

Body:
The following snippet is the part of our WSDL that may be helpful if you have ability to change your WSDL. You will likely only need a bit of the namespaces, particularly the "addressing" related items. The "wsaw" namespace is the one used on our Action attributes that live on wsdl:input attributes under path of wsdl:portType -> wsdl:operation.

  <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="OurTargetNamespaceHere" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" name="OurServiceNameHere" targetNamespace="OurTargetNamespaceHere">
  <wsp:Policy wsu:Id="OurCustomPolicy_policy">
    <wsp:ExactlyOne>
      <wsp:All>
        <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
          <wsp:Policy>
            <sp:TransportToken>
              <wsp:Policy>
                <sp:HttpsToken RequireClientCertificate="false"/>
              </wsp:Policy>
            </sp:TransportToken>
            <sp:AlgorithmSuite>
              <wsp:Policy>
                <sp:Basic256/>
              </wsp:Policy>
            </sp:AlgorithmSuite>
            <sp:Layout>
              <wsp:Policy>
                <sp:Strict/>
              </wsp:Policy>
            </sp:Layout>
          </wsp:Policy>
        </sp:TransportBinding>
      </wsp:All>
    </wsp:ExactlyOne>
  </wsp:Policy>


问:
Usage of ember generate command for addon
I have my Ember engine/addon which has package.json as below;

```<code>{
  "name": "my-addon-ui",
  "version": "1.0.0",
  "devDependencies": {
    "test-addon": "http://example.com/test-addon-1.1.1.tgz",
  }
}
</code>```

Also the package.json of the dependency test-addon looks like below;

```<code>{
  "name": "test-addon",
  "ember-addon": {
  },
  "keywords": [
    "ember-addon",
    "blueprint",
    "test-addon"
  ]
}
</code>```

Now I see the following commands are used;

```<code>npm install
ember generate test-addon
</code>```

While I understand what npm install does, I am confused about the usage of ember generate test-addon

What does it do exactly ? Does it map to the entries specified in keywords of "test-addon" ?

I am confused with the usage of ember generate without the type like

```<code>ember generate route OR
ember generate controller
</code>```

答:
Ember Generate is an Ember-CLI tool to help you quickly generate boilerplate (AKA redundant) code for your Ember application. You typically use ember g for routes, controllers, helpers, or some other common building blocks of Ember.

However, you also have the ability to create your own "blueprints". "test-addon" is not included in your ember application by default. When you call ember g test-addon, you are creating boilerplate code for that specific addon.

When you call ember generate test-addon, Ember looks for a blueprint for the node-module test-addon.

Likewise, when you call ember generate blueprint example-blueprint, you are writing your own blueprint to be used by someone else.

https://ember-cli.com/generators-and-blueprints

Body:
I have my Ember engine/addon which has package.json as below;

{
  "name": "my-addon-ui",
  "version": "1.0.0",
  "devDependencies": {
    "test-addon": "http://example.com/test-addon-1.1.1.tgz",
  }
}

Also the package.json of the dependency test-addon looks like below;

{
  "name": "test-addon",
  "ember-addon": {
  },
  "keywords": [
    "ember-addon",
    "blueprint",
    "test-addon"
  ]
}

Now I see the following commands are used;

npm install
ember generate test-addon

While I understand what npm install does, I am confused about the usage of ember generate test-addon

What does it do exactly ? Does it map to the entries specified in keywords of "test-addon" ?

I am confused with the usage of ember generate without the type like

ember generate route OR
ember generate controller


问:
NLog Writing a GUID to database
I am having trouble inserting a guid Id each time a log is written in the database. It throws these errors:

```<code>Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll
</code>```

What I have so far:

```<code>    @"INSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)";

    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString()));
    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));
</code>```

Thanks.

答:
Ended up doing this:</p>

```<code>@"INSERT INTO [dbo].[Nlogs]
        (Id,Message)
        values
        (NewID(),@Message)";

databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));
</code>```

Title: NLog Writing a GUID to database

Body:
I am having trouble inserting a guid Id each time a log is written in the database. It throws these errors:

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll

What I have so far:

    @"INSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)";

    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString()));
    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));

Thanks.

Body:
Ended up doing this:

@"INSERT INTO [dbo].[Nlogs]
        (Id,Message)
        values
        (NewID(),@Message)";

databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));


问:
AndroidJavaProxy is not an interface
I'm trying to use an Android phone's camera in Unity. I need to pass a CameraDevice.StateCallback to the CameraManager.openCamera method, which I have constructed as such:

```<code>public class OpenCameraCallbackProxy : AndroidJavaProxy
{
    public OpenCameraCallbackProxy() : base("android.hardware.camera2.CameraDevice$StateCallback")
    {

    }

    public void onOpened(AndroidJavaObject cameraDevice)
    {
        // etc...
    }
}
</code>```

When calling the openCamera method (cameraManager is an instance of AndroidJavaObject):

```<code>cameraManager.Call("openCamera", cameraId, new OpenCameraCallbackProxy(), null);
</code>```

I get the following exception:

java.lang.IllegalArgumentException: class android.hardware.camera2.CameraDevice$StateCallback is not an interface.

I am also using a proprietary Java library elsewhere in my application which uses callbacks, and this method (using AndroidJavaProxy) works properly. I'm guessing that there must be a check in openCamera to throw if not callback.getClass().isInterface() or something like that. Is there any way I could get around this?

Thanks in advance.

答:
AndroidJavaProxy's constructor requires the fully qualified name string of the interface to be implemented for the callback. Presumably this is because the object passed back to you is a runtime constructed class, so its signature is not available at compile time, but that the code that constructs the runtime object can implement a given interface (how? I have no idea, other than it would use ASM, but that's like saying "I don't know how they made that dresser, but a saw was probably involved").

However, CameraDevice.StateCallback is not an interface, it is an abstract class.

The Unity example for using the AndroidJavaProxy uses a DatePickerDialog$OnDateSetListener callback interface, which we can see is actually an interface.

I am not sure what you should be doing instead (possibly subclassing CameraDevice.StateCallback? That's what this guy did) as I've never tried to do this, but that's why you're getting the error your getting.

Title: AndroidJavaProxy is not an interface

Body:
I'm trying to use an Android phone's camera in Unity. I need to pass a CameraDevice.StateCallback to the CameraManager.openCamera method, which I have constructed as such:

public class OpenCameraCallbackProxy : AndroidJavaProxy
{
    public OpenCameraCallbackProxy() : base("android.hardware.camera2.CameraDevice$StateCallback")
    {

    }

    public void onOpened(AndroidJavaObject cameraDevice)
    {
        // etc...
    }
}

When calling the openCamera method (cameraManager is an instance of AndroidJavaObject):

cameraManager.Call("openCamera", cameraId, new OpenCameraCallbackProxy(), null);

I get the following exception:

java.lang.IllegalArgumentException: class android.hardware.camera2.CameraDevice$StateCallback is not an interface.

I am also using a proprietary Java library elsewhere in my application which uses callbacks, and this method (using AndroidJavaProxy) works properly. I'm guessing that there must be a check in openCamera to throw if not callback.getClass().isInterface() or something like that. Is there any way I could get around this?

Thanks in advance.


问:
bash sort unusual order. Problem with spaces?
Lots of time gone in to a bug, which tracks back to sort...

Can someone explain why I get this unsorted result, when the bash docs tell me the delimiter is a transition from white to non-white characters? Shouldn't the first field be sorted?

```<code>>sort myfile.txt
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_1000000 44
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16
</code>```

of course using +0 -1 gives me my expected result:

```<code>>sort +0 -1 myfile.txt
10_1000000 44
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16
</code>```

Some metainfo:

```<code>>type sort
sort is hashed (/bin/sort)
</code>```

I am using

```<code>sort (GNU coreutils) 5.97

>locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
</code>```

Body:
Lots of time gone in to a bug, which tracks back to sort...

Can someone explain why I get this unsorted result, when the bash docs tell me the delimiter is a transition from white to non-white characters? Shouldn't the first field be sorted?

>sort myfile.txt
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_1000000 44
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16

of course using +0 -1 gives me my expected result:

>sort +0 -1 myfile.txt
10_1000000 44
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16

Some metainfo:

>type sort
sort is hashed (/bin/sort)

I am using

sort (GNU coreutils) 5.97

>locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

Body:
Works right for me:

$ sort myfile.txt
10_1000000 44
10_10000000 19
10_10000001 20
10_10000002 19
10_10000003 17
10_10000004 16
10_10000005 16
10_10000006 16
10_10000007 17
10_10000008 16

$ sort --version
sort (GNU coreutils) 8.5

Perhaps your version requires the -n flag to turn on numerical-sort?


问:
Convert Json to XML properly
I have following dictionary structure

```<code>[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]
</code>```

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>
```

<p>However, after applying the next code:</p>

```dicttoxml.dicttoxml(result, attr_type=False, root=True)
```

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?

答:
Probably you'll have to code a function to generate the xml for the list the way you want:
https://github.com/quandyfactory/dicttoxml/blob/master/dicttoxml.py

(see dicttoxml function comment)

Seems the "<item>whatever</item>" pattern is hardcoded and if you use cdata=True you'll get the whole '<![CDATA[whatever]]>' stuff.

Title: Convert Json to XML properly

Body:
I have following dictionary structure

[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>

However, after applying the next code:

dicttoxml.dicttoxml(result, attr_type=False, root=True)

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?


问:
Can't find Main when executing a Java class from Gradle
I've  been attempting to run a java main from Gradle however Gradle keeps giving me the error

Execution failed for task ':myTask'

No main class specified

I've attached the code below

```<code>sourceSets {
    main {
        java {
            srcDirs 'src/myPackage/downloadupdater'
            srcDirs 'src/myPackage/downloadupdater/util'
            srcDirs 'src/myPackage/downloadupdater/dao'
        }
        // output.classesDir = "/bin"
    }
}

task myTask(dependsOn : compileJava, type : JavaExec){
    group = "Custom"
    description = "Acquires the weekly stats"

    doLast{
        classpath = sourceSets.main.output.classesDir
        main = "myPackage.SomeClass"
        args "-w"
    }
}
</code>```

The java class I'm calling is:

```<code>package myPackage
public class SomeClass{

    private static DownloadUpdater updater;

    public static void main (String [] args) {

        updater = new DownloadUpdater();

        updater.whichStatistics(args[0]);

        updater.setCalendar();

        updater.secureWorkbook();

        updater.getStatistics();

    }
}
</code>```

After building, my directories come up with a build-classes-java-main-myPackage but gradle still can't find the main class.

答:
Either move java source files to src/main/java instead of just src. Or set

```<code>sourceSet properly
sourceSets.main.java.srcDirs = ['src']
</code>```

and use

```<code>task execute(type:JavaExec) {
main = "myPackage.SomeClass"
classpath = sourceSets.main.runtimeClasspath
}
</code>```

for more refer : Gradle to execute Java class (without modifying build.gradle)

Body:
I've  been attempting to run a java main from Gradle however Gradle keeps giving me the error

Execution failed for task ':myTask'

No main class specified

I've attached the code below

sourceSets {
    main {
        java {
            srcDirs 'src/myPackage/downloadupdater'
            srcDirs 'src/myPackage/downloadupdater/util'
            srcDirs 'src/myPackage/downloadupdater/dao'
        }
        // output.classesDir = "/bin"
    }
}

task myTask(dependsOn : compileJava, type : JavaExec){
    group = "Custom"
    description = "Acquires the weekly stats"

    doLast{
        classpath = sourceSets.main.output.classesDir
        main = "myPackage.SomeClass"
        args "-w"
    }
}

The java class I'm calling is:

package myPackage
public class SomeClass{

    private static DownloadUpdater updater;

    public static void main (String [] args) {

        updater = new DownloadUpdater();

        updater.whichStatistics(args[0]);

        updater.setCalendar();

        updater.secureWorkbook();

        updater.getStatistics();

    }
}

After building, my directories come up with a build-classes-java-main-myPackage but gradle still can't find the main class.

Body:
Either move java source files to src/main/java instead of just src. Or set

sourceSet properly
sourceSets.main.java.srcDirs = ['src']

and use

task execute(type:JavaExec) {
main = "myPackage.SomeClass"
classpath = sourceSets.main.runtimeClasspath
}

for more refer : Gradle to execute Java class (without modifying build.gradle)


问:
Microsoft One Drive solution for Files and Folders - Around 300 Systems
I need Files and Folders backup of 300 Windows 8+ System. I opted One Drive Solution. So do i need to buy 300 License of One Drive for Business or Can i buy 1 license and can create and share 300 folders for each person?

In any of the option, the user can upload data to their space but admin can see all the folders.

答: A third-party tool e.g.Cloudberry MBS may be a solution in your case.It works rather well with any number of machines. What I like more is that the tool is intergrated with leading cloud storages like Amazon, Google, Openstack etc.</p>


问:
Debug in visual studio code is not working
Launch Configuration

```<code>{
    // Use IntelliSense to learn about possible Node.js debug attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach",
            "port": 5858
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/src/app.js",
            "cwd": "${workspaceRoot}"
        }
    ]
}
</code>```

I am getting the following error while debugging my react code in visual studio code. Actually I have created the project with node+react and use visual studio as IDE and want to debug my code. I have tried a lot but not able to success to debug my code.

Debugging with legacy protocol because Node.js v6.10.2 was detected.Program path uses differently cased character as file on disk; this might result in breakpoints not being hit.
node --debug-brk=21730 --nolazy src\app.js
    Debugger listening on [::]:21730
    e:\reactjs\reactFacebook\my-app\src\app.js:1
    (function (exports, require, module, __filename, __dirname) { import React, { Component } from 'react';
                                                                  ^^^^^^
    SyntaxError: Unexpected token import
        at createScript (vm.js:56:10)
        at Object.runInThisContext (vm.js:97:10)
        at Module._compile (module.js:542:28)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
        at ontimeout (timers.js:380:14)
        at tryOnTimeout (timers.js:244:5)
```

答:
I had the same issue, turns out the clue was in the console: Debugging with legacy protocol because Node.js v6.10.2 was detected.

I resolved it using the following steps:

Shutdown VS Code

Uninstall node

Install node v5 using NVM

Delete node_modules folder in project

Re-open VS Code

Run npm install

Place a breakpoint and try again.

Body:
Launch Configuration

{
    // Use IntelliSense to learn about possible Node.js debug attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach",
            "port": 5858
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/src/app.js",
            "cwd": "${workspaceRoot}"
        }
    ]
}

I am getting the following error while debugging my react code in visual studio code. Actually I have created the project with node+react and use visual studio as IDE and want to debug my code. I have tried a lot but not able to success to debug my code.

Debugging with legacy protocol because Node.js v6.10.2 was detected.Program path uses differently cased character as file on disk; this might result in breakpoints not being hit.
node --debug-brk=21730 --nolazy src\app.js
    Debugger listening on [::]:21730
    e:\reactjs\reactFacebook\my-app\src\app.js:1
    (function (exports, require, module, __filename, __dirname) { import React, { Component } from 'react';
                                                                  ^^^^^^
    SyntaxError: Unexpected token import
        at createScript (vm.js:56:10)
        at Object.runInThisContext (vm.js:97:10)
        at Module._compile (module.js:542:28)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
        at ontimeout (timers.js:380:14)
        at tryOnTimeout (timers.js:244:5)


问:
How to interpolate variables in strings in JavaScript, without concatenation?
I know in PHP we can do something like this:

```<code>$hello = "foo";
$my_string = "I pity the $hello";
</code>```

Output: "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

答:
Complete and ready to be used answer for <ES6:

```<code> var Strings = {
        create : (function() {
                var regexp = /{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};
</code>```

Call as

```<code>Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
</code>```

To attach it to String.prototype:

```<code>String.prototype.create = function(o) {
           return Strings.create(this, o);
}
</code>```

Then use as :

```<code>"My firstname is ${first}".create({first:'Neo'});
</code>```

If you are on >ES6 then you can also do:

```<code>let first = 'Neo';
`My firstname is ${first}`;
</code>```

Body:
I know in PHP we can do something like this:

$hello = "foo";
$my_string = "I pity the $hello";

Output: "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

Body:
Complete and ready to be used answer for <ES6:

 var Strings = {
        create : (function() {
                var regexp = /{([^{]+)}/g;

                return function(str, o) {
                     return str.replace(regexp, function(ignore, key){
                           return (key = o[key]) == null ? '' : key;
                     });
                }
        })()
};

Call as

Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});

To attach it to String.prototype:

String.prototype.create = function(o) {
           return Strings.create(this, o);
}

Then use as :

"My firstname is ${first}".create({first:'Neo'});

If you are on >ES6 then you can also do:

let first = 'Neo';
`My firstname is ${first}`;