问:
ASP GridView DropdownList EDIT/UPDATE
I have a GridView on a ASP-Page binding to a table with foreign-keys, where the Columns have DropdownLists with TEXT gathering to the VALUES, in other Tables.

When I EDIT the Row of the GridView, I add the Text of the Dropdowns in CodeBehind. This is all working fine. But when UPDATING I am trying to set the UpdateParameters of the DataSource manually, so i want to check which values in DropDowns are selected. But in every event i tried, the dropdowns are NULL.

I have tried:

RowUpdating- and RowEditing-Events of the GridView

Updating-Event of the DataSource

ASPX:

```<code><asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" AllowSorting="True" Width="90%" DataKeyNames="id" Font-Size="Large">

    <Columns>
        <asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
                <EditItemTemplate>
                    <asp:Label ID="LabelIDe" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelIDi" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:TemplateField HeaderText="Mitglied" InsertVisible="False" SortExpression="mitgliedid">
                <EditItemTemplate>
                    <asp:Label ID="LabelMe" runat="server" Text='<%# Bind("mitgliedid") %>' Visible="false"></asp:Label>
                    <asp:DropDownList runat="server" ID="mitgliederDD">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelMi" runat="server" Text='<%# Bind("mitgliedid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:TemplateField HeaderText="Amt" InsertVisible="False" SortExpression="amtid">
                <EditItemTemplate>
                    <asp:Label ID="LabelAe" runat="server" Text='<%# Bind("amtid") %>' Visible="false"></asp:Label>
                    <asp:DropDownList runat="server" ID="ämterDD">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelAi" runat="server" Text='<%# Bind("amtid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right" />
    </Columns>

    <EditRowStyle BackColor="#7C6F57" HorizontalAlign="Center"></EditRowStyle>
    <FooterStyle BackColor="#1C5E55" BorderStyle="None" Font-Bold="True" ForeColor="White"></FooterStyle>
    <HeaderStyle BackColor="#666666" Font-Bold="True" ForeColor="White" CssClass="gridHeader"></HeaderStyle>
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" CssClass="gridPager" Font-Bold="True"></PagerStyle>
    <RowStyle BackColor="#E3EAEB" HorizontalAlign="Center"></RowStyle>
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

    <SortedAscendingCellStyle BackColor="#F8FAFA"></SortedAscendingCellStyle>
    <SortedAscendingHeaderStyle BackColor="#246B61"></SortedAscendingHeaderStyle>
    <SortedDescendingCellStyle BackColor="#D4DFE1"></SortedDescendingCellStyle>
    <SortedDescendingHeaderStyle BackColor="#15524A"></SortedDescendingHeaderStyle>
    <EmptyDataTemplate>Zur Zeit kein Datensatz in dieser Tabelle !</EmptyDataTemplate>

</asp:GridView>

<asp:SqlDataSource runat="server" ID="SqlDataSource1" OnUpdating="SqlDataSource1_Updating" ConnectionString='<%$ ConnectionStrings:ConnectionStringAPPDATA %>' SelectCommand="SELECT [id], [amtid], [mitgliedid] FROM [aemter_mitglieder]" DeleteCommand="DELETE FROM [aemter_mitglieder] WHERE [id] = @id" InsertCommand="INSERT INTO [aemter_mitglieder] ([amtid], [mitgliedid]) VALUES (@amtid, @mitgliedid)" UpdateCommand="UPDATE [aemter_mitglieder] SET [amtid] = @amtid, [mitgliedid] = @mitgliedid WHERE [id] = @id">
    <DeleteParameters>
        <asp:Parameter Name="id" Type="Int32"></asp:Parameter>
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="id" Type="Int32"></asp:Parameter>
    </UpdateParameters>
</asp:SqlDataSource>
</code>```

**

CODE BEHIND:

**

```<code>protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)GridView1.FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)GridView1.FindControl("mitgliederDD");
        if(mitgliederDD != null && ämterDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
        if (ämterDD != null && mitgliederDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
        if(ämterDD != null && mitgliederDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }
</code>```

Can anyone help me how i can set update-parameters of the GridView in code behind ?!

答:
This code will help you to update your grid view data.</p>

```<code>    protected void GridView1_RowUpdating(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow && gridView.EditIndex == e.Row.RowIndex)
        {
           DropDownList ddlämter = (DropDownList)e.Row.FindControl("ddlämter");
            Label LabelAe = (Label)e.Row.FindControl("LabelAe");
            string strValue = Convert.ToString(LabelAe.Text);
              // Bind Your Drop down Here
            ddlämter.DataSource = ds;
            ddlämter.DataTextField = "dbRequestType";
            ddlämter.DataValueField = "dbID";
            ddlämter.DataBind();
            ddlämter.Items.Insert(0, new ListItem("--Choose--", "0"));
             if (strValue != null && strValue != "")
                ddlämter .Items.FindByValue(strValue).Selected = true;
        }
    }

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
     DropDownList ddlämter = DropDownList)gvDeliverable.Rows[e.RowIndex].FindControl("ämterDD");
     SqlDataSource2.UpdateParameters["amtid"].DefaultValue = Convert.ToInt32(ddlämter.SelectedValue);
}
</code>```

Title: ASP GridView DropdownList EDIT/UPDATE

Body:
I have a GridView on a ASP-Page binding to a table with foreign-keys, where the Columns have DropdownLists with TEXT gathering to the VALUES, in other Tables.

When I EDIT the Row of the GridView, I add the Text of the Dropdowns in CodeBehind. This is all working fine. But when UPDATING I am trying to set the UpdateParameters of the DataSource manually, so i want to check which values in DropDowns are selected. But in every event i tried, the dropdowns are NULL.

I have tried:

RowUpdating- and RowEditing-Events of the GridView

Updating-Event of the DataSource

ASPX:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" AllowSorting="True" Width="90%" DataKeyNames="id" Font-Size="Large">

    <Columns>
        <asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
                <EditItemTemplate>
                    <asp:Label ID="LabelIDe" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelIDi" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:TemplateField HeaderText="Mitglied" InsertVisible="False" SortExpression="mitgliedid">
                <EditItemTemplate>
                    <asp:Label ID="LabelMe" runat="server" Text='<%# Bind("mitgliedid") %>' Visible="false"></asp:Label>
                    <asp:DropDownList runat="server" ID="mitgliederDD">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelMi" runat="server" Text='<%# Bind("mitgliedid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:TemplateField HeaderText="Amt" InsertVisible="False" SortExpression="amtid">
                <EditItemTemplate>
                    <asp:Label ID="LabelAe" runat="server" Text='<%# Bind("amtid") %>' Visible="false"></asp:Label>
                    <asp:DropDownList runat="server" ID="ämterDD">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelAi" runat="server" Text='<%# Bind("amtid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right" />
    </Columns>

    <EditRowStyle BackColor="#7C6F57" HorizontalAlign="Center"></EditRowStyle>
    <FooterStyle BackColor="#1C5E55" BorderStyle="None" Font-Bold="True" ForeColor="White"></FooterStyle>
    <HeaderStyle BackColor="#666666" Font-Bold="True" ForeColor="White" CssClass="gridHeader"></HeaderStyle>
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" CssClass="gridPager" Font-Bold="True"></PagerStyle>
    <RowStyle BackColor="#E3EAEB" HorizontalAlign="Center"></RowStyle>
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

    <SortedAscendingCellStyle BackColor="#F8FAFA"></SortedAscendingCellStyle>
    <SortedAscendingHeaderStyle BackColor="#246B61"></SortedAscendingHeaderStyle>
    <SortedDescendingCellStyle BackColor="#D4DFE1"></SortedDescendingCellStyle>
    <SortedDescendingHeaderStyle BackColor="#15524A"></SortedDescendingHeaderStyle>
    <EmptyDataTemplate>Zur Zeit kein Datensatz in dieser Tabelle !</EmptyDataTemplate>

</asp:GridView>

<asp:SqlDataSource runat="server" ID="SqlDataSource1" OnUpdating="SqlDataSource1_Updating" ConnectionString='<%$ ConnectionStrings:ConnectionStringAPPDATA %>' SelectCommand="SELECT [id], [amtid], [mitgliedid] FROM [aemter_mitglieder]" DeleteCommand="DELETE FROM [aemter_mitglieder] WHERE [id] = @id" InsertCommand="INSERT INTO [aemter_mitglieder] ([amtid], [mitgliedid]) VALUES (@amtid, @mitgliedid)" UpdateCommand="UPDATE [aemter_mitglieder] SET [amtid] = @amtid, [mitgliedid] = @mitgliedid WHERE [id] = @id">
    <DeleteParameters>
        <asp:Parameter Name="id" Type="Int32"></asp:Parameter>
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
        <asp:Parameter Name="id" Type="Int32"></asp:Parameter>
    </UpdateParameters>
</asp:SqlDataSource>

**

CODE BEHIND:

**

protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)GridView1.FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)GridView1.FindControl("mitgliederDD");
        if(mitgliederDD != null && ämterDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
        if (ämterDD != null && mitgliederDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
        DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
        if(ämterDD != null && mitgliederDD != null)
        {
            SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
            SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
        }
    }

Can anyone help me how i can set update-parameters of the GridView in code behind ?!

Body:
This code will help you to update your grid view data.

    protected void GridView1_RowUpdating(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow && gridView.EditIndex == e.Row.RowIndex)
        {
           DropDownList ddlämter = (DropDownList)e.Row.FindControl("ddlämter");
            Label LabelAe = (Label)e.Row.FindControl("LabelAe");
            string strValue = Convert.ToString(LabelAe.Text);
              // Bind Your Drop down Here
            ddlämter.DataSource = ds;
            ddlämter.DataTextField = "dbRequestType";
            ddlämter.DataValueField = "dbID";
            ddlämter.DataBind();
            ddlämter.Items.Insert(0, new ListItem("--Choose--", "0"));
             if (strValue != null && strValue != "")
                ddlämter .Items.FindByValue(strValue).Selected = true;
        }
    }

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
     DropDownList ddlämter = DropDownList)gvDeliverable.Rows[e.RowIndex].FindControl("ämterDD");
     SqlDataSource2.UpdateParameters["amtid"].DefaultValue = Convert.ToInt32(ddlämter.SelectedValue);
}


来源: stackexchange

问:
Can I convert this String type variable to Map type in scala language?
Can I convert this String type variable to Map type?
for example...

```<code>scala> aa.getClass
res35: Class[_ <: Object] = class java.lang.String

scala> aa
res36: Object = Map(MetricName [name=response-rate, group=consumer-node-metrics, description=The average number of responses received per second., tags={client-id=consumer-2, node-id=node--1}] -> org.apache.kafka.common.metrics.KafkaMetric@c19540f
</code>```

I would like to change this aa variable to the real Map type of scala.
For reference, the types in the Map are the classes of the Kafka library.

答:
If I understand your question correctly, aa is the result of calling toString on some Map and you want to know whether it's possible to get the map back from aa.

In general the answer is no, because multiple different maps can have the same string representation. Here is an easier-to-see example with List instead of Map: List("a","b").toString is the same as List("a,b").toString.

For your specific use-case, you may be able to write a parser but I would be surprised if you can find an existing one.

ContentLicense: CC BY-SA 3.0

Body:
Can I convert this String type variable to Map type?
for example...

scala> aa.getClass
res35: Class[_ <: Object] = class java.lang.String

scala> aa
res36: Object = Map(MetricName [name=response-rate, group=consumer-node-metrics, description=The average number of responses received per second., tags={client-id=consumer-2, node-id=node--1}] -> org.apache.kafka.common.metrics.KafkaMetric@c19540f

I would like to change this aa variable to the real Map type of scala.
For reference, the types in the Map are the classes of the Kafka library.


问:
Gnuplot: set fixed width for color box
I am using gnuplot to plot some matrix files as heatmaps. These matrixes can be horizontal (height of matrix is lower than its width) or vertical (height of matrix is higher than its width).

Everything is working fine - except the color box. I Have set set size ratio -1 to get a heatmap with quadrats that have an aspect ration of 1:1. This command stretches or shrinks the graph. But it also stretches or shrinks the color box.

I would like to have a fixed width for my color box because some of my matrix files have got a very small width - this results in a very thin color box. I have tried to set the width of my colorbox manually. But this isn't possible without setting its origin and complete size manually, too.

Examples

Horizontal:

```<code>unset key
set cbrange [0:5]
set xrange [0:10]
set yrange [0:5]
set size ratio -1
set cbtics out nomirror
$map1 << EOD
5 4 3 1 0 5 4 3 1 0
2 2 0 0 1 2 2 0 0 1
0 0 0 1 0 0 0 0 1 0
0 0 0 2 3 0 0 0 2 3
0 1 2 4 3 2 2 0 0 1
EOD
plot '$map1' using ($1+.5):($2+.5):($3) matrix with image
</code>```

Vertical:

```<code>unset key
set cbrange [0:5]
set xrange [0:5]
set yrange [0:10]
set size ratio -1
set cbtics out nomirror
$map1 << EOD
5 4 3 1 0
2 2 0 0 1
0 0 0 1 0
0 0 0 2 3
0 1 2 4 3
5 4 3 1 0
2 2 0 0 1
0 0 0 1 0
0 0 0 2 3
2 2 0 0 1
EOD
plot '$map1' using ($1+.5):($2+.5):($3) matrix with image
</code>```

答:
@user8153 offered a nice solution for my problem. It works like a charm for my given examples. But I had to change his commands a little bit. Otherwise it wouldn't work with my real input data:

```<code># [...]
cbwidth = 0.034
rightmargin = 0.875
set colorbox user origin graph 1, graph 0 size cbwidth, graph 1
set rmargin at screen rightmargin
# [...]
</code>```

This will plot a graph with a colorbox next to it (without any space between the graphs window and the color box - we will fix that later). The colorboxs width is 3.4% of the output width (when using a term like png or pngcairo, svg or eps and so on...).

I prefer a little bit space between the graph and colorbox. The origin (position) of my colorbox is graph 1, graph 0. This position is equal to the lower right handcorner of the graphs window. 1 means 100% of this window. So if we like to add some extra space we just have to increase this percentage. @user8153 decided to add 10% extra space = origin graph 1.1, graph 0 (have a look at his comment - I changed first 0 to graph 0). Unfortunality we can not set a static percentage in this case because this 100% refers to the graphs window (not to the canvas width - respectively the  hole plot image) and the width of the graphs window changes with the matrixes aspect ratio. So you have to adjust this value everytime depending on the real width of the graphs window.

To get this done automatically I would suggest to set the size of the terminal manually to a higher value than 640x480 (in this case 1200x1200, crop will cut white space):

```<code>set term pngcairo size 1200,1200 crop
</code>```

After that you are free to calculate the x-position of your colorbox. Either use gnuplots if/else or use another language (in my case it's typescript because I am calling gnuplot through a node.js-gnuplot-wrapper - but the logic is the same):

```<code>const size = 1200             // canvas size (width and height): 1200px
const cbspace = 0.017;        // prefered space between colorbox and window: 20px / 1200px
const rmargin = 0.875;        // right margin next to the graphs window
let graphWindowWidth: number; // real width of the graphs window

if (matrixHeight > matrixWidth) {
    graphWindowWidth = (matrixWidth / matrixHeight) * size;
} else {
    graphWindowWidth = size * rmargin;
}
let cbPosX = (cbspace * size + graphWidth) / graphWidth;
</code>```

Of course you shouldn't forget that xtics and ytics, labels for x- and y-axis and the title need some space to. These are not included in the upper algorithm. Maybe somebody has got a better solution about how to get the real graphs window width. Once you got that value you can modify the origin command part of the colorbox:

from: set colorbox user origin graph 1, graph 0 size cbwidth, graph 1

to: set colorbox user origin graph cbPosX, graph 0 size cbwidth, graph 1

Title: Gnuplot: set fixed width for color box

Body:
I am using gnuplot to plot some matrix files as heatmaps. These matrixes can be horizontal (height of matrix is lower than its width) or vertical (height of matrix is higher than its width).

Everything is working fine - except the color box. I Have set set size ratio -1 to get a heatmap with quadrats that have an aspect ration of 1:1. This command stretches or shrinks the graph. But it also stretches or shrinks the color box.

I would like to have a fixed width for my color box because some of my matrix files have got a very small width - this results in a very thin color box. I have tried to set the width of my colorbox manually. But this isn't possible without setting its origin and complete size manually, too.

Examples

Horizontal:

unset key
set cbrange [0:5]
set xrange [0:10]
set yrange [0:5]
set size ratio -1
set cbtics out nomirror
$map1 << EOD
5 4 3 1 0 5 4 3 1 0
2 2 0 0 1 2 2 0 0 1
0 0 0 1 0 0 0 0 1 0
0 0 0 2 3 0 0 0 2 3
0 1 2 4 3 2 2 0 0 1
EOD
plot '$map1' using ($1+.5):($2+.5):($3) matrix with image

Vertical:

unset key
set cbrange [0:5]
set xrange [0:5]
set yrange [0:10]
set size ratio -1
set cbtics out nomirror
$map1 << EOD
5 4 3 1 0
2 2 0 0 1
0 0 0 1 0
0 0 0 2 3
0 1 2 4 3
5 4 3 1 0
2 2 0 0 1
0 0 0 1 0
0 0 0 2 3
2 2 0 0 1
EOD
plot '$map1' using ($1+.5):($2+.5):($3) matrix with image

Body:
@user8153 offered a nice solution for my problem. It works like a charm for my given examples. But I had to change his commands a little bit. Otherwise it wouldn't work with my real input data:

# [...]
cbwidth = 0.034
rightmargin = 0.875
set colorbox user origin graph 1, graph 0 size cbwidth, graph 1
set rmargin at screen rightmargin
# [...]

This will plot a graph with a colorbox next to it (without any space between the graphs window and the color box - we will fix that later). The colorboxs width is 3.4% of the output width (when using a term like png or pngcairo, svg or eps and so on...).

I prefer a little bit space between the graph and colorbox. The origin (position) of my colorbox is graph 1, graph 0. This position is equal to the lower right handcorner of the graphs window. 1 means 100% of this window. So if we like to add some extra space we just have to increase this percentage. @user8153 decided to add 10% extra space = origin graph 1.1, graph 0 (have a look at his comment - I changed first 0 to graph 0). Unfortunality we can not set a static percentage in this case because this 100% refers to the graphs window (not to the canvas width - respectively the  hole plot image) and the width of the graphs window changes with the matrixes aspect ratio. So you have to adjust this value everytime depending on the real width of the graphs window.

To get this done automatically I would suggest to set the size of the terminal manually to a higher value than 640x480 (in this case 1200x1200, crop will cut white space):

set term pngcairo size 1200,1200 crop

After that you are free to calculate the x-position of your colorbox. Either use gnuplots if/else or use another language (in my case it's typescript because I am calling gnuplot through a node.js-gnuplot-wrapper - but the logic is the same):

const size = 1200             // canvas size (width and height): 1200px
const cbspace = 0.017;        // prefered space between colorbox and window: 20px / 1200px
const rmargin = 0.875;        // right margin next to the graphs window
let graphWindowWidth: number; // real width of the graphs window

if (matrixHeight > matrixWidth) {
    graphWindowWidth = (matrixWidth / matrixHeight) * size;
} else {
    graphWindowWidth = size * rmargin;
}
let cbPosX = (cbspace * size + graphWidth) / graphWidth;

Of course you shouldn't forget that xtics and ytics, labels for x- and y-axis and the title need some space to. These are not included in the upper algorithm. Maybe somebody has got a better solution about how to get the real graphs window width. Once you got that value you can modify the origin command part of the colorbox:

from: set colorbox user origin graph 1, graph 0 size cbwidth, graph 1

to: set colorbox user origin graph cbPosX, graph 0 size cbwidth, graph 1


问:
Launching different activities
I have two activities.one is main activity and second is lock screen activity.what main activity contains the content of the application and the lock screen activity displays the lock screen.
what i want is that when the user opens the app it should display main activity. but when the user plugs in the charger it should automatically open the lock screen activity even if the application is closed.
I have done all of the work required to do this.but when the user plugs in the charger it runs main activity instead of lock screen activity.
if anyone knows how to open lock screen activity on plug in charger and normally it should display main activity then please tell me how?
any help is appreciated </p>

答:
You need to use Broadcast Receiver when user plugin charger then your app receive broadcast.

in Menifest

```<code><receiver android:name=".PlugInReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    </intent-filter>
</receiver>
</code>```

your reciever class

```<code>public class PlugInReceiver extends BroadcastReceiver {
public void onReceive(Context context , Intent intent) {

String action = intent.getAction();

       if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
           // Do something when power connected
       }
       else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
           // Do something when power disconnected
       }
   }
}
</code>```

Title: Launching different activities

Body:
You need to use Broadcast Receiver when user plugin charger then your app receive broadcast.

in Menifest

<receiver android:name=".PlugInReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    </intent-filter>
</receiver>

your reciever class

public class PlugInReceiver extends BroadcastReceiver {
public void onReceive(Context context , Intent intent) {

String action = intent.getAction();

       if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
           // Do something when power connected
       }
       else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
           // Do something when power disconnected
       }
   }
}


问:
Using environment variables in AppDynamics Python Agent configuration
What is the meaning and use of environment variables in the Python Agent configuration for App Dynamics, as documented here:

https://docs.appdynamics.com/display/PRO42/Python+Agent+Settings

More specifically:

If a value is set in the file and the corresponding environment variable is also set, which one takes precedence?

If I want to use environment variables for some of these values, can they be omitted from the file?

答:
You can configure the python agent in your code like so:

```<code>from appdynamics.agent import api as appd

appd.init(environ={'APPD_APP_NAME': 'appname',
                   'APPD_TIER_NAME': 'yourtier',
                   'APPD_NODE_NAME': 'yournode'})
</code>```

Alternatively, you can pass in the location of your appdynamics.cfg file. That is to say, setting environment variables is not enough.

Then you need to manually start the proxy (after you appd.init) by running
pyagent proxy start

The agent configuration from your code will be automatically used by the proxy.

For a full list of config keys see the setting docs

Body:
You can configure the python agent in your code like so:

from appdynamics.agent import api as appd

appd.init(environ={'APPD_APP_NAME': 'appname',
                   'APPD_TIER_NAME': 'yourtier',
                   'APPD_NODE_NAME': 'yournode'})

Alternatively, you can pass in the location of your appdynamics.cfg file. That is to say, setting environment variables is not enough.

Then you need to manually start the proxy (after you appd.init) by running
pyagent proxy start

The agent configuration from your code will be automatically used by the proxy.

For a full list of config keys see the setting docs


问:
Trouble formatting images in my CSS
community!
I am having trouble getting the formatting down for a few images I have.

HTML

```<code><footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>
</code>```

CSS

```<code>.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}
</code>```

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

答:
you can simply do this (no need float and left property):

img.sm {
  max-width:30px;
  width:100%;
  margin:5px;
}

/* Add a hover effect */

img.sm:hover {
  opacity: 0.7;
}

.socialmedia {
  display: block;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <section class="socialmedia">
    <img src="https://lorempixel.com/100/100/" class="sm">
    <img src="https://lorempixel.com/200/200/" class="sm">
    <img src="https://lorempixel.com/150/150/" class="sm">
  </section>
</footer></code>```

Title: Trouble formatting images in my CSS

Body:
community!
I am having trouble getting the formatting down for a few images I have.

HTML

CSS

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

Body:
you can simply do this (no need float and left property):

img.sm {
  max-width:30px;
  width:100%;
  margin:5px;
}

/* Add a hover effect */

img.sm:hover {
  opacity: 0.7;
}

.socialmedia {
  display: block;
  text-align:center;
}

<footer>
  <section class="socialmedia">
    <a href=""><img src="https://lorempixel.com/100/100/" class="sm"></a>
    <a href=""><img src="https://lorempixel.com/200/200/" class="sm"></a>
    <a href=""><img src="https://lorempixel.com/150/150/" class="sm"></a>
  </section>
</footer>


问:
Equal Transition
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}
```

<p>This is what I'm working with:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}</code>```

```

Thanks!

答:
Not sure you guys really get what I'm trying to do. I'm not just trying to remove the overlapping, I'm trying to make the div expand on both top and bottom without interacting differently on top then on the bottom.

So for an example, if I hover over the red div, it pushes both blue divs touching it away OR overlapping both. I'm fine with either. Right now it overlaps on one end and pushes away on the other.

So to be clear, I DON'T want to simply make the div bigger without overlapping.

Thanks for the answers so far though!

Title: Equal Transition

Body:
I want to have a transition that extends a div both at the top and bottom on hover. Right now it overlaps the div above and pushes away the div on the bottom.

I want to either push away on both sides or overlap on both sides. Not one of both.

#blue, #red {
  width: 100%;
  height: 100px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 24px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 200px;
  font-size: 48px;
  margin-top: -50px;
}

This is what I'm working with:

#blue, #red {
  width: 100%;
  height: 50px;
  float: left;
  transition: 0.8s;
  transition-timing-function: ease-out;
  font-size: 12px;
  margin-top: 0;
  margin-bottom: 0;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#blue:hover, #red:hover {
  height: 100px;
  margin-top: -25px;
}

Thanks!


问:
Is there a better way to write lots of repeated instances of "if(string.IsNullOrEmpty())"
Sorry if this is something that has been answered before, I wasn't really sure what to search for. I have some code which has lots of null/empty checks before executing single lines of code. It's quite ugly and I feel like there's probably a better way to do this.

Example:

```<code>private XElement getWhereXMLNode()
{
    XElement where = new XElement("where");

    if (!string.IsNullOrEmpty(County))
    {
        where.Add(new XElement("county", County));
    }
    if (!string.IsNullOrEmpty(District))
    {
        where.Add(new XElement("district", District));
    }
    if (!string.IsNullOrEmpty(Parish))
    {
        where.Add(new XElement("parishLAStyle", Parish));
    }
    if (!string.IsNullOrEmpty(ParliamentaryConstituency))
    {
        where.Add(new XElement("parCon", ParliamentaryConstituency));
    }
    if (!string.IsNullOrEmpty(GovernmentRegion))
    {
         where.Add(new XElement("govReg", GovernmentRegion));
    }
    if (!string.IsNullOrEmpty(MainQuery))
    {
        where.Add(new XElement("freetext_where", MainQuery));
    }

    return where;
}
</code>```

答:
In this case, you can use the fact that LINQ to XML ignores null values on construction. Create a small local method that takes an element name and the value, and returns either an element or null:</p>

```<code>private XElement CreateWhereElement()
{
    return new XElement("where",
        CreateChild("county", County),
        CreateChild("district", District),
        CreateChild("parishLAStyle", Parish),
        CreateChild("parCon", ParliamentaryConstituency),
        CreateChild("govReg", GovernmentRegion),
        CreateChild("freetext_where", MainQuery));

    XElement CreateChild(string name, string value) =>
        string.IsNullOrEmpty(value) ? null : new XElement(name, value);
}
</code>```

Body:
Sorry if this is something that has been answered before, I wasn't really sure what to search for. I have some code which has lots of null/empty checks before executing single lines of code. It's quite ugly and I feel like there's probably a better way to do this.

Example:

private XElement getWhereXMLNode()
{
    XElement where = new XElement("where");

    if (!string.IsNullOrEmpty(County))
    {
        where.Add(new XElement("county", County));
    }
    if (!string.IsNullOrEmpty(District))
    {
        where.Add(new XElement("district", District));
    }
    if (!string.IsNullOrEmpty(Parish))
    {
        where.Add(new XElement("parishLAStyle", Parish));
    }
    if (!string.IsNullOrEmpty(ParliamentaryConstituency))
    {
        where.Add(new XElement("parCon", ParliamentaryConstituency));
    }
    if (!string.IsNullOrEmpty(GovernmentRegion))
    {
         where.Add(new XElement("govReg", GovernmentRegion));
    }
    if (!string.IsNullOrEmpty(MainQuery))
    {
        where.Add(new XElement("freetext_where", MainQuery));
    }

    return where;
}

Body:
In this case, you can use the fact that LINQ to XML ignores null values on construction. Create a small local method that takes an element name and the value, and returns either an element or null:

private XElement CreateWhereElement()
{
    return new XElement("where",
        CreateChild("county", County),
        CreateChild("district", District),
        CreateChild("parishLAStyle", Parish),
        CreateChild("parCon", ParliamentaryConstituency),
        CreateChild("govReg", GovernmentRegion),
        CreateChild("freetext_where", MainQuery));

    XElement CreateChild(string name, string value) =>
        string.IsNullOrEmpty(value) ? null : new XElement(name, value);
}


问:
How to display following response using vue js?
This is my response.. How to display the error message? passwords do not match

```<code> {"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0}
</code>```

Currently my code is

```<code><script>
regBox = new Vue({
el: "#regBox",
  data: {
   ..........
    response: {
        message: '',
        status: '',
        state: '',
        errors: '',
    }
  },
methods: {
     handelSubmit: function(e) {
           var vm = this;
           data = {};
         ..............
            $.ajax({
              url: '',
              data: data,
              type: "POST",
              dataType: 'json',
              success: function(e) {
              if (e.status)
              {
               alert(" Success")

            }
              else {
                vm.response = e;
               alert(" Failed")
              }
          }
            });
            return false;
}
},
});
</script>
</code>```

My html code to display the same is

```<code> <p class="error">{{response.errors.password}}</p>
</code>```

Currently i am getting error message as
["Passwords donot match"]

How to get only message as

Passwords donot match.. so, how can i able to get it.. can anybody help

答:
This should work:</p>

```<code><p class="error">{{response.errors.password[0]}}</p>
</code>```

Body:
This is my response.. How to display the error message? passwords do not match

 {"errors": {"password": ["Passwords donot match"]}, "status": false, "msg": "Validation erro", "error-type": 0}

Currently my code is

My html code to display the same is

{{response.errors.password}}

Currently i am getting error message as
["Passwords donot match"]

How to get only message as

Passwords donot match.. so, how can i able to get it.. can anybody help

Body:
This should work:

<p class="error">{{response.errors.password[0]}}</p>


问:
How can I merge overlapping strings in python?
I have some strings,

```<code>['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']
</code>```

These strings partially overlap each other. If you manually overlapped them you would get:

```<code>SGALWDVPSPV
</code>```

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!

答:
Once the peptides start to grow to 20 aminoacids cdlane's code chokes and spams (multiple) incorrect answer(s) with various amino acid lengths.

Try to add and use AA sequence 'VPSGALWDVPS' with or without 'D' and the code starts to fail its task because the N-and C-terminus grow and do not reflect what Adam Price is asking for. The output is: 'SGALWDVPSGALWDVPSPV' and thus 100% incorrect despite the effort.

Tbh imo there is only one 100% answer and that is to use BLAST and its protein search page or BLAST in the BioPython package. Or adapt cdlane's code to reflect AA gaps, substitutions and AA additions.

Body:
I have some strings,

['SGALWDV', 'GALWDVP', 'ALWDVPS', 'LWDVPSP', 'WDVPSPV']

These strings partially overlap each other. If you manually overlapped them you would get:

SGALWDVPSPV

I want a way to go from the list of overlapping strings to the final compressed string in python.  I feel like this must be a problem that someone has solved already and am trying to avoid reinventing the wheel.  The methods I can imagine now are either brute force or involve getting more complicated by using biopython and sequence aligners than I would like.  I have some simple short strings and just want to properly merge them in a simple way.

Does anyone have any advice on a nice way to do this in python?  Thanks!


问:
In which scenario do I use a particular STL container?
I've been reading up on STL containers in my book on C++, specifically the section on the STL and its containers. Now I do understand each and every one of them have their own specific properties, and I'm close to memorizing all of them... But what I do not yet grasp is in which scenario each of them is used.

What is the explanation? Example code is much prefered.

答:
One lesson I've learned is: Try to wrap it in a class, since changing the container type one fine day can yield big surprises.

```<code>class CollectionOfFoo {
    Collection<Foo*> foos;
    .. delegate methods specifically
}
</code>```

It doesn't cost much up front, and saves time in debugging when you want to break whenever somebody does operation x on this structure.

Coming to selecting the perfect data structure for a job:

Each data structure provides some operations, which can be varying time complexity:

O(1), O(lg N), O (N), etc.

You essentially have to take a best guess, on which operations will be done most, and use a data structure which has that operation as O(1).

Simple, isn't it (-:

OwnerDisplayName: Daniel

LastEditorDisplayName: Daniel

Body:
One lesson I've learned is: Try to wrap it in a class, since changing the container type one fine day can yield big surprises.

class CollectionOfFoo {
    Collection<Foo*> foos;
    .. delegate methods specifically
}

It doesn't cost much up front, and saves time in debugging when you want to break whenever somebody does operation x on this structure.

Coming to selecting the perfect data structure for a job:

Each data structure provides some operations, which can be varying time complexity:

O(1), O(lg N), O (N), etc.

You essentially have to take a best guess, on which operations will be done most, and use a data structure which has that operation as O(1).

Simple, isn't it (-:

OwnerDisplayName: VardhanDotNet

LastEditorDisplayName: Iraimbilanja


问:
What is sizeof(something) == 0?
I have a template that takes a struct with different values, for example:

```<code>struct Something
{
    char str[10];
    int value;
    ...
    ...
};
</code>```

And inside the function I use the sizeof operator: jump in memory sizeof(Something);

Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I put in an empty struct it will return 1; what can I put in the template to make sizeof return zero?

答:
What do you think about it?

```<code> #include <iostream>
 struct ZeroMemory {
     int *a[0];
 };
 int main() {
     std::cout << sizeof(ZeroMemory);
 }
</code>```

Yes, output is 0.

But this code is not standard C++.

Title: What is sizeof(something) == 0?

Body:
I have a template that takes a struct with different values, for example:

struct Something
{
    char str[10];
    int value;
    ...
    ...
};

And inside the function I use the sizeof operator: jump in memory sizeof(Something);

Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I put in an empty struct it will return 1; what can I put in the template to make sizeof return zero?

Body:
What do you think about it?

 #include <iostream>
 struct ZeroMemory {
     int *a[0];
 };
 int main() {
     std::cout << sizeof(ZeroMemory);
 }

Yes, output is 0.

But this code is not standard C++.


问:
Validate form within ngDialog openConfirm before closing
I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.

Here is a simplified version of my code:

```<code>someFunction() {
    let newScope = $scope.$new();
    newScope.vm = vm;
    ngDialog.openConfirm({
        scope: newScope,
        template: 'componentDescription.html'
    })
}
</code>```

And my html:

```<code><form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
</code>```

I would like for the Dialog to only be submitted if the form is valid.

I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.

Any ideas?

UPDATE:
I've changed my html like so:

```<code><form role="form" name="subForm" novalidate ng-submit="confirm(0)">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="submit">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
</code>```

This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.

答:
you can disable submit button if length of input string is less then 20

```<code><button type="button" ng-disabled="vm.compDesc.length < 20" ng-click="confirm(0)">Submit</button>
</code>```

you can also display an error message below text area so users can understand why submit button is not enabled

```<code><form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <p ng-show="vm.compDesc.length < 20" style="color:#cc5965">Description should be at least 20 characters</p>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
</code>```

Body:
I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.

Here is a simplified version of my code:

someFunction() {
    let newScope = $scope.$new();
    newScope.vm = vm;
    ngDialog.openConfirm({
        scope: newScope,
        template: 'componentDescription.html'
    })
}

And my html:

<form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

I would like for the Dialog to only be submitted if the form is valid.

I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.

Any ideas?

UPDATE:
I've changed my html like so:

<form role="form" name="subForm" novalidate ng-submit="confirm(0)">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="submit">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.

Body:
you can disable submit button if length of input string is less then 20

<button type="button" ng-disabled="vm.compDesc.length < 20" ng-click="confirm(0)">Submit</button>

you can also display an error message below text area so users can understand why submit button is not enabled

<form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <p ng-show="vm.compDesc.length < 20" style="color:#cc5965">Description should be at least 20 characters</p>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>


问:
Button to change background colour
I'm developing a UWP app. I would like to have a radio button change the background of the mainpage and settings page when clicked. The radio button code below is in Settings.xaml.cs

```<code>private void BGRadioButtonGreen_Checked(object sender, RoutedEventArgs e)
    {
        MainPage.Background = Brushes.Red??;
    }
</code>```

In this example I'm trying to select a radio button and have it change the settings and mainpage background to Green.However it doesn't seem to be working. Thanks in advance

答:
You can do it be setting background color of root grid. Like in example below, after radio button checked color would change to red. This should be what you're looking for.

```<code><Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Background="Blue">

<Grid x:Name="MainGrid" Background="Green">
    <StackPanel>
        <RadioButton Content="Red" Tag="Green" Checked="RadioButton_Checked"/>
    </StackPanel>
</Grid>
</code>```

```<code>private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    MainGrid.Background = new SolidColorBrush(Windows.UI.Colors.Red);
}
</code>```

Title: Button to change background colour

Body:
I'm developing a UWP app. I would like to have a radio button change the background of the mainpage and settings page when clicked. The radio button code below is in Settings.xaml.cs

private void BGRadioButtonGreen_Checked(object sender, RoutedEventArgs e)
    {
        MainPage.Background = Brushes.Red??;
    }

In this example I'm trying to select a radio button and have it change the settings and mainpage background to Green.However it doesn't seem to be working. Thanks in advance

Body:
You can do it be setting background color of root grid. Like in example below, after radio button checked color would change to red. This should be what you're looking for.

<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Background="Blue">

<Grid x:Name="MainGrid" Background="Green">
    <StackPanel>
        <RadioButton Content="Red" Tag="Green" Checked="RadioButton_Checked"/>
    </StackPanel>
</Grid>

private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    MainGrid.Background = new SolidColorBrush(Windows.UI.Colors.Red);
}


问:
Powershell - Do "Grant Permissions" action on Azure AD Application with Powershell
I'm creating an Azure AD application using AzureAD module to call Microsoft Graph API. I can successfully generate the access token. But, when I try to call the API I have an error "message": "Invalid scope claims/roles.".

When I click on "Grant Permissions" button in my created application in Azure Portal and retry the call to API, the call is working.

I don't find anywhere how to do this "Grant Permissions" actions with Powershell. Is there a way to do that ?

Thanks

Damien

答:
If I am not wrong, then it is using "Admin Consent". In that case, you should be using &prompt=admin_consent in the auth request directly.

If your application requests an app-only permission and a user tries to sign in to the application, an error message is displayed saying the user isn’t able to consent.

Whether or not a permission requires admin consent is determined by the developer that published the resource, and can be found in the documentation for the resource.

Link: Multi-tenant App pattern

List of Available permissions for the Azure AD Graph API and Microsoft Graph API are

Graph API Permission Scopes

Consent Framework

Hope it helps.


问:
Can a non-SF project make use of the applicationmanifest configuration values?
I've got a Service Fabric Application set up in the following way:

```<code>Solution
--SF Project
  --ApplicationManifest.xml
--Stateless Project (uses app manifest values)
--Stateless Project (uses app manifest values)
--Class Library (used as a repository by the above two projects)
</code>```

How can I enable the class library to make use of the ApplicationManifest.xml configuration file from the SF Project?

To allow the projects to be able to use the AppManifest for build/deployment, they simply need to be created like so:

How does a project that does not get added as a Service Fabric project make use of the applicationmanifest?

The Service Fabric projects are able to use the appmanifest by including parameters in settings.xml and servicemanifest (but non-SF projects cannot):

答:
Option #1

If you need to access the parameters defined in your service's setting.xml, the next should work -

In your non-SF project, install
Microsoft.Extensions.Configuration and ServiceFabric.Extensions.Configuration NuGet packages

Wherever you decide to access the parameters, use the next code snippet -

```<code>var builder = new ConfigurationBuilder().AddFabricConfiguration("Config");
var configuration = builder.Build();
var section = configuration.GetSection("MyConfigSection");
var parameterValue = section["MyParameter"];
</code>```

One note though - you will get access to only one SF service at a time. That's because AddFabricConfiguration() works by calling FabricRuntime.GetActivationContext(), which ties settings being loaded with the SF service you're calling a non-SF code from.

Option #2

Next option will work from any place where you could establish connection with the SF. Using code below, you could read any parameter passed into the app manifest -

```<code>var fClient = new FabricClient();
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("ns", "http://schemas.microsoft.com/2011/01/fabric");
var manifest = XDocument.Parse(fClient.ApplicationManager.GetApplicationManifestAsync("YOUR_APP_TYPE_NAME", "YOUR_APP_TYPE_VERSION").Result);
var parameterValue = manifest.XPathSelectElement("/ns:ApplicationManifest/ns:Parameters/ns:Parameter[@Name='PARAMETER_NAME']", namespaceManager).Attribute("DefaultValue").Value;
</code>```

Body:
I've got a Service Fabric Application set up in the following way:

Solution
--SF Project
  --ApplicationManifest.xml
--Stateless Project (uses app manifest values)
--Stateless Project (uses app manifest values)
--Class Library (used as a repository by the above two projects)

How can I enable the class library to make use of the ApplicationManifest.xml configuration file from the SF Project?

To allow the projects to be able to use the AppManifest for build/deployment, they simply need to be created like so:

How does a project that does not get added as a Service Fabric project make use of the applicationmanifest?

The Service Fabric projects are able to use the appmanifest by including parameters in settings.xml and servicemanifest (but non-SF projects cannot):

Body:
Option #1

If you need to access the parameters defined in your service's setting.xml, the next should work -

In your non-SF project, install
Microsoft.Extensions.Configuration and ServiceFabric.Extensions.Configuration NuGet packages

Wherever you decide to access the parameters, use the next code snippet -

var builder = new ConfigurationBuilder().AddFabricConfiguration("Config");
var configuration = builder.Build();
var section = configuration.GetSection("MyConfigSection");
var parameterValue = section["MyParameter"];

One note though - you will get access to only one SF service at a time. That's because AddFabricConfiguration() works by calling FabricRuntime.GetActivationContext(), which ties settings being loaded with the SF service you're calling a non-SF code from.

Option #2

Next option will work from any place where you could establish connection with the SF. Using code below, you could read any parameter passed into the app manifest -

var fClient = new FabricClient();
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("ns", "http://schemas.microsoft.com/2011/01/fabric");
var manifest = XDocument.Parse(fClient.ApplicationManager.GetApplicationManifestAsync("YOUR_APP_TYPE_NAME", "YOUR_APP_TYPE_VERSION").Result);
var parameterValue = manifest.XPathSelectElement("/ns:ApplicationManifest/ns:Parameters/ns:Parameter[@Name='PARAMETER_NAME']", namespaceManager).Attribute("DefaultValue").Value;


问:
Regex and negative look ahead
I am trying to create some regex patterns that match a website domain.

The rules are as below :

```<code>For France, the URL pattern must have /fr-fr (followed by anything else) after the domain name, ie www.domain.com/fr-fr/anything
For Germany, the URL pattern must have /de-de (followed by anything else) after the domain name, ie www.domain.com/de-de/anything
And for all other countries, the URL pattern can be the root domain (ie www.domain.com) OR anything EXCEPT fr-fr and de-de after the domain name
</code>```

I have these Regex patterns for France and Germany which work fine :

```<code>https?://www.domain.com.*?/(?i)FR-FR.\*
</code>```

and

```<code>https?://www.domain.com.*?/(?i)DE-DE.\*
</code>```

However, I am struggling to get a Regex pattern that will match the root domain and other domains (such as www.domain.com/en-us with anything after it) but EXCLUDE /fr-fr.* and /de-de.*

I have tried a negative lookahead, such as this (for example, NOT france) :

```<code>https?://www.domain.com.*?/(?!fr-fr).\*
</code>```

But this does not seem to work, and matches against URLs that it should not.

Maybe I am missing something obvious.

Any help very much appreciated.

答:
Only "Germany" URLs:

^(?i)https?://www.domain.com(:\d+)?/de-de(/.*)?$
```

<p>Only "France" URLs:</p>

<pre class="lang-none prettyprint-override"><code>^(?i)https?://www.domain.com(:\d+)?/fr-fr(/.*)?$
</code>```

URLs that are neither "Germany" nor "France"

^(?i)https?://www.domain.com(:\d+)?(?!/fr-fr|/de-de)(/.*)?$
```

Title: Regex and negative look ahead

Body:
I am trying to create some regex patterns that match a website domain.

The rules are as below :

For France, the URL pattern must have /fr-fr (followed by anything else) after the domain name, ie www.domain.com/fr-fr/anything
For Germany, the URL pattern must have /de-de (followed by anything else) after the domain name, ie www.domain.com/de-de/anything
And for all other countries, the URL pattern can be the root domain (ie www.domain.com) OR anything EXCEPT fr-fr and de-de after the domain name

I have these Regex patterns for France and Germany which work fine :

https?://www.domain.com.*?/(?i)FR-FR.\*

and

https?://www.domain.com.*?/(?i)DE-DE.\*

However, I am struggling to get a Regex pattern that will match the root domain and other domains (such as www.domain.com/en-us with anything after it) but EXCLUDE /fr-fr.* and /de-de.*

I have tried a negative lookahead, such as this (for example, NOT france) :

https?://www.domain.com.*?/(?!fr-fr).\*

But this does not seem to work, and matches against URLs that it should not.

Maybe I am missing something obvious.

Any help very much appreciated.

Body:
Only "Germany" URLs:

^(?i)https?://www.domain.com(:\d+)?/de-de(/.*)?$

Only "France" URLs:

^(?i)https?://www.domain.com(:\d+)?/fr-fr(/.*)?$

URLs that are neither "Germany" nor "France"

^(?i)https?://www.domain.com(:\d+)?(?!/fr-fr|/de-de)(/.*)?$


问:
Get similiar/closest numbers from the array
I'm trying to find the efficient way of finding the similar numbers (where the difference between the numbers is "almost constant" - close to some constant).

For example having array like:

```<code>const arr = [23, 130, 142, 151, 163, 200];
</code>```

would return a new array:

```<code>const similarNumbers = [130, 142, 151, 163];
</code>```

Currently the way I try to solve it is to map through the first array and try to find smallest difference between the numbers and then map again and check if the absolute value of currentValue - previousValue -  smallestGap < SOME_THRESHOLD, but this is not ideal and only works in some of the particular cases.

Ideally what I'd like to achieve is for the function to return a few arrays with the grouped similar numbers:

```<code>const someArr = [23, 130, 142, 151, 163, 200, 232, 261];
</code>```

would return two arrays:

```<code>group1 = [130, 142, 151, 163];
</code>```

and:

```<code>group2 = [200, 232, 261];
</code>```

答:
This is a simple (and not perfect) function I just wrote. It will group numbers into groups based on a threshold value which defines the maximum derivation from the groups average.

const someArr = [23, 130, 142, 151, 163, 200, 232, 261];
var threshold = 50;

var relations = {};
var groups = {};

i = 0;
for (var j = 0; j < someArr.length; j++) {
  var number = someArr[j];
  if (i == 0) {
    relations[number] = i;
    groups[i] = [];
    groups[i].push(number);
  }
  else {
    var added = false;
    var n_groups = 0;
    for (var g in groups) {
      var sum = 0;
      var group = groups[g];
      if (group.length == 1 && Math.abs(number - group[0]) <= 2 * threshold) {
        relations[number] = parseInt(g, 10);
        groups[g].push(number);
        added = true;
      }
      else {
      for( var n = 0; n < group.length; n++ ){
          sum += group[n];
      }
      var avg = sum/group.length;
      if (Math.abs(number - avg) <= threshold) {
        relations[number] = parseInt(g, 10);
        groups[g].push(number);
        added = true;
      }
      }
      n_groups++;
    }
    if (!added) {
      var h = n_groups;
      relations[number] = parseInt(h, 10);
      groups[h] = [];
      groups[h].push(number);
    }
  }
  i++;
}

//console.log(relations, groups);

document.getElementById('grouped').innerHTML = JSON.stringify(groups);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Input</h3><div id="original">[23, 130, 142, 151, 163, 200, 232, 261]</div>
<h3>Output</h3><div id="grouped"></div></code>```

Body:
I'm trying to find the efficient way of finding the similar numbers (where the difference between the numbers is "almost constant" - close to some constant).

For example having array like:

const arr = [23, 130, 142, 151, 163, 200];

would return a new array:

const similarNumbers = [130, 142, 151, 163];

Currently the way I try to solve it is to map through the first array and try to find smallest difference between the numbers and then map again and check if the absolute value of currentValue - previousValue -  smallestGap < SOME_THRESHOLD, but this is not ideal and only works in some of the particular cases.

Ideally what I'd like to achieve is for the function to return a few arrays with the grouped similar numbers:

const someArr = [23, 130, 142, 151, 163, 200, 232, 261];

would return two arrays:

group1 = [130, 142, 151, 163];

and:

group2 = [200, 232, 261];

Body:
This is a simple (and not perfect) function I just wrote. It will group numbers into groups based on a threshold value which defines the maximum derivation from the groups average.

const someArr = [23, 130, 142, 151, 163, 200, 232, 261];
var threshold = 50;

var relations = {};
var groups = {};

i = 0;
for (var j = 0; j < someArr.length; j++) {
  var number = someArr[j];
  if (i == 0) {
    relations[number] = i;
    groups[i] = [];
    groups[i].push(number);
  }
  else {
    var added = false;
    var n_groups = 0;
    for (var g in groups) {
      var sum = 0;
      var group = groups[g];
      if (group.length == 1 && Math.abs(number - group[0]) <= 2 * threshold) {
        relations[number] = parseInt(g, 10);
        groups[g].push(number);
        added = true;
      }
      else {
      for( var n = 0; n < group.length; n++ ){
          sum += group[n];
      }
      var avg = sum/group.length;
      if (Math.abs(number - avg) <= threshold) {
        relations[number] = parseInt(g, 10);
        groups[g].push(number);
        added = true;
      }
      }
      n_groups++;
    }
    if (!added) {
      var h = n_groups;
      relations[number] = parseInt(h, 10);
      groups[h] = [];
      groups[h].push(number);
    }
  }
  i++;
}

//console.log(relations, groups);

document.getElementById('grouped').innerHTML = JSON.stringify(groups);

<h3>Input</h3><div id="original">[23, 130, 142, 151, 163, 200, 232, 261]</div>
<h3>Output</h3><div id="grouped"></div>


问:
safe dynamic_cast from c-Structure?
I have some C-structures that are used through some algorithms that link together c++ parts.

On the input end there is a c++ structure that inherits from the c structure to add some members. at the output end there are some  components that also may require this data.

Is there a safe way to detect if this C structure actually is the mentioned c++ class? maybe by making c++ child classes polymorphic and using dynamic casts?

```<code>struct Cstruct{
  int someData;
};

class CPPclass: public Cstruct{
  CPPclass(){};
  int someMoreData;
};
</code>```

so maybe something like

```<code>class CPPclass: public Cstruct{
  virtual ~CPPclass(){};
  CPPclass(){};
  int someMoreData;
};

void test(Cstruct* i_c){
  auto cpp = dynamic_cast<CPPclass*>(i_c);   // < does not work, because Cstruct is not polymorphic
  if(cpp){
      // da;
  }
}
</code>```

but maybe?:

```<code>class CPPclassHelper: public Cstruct{
  virtual ~CPPclassHelper(){};
  CPPclassHelper(){};
  int someMoreData;
};

class CPPclass: public CPPclassHelper{
  virtual ~CPPclassHelper(){};
};

void test(Cstruct* i_c){
  auto cpph = static_cast<CPPclassHelper*>(i_c);
  auto cpp = dynamic_cast<CPPclass*>(cpph );
  if(cpp){
      // da;
  }
}
</code>```

答:
You could maintain the type information yourself. Use a static set of all pointers to Cstruct that are bases of CPPclass. Insert the base in all constructors of CPPclass and remove in the destructor. Safe cast can then be implemented using a lookup into that set.

Here is an example:

```<code>struct CPPclass: Cstruct{
    CPPclass(){
        bases.insert(this);
    };
    CPPclass(const CPPclass&){
        bases.insert(this);
    };
    CPPclass(CPPclass&&){
        bases.insert(this);
    };
    ~CPPclass(){
        bases.erase(this);
    };

    static CPPclass* safe_cast(Cstruct* c) {
        auto it = bases.find(c);
        return it == bases.end()
            ? nullptr
            : static_cast<CPPclass*>(*it);
    }

private:
    static std::unordered_set<Cstruct*> bases;
};
</code>```

Usage:

```<code>int main() {
    CPPclass cpp;
    Cstruct  c;

    Cstruct* ptr_cpp = &cpp;
    Cstruct* ptr_c   = &c;

    std::cout << CPPclass::safe_cast(ptr_cpp) << '\n'; // some address equal to &cpp
    std::cout << CPPclass::safe_cast(ptr_c)   << '\n'; // null
}
</code>```

Title: safe dynamic_cast from c-Structure?

Body:
I have some C-structures that are used through some algorithms that link together c++ parts.

On the input end there is a c++ structure that inherits from the c structure to add some members. at the output end there are some  components that also may require this data.

Is there a safe way to detect if this C structure actually is the mentioned c++ class? maybe by making c++ child classes polymorphic and using dynamic casts?

struct Cstruct{
  int someData;
};

class CPPclass: public Cstruct{
  CPPclass(){};
  int someMoreData;
};

so maybe something like

class CPPclass: public Cstruct{
  virtual ~CPPclass(){};
  CPPclass(){};
  int someMoreData;
};

void test(Cstruct* i_c){
  auto cpp = dynamic_cast<CPPclass*>(i_c);   // < does not work, because Cstruct is not polymorphic
  if(cpp){
      // da;
  }
}

but maybe?:

class CPPclassHelper: public Cstruct{
  virtual ~CPPclassHelper(){};
  CPPclassHelper(){};
  int someMoreData;
};

class CPPclass: public CPPclassHelper{
  virtual ~CPPclassHelper(){};
};

void test(Cstruct* i_c){
  auto cpph = static_cast<CPPclassHelper*>(i_c);
  auto cpp = dynamic_cast<CPPclass*>(cpph );
  if(cpp){
      // da;
  }
}

Body:
You could maintain the type information yourself. Use a static set of all pointers to Cstruct that are bases of CPPclass. Insert the base in all constructors of CPPclass and remove in the destructor. Safe cast can then be implemented using a lookup into that set.

Here is an example:

struct CPPclass: Cstruct{
    CPPclass(){
        bases.insert(this);
    };
    CPPclass(const CPPclass&){
        bases.insert(this);
    };
    CPPclass(CPPclass&&){
        bases.insert(this);
    };
    ~CPPclass(){
        bases.erase(this);
    };

    static CPPclass* safe_cast(Cstruct* c) {
        auto it = bases.find(c);
        return it == bases.end()
            ? nullptr
            : static_cast<CPPclass*>(*it);
    }

private:
    static std::unordered_set<Cstruct*> bases;
};

Usage:

int main() {
    CPPclass cpp;
    Cstruct  c;

    Cstruct* ptr_cpp = &cpp;
    Cstruct* ptr_c   = &c;

    std::cout << CPPclass::safe_cast(ptr_cpp) << '\n'; // some address equal to &cpp
    std::cout << CPPclass::safe_cast(ptr_c)   << '\n'; // null
}


问:
Python multiprocessing with different constant for each thread
I want to create a pool with a function calling the boto3 api and using a different bucket name for each thread:

my function is:

def face_reko(source_data, target_data):

        bucket = s3.Bucket(bucket_name)
    for key in bucket.objects.all():
        key.delete()

    s3_client.put_object(Bucket=bucket_name, Key=target_img, Body=target_data)
    s3_client.put_object(Bucket=bucket_name, Key=source_img, Body=source_data)

    response = reko.compare_faces(
        SourceImage={
            'S3Object': {
                'Bucket': bucket_name,
                'Name' : source_img
            }
        },
        TargetImage={
            'S3Object' : {
                'Bucket' : bucket_name,
                'Name' : target_img
            }
        }
    )
    if len(response['FaceMatches']) > 0:
        return True
    else:
        return False
```

So basically it deletes all in the bucket, upload 2 new image then use the Rekognition api to compare the 2 images. Since I can't create the same image twice in the same bucket, i'd like to create a bucket for each thread then pass a constant to the function for the bucket name instead of the bucket_name const.

答:
So finally I've been able to find a way to work around my issue. Instead of maping my function to a pool, I've created a Worker class defined like this:

class Worker():
def __init__(self, proc_number, splited_list):
    self.pool = Pool(proc_number)
    self.proc_number = proc_number
    self.splited_list = splited_list

def callback(self, result):
    if result:
        self.pool.terminate()

def do_job(self):
    for i in range(self.proc_number):
        self.pool.apply_async(face_reko, args=(self.splited_list[i],source_data, i), callback=self.callback)
    self.pool.close()
    self.pool.join()
```

<p>So the <code>Worker</code> obj is construct with a number of processes and a list of list (<code>splitted_list</code> is my main list splited in <code>number_of_proc</code>). Then when the <code>do_job</code> function is called, the pool starts by creating processes with an id <code>i</code> that can be use in the <code>face_reko</code> function. The pool stops when <code>face_reko</code> returns <code>True</code>. To start the <code>Worker.pool</code>, just create a <code>Worker</code> and call the <code>do_job</code> function like so:</p>

<pre class="lang-python prettyprint-override"><code>w = Worker(proc_number=proc_number, splited_list=splited_list)
w.do_job()
</code>```

Hoping it'll help someone else!

Body:
I want to create a pool with a function calling the boto3 api and using a different bucket name for each thread:

my function is:

def face_reko(source_data, target_data):

        bucket = s3.Bucket(bucket_name)
    for key in bucket.objects.all():
        key.delete()

    s3_client.put_object(Bucket=bucket_name, Key=target_img, Body=target_data)
    s3_client.put_object(Bucket=bucket_name, Key=source_img, Body=source_data)

    response = reko.compare_faces(
        SourceImage={
            'S3Object': {
                'Bucket': bucket_name,
                'Name' : source_img
            }
        },
        TargetImage={
            'S3Object' : {
                'Bucket' : bucket_name,
                'Name' : target_img
            }
        }
    )
    if len(response['FaceMatches']) > 0:
        return True
    else:
        return False

So basically it deletes all in the bucket, upload 2 new image then use the Rekognition api to compare the 2 images. Since I can't create the same image twice in the same bucket, i'd like to create a bucket for each thread then pass a constant to the function for the bucket name instead of the bucket_name const.

Body:
So finally I've been able to find a way to work around my issue. Instead of maping my function to a pool, I've created a Worker class defined like this:

class Worker():
def __init__(self, proc_number, splited_list):
    self.pool = Pool(proc_number)
    self.proc_number = proc_number
    self.splited_list = splited_list

def callback(self, result):
    if result:
        self.pool.terminate()

def do_job(self):
    for i in range(self.proc_number):
        self.pool.apply_async(face_reko, args=(self.splited_list[i],source_data, i), callback=self.callback)
    self.pool.close()
    self.pool.join()

So the Worker obj is construct with a number of processes and a list of list (splitted_list is my main list splited in number_of_proc). Then when the do_job function is called, the pool starts by creating processes with an id i that can be use in the face_reko function. The pool stops when face_reko returns True. To start the Worker.pool, just create a Worker and call the do_job function like so:

w = Worker(proc_number=proc_number, splited_list=splited_list)
w.do_job()

Hoping it'll help someone else!


问:
How do I set a default value on a bit field using Entity Framework Core code-first?
Here is my code:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Skill>()
        .Property(s => s.FlagTrainedOnly)
        .HasDefaultValue(false);
}
</code>```

And the error I get:

Error CS1061

  'PropertyBuilder' does not contain a definition for 'HasDefaultValue' and no extension method 'HasDefaultValue' accepting a first argument of type 'PropertyBuilder' could be found (are you missing a using directive or an assembly reference?)

答:
Make sure you've got

```<code>using Microsoft.EntityFrameworkCore;
</code>```

at the top and then try putting it on one line like this

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Entity<Skill>().Property(p => p.FlagTrainedOnly).HasDefaultValue(false);
}
</code>```

Then put it on multiple lines. I think sometimes it needs to be reminded that the dot extensions exist.

Body:
Here is my code:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Skill>()
        .Property(s => s.FlagTrainedOnly)
        .HasDefaultValue(false);
}

And the error I get:

Error CS1061

  'PropertyBuilder' does not contain a definition for 'HasDefaultValue' and no extension method 'HasDefaultValue' accepting a first argument of type 'PropertyBuilder' could be found (are you missing a using directive or an assembly reference?)

Body:
Make sure you've got

using Microsoft.EntityFrameworkCore;

at the top and then try putting it on one line like this

protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Entity<Skill>().Property(p => p.FlagTrainedOnly).HasDefaultValue(false);
}

Then put it on multiple lines. I think sometimes it needs to be reminded that the dot extensions exist.


问:
How to print variables using Console.WriteLine
The following code demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

When I run this code :-

```<code>class Program
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            Console.WriteLine("Child thread starts");

            // the thread is paused for 5000 milliseconds
            int sleepfor = 5000;

            Console.WriteLine("Child Thread Paused for {0} seconds");
            Thread.Sleep(sleepfor);
            Console.WriteLine("Child thread resumes");
        }

        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("In Main: Creating the Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            Console.ReadKey();
        }
    }
}
</code>```

I  get this output-

```<code>In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes
</code>```

But what i expect is :-

```<code>In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes
</code>```

How can I do it any suggestions?

答:
I think this is where you mistake is:

```<code>Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());
</code>```

You didn't specify where the value for the {0} comes from.

Also you need to calculate from milliseconds to seconds, thats why /1000

Body:
The following code demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

When I run this code :-

class Program
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            Console.WriteLine("Child thread starts");

            // the thread is paused for 5000 milliseconds
            int sleepfor = 5000;

            Console.WriteLine("Child Thread Paused for {0} seconds");
            Thread.Sleep(sleepfor);
            Console.WriteLine("Child thread resumes");
        }

        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("In Main: Creating the Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            Console.ReadKey();
        }
    }
}

I  get this output-

In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes

But what i expect is :-

In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes

How can I do it any suggestions?

Body:
I think this is where you mistake is:

Console.WriteLine("Child Thread Paused for {0} seconds", (sleepfor/1000).ToString());

You didn't specify where the value for the {0} comes from.

Also you need to calculate from milliseconds to seconds, thats why /1000


问:
File cannot be opened when using webclient.DownloadFile not working with long URI
I'm using C# and I'm trying to download a file and save it to the disk. Everything works with not too long URIs, but when I have very long one (around 300 characters), the file gets downloaded to the disk and save, but when I try to open it says it can't be opened, not a valid bitmap file or format is not supported (it's a jpg file)

The filename I'm using is short, and I see the file in the disk with a size of 88KB, so seems it has something but doesn't work.

I'm using Windows Server 2012.

Any idea how to solve this?

UPDATE

If I open the image (in Amazon S3) from the browser I can see the image file, if I save the file to disk (using right click on the image), then the image get saved corrupted (I can't open it).

Any idea why?

Thanks in advance. Guillermo.

答:
If I understand well, you are writing a C# code which tries to Download a file from a URL.
When this file is reprensented by a long URI, you download something but it seems correputed.
Am I correct ?
If yes, I would have a look into this article I found

https://serverfault.com/questions/232986/overcoming-maximum-file-path-length-restrictions-in-windows

It seems there are some issues with deep path. Any chance you can manage some aliases on the Server side ?


问:
jQuery not works on first click
I am using Rails and I am trying to create a bookmark icon in ajax.
The code works, the problem is on the first click the request is sent but the image doesn't change, for the next clicks the behavior is OK (request sent and image change).

My view:

```<code><%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>
  <span class="favorite">
    <% if candidate.favorite %>
      <img src="<%= asset_url "favorite-activated.png" %>" alt="favorito" class="img-40" id="favorite_activated_<%= candidate.id %>">
    <% else %>
      <img src="<%= asset_url "favorite.png"%>" alt="favorito" class="img-40" id="favorite_<%= candidate.id %>">
    <% end %>
  </span>
<% end %>
</code>```

My file favorite.js.erb

```<code>$('#favorite_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
    $('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');
  }
});

$('#favorite_activated_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
    $('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
  }
});
</code>```

My controller:

```<code>def favorite
    @matching = @job.matchings.find(params[:matching_id])
    if @matching.favorite
      @matching.favorite = false
    else
      @matching.favorite = true
    end
    @matching.save
    respond_to do |format|
      format.html { redirect_to company_job_path(@job) }
      format.js  # <-- will render `app/views/company/jobs/favorite.js.erb`
    end
  end
</code>```

Any idea?

答:
What I see from your code right now, that in your response you just setup listeners for click, while what you actually need to do is just to launch your code. You don't need listeners, because you've already setup them in rails itself:

```<code><%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>
</code>```

I think that changing your favorite.js.erb and setup just a part of code that you expect to be a callback:

```<code>$('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
$('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');

$('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
$('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
</code>```

should work for you. Hope this helps

Title: jQuery not works on first click

Body:
I am using Rails and I am trying to create a bookmark icon in ajax.
The code works, the problem is on the first click the request is sent but the image doesn't change, for the next clicks the behavior is OK (request sent and image change).

My view:

<%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>

    <% if candidate.favorite %>
      <img src="<%= asset_url "favorite-activated.png" %>" alt="favorito" class="img-40" id="favorite_activated_<%= candidate.id %>">
    <% else %>
      <img src="<%= asset_url "favorite.png"%>" alt="favorito" class="img-40" id="favorite_<%= candidate.id %>">
    <% end %>

<% end %>

My file favorite.js.erb

$('#favorite_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
    $('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');
  }
});

$('#favorite_activated_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
    $('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
  }
});

My controller:

def favorite
    @matching = @job.matchings.find(params[:matching_id])
    if @matching.favorite
      @matching.favorite = false
    else
      @matching.favorite = true
    end
    @matching.save
    respond_to do |format|
      format.html { redirect_to company_job_path(@job) }
      format.js  # <-- will render `app/views/company/jobs/favorite.js.erb`
    end
  end

Any idea?

Body:
What I see from your code right now, that in your response you just setup listeners for click, while what you actually need to do is just to launch your code. You don't need listeners, because you've already setup them in rails itself:

<%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>

I think that changing your favorite.js.erb and setup just a part of code that you expect to be a callback:

$('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
$('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');

$('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
$('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');

should work for you. Hope this helps


答:
If you want to see Child thread passed for <5> seconds, then you need to print exactly that.

Below is the problem line of your code

```<code>Console.WriteLine("Child Thread Paused for {0} seconds");
</code>```

This should be

```<code>Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
</code>```

As you notice, you haven't specified the parameter {0} in your call. You can refer to the documentation on Console.WriteLine()

Note that Console.WriteLine follows the formatting rules set by String.Format. The format string rules can be seen here.

In the newer syntax you don't need to use the place holders like {0} but can embed the expression itself in the string, called Interpolated Strings

```<code>Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");
</code>```

Title: How to print variables using Console.WriteLine

Body:
If you want to see Child thread passed for <5> seconds, then you need to print exactly that.

Below is the problem line of your code

Console.WriteLine("Child Thread Paused for {0} seconds");

This should be

Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);

As you notice, you haven't specified the parameter {0} in your call. You can refer to the documentation on Console.WriteLine()

Note that Console.WriteLine follows the formatting rules set by String.Format. The format string rules can be seen here.

In the newer syntax you don't need to use the place holders like {0} but can embed the expression itself in the string, called Interpolated Strings

Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");


问:
How to take screenshot of application excluding the statusbar using Appium

Environment details

Appium Version 1.7

Android version Nougat

And below is my code

```<code>    public class CaptureScreenShot {
    AppiumDriver<WebElement> driver;
 Dimension size;
 String destDir;
 DateFormat dateFormat;
 BufferedImage expectedImage;
 BufferedImage actualImage;

 @BeforeTest
 public void setUp() throws Exception {
     DesiredCapabilities dc = new DesiredCapabilities();
        dc.setCapability(CapabilityType.BROWSER_NAME,"Android");
        dc.setCapability(CapabilityType.VERSION,"7.0");
        dc.setCapability("deviceName","ce041714c44ebd1802");
        dc.setCapability("platformName", "Android");
        dc.setCapability("appPackage", "io.ionic.starter");
        dc.setCapability("appActivity", "io.ionic.starter.MainActivity");
                try {
                    driver= new AppiumDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), dc);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

 }

 @Test
 public void ScrollToTab() {
  takeScreenShot();

 }

 public void takeScreenShot() {
   destDir = "<<local path>>\";

  File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

  dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");

  new File(destDir).mkdirs();

  String destFile = dateFormat.format(new Date()) + ".png";

  try {

   FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 @Test
 public void verify(){
     try {
        expectedImage = ImageIO.read(new File("<local path>"));
    } catch (IOException e) {
      e.printStackTrace();
    }
     try {
        actualImage = ImageIO.read(new File("<local path>"));
    } catch (IOException e) {
        e.printStackTrace();
    }
     ImageDiffer imgDiff = new ImageDiffer();
     ImageDiff diff = imgDiff.makeDiff(expectedImage, actualImage);
     Assert.assertFalse(diff.hasDiff(),"Images are Same");
 }

 @AfterTest
 public void End() {
  driver.quit();
 }
}
</code>```

This code works fine but along with the screenshot the android status bar also getting captured and the tests fails as the status screen elements are dynamic.
can anyone help me to take the screenshot without including the status-bar.

答:
This code might solve your problem by taking subImage from full screenshot:</p>

```<code>import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

AppiumDriver driver;
By locator = By.xpath("(//android.widget.FrameLayout)[1]");
// in my case this locator match everything except status bar

public BufferedImage getSubImage() throws IOException {
    final byte[] srcImage = ((TakesScreenshot) driver).
      getScreenshotAs(OutputType.BYTES);
    final BufferedImage screenshot = ImageIO.read(
      new ByteArrayInputStream(srcImage));

    final WebElement element = driver.findElement(locator);
    final Point elementLocation = element.getLocation();
    final Dimension elementSize = element.getSize();
    return screenshot.getSubimage(elementLocation.x, elementLocation.y,
      elementSize.width, elementSize.height);
}
</code>```

Body:
Environment details

Appium Version 1.7

Android version Nougat

And below is my code

    public class CaptureScreenShot {
    AppiumDriver<WebElement> driver;
 Dimension size;
 String destDir;
 DateFormat dateFormat;
 BufferedImage expectedImage;
 BufferedImage actualImage;

 @BeforeTest
 public void setUp() throws Exception {
     DesiredCapabilities dc = new DesiredCapabilities();
        dc.setCapability(CapabilityType.BROWSER_NAME,"Android");
        dc.setCapability(CapabilityType.VERSION,"7.0");
        dc.setCapability("deviceName","ce041714c44ebd1802");
        dc.setCapability("platformName", "Android");
        dc.setCapability("appPackage", "io.ionic.starter");
        dc.setCapability("appActivity", "io.ionic.starter.MainActivity");
                try {
                    driver= new AppiumDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), dc);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

 }

 @Test
 public void ScrollToTab() {
  takeScreenShot();

 }

 public void takeScreenShot() {
   destDir = "<<local path>>\";

  File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

  dateFormat = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");

  new File(destDir).mkdirs();

  String destFile = dateFormat.format(new Date()) + ".png";

  try {

   FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 @Test
 public void verify(){
     try {
        expectedImage = ImageIO.read(new File("<local path>"));
    } catch (IOException e) {
      e.printStackTrace();
    }
     try {
        actualImage = ImageIO.read(new File("<local path>"));
    } catch (IOException e) {
        e.printStackTrace();
    }
     ImageDiffer imgDiff = new ImageDiffer();
     ImageDiff diff = imgDiff.makeDiff(expectedImage, actualImage);
     Assert.assertFalse(diff.hasDiff(),"Images are Same");
 }

 @AfterTest
 public void End() {
  driver.quit();
 }
}

This code works fine but along with the screenshot the android status bar also getting captured and the tests fails as the status screen elements are dynamic.
can anyone help me to take the screenshot without including the status-bar.

Body:
This code might solve your problem by taking subImage from full screenshot:

import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

AppiumDriver driver;
By locator = By.xpath("(//android.widget.FrameLayout)[1]");
// in my case this locator match everything except status bar

public BufferedImage getSubImage() throws IOException {
    final byte[] srcImage = ((TakesScreenshot) driver).
      getScreenshotAs(OutputType.BYTES);
    final BufferedImage screenshot = ImageIO.read(
      new ByteArrayInputStream(srcImage));

    final WebElement element = driver.findElement(locator);
    final Point elementLocation = element.getLocation();
    final Dimension elementSize = element.getSize();
    return screenshot.getSubimage(elementLocation.x, elementLocation.y,
      elementSize.width, elementSize.height);
}


问:
Drupal 8 - Get comments area on custom template
I am trying to get the comment form with all comments on a custom template article page of drupal. I can get the whole content with {{ page.content }} or get the comments by using {{ node.field_comments }} and make a loop on it (assuming my field comment machine name is field_comments).

But does anyone know I to render the whole comments block with :

links to add a comment

comments

comment form

Thank you very much for your help !

答:
In template files for a content type (eg node--article.html.twig), you have the 'content' variable available. I use this bit of Twig to render the whole comments block:-</p>

```<code>{{ content.comment }}
</code>```

Body:
In template files for a content type (eg node--article.html.twig), you have the 'content' variable available. I use this bit of Twig to render the whole comments block:-

{{ content.comment }}