text:
Q: Insert into in Gridview. Makes insert on refresh..asp.net I have a customer Gridview with the possibility to make an insert of a new customer in the footertemplate.
When i press my insert button i make a Redirect to the same page and i can see my new customer in the gridview.
What a noticed was that when i make a refresh directly on the page it adds the same customer again. That's really strange for me because after my Redirect my requiredfields like firstname lastname and so on are all empty of course but still the page grabs the values from before and makes another insert.
Why is it like that and how can i solve this Problem?
aspx

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" DataKeyNames="CustID" DataSourceID="Event" GridLines="Horizontal" ShowFooter="True" AllowPaging="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" OnRowDataBound="GridView1_RowDataBound">
    <AlternatingRowStyle BackColor="#F7F7F7" HorizontalAlign="Center" />
    <Columns>
        <asp:CommandField ShowEditButton="True" />
        <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="CustID">
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("CustID") %>'></asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("CustID") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:LinkButton ValidationGroup="INSERT" OnClick="lbInsert_Click"  ID="lbInsert" runat="server" >Insert</asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Anrede" SortExpression="Gender">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1" DataTextField="Gender" DataValueField="Gender" SelectedValue='<%# Bind("Gender") %>'>
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EventConnectionString %>" SelectCommand="SELECT DISTINCT [Gender] FROM [Customer]"></asp:SqlDataSource>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Gender") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label13" runat="server" Text="Anrede"></asp:Label>
                <asp:DropDownList ID="ddlGender" runat="server">
                    <asp:ListItem>Anrede Auswählen</asp:ListItem>
                    <asp:ListItem>Herr</asp:ListItem>
                    <asp:ListItem>Frau</asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfvInsGender" runat="server" ErrorMessage="Anrede ist ein Pflichtfeld"
                    ControlToValidate="ddlGender" ValidationGroup="INSERT" Text="*" ForeColor="Red" InitialValue="Anrede Auswählen">
                </asp:RequiredFieldValidator>

            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name" SortExpression="LastName">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdLastName" runat="server" ErrorMessage="Name ist ein Pflichtfeld"
                    ControlToValidate="TextBox2" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label14" runat="server" Text="Name"></asp:Label>

                <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsLastName" runat="server" ErrorMessage="Name ist ein Pflichtfeld"
                    ControlToValidate="txtLastName" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Vorname" SortExpression="FirstName">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdFirstName" runat="server" ErrorMessage="VorName ist ein Pflichtfeld"
                    ControlToValidate="TextBox3" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label4" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label15" runat="server" Text="Vorname"></asp:Label>

                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsFirstName" runat="server" ErrorMessage="VorName ist ein Pflichtfeld"
                    ControlToValidate="txtFirstName" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Strasse" SortExpression="Street">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Street") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdStreet" runat="server" ErrorMessage="Strasse ist ein Pflichtfeld"
                    ControlToValidate="TextBox4" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label5" runat="server" Text='<%# Bind("Street") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label16" runat="server" Text="Strasse"></asp:Label>

                <asp:TextBox ID="txtStreet" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsStreet" runat="server" ErrorMessage="Strasse ist ein Pflichtfeld"
                    ControlToValidate="txtStreet" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="House Nr" SortExpression="HouseNr">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("HouseNr") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdHouseNr" runat="server" ErrorMessage="House Nr ist ein Pflichtfeld"
                    ControlToValidate="TextBox5" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label6" runat="server" Text='<%# Bind("HouseNr") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label17" runat="server" Text="House Nr"></asp:Label>

                <asp:TextBox ID="txtHouseNr" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsHouseNr" runat="server" ErrorMessage="House Nr ist ein Pflichtfeld"
                    ControlToValidate="txtHouseNr" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="PLZ" SortExpression="Zip">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("Zip") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdZip" runat="server" ErrorMessage="PLZ ist ein Pflichtfeld"
                    ControlToValidate="TextBox6" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label7" runat="server" Text='<%# Bind("Zip") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label18" runat="server" Text="PLZ"></asp:Label>

                <asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsZip" runat="server" ErrorMessage="PLZ ist ein Pflichtfeld"
                    ControlToValidate="txtZip" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Ort" SortExpression="City">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox7" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvEdCity" runat="server" ErrorMessage="Ort ist ein Pflichtfeld"
                    ControlToValidate="TextBox7" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label8" runat="server" Text='<%# Bind("City") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label19" runat="server" Text="Ort"></asp:Label>

                <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvInsCity" runat="server" ErrorMessage="Ort ist ein Pflichtfeld"
                    ControlToValidate="txtCity" ValidationGroup="INSERT" Text="*" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Telefon" SortExpression="Phone">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox8" runat="server" Text='<%# Bind("Phone") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label9" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label20" runat="server" Text="Telefon"></asp:Label>

                <asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="E-mail" SortExpression="Email">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox9" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label10" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label21" runat="server" Text="E-mail"></asp:Label>

                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Firma" SortExpression="Company">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox10" runat="server" Text='<%# Bind("Company") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label11" runat="server" Text='<%# Bind("Company") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label22" runat="server" Text="Firma"></asp:Label>

                <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Status" SortExpression="Active">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource2" DataTextField="Active" DataValueField="Active" SelectedValue='<%# Bind("Active") %>'>
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:EventConnectionString %>" SelectCommand="SELECT DISTINCT [Active] FROM [Customer]"></asp:SqlDataSource>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label12" runat="server" Text='<%# Bind("Active") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>

<asp:Label ID="Label23" runat="server" Text="Status"></asp:Label>

                <asp:DropDownList ID="ddlActive" runat="server">
                    <asp:ListItem>Status Auswählen</asp:ListItem>
                    <asp:ListItem>Aktiv</asp:ListItem>
                    <asp:ListItem>Passiv</asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfvInsActive" runat="server" ErrorMessage="Status ist ein Pflichtfeld"
                    ControlToValidate="ddlActive" ValidationGroup="INSERT" Text="*" ForeColor="Red" InitialValue="Status Auswählen">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>

    </Columns>
    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
    <HeaderStyle BackColor="#B5C7DE" Font-Bold="True" ForeColor="#4A3C8C" />
    <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
    <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
    <SortedAscendingCellStyle BackColor="#F4F4FD" />
    <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
    <SortedDescendingCellStyle BackColor="#D8D8F0" />
    <SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>

<asp:ValidationSummary ValidationGroup="INSERT" ID="ValidationSummary1" ForeColor="Red" runat="server" />
<asp:ValidationSummary ID="ValidationSummary2" ForeColor="Red" runat="server" />
<asp:SqlDataSource ID="Event" runat="server" ConnectionString="<%$ ConnectionStrings:EventConnectionString %>" DeleteCommand="DELETE FROM [Customer] WHERE [CustID] = @CustID" InsertCommand="INSERT INTO [Customer] ([Gender], [LastName], [FirstName], [Street], [HouseNr], [Zip], [City], [Phone], [Email], [Company], [Active]) VALUES (@Gender, @LastName, @FirstName, @Street, @HouseNr, @Zip, @City, @Phone, @Email, @Company, @Active)" SelectCommand="SELECT [CustID], [Gender], [LastName], [FirstName], [Street], [HouseNr], [Zip], [City], [Phone], [Email], [Company], [Active] FROM [Customer]" UpdateCommand="UPDATE [Customer] SET [Gender] = @Gender, [LastName] = @LastName, [FirstName] = @FirstName, [Street] = @Street, [HouseNr] = @HouseNr, [Zip] = @Zip, [City] = @City, [Phone] = @Phone, [Email] = @Email, [Company] = @Company, [Active] = @Active WHERE [CustID] = @CustID">
    <DeleteParameters>
        <asp:Parameter Name="CustID" Type="Decimal" />
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="Gender" Type="String" />
        <asp:Parameter Name="LastName" Type="String" />
        <asp:Parameter Name="FirstName" Type="String" />
        <asp:Parameter Name="Street" Type="String" />
        <asp:Parameter Name="HouseNr" Type="String" />
        <asp:Parameter Name="Zip" Type="String" />
        <asp:Parameter Name="City" Type="String" />
        <asp:Parameter Name="Phone" Type="String" />
        <asp:Parameter Name="Email" Type="String" />
        <asp:Parameter Name="Company" Type="String" />
        <asp:Parameter Name="Active" Type="String" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="Gender" Type="String" />
        <asp:Parameter Name="LastName" Type="String" />
        <asp:Parameter Name="FirstName" Type="String" />
        <asp:Parameter Name="Street" Type="String" />
        <asp:Parameter Name="HouseNr" Type="String" />
        <asp:Parameter Name="Zip" Type="String" />
        <asp:Parameter Name="City" Type="String" />
        <asp:Parameter Name="Phone" Type="String" />
        <asp:Parameter Name="Email" Type="String" />
        <asp:Parameter Name="Company" Type="String" />
        <asp:Parameter Name="Active" Type="String" />
        <asp:Parameter Name="CustID" Type="Decimal" />
    </UpdateParameters>
</asp:SqlDataSource>

aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void lbInsert_Click(object sender, EventArgs e)
    {
        Event.InsertParameters["Gender"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
        Event.InsertParameters["LastName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
        Event.InsertParameters["FirstName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
        Event.InsertParameters["Street"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtStreet")).Text;
        Event.InsertParameters["HouseNr"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtHouseNr")).Text;
        Event.InsertParameters["Zip"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtZip")).Text;
        Event.InsertParameters["City"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
        Event.InsertParameters["Phone"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtPhone")).Text;
        Event.InsertParameters["Email"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtEmail")).Text;
        Event.InsertParameters["Company"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
        Event.InsertParameters["Active"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlActive")).SelectedValue;

        Event.Insert();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var dr = e.Row.DataItem as DataRowView;

            if (dr["CustID"].ToString() == "60" || dr["CustID"].ToString() == "62")
            {
                e.Row.Enabled = false;  //OR dr.Enabled = false;
                //DISABLED Controls only
                //((TextBox)e.Row.FindControl("TextBox1")).Enabled = false;
            }
        }
    }

A: Create one method to bind the Grid and while you insert the data into grid than just call this method to bind grid...Try this...

A: private void BindGrid()
{
    //Your Code For Fill the Grid...Possibly If You Use Database than Fired Query to fetch data and fill Grid...
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var dr = e.Row.DataItem as DataRowView;

        if (dr["CustID"].ToString() == "60" || dr["CustID"].ToString() == "62")
        {
            e.Row.Enabled = false;  //OR dr.Enabled = false;
            //DISABLED Controls only
            //((TextBox)e.Row.FindControl("TextBox1")).Enabled = false;
        }
    }
    BindGrid();
}

A: What you all need is to use
Response.Redirect(Request.Url.AbsolutePath);

use it at the bottom of your button click event code
 protected void lbInsert_Click(object sender, EventArgs e)
    {
        Event.InsertParameters["Gender"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
        Event.InsertParameters["LastName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLastName")).Text;
        Event.InsertParameters["FirstName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtFirstName")).Text;
        Event.InsertParameters["Street"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtStreet")).Text;
        Event.InsertParameters["HouseNr"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtHouseNr")).Text;
        Event.InsertParameters["Zip"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtZip")).Text;
        Event.InsertParameters["City"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
        Event.InsertParameters["Phone"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtPhone")).Text;
        Event.InsertParameters["Email"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtEmail")).Text;
        Event.InsertParameters["Company"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
        Event.InsertParameters["Active"].DefaultValue = ((DropDownList)GridView1.FooterRow.FindControl("ddlActive")).SelectedValue;

        Event.Insert();
        Response.Redirect(Request.Url.AbsolutePath);
    }


text:
Q: WordPress: Get ACF Post Object selection (Post ID) and use it with $post = get_post(); I'm having a hard time understanding how to use two PHP snippets together.
My situation: The standard WordPress Post Type "Pages" has got its own ACF field "header-selection". This field is a Post Object and the return format is the Post ID. A selection can be made from the available posts of the CPT "Headers".
With the following code it is possible for me to get the selected Post/ID:
$value = get_field( "header-selection" );

Now I want to integrate the ID in the following code:
$post = get_post(18);
$the_content = apply_filters('the_content', $post->post_content);
if ( !empty($the_content) ) {
  echo $the_content;
}

Instead of the Post ID "18", I would like to have the selection of the ACF field "header-selection".
I am sorry if I get things wrong. Unfortunately I have problems understanding PHP.
I would be very grateful for a suggested solution or an idea.

A: Save the ACF value to a variable than use that variable in-place of the hardcoded id like below:
$header_selection_id = get_field( "header-selection" );
$post = get_post($header_selection_id);

redpajama_set_name: RedPajamaStackExchange


text:
Q: select new column as null string in spark I am attempting to generate a column of null values in spark, NOT a null datatype though.
So
sqlContext.sql("select null as newcol from db.table")

Will not work, as it will set newcol datatype to be null.
sqlContext.sql("select cast(null as newcol as string) from db.table")

Will not work because it will make all values "null" as the 4 character string representation.
How can I accomplish this?
The end goal is write this to a csv, which does not support the null column type and I need the actual values in the dataframe to be null and not empty strings.

A: I think the syntax you want is:
select cast(null as string) as newcol from db.table

The expression is cast(null as string) -- this is just any old expression and could be much more complicated.  The column alias is provided using as newcol, which goes after the expression.
It is just a coincidence that as is begin used twice (for different things) in the definition of newcol.


text:
Q: Using graph traversal to test is a graph is a perfect binary tree When given an undirected graph G represented by an adjacency list how can you use a DFS to see if that graph is a perfect binary tree?
I have been able to identify edge cases: such as using the fact that for a depth D you need 2^n-1 nodes you can can work out the max depth using a logarithm and if that isn't whole you know you don't have a perfect tree but I cant think of an efficient way of using the adjacency list and DFS to test.

A: In a perfect binary tree that is not empty, with  nodes, we have these properties:

*

*The number of nodes  is one less than a power of 2, i.e. ℎ=log2(+1) is integer. =2ℎ−1

*The number of edges is −1

*There are no nodes with more than 3 neighbors.

*When  > 1, there is (only) one node with exactly 2 neighbors: it is the root.

*When  > 1, the leaves of the tree have only one neighbor: there are 2ℎ-1 of them.

*The distance between the root and any leaf is ℎ−1.

These properties can be checked one after the other. Once you have identified the root, you can perform a traversal to check the distance property. Either with DFS or BFS.

A: If the graph is empty, or has only one vertex, then return true.
Otherwise, check to make sure the graph is connected and acyclic.
Then, if it's a perfect binary tree, there must be only one vertex of degree 2. That's the root.  Let a and b be its two children.  Then:
let depthA = depthIfPerfect(a, root);
let depthB = depthIfPerfect(b, root);
return depthA == depthB && depthA >=0

where:
depthIfPerfect(node, parent):

    if degree(node) == 1:
        return 1;
    if degree(node) != 3:
        return -1; //not perfect

    let a and b be the neighbors that aren't parent

    let depthA = depthIfPerfect(a, node);
    let depthB = depthIfPerfect(b, node);

    if (depthA != depthB || depthA < 0):
        return -1: //not perfect
    return depthA+1;

You can mix the check for connectedness and acyclicity into this traversal if you like.


text:
Q: VOIP Services not working in Production environment, but working fine in test server I am using APNS Certificate & VOIP Services Certificate in parallel in my iOS apps, I have created APNS (both Sandbox & Production), then uses AWS SNS as an intermediate and then creates application ARN and endpoints at SNS and send push from my server via SNS (with the corresponding certificates), these steps work fine for APNS, Push notifications are working fine.
But when I go to VOIP, I am able to get the app working fine in my test server (that is I am getting VOIP notification when using test server), but in case of production, it's not working...
FYI

*

*Am using two different tokens for both APNS & VOIP

*Have created & rechecked the VOIP certificates(single certificate for both test & production)

Am not getting any idea of whats wrong... TIA... Requesting for suggestions or anyone faced the same issue?

A: It sounds like you did everything correct.
What I can recommend as an alternative solution is to create a single Universal APNS certificate which works everywhere - for Production/Sandbox standard pushes + VoIP Production/Sandbox
And use this single certificate for both cases
Here is a very simple guide I used to generate single Universal certificate which works everywhere https://developers.connectycube.com/ios/how-to-create-apns-certificate

A: You have to check the endpoint for the APNS. So when you are working in dev environment you should send in APNS_ENDPOINT: api.development.push.apple.com and when in production in APNS_ENDPOINT: api.push.apple.com


text:
Q: Materialize TextArea not dynamically changing? Working with a TextArea, class="materialize-textarea".
On the documentation at https://materializecss.com/forms.html there should be no javaScript or jQuery needed for the TextArea to expand downwards and move the page's content along with it.
When I enter text inside the TextArea I cannot hit enter to move down. I can only write along the line to infinity. Which is not what I want, obviously, what I want is for the TextArea to resize as the text reaches end of the row, but it doesn't. Anyone encountered this issue before?
HTML:

APPLY FOR MEMBERSHIP

        <form class="col s12">

                    By submitting your company details you can get access to StoryTourist and create your own
                    customized stories for your audience to enjoy around the world!

                    business
                    <input placeholder="Company Name" type="text" class="validate">

                    mail outline
                    <input placeholder="Company e-mail" type="text" class="validate">

                    phone
                    <input placeholder="Company phone-number" type="text" class="validate">

                    mode_edit
                    <input placeholder="Message us..." textarea id="textArea1" class="materialize-textarea"></textarea>

        </form>

        Submit details

UPDATE
Changed:
<input placeholder="Message us..." textarea id="textArea1" class="materialize-textarea"></textarea>

To:
<textarea placeholder="Message us..." textarea id="textArea1" class="materialize-textarea"></textarea>

Now faced with issue that page doesn't dynamically change with TextArea, there are no fixed heights in my CSS.

A: You need to change this
<input placeholder="Message us..." textarea id="textArea1" class="materialize-textarea"></textarea>

To this
<textarea placeholder="Message us..." id="textArea1" class="materialize-textarea"></textarea>

That should fix your issue. You opened with an <input> tag but closed with a </textarea> tag.

A: I know this is really late, but when you download the Materialize folder - if you want it to auto resize, materialize uses javascript, so you must include the javascript file as well as the css file


text:
Q: how to enter $email into mailto i created a table to view user details where all the detils would be retrieved from the database. i want to set the retrieved emal address as a link so it could open in the default email application. this code here works but in the To: textbox [default email app], the email address is not correctly displayed i want to know how to enter $email into mailto i would request someone to pls provide me some help
if($query === false)
                                {
                                    throw new Exception(mysql_error($conn));
                                }
                                while($row=mysqli_fetch_array($query))
                                {
                                    $tea_id=$row['tea_id'];
                                    $fname=$row['fname'];
                                    $lname=$row['lname'];

                                    $email=$row['email'];

                                     $username = $row['username'];
                        ?>

                      <?php echo $row['tea_id'] ?>
                    <?php echo $row['fname'] ?>
                     <?php echo $row['lname'] ?>

                           <?php

                           // echo $row['email']
                           echo ('' . $email . '')

                        ?>

---------------------------------------CLICK HERE TO VIEW CODE-----------------------------------

A:
echo "".$email."";

A: The email line should be :
echo '' . $email . ''

With a subject :
echo '' . $email . ''

and ofcourse you should set the $subject variable first.. :)

A: You can use concatenation to join the mailto statement and the email variable from the database.
echo '<a href = "mailto:' . $your_email .'" . ''


text:
Q: MySQL server has gone away Here my code snippet:
query.next();
qDebug()<<query.lastError();
qlonglong res=query.value(0).toLongLong();
qDebug()<<query.lastError();

and the corresponding log I have:
Debug: QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
Warning: QSqlQuery::value: not positioned on a valid record
Debug: QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")

Normally my program works just fine (it works on a server and accepts connections from  clients), but every morning when I tried to connect it, I'm getting messages above.
What can be the problem with MySQL server?

A: From the MySQL Manual:

The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.
...
By default, the server closes the connection after eight hours if nothing has happened. You can change the time limit by setting the wait_timeout variable when you start mysqld.
...
If you have a script, you just have to issue the query again for the client to do an automatic reconnection. This assumes that you have automatic reconnection in the client enabled (which is the default for the mysql command-line client).

See this manual page for more details on this error.

A: I know this is old but happens to be the first google hit for "MySQL server has gone away QMYSQL: Unable to execute query".
It seems QSqlDatabase::isOpen() will still return true even though we don't have a connection anymore. Here is how I catch it:
QSqlDatabase db = QSqlDatabase::database();
QSqlQuery query(db);
QString q = "SELECT * FROM myTable;";
if (!query.exec(q))
{
    int err = query.lastError().number();
    if (err == 2006) // Might want to do #2013 here also?
    {
        db.close();
        if (db.open() && !query.exec(q))
        {
            // handle error here we still failed...
        }
    }
    else
    {
        // handle normal query errors here
    }
}

I was able to mimic this situation by restarting the server with "/etc/init.d/mysql restart" and keep sending queries to it and it eventually throws this error. I feel this shouldn't be changed server side, in fact 8 hours seems extremely long to keep an idle connection open.


text:
Q: Upgrade from Spring Cloud Angel SR3 to Brixton M1 produces method not found error I updated from spring cloud Angel.SR3 to Brixton.M1 versions of spring cloud and suddenly I am getting a method not found error as follows:
LARMITCH-M-700M:customerservice larrymitchell$ java -jar target/customerservice.jar
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: org.springframework.core.ResolvableType.forInstance(Ljava/lang/Object;)Lorg/springframework/core/ResolvableType;
    at org.springframework.context.event.SimpleApplicationEventMulticaster.resolveDefaultEventType(SimpleApplicationEventMulticaster.java:142)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:119)
    at org.springframework.boot.context.event.EventPublishingRunListener.publishEvent(EventPublishingRunListener.java:111)
    at org.springframework.boot.context.event.EventPublishingRunListener.started(EventPublishingRunListener.java:60)
    at org.springframework.boot.SpringApplicationRunListeners.started(SpringApplicationRunListeners.java:47)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:271)
    at com.libertas.vipaas.CustomerServiceApplication.main(CustomerServiceApplication.java:40)
    ... 6 more
LARMITCH-M-700M:customerservice larrymitchell$

Here is the particular Main class that we use:
@EnableCircuitBreaker
@EnableDiscoveryClient
@Configuration
@ComponentScan
@EnableAutoConfiguration(
        exclude = {
                MongoRepositoriesAutoConfiguration.class
        }
)
@Slf4j
public class CustomerServiceApplication implements CommandLineRunner {

    /**
     * The main entry point
     *
     * @param args the command args
     */
    public static void main(String[] args) {
        // create our application
        ApplicationContext ctx = new SpringApplication(CustomerServiceApplication.class).run(args);

    }

    /**
     * the initialization section, put any initialization code such as database init here
     * <p/>
     *
     * @param args the passed in parameter set from the command line
     * @throws Exception if we failed
     */
    @Override
    public void run(String... args) throws Exception {
        log.info("Put command runner code here.  This is run after the entire spring application is ready to run");

    }
}

According to the spring blog entry for  to update I followed putting this in as the parent:
<parent>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-parent</artifactId>
    <version>Brixton.M1</version>
</parent>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

Any ideas what might be causing this issue?
Addition:   Here is the mvn dependency tee:
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building customerservice 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ customerservice ---
[INFO] com.libertas.vipaas:customerservice:jar:1.0-SNAPSHOT
[INFO] +- com.libertas.vipaas:vipaasfoundations:jar:1.0.0:compile
[INFO] |  +- org.springframework.data:spring-data-redis:jar:1.6.0.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-context-support:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-tx:jar:4.2.1.RELEASE:compile
[INFO] |  +- redis.clients:jedis:jar:2.7.3:compile
[INFO] |  +- com.bfjournal:embedded-redis:jar:0.11.0:compile
[INFO] |  +- org.springframework.security:spring-security-jwt:jar:1.0.3.RELEASE:compile
[INFO] |  |  \- org.bouncycastle:bcpkix-jdk15on:jar:1.47:compile
[INFO] |  |     \- org.bouncycastle:bcprov-jdk15on:jar:1.47:compile
[INFO] |  +- com.googlecode.json-simple:json-simple:jar:1.1.1:compile
[INFO] |  +- commons-io:commons-io:jar:2.4:compile
[INFO] |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  +- commons-codec:commons-codec:jar:1.10:compile
[INFO] |  \- org.apache.httpcomponents:httpclient:jar:4.5:compile
[INFO] |     \- org.apache.httpcomponents:httpcore:jar:4.4.1:compile
[INFO] +- com.libertas.vipaas:vipaaspersistency:jar:1.0.0:compile
[INFO] +- com.libertas.vipaas:vipaassecurity:jar:1.0.0:compile
[INFO] +- org.springframework.boot:spring-boot-starter:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework.boot:spring-boot:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.3.0.M5:compile
[INFO] |  |  +- ch.qos.logback:logback-classic:jar:1.1.3:compile
[INFO] |  |  |  \- ch.qos.logback:logback-core:jar:1.1.3:compile
[INFO] |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.12:compile
[INFO] |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.12:compile
[INFO] |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.12:compile
[INFO] |  +- org.springframework:spring-core:jar:4.1.7.RELEASE:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.16:compile
[INFO] +- org.springframework.boot:spring-boot-starter-actuator:jar:1.3.0.M5:compile
[INFO] |  \- org.springframework.boot:spring-boot-actuator:jar:1.3.0.M5:compile
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-validation:jar:1.3.0.M5:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.0.26:compile
[INFO] |  |  \- org.hibernate:hibernate-validator:jar:5.2.1.Final:compile
[INFO] |  |     +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |     \- org.jboss.logging:jboss-logging:jar:3.2.1.Final:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.6.1:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.6.1:compile
[INFO] |  +- org.springframework:spring-web:jar:4.2.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.2.1.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-jetty:jar:1.3.0.M5:compile
[INFO] |  +- org.eclipse.jetty:jetty-servlets:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-continuation:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-http:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-util:jar:9.2.13.v20150730:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-io:jar:9.2.13.v20150730:compile
[INFO] |  +- org.eclipse.jetty:jetty-webapp:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-xml:jar:9.2.13.v20150730:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-servlet:jar:9.2.13.v20150730:compile
[INFO] |  |     \- org.eclipse.jetty:jetty-security:jar:9.2.13.v20150730:compile
[INFO] |  |        \- org.eclipse.jetty:jetty-server:jar:9.2.13.v20150730:compile
[INFO] |  +- org.eclipse.jetty.websocket:websocket-server:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-common:jar:9.2.13.v20150730:compile
[INFO] |  |  |  \- org.eclipse.jetty.websocket:websocket-api:jar:9.2.13.v20150730:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-client:jar:9.2.13.v20150730:compile
[INFO] |  |  \- org.eclipse.jetty.websocket:websocket-servlet:jar:9.2.13.v20150730:compile
[INFO] |  \- org.eclipse.jetty.websocket:javax-websocket-server-impl:jar:9.2.13.v20150730:compile
[INFO] |     +- org.eclipse.jetty:jetty-annotations:jar:9.2.13.v20150730:compile
[INFO] |     |  +- org.eclipse.jetty:jetty-plus:jar:9.2.13.v20150730:compile
[INFO] |     |  |  \- org.eclipse.jetty:jetty-jndi:jar:9.2.13.v20150730:compile
[INFO] |     |  +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] |     |  +- org.ow2.asm:asm:jar:5.0.1:compile
[INFO] |     |  \- org.ow2.asm:asm-commons:jar:5.0.1:compile
[INFO] |     |     \- org.ow2.asm:asm-tree:jar:5.0.1:compile
[INFO] |     +- org.eclipse.jetty.websocket:javax-websocket-client-impl:jar:9.2.13.v20150730:compile
[INFO] |     \- javax.websocket:javax.websocket-api:jar:1.0:compile
[INFO] +- org.springframework.boot:spring-boot-starter-aop:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.2.1.RELEASE:compile
[INFO] |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.aspectj:aspectjrt:jar:1.8.6:compile
[INFO] |  \- org.aspectj:aspectjweaver:jar:1.8.6:compile
[INFO] +- org.springframework.boot:spring-boot-starter-data-mongodb:jar:1.3.0.M5:compile
[INFO] |  +- org.mongodb:mongo-java-driver:jar:2.13.2:compile
[INFO] |  \- org.springframework.data:spring-data-mongodb:jar:1.8.0.RELEASE:compile
[INFO] |     \- org.springframework.data:spring-data-commons:jar:1.11.0.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-security:jar:1.3.0.M5:compile
[INFO] |  +- org.springframework.security:spring-security-config:jar:4.0.2.RELEASE:compile
[INFO] |  \- org.springframework.security:spring-security-web:jar:4.0.2.RELEASE:compile
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.7.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.2.1.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-core:jar:4.0.2.RELEASE:compile
[INFO] |  \- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |     \- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] +- org.springframework.cloud:spring-cloud-starter:jar:1.1.0.M1:compile
[INFO] |  +- org.springframework.cloud:spring-cloud-context:jar:1.1.0.M1:compile
[INFO] |  |  \- org.springframework.security:spring-security-crypto:jar:4.0.2.RELEASE:compile
[INFO] |  \- org.springframework.cloud:spring-cloud-commons:jar:1.1.0.M1:compile
[INFO] +- org.springframework.cloud:spring-cloud-starter-eureka:jar:1.1.0.M1:compile
[INFO] |  +- org.springframework.cloud:spring-cloud-starter-ribbon:jar:1.1.0.M1:compile
[INFO] |  |  +- com.netflix.ribbon:ribbon:jar:2.1.0:compile
[INFO] |  |  |  +- com.netflix.ribbon:ribbon-transport:jar:2.1.0:runtime
[INFO] |  |  |  |  +- io.reactivex:rxnetty-contexts:jar:0.4.9:runtime
[INFO] |  |  |  |  \- io.reactivex:rxnetty-servo:jar:0.4.9:runtime
[INFO] |  |  |  \- io.reactivex:rxnetty:jar:0.4.9:runtime
[INFO] |  |  +- com.netflix.ribbon:ribbon-core:jar:2.1.0:compile
[INFO] |  |  +- com.netflix.ribbon:ribbon-httpclient:jar:2.1.0:compile
[INFO] |  |  |  \- com.netflix.netflix-commons:netflix-commons-util:jar:0.1.1:runtime
[INFO] |  |  +- com.netflix.ribbon:ribbon-loadbalancer:jar:2.1.0:compile
[INFO] |  |  |  \- com.netflix.netflix-commons:netflix-statistics:jar:0.1.1:runtime
[INFO] |  |  \- io.reactivex:rxjava:jar:1.0.14:compile
[INFO] |  \- com.netflix.ribbon:ribbon-eureka:jar:2.1.0:compile
[INFO] |     \- com.netflix.eureka:eureka2-client-shaded:jar:2.0.0-rc.2:runtime
[INFO] |        +- io.netty:netty-codec-http:jar:4.0.25.Final:runtime
[INFO] |        |  +- io.netty:netty-codec:jar:4.0.25.Final:runtime
[INFO] |        |  \- io.netty:netty-handler:jar:4.0.25.Final:runtime
[INFO] |        \- io.netty:netty-transport-native-epoll:jar:4.0.25.Final:runtime
[INFO] |           +- io.netty:netty-common:jar:4.0.25.Final:runtime
[INFO] |           +- io.netty:netty-buffer:jar:4.0.25.Final:runtime
[INFO] |           \- io.netty:netty-transport:jar:4.0.25.Final:runtime
[INFO] +- org.springframework.cloud:spring-cloud-config-client:jar:1.1.0.M1:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.6.1:compile
[INFO] +- org.springframework.cloud:spring-cloud-netflix-core:jar:1.1.0.M1:compile
[INFO] +- org.springframework.cloud:spring-cloud-starter-hystrix:jar:1.1.0.M1:compile
[INFO] |  +- com.netflix.hystrix:hystrix-core:jar:1.4.13:compile
[INFO] |  +- com.netflix.hystrix:hystrix-metrics-event-stream:jar:1.4.13:compile
[INFO] |  \- com.netflix.hystrix:hystrix-javanica:jar:1.4.13:compile
[INFO] |     \- com.google.code.findbugs:jsr305:jar:2.0.0:runtime
[INFO] +- org.springframework.cloud:spring-cloud-starter-bus-amqp:jar:1.1.0.M1:compile
[INFO] |  +- org.springframework.cloud:spring-cloud-bus:jar:1.1.0.M1:compile
[INFO] |  +- org.springframework.integration:spring-integration-java-dsl:jar:1.0.0.RELEASE:compile
[INFO] |  |  \- org.springframework.integration:spring-integration-core:jar:4.2.0.RELEASE:compile
[INFO] |  |     \- org.springframework.retry:spring-retry:jar:1.1.2.RELEASE:compile
[INFO] |  +- org.springframework.integration:spring-integration-amqp:jar:4.2.0.RELEASE:compile
[INFO] |  |  \- org.springframework.amqp:spring-rabbit:jar:1.5.0.RC1:compile
[INFO] |  |     +- org.springframework.amqp:spring-amqp:jar:1.5.0.RC1:compile
[INFO] |  |     +- com.rabbitmq:amqp-client:jar:3.5.4:compile
[INFO] |  |     \- com.rabbitmq:http-client:jar:1.0.0.RELEASE:compile
[INFO] |  \- org.springframework.integration:spring-integration-event:jar:4.2.0.RELEASE:compile
[INFO] +- org.springframework.cloud:spring-cloud-netflix-hystrix-amqp:jar:1.1.0.M1:compile
[INFO] |  \- org.springframework.boot:spring-boot-starter-amqp:jar:1.3.0.M5:compile
[INFO] |     \- org.springframework:spring-messaging:jar:4.2.1.RELEASE:compile
[INFO] +- org.springframework.session:spring-session:jar:1.0.2.RELEASE:compile
[INFO] +- org.springframework.session:spring-session-data-redis:pom:1.0.2.RELEASE:compile
[INFO] |  \- org.apache.commons:commons-pool2:jar:2.4.2:compile
[INFO] +- org.springframework.boot:spring-boot-starter-redis:jar:1.3.0.M5:compile
[INFO] +- org.jolokia:jolokia-core:jar:1.3.1:compile
[INFO] +- com.thoughtworks.xstream:xstream:jar:1.4.7:compile
[INFO] |  +- xmlpull:xmlpull:jar:1.1.3.1:compile
[INFO] |  \- xpp3:xpp3_min:jar:1.1.4c:compile
[INFO] +- org.springframework:spring-oxm:jar:4.2.1.RELEASE:compile
[INFO] +- org.apache.commons:commons-lang3:jar:3.2.1:compile
[INFO] +- com.google.maps:google-maps-services:jar:0.1.7:compile
[INFO] |  +- com.google.code.gson:gson:jar:2.3.1:compile
[INFO] |  +- com.squareup.okhttp:okhttp:jar:2.0.0:compile
[INFO] |  |  \- com.squareup.okio:okio:jar:1.0.0:compile
[INFO] |  \- joda-time:joda-time:jar:2.8.2:compile
[INFO] +- com.mangofactory:swagger-springmvc:jar:0.8.8:compile
[INFO] |  +- com.wordnik:swagger-core_2.10:jar:1.3.5:compile
[INFO] |  |  +- commons-lang:commons-lang:jar:2.4:compile
[INFO] |  |  +- com.fasterxml.jackson.module:jackson-module-scala_2.10:jar:2.1.5:compile
[INFO] |  |  |  +- org.scala-lang:scala-library:jar:2.10.0:compile
[INFO] |  |  |  +- com.thoughtworks.paranamer:paranamer:jar:2.3:compile
[INFO] |  |  |  \- org.scala-lang:scala-reflect:jar:2.10.0:compile
[INFO] |  |  +- com.fasterxml.jackson.module:jackson-module-jsonSchema:jar:2.1.0:compile
[INFO] |  |  +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar:2.0.0:compile
[INFO] |  |  |  \- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.0.0:compile
[INFO] |  |  +- com.wordnik:swagger-annotations:jar:1.3.5:compile
[INFO] |  |  +- org.json4s:json4s-ext_2.10:jar:3.2.5:compile
[INFO] |  |  |  \- org.joda:joda-convert:jar:1.2:compile
[INFO] |  |  +- org.json4s:json4s-native_2.10:jar:3.2.5:compile
[INFO] |  |  |  \- org.json4s:json4s-core_2.10:jar:3.2.5:compile
[INFO] |  |  |     +- org.json4s:json4s-ast_2.10:jar:3.2.5:compile
[INFO] |  |  |     \- org.scala-lang:scalap:jar:2.10.0:compile
[INFO] |  |  |        \- org.scala-lang:scala-compiler:jar:2.10.0:compile
[INFO] |  |  \- org.json4s:json4s-jackson_2.10:jar:3.2.5:compile
[INFO] |  +- cglib:cglib:jar:2.2:compile
[INFO] |  |  \- asm:asm:jar:3.1:compile
[INFO] |  +- com.google.guava:guava:jar:18.0:compile
[INFO] |  +- com.mangofactory.swagger:swagger-models:jar:0.8.8:compile
[INFO] |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:provided
[INFO] +- javax.servlet.jsp:jsp-api:jar:2.2.1-b03:provided
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] +- com.jayway.jsonpath:json-path:jar:2.0.0:runtime
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.12:compile
[INFO] |  \- net.minidev:json-smart:jar:2.1.1:runtime
[INFO] |     \- net.minidev:asm:jar:1.0.2:runtime
[INFO] +- org.projectlombok:lombok:jar:1.16.6:compile
[INFO] +- com.netflix.eureka:eureka-client:jar:1.2.0:compile
[INFO] |  +- org.codehaus.jettison:jettison:jar:1.3.7:runtime
[INFO] |  |  \- stax:stax-api:jar:1.0.1:runtime
[INFO] |  +- com.netflix.netflix-commons:netflix-eventbus:jar:0.1.2:runtime
[INFO] |  |  +- org.apache.commons:commons-math:jar:2.2:runtime
[INFO] |  |  \- com.netflix.netflix-commons:netflix-infix:jar:0.1.2:runtime
[INFO] |  |     +- commons-jxpath:commons-jxpath:jar:1.3:runtime
[INFO] |  |     \- org.antlr:antlr-runtime:jar:3.4:runtime
[INFO] |  |        +- org.antlr:stringtemplate:jar:3.2.1:runtime
[INFO] |  |        \- antlr:antlr:jar:2.7.7:runtime
[INFO] |  +- com.netflix.archaius:archaius-core:jar:0.6.5:runtime
[INFO] |  |  +- commons-configuration:commons-configuration:jar:1.8:runtime
[INFO] |  |  \- com.google.code.findbugs:annotations:jar:2.0.0:runtime
[INFO] |  +- javax.ws.rs:jsr311-api:jar:1.1.1:compile
[INFO] |  +- com.netflix.servo:servo-core:jar:0.9.4:runtime
[INFO] |  |  \- com.netflix.servo:servo-internal:jar:0.9.4:runtime
[INFO] |  +- com.sun.jersey:jersey-core:jar:1.13:runtime
[INFO] |  +- com.sun.jersey:jersey-client:jar:1.13:runtime
[INFO] |  +- com.sun.jersey.contribs:jersey-apache-client4:jar:1.11:runtime
[INFO] |  +- com.google.inject:guice:jar:4.0:runtime
[INFO] |  |  \- javax.inject:javax.inject:jar:1:runtime
[INFO] |  \- com.netflix.governator:governator-annotations:jar:1.7.5:runtime
[INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.3.0.M5:test
[INFO] |  +- junit:junit:jar:4.12:compile
[INFO] |  +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] |  \- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] +- com.github.fakemongo:fongo:jar:1.5.7:compile
[INFO] |  +- com.github.davidmoten:geo:jar:0.6.6:compile
[INFO] |  +- rhino:js:jar:1.7R2:compile
[INFO] |  \- com.vividsolutions:jts:jar:1.13:compile
[INFO] +- org.mockito:mockito-core:jar:1.9.5:test
[INFO] |  \- org.objenesis:objenesis:jar:2.1:test
[INFO] +- org.powermock:powermock-easymock-release-full:jar:full:1.5.5:test
[INFO] |  +- org.powermock:powermock-core:jar:1.5.5:test
[INFO] |  |  \- org.javassist:javassist:jar:3.18.1-GA:test
[INFO] |  +- org.powermock:powermock-api-easymock:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4-common:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4-legacy:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit3:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-reflect:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-api-support:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-testng:jar:1.5.5:test
[INFO] |  |  \- org.testng:testng:jar:6.8.8:test
[INFO] |  |     +- org.beanshell:bsh:jar:2.0b4:test
[INFO] |  |     \- com.beust:jcommander:jar:1.27:test
[INFO] |  +- org.powermock:powermock-module-testng-common:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-classloading-base:jar:1.5.5:test
[INFO] |  +- org.powermock:powermock-core:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-api-easymock:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4-common:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit4-legacy:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-junit3:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-module-testng:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-reflect:jar:sources:1.5.5:test
[INFO] |  +- org.powermock:powermock-api-support:jar:sources:1.5.5:test
[INFO] |  \- org.powermock:powermock-classloading-base:jar:sources:1.5.5:test
[INFO] +- org.easymock:easymock:jar:3.2:test
[INFO] |  \- cglib:cglib-nodep:jar:3.1:test
[INFO] \- org.springframework:spring-test:jar:4.2.1.RELEASE:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

A: You have a mixture of Spring 4.2.1.RELEASE and 4.1.7.RELEASE on the classpath. You need the former rather than the latter. Specifically, you have the wrong version of spring-core on the classpath:
[INFO] |  +- org.springframework:spring-core:jar:4.1.7.RELEASE:compile

I would guess you have a dependency on spring-core with an explicit version declared on it. If you remove the <version>, the dependency management provided by spring-cloud-starter-parent will give you the right version (4.2.1.RELEASE).


text:
Q: setState for an array of objects in handleChange is not working I au using elasticsearch to do searching in my view (ReactJs). I created a function handleChange to change the state of the data in the table according to what I am searching.
so I did this so far in my code :
var esClient = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'info'
});

class MesExtraits extends Component {

  constructor() {
    super();
    this.state = {
      MP3info: [],
      searchText: '',
    }
  }

  updateSearch = (evt) => {
    this.setState({ searchText: evt.target.value, });
    var searchQ = evt.target.value;
    var search_queryES = "titre:" + searchQ + "*"

    esClient.search({
      q: search_queryES
    }).then(function (body) {
      this.setState({ MP3info: body.hits.hits.map(i => i._source) })

      console.log(this.state.MP3info)

      console.log(body.hits.hits.map(i => i._source))

    }.bind(this), function (error) {
      console.trace(error.message);
    });
  };

  render() {

    const { MP3info } = this.state;
    return (

        <SearchBox styleName="gx-d-none gx-d-lg-block gx-lt-icon-search-bar-lg"
          placeholder="Search in app..."
          onChange={this.updateSearch.bind(this)}
          value={this.state.searchText}
        />
        <Paper className={classes.root}>

            <TableHead>
              <TableRow>
                <TableCell><IntlMessages id="MP3.titre" /></TableCell>
                <TableCell align="left"><IntlMessages id="MP3.descfiption" /></TableCell>
                <TableCell align="left"><IntlMessages id="MP3.langue" /></TableCell>
                <TableCell align="left"><IntlMessages id="MP3.stats" /></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {MP3info.map(row => (
                <TableRow key={row.titre}>
                  <TableCell component="th" scope="row">
                    {row.titre}
                  </TableCell>
                  <TableCell align="left">{row.description}</TableCell>
                  <TableCell align="left">{row.langue}</TableCell>
                  <TableCell align="left">   </TableCell>
                </TableRow>
              ))}
            </TableBody>

        </Paper>

    );
  }
}

The problem is when I console.log(this.state.MP3info) after setState for MP3info it is not changing.
Any help would be appreciated.

A: setState is asynchronous.
so it will work like this:
this.setState({ MP3info: body.hits.hits.map(i => i._source) }, () => {
    console.log(this.state.MP3info)
})

from documentation:

setState() does not always immediately update the component. It may
  batch or defer the update until later. This makes reading this.state
  right after calling setState() a potential pitfall. Instead, use
  componentDidUpdate or a setState callback (setState(updater,
  callback)), either of which are guaranteed to fire after the update
  has been applied.

A: After calling setState, you cannot expect the state to be updated immediately since setState is an asynchronous operation.
However, there is an optional 2nd parameter of a callback function which you can use in setState, if you want to do something immediately after updating the state.
this.setState({
        value: newStateValue,
    }, () => {
     const { value } = this.state; // access the updated value here
    })

Please follow this beautiful explanation of how setState works! link
Also:
When not to use the callback:
React docs recommend that you use the lifecycle events.
Here's why.
PureComponent and shouldComponentUpdate can be used to tune up a component's performance. They work by preventing lifecycle methods from firing when props and state haven't changed.

The setState callback fires regardless of what shouldComponentUpdate returns. So, the setState callback will fire, even when state hasn't changed.

So.. Don't be afraid to use the setState callback. It's there for a reason. But when you do, keep an eye on shouldComponentUpdate, if you see any shiftiness.


text:
Q: the inverse function with 2 variables $f(x,y)=(x+y+1,x-y-1)$. Find the inverse of $f$.
$f^{-1}(x+y+1,x-y-1)=(x,y).$
Let $u=x+y+1$ and $v=x-y-1.$
Here, without $1$ and $-1$, I can invert this:
$$\begin{bmatrix}1&1\\1&-1\end{bmatrix}^{-1}=\frac 1{-2}\begin{bmatrix}-1&-1\\-1&1\end{bmatrix}.$$
Then, $f^{-1}(x,y)=(\frac{x+y}{2},\frac{x-y}{2}).$ But, I don't know how to deal with $1$ and $-1$. I appreciate any hint.

A: We have that
$$f(x,y)=\begin{bmatrix}f_1\\f_2\end{bmatrix}=\begin{bmatrix}1&1\\1&-1\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}+\begin{bmatrix}1\\-1\end{bmatrix}$$
then
$$\begin{bmatrix}1&1\\1&-1\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}=\begin{bmatrix}f_1\\f_2\end{bmatrix}-\begin{bmatrix}1\\-1\end{bmatrix}$$
and thus
$$\begin{bmatrix}x\\y\end{bmatrix}=\begin{bmatrix}1&1\\1&-1\end{bmatrix}^{-1}\begin{bmatrix}f_1\\f_2\end{bmatrix}-\begin{bmatrix}1&1\\1&-1\end{bmatrix}^{-1}\begin{bmatrix}1\\-1\end{bmatrix}$$


text:
Q: How To Use Module Exports Properly In JavaScript I just started learning JS and when i try to export a simple function inside a file called function_module.js using this code
module.exports.squareFunction = function(nb){
return nb * nb ;
}

in other file in the same directory i tried to import the function using this code
const importedfun = require('./function_module.js');
console.log(importedfun(5));

i got this error
JavaScript\CodeAcademy\module\test_module.js:2
console.log(importedfun(5));
        ^

TypeError: importedfun is not a function
at Object.<anonymous>

can anyone tell me what is my fault ?

A: By doing module.exports.squareFunction, you create a named export using commonjs syntax. You can either require it in another module using brackets {nameOfYourExportedFunction} or do a default export instead.
Named export
module.exports.squareFunction = function(nb){
    return nb * nb ;
}

//////

// Notice the brackets wrapping the function
const {squareFunction} = require('./function_module.js');
console.log(squareFunction(5));

Default export
module.exports = function(nb){
    return nb * nb ;
}

//////

// You can name it however you want since it will refer to the default export
const importedFun = require('./function_module.js');
console.log(importedfun(5));


text:
Q: Preventing memory leaks when using instantiateViewController I am new to ios development so please forgive the ignorance. I noticed that when I'm using the UICollectionViewCell I am able to call dequeueReusableCell to either instantiate or call an existing cell. I was wondering if there is something similar for view controllers. Or if not what would be the right way to prevent re-instantiation of view controllers unnecessarily while navigating around in an app?

A: I think you mean something like ARC (automatic reference counter) which in swift takes control of deallocating every useless part in your app, to reuse memory. You should not bother on this one, because this is fully automatic, for ex. if your vc has been instantiated, and you've moved to another vc arc will deallocate that first vc because there aren't any references to it, and only problem would be if you mistekenly made a connection (reference) to that first vc from some (mostly) closure in your app, then ARC wouldn't remove that vc from memory because connection is still there and ARC knows about it - then you have leaks, and the handy tools to check if every part of your app ui is deallocated correctly are Instruments provided by Apple.

A: Table and collection cells reuse their views because users often scroll through many items very quickly and tearing down and reallocating memory for each item isn't efficient enough for that to perform well.  The same is not true of view controllers, so this mechanism isn't needed for them.
Having more than one instance of a view controller is fine; it's not a memory leak.

A: If you're using navigationController e.g. the iPhone has Settings >> General >> About.
When you are in Settings, there is no GeneralVC loaded. When you go to general then you now have SettingVC & GeneralVC but no AboutVC. If you go to About and then come back to General then AboutVC is completely deallocated.
For navigationControllers every time you load a viewController the viewDidLoad will get called.

For tabBarControllers, like your Phone App, all the tabs (Favorites, Recents, Contacts, Keypad, Voicemail) are always in the memory. They won't get deallocated. If you are on KeypadVC, then all other VCs are still in the memory.
For tabBarControllers every time you load a viewController the viewWillAppear will get called. The viewDidLoad will get called on the first time it's loaded.
So depending on what you're doing (tabBarController or navigationcontroller) the viewController may or may not exist after you move away from it.
Additionally I find this comment thread and the question related. The question is a bit old yet it helps you better understand some of the older answers and this very question of yours.


text:
Q: Посоветуйте, пожалуйста, дорожную карту для разработчика Java? Я учусь на втором курсе универститета. Изучаю C# и Python в университетской программе. Всё ограничивается лишь проектиками на понимание алгоритмов и структур данных. Это, конечно, очень полезно. Однако я хочу параллельно развиваться в стеке Java потому, что этот язык популярен в моём регионе и интересен лично мне. Также к окончанию университета или при учёбе в старших курсах уже хочу с имеющимся стеком знаний и портфолио устроиться на достойную должность Java-разработчика. Сейчас начал изучать язык программирования Java, выучил основы. Дальше хочу интенсивно двигаться вглубь этого направления.
Пожалуйста, опытные разработчики, посоветуйте мне ту дорожную карту, которая помогла вам или которая, на ваш взгляд, подходящая для неопытного разработчика.
Хочу специализироваться на разработке программ для ПК. Спасибо.

A: Java core, Герберт Шилдт java для начинающих,
Многопоточность,
(swing, javaFX) - десктоп UI, щас все переходит на веб не думаю что стоит затягивать, познакомиться и знать как работает.
DAO pattern,
SQL,
Servlets and JSP(щас есть ему замена themyleaf),
Hibernate,
Spring,
MVC - паттерн, так же поймёшь что нужно html + css + js а дальше куча веб фреймворков в разных компаниях используются разные фреймы.
Я по такому принципу учусь
Чекни в комментариях ссылку.

A: Вроде бы, довольно таки легко это "гуглится":

Изображение взято из статьи: https://dzone.com/articles/the-2019-java-developer-roadmap


text:
Q: What does it mean when "virtual" is in "class Foo : public virtual Bar" as opposed to "virtual void frob()"? I understand virtual in the context of a member function, like virtual void frob(). But what does it mean in the context of the class declaration, like class Foo : public virtual Bar?
For a given method there are 8 cases stemming from the presence or absence of virtual in the following three locations: 1) a superclass's functions; 2) the inheritance chain for this class; 3) this class's functions.
I think I understand how 1) and 3) interact, but 2) seems redundant. Is it? What am I not understanding?

A: That's virtual inheritance, you do it when you know you'll be doing multiple inheritance. That page goes into way more detail.


text:
Q: Can I play without a DVD Drive? I bought GTA IV - EFLC today.
I have got 2 DVDs and CD-Key. (also a printed map and manual. I like it.)
What I don't have yet is a DVD Drive on my Gaming Rig.
Any Ideas on how to run it?
Can I make iso files of the DVDs from my laptop and use them.
Did anyone try this? Did it work?
Does shared network drive work?
http://www.howtogeek.com/114254/how-to-share-cd-dvd-drives-over-the-network-on-windows/

A: You need to have the the game's DVD-ROM in a DVD drive attached to your laptop. The PC version of GTA IV uses a disk check as part of its copy protection. There's no way around this without defeating this copy protection measure, something we can't help you with here.
Connecting a USB DVD drive to your PC should allow you to play the game. Alternatively the Steam version of GTA IV doesn't require a disk in the drive, but that would be mean buying a second copy of the game.

A: Since March 19, 2020 all of the Retail game copies can be activated on Steam or the Rockstar Games Social Club to activate Grand Theft Auto IV: Complete Edition. From the Steam Page:

Games not previously activated using Games for Windows Live will be able to use the Key on the back of the game manual to activate and update to Grand Theft Auto IV: Complete Edition

Activating the Retail copy of Episodes from Liberty City on Steam or the RGL will automatically give you GTA IV and vice versa for free.


text:
Q: Why applying seq on a LazySeq returns ChunkedCons? (class (range 10))
;=> clojure.lang.LazySeq

(class (seq (range 10))
;=> clojure.lang.ChunkedCons

From my understanding, LazySeq is already an sequence, since:
(seq? (range 10))
;=> true

A: I guess I have an answer.
That's because using seq enforces the evaluation of the first element of LazySeq. Because seq returns nil when the collection & sequence is empty, it has to eval the element to decide that.
That's the exactly reason why rest is lazier than next, because (next s) is just (seq (rest s)).

A: To expand upon your answer (and because comments don't support new lines):
user=> (def r (range 10))
#'user/r
user=> (realized? r)
false
user=> (class r)
clojure.lang.LazySeq
user=> (def r2 (rest r))
#'user/r2
user=> (realized? r2)
ClassCastException clojure.lang.ChunkedCons cannot be cast to clojure.lang.IPending  clojure.core/realized? (core.clj:6607)
user=> (class r2)
clojure.lang.ChunkedCons
user=> (realized? r)
true


text:
Q: How to use a java socket in tapestry5? How do I implement a java socket in tapestry5?
What I want to do is create a socket which I can send an XmlHttpRequest over, through a piece of javascript code.
function sendPost(url, postdata, callback) {

 xmlHttp=GetXmlHttpObject()

 if (xmlHttp==null) {
  alert ("Browser does not support HTTP Request")
  return
 }

 xmlHttp.onreadystatechange=callback
 xmlHttp.open("POST",url,true)
 xmlHttp.send(postdata);

}

Where the URL is the socket i have just created.

A: So you want to do an AJAX request from your client code to the server, recieve a response and process it in some way? You will not need sockets. Instead, use Tapestry's built-in AJAX functionality.
If you're loading additional content inside your page via Javascript, chances are you will not need to write any code at all. Be sure you have read the AJAX section from the Tapestry docs, and you understand what a Zone is and how it works.
Here's a basic example. Template:

      ... [Initial content, if any] ...

Update

And class:
@Inject
private Zone myZone;

@Inject
private Request request;

@OnEvent(component = "updateContent")
Object updateContent() {
     ... [your code] ....

     if (this.request.isXHR()) {
         return this.myZone.getBody();
     } else {
         return this;
     }
}

Tapestry will do everything else, like registering the proper event listener on the link and inserting the updated content in the proper place. The if (this.request.isXHR()) makes sure your page will degrade gracefully for clients without JavaScript enabled.
If you'd like to do something else entirely, like returning a JSON object and processing it with your own JavaScript code, you can return any of these JSON classes from your event handler.
Also, if you want to write your own client-side code, be sure to use the built-in, cross-browser AJAX functionality of Prototype, which ships with Tapestry.
Edit based on comment:
You won't be able to access a different server (host + port) through AJAX because of the same origin policy. You could, however, proxy the call through your Tapestry app. I've modified my code to illustrate this (assuming the thing listening on port 2112 is an HTTP server, otherwise change as needed):
@OnEvent(component = "updateContent")
Object updateContent() throws IOException {
     final URL url = new URL("http://localhost:2112");
     final HttpURLConnection con = url.openConnection();

     final String content;

     InputSteam input = null;
     try {
         input = con.getInputStream();
         content = IOUtils.toString(input);
     } finally {
         IOUtils.closeQuietly(input);
     }

     return new StreamResponse() {
         @Override
         public String getContentType() {
             return "text/javascript";
         }

         @Override
         public InputStream getStream() throws IOException {
             return new ByteArrayInputStream(content.getBytes("UTF-8"));
         }

         @Override
         public void prepareResponse(Response response) {
             response.setHeader("Expires", "0");
             response.setHeader("Cache-Control",
                 "must-revalidate, post-check=0, pre-check=0");
         }
     }
}

A: Use of Sockets is independent of your webapp view framework - you would do it pretty much the same way regardless of how the view is coded. The only thing that changes is once you've implemented your code that uses sockets, is how that's invoked.
I used tapestry with spring, and so injecting services into the spring context is the most natural approach.
The services subpackage in tapestry is mostly for creating implementations that plug into tapestry, like encoders, property conduits, and binding factories.  So whether you use this or not depends upon what you are trying to achieve.
For example, if you are creating a component that reads from a socket, and renders the data read in, then you can create that as a regular component, in the components subpackage.

A: The XmlHttpRequest will just do a web server request which can be handled perfectly well by whatever you use to run Tapestry in. There is no need to open sockets and stuff.
Just define a route in your wep application to accept the XmlHttpRequest and have a handler, servlet, controller, ... collect the necessary data, transform it to xml and send it to the Javascript component.
I found an example here


text:
Q: Rendering view via AJAX I'm trying to do an infinite scroll i.e., when a user gets to the bottom of a page more content loads. I make an ajax call and then on the backend I'm trying to render the new view and return that view so then on the frontend I can append it to the existing DOM. However when I console.log(rendered) in the backend I'm getting undefined, and I'm also getting the error "Callback was already called." Specifically I'm using Express on the backend with the frontend views built in dust which is a similar to Jade etc.
router.get('/get_more_content', function(req, res) {
    ... (db parsing logic - this part works fine) ...
    rendered = res.render('galleries');
    return res.status(200).send({ rendered: rendered });
})

A: You are getting this error because res.render ends the connection unless you specify callback argument.
You can access html using this snippet:
res.render('galleries', function(err, html) {
  res.status(200).send({ rendered: html });
});

For more information please refer to http://expressjs.com/en/api.html#res.render


text:
Q: Using the int type in the printf function does not add the same value as the float type When I use the following code, the output result is 0 when adding the sum in the printf function, but when I add the printf function it should be printf("test: %d", c/ 2);The output is 1,
Why?
int main() {
    float a = 1.5;
    int b = 2;
    int c = a + b;
    printf("test: %d", (a+b)/ 2);
}

A: Since you assign the result of a + b to an int variable, its result will be truncated.
So while the result of 1.5 + 2 is 3.5, the result assigned to c will be the integer 3.
And since both c and 2 are int values the result of c / 2 will be an int which will be truncated. So the result of 3 / 2 will simply be 1.

With the edit and the new print:
printf("test: %d", (a+b)/ 2);

Because one of the values involved in the expression a + b if a float, the result will be a float. And because of that the result of the division will also be a float.
The result of (a + b) / 2 will be a float. But since it's passed as an argument to a variable-argument function like printf it will be promoted to a double. So your statement is essentially equivalent to:
printf("test: %d", (double)((a+b)/ 2));

Now for the big problem: The %d format specifier expects an int value. Mismatching format specifier and argument type leads to undefined behavior.


text:
Q: When I pass to another radio button both buton's values come I want to do two radio buttons. Their names will be car and home. If I click car, an input box about the car section will be shown and if I click home, an input box about the home will be shown.
I have found an example about this and I have a problem about it. The codes are below.

<form name="theForm">
    Type

    <input type="radio" name="married" value="yes" onclick="return toggleMe(this, 'Car')"> Car
    <input type="radio" name="married" value="yes" onclick="return toggleMe(this, 'Home')"> Home

                Car InputBox
                <input name="name" type="text">

                Home InputBox:
                <input name="name" type="text">

</form>

Output of these codes
If I click the car first, the input box of the car section is shown. If I click the home first, the input box of the home section is shown. After I click the car or home first (doesn't matter) if I click another one, both input boxes are shown.
How can I solve this problem? When I click home, the home input box should be shown and when I click car, the car input box should be shown as well. Not both of them.

A: What about this? Using jquery it's easier. I made it universal, so you could add more radio buttons (using myradio and myinput css classes) without touching the JS.

$( "input.myradio" ).click(function() {
    $( "div.myinput").hide();
    $( "div#"+$(this).attr('id')).toggle( "slow", function() {
    // Animation complete.
    });
});

<form name="theForm">
    Type

    <input id="Car" type="radio" name="married" class="myradio" value="yes" />Car
    <input id="Home" type="radio" name="married" class="myradio" value="yes" />Home

                Car InputBox
                <input name="name" type="text">

                Home InputBox:
                <input name="name" type="text">

</form>

JSFiddle

A: HTML

    <input type="radio" name="option" value="car" onclick="toggleInput(this)" /> Car

    <input type="radio" name="option" value="home" onclick="toggleInput(this)" /> Home

    Car InputBox
    <input name="name" type="text" />

    Home InputBox
    <input name="name" type="text" />

Javascript
function toggleInput(obj){
    var a =document.getElementsByClassName("hide");
    for(var i=0; i<a.length; i++){
      a[i].style.display = "none";
    }
    document.getElementById(obj.value + "-input-group").style.display = "block"
}

css
.hide{
    display: none
}

Working example: http://plnkr.co/edit/wPdTldCXG0LTJWEtzIxE?p=preview


text:
Q: update sqlite columns based on other columns information I am trying to use information from a sqlite db and update another columns with some conditions using Python 3.6
python 3.6 and sqlite
def open_days(signed_date,completed_date):
    fmt = '%Y-%m-%d'
    if completed_date == '':
        if signed_date:
            sdate = datetime.strptime(signed_date, fmt)
            tdate = datetime.now()
            delta = str((tdate - sdate).days)

            return delta

    else:
        sdate = datetime.strptime(signed_date, fmt)
        cdate = datetime.strptime(completed_date, fmt)
        delta = str((cdate - sdate).days)

        return delta

conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute("SELECT * FROM data_table")
for row in cur:
    cur.execute("UPDATE data_table SET days_open=? WHERE numid=?", (open_days(row[1],row[2]),row[0]))
    cur.fetchall()

cur.close()
conn.commit()

I am expecting the result to be:
numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,32
3456,2019-04-29,2019-05-13,14
4567,,,None

the value are not udpated with the correct value if the number of days is set manually
numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,16
3456,2019-04-29,2019-05-13,16
4567,,,16

Note that it can be that no signed date and no completed date is already register into the db as per example showing some blank space between coma.
if signed date and completed date are registered then the number of day is the difference between completed date and signed date
if only signed date is registered then number of day is the difference between today's date and signed date
if no signed date then number of day is None

A: I have found a way to update the rows:
conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()

for row in cur.execute('SELECT signed_date, completed_date, open_days(signed_date,completed_date) FROM data_table'):
    cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()

change to as per Sam input:
conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()
cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()


text:
Q: What is this design pattern used in Enumerator.? I've seen this pattern in Enumerator. It makes sure the collection haven't been altered while enumerating over the items.
public class Versioned
{
    internal int version = 0;

    public void ThisBreaksVersion()
    {
        version++;
    }
}

public class WorksOnVersioned
{
    private readonly int version;
    private readonly Versioned versioned;

    public WorksOnVersioned(Versioned versioned)
    {
        this.versioned = versioned;
        this.version = versioned.version;
    }

    public void DoWork()
    {
        if( version != other.version )
            throw new Exception(); // Ooop.. Out of sync!
    }
}

var v1 = new Versioned();
var w1 = WorksOnVersioned(v1);
w1.DoWork(); // Yup

var v2 = new Versioned();
var w2 = WorksOnVersioned(v2);
v2.ThisBreaksVersion();
w2.DoWork(); // v2 has changed -> exception!

I can also see this is useful when using a shared resource to make sure the local copy is the same as the one in the resource.
But what is this pattern called? Is there something else it can be useful for?

A: I don't know of any named pattern for this - you might call it "version snapshotting" or something like that, where the important part is that you don't need to snapshot the whole of the mutable data if all you're interested in is knowing whether or not it's changed. (i.e. a snapshot simply becomes invalid, rather than remaining unchanged in the face of changes to the original.)


text:
Q: Optidef Environment I am using the optidef package in writing optimization problems. For example, I am using the following formulation:
\documentclass{ieeeaccess}
\usepackage{cite}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{textcomp}
\newcommand{\mbf}[1]{\boldsymbol{#1}}
\usepackage{afterpage}
\usepackage{verbatim}
\usepackage{psfrag}
\usepackage{times}
\usepackage{wrapfig}
\usepackage{multirow}
\usepackage{setspace}
\usepackage{epsfig}
\usepackage{epstopdf}
\usepackage{footmisc}
\usepackage{fmtcount}
\usepackage{stackrel}
\usepackage{float}
\usepackage{breqn}
\usepackage{enumerate}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{hypcap}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}
\usepackage[normalem]{ulem}
\usepackage{authblk}
\usepackage{array}
\usepackage{tabularx}
\usepackage{bbm}
\usepackage{array}
\usepackage{mathtools}
\usepackage[short]{optidef}
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\makeatletter
\newcommand\semiHuge{\@setfontsize\semiHuge{23}{28}}
\makeatother
\usepackage{indentfirst}
\newcommand{\red}[1]{\textcolor{red}{#1}}
\newcommand{\blue}[1]{\textcolor{blue}{#1}}
\newcommand{\green}[1]{\textcolor{green}{#1}}
\DeclareMathOperator*{\E}{\mathbb{E}}
\DeclareMathOperator*{\1}{\mathbbmss{1}}
\renewcommand{\vec}[1]{\boldsymbol{#1}}

\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\begin{document}

     \begin{mini!}
            {\boldsymbol{w},\boldsymbol{\Phi}}    {\| \boldsymbol{w}\|^2 }
            {\label{eq:minp}}{}
            \addConstraint{|(\boldsymbol{h}_r^H \boldsymbol{\Theta} \boldsymbol{G} + \boldsymbol{h}_d^H)\boldsymbol{w}| \geq \gamma \sigma^2} \label{eq:snd}
            \addConstraint{\Phi_n \in \mathcal{F}, \forall n}\label{eq:pha}
        \end{mini!}
\end{document}

and I am getting this:

My question is how to make the word "min" or "max"  not in italic mode?


text:
Q: css file can't be loaded with spring boot following is my file dir tree, and html files is in src/main/webapp/templates, have added src/main/webapp into classpath.
src──main
     ├─java
     │  └─com
     │      └─ma2oo
     │          └─quizbox
     │              ├─application
     │              ├─config
     │              └─controllers
     ├─resources
     └─webapp
         ├─static
         │  ├─css
         │  └─js
         └─templates

The web config file is:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("reached here ");
        registry.addResourceHandler("/resources/**").addResourceLocations("/static/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }
}

And the ref link in html is:
  <link href="/static/css/components.css" rel="stylesheet"></link>

When web server is running, I can't get the expected result from browser, it's just same with there is no css existed.
Could anyone help with it please?
Thanks in advance.

A: Since you are using Spring Boot, it is not the best idea to have the resources in under webapp. See this part of this official Spring Boot documentation
I propose you move all the static content you now have under /webapp to /resources and also get rid of the addResourceHandlers configuration method since Spring boot will automatically map the static content correctly.
Then for example you would have <link href="css/components.css" rel="stylesheet"></link>
For a sample spring boot project that uses static content, check out this.

A: If you have annotated your controller class, or one of your methods in your controller class, with @RequestMapping("/") remove the annotation and try it.

A: The URL you're using to reference the CSS file does not match the path pattern you registered in your resource handler. You need to use a link such as the following instead:
<link href="/resources/css/components.css" rel="stylesheet"></link>
(Note that by default Spring Boot registers a handler for resources in the webapp root. However, by using the @EnableWebMvc annotation, you are overriding that default behavior. If you remove that annotation, then your existing HTML link would work as is.)


text:
Q: Get Portion of String I need to get the values after "Swap:".

I've already developed a method to get the output from a shell command so I have a string that contains everything you see in the picture but now from the string I want to get ONLY the value after the Swap: How can i do this? These value are variable and can be even all three 0.

A: Let's say you have the text stored in a String called textContent. Assuming the Swap-line is the last part of your String, then you could do something like this:
int index = textContent.indexOf("Swap:");

index += "Swap:".length();
textContent.subString(index);

A: Try this:
String[] stringParts = text.substring(text.indexOf("Swap:") + 5).trim().split("( )+");

int[] parts = new int[stringParts.length];
for (int i = 0; i < stringParts.length; i++)
    parts[i] = Integer.parseInt(stringParts[i]);

It will fill an integer array will the values after the "Swap" part.

A: Since you have already stored the output of the shell command, you simply need to do some string manipulation to search and extract the relevant information. The following particular string manipulation methods might be of interest to you: trim(), indexOf(), and substring().
Below is a simple example code on how to extract the value under the total's column using the above String methods:
public class ShellOutput {

    public ShellOutput() {
        final String extract = "Swap:"; // the keyword to search

        String shellOutput = "Swap:          75692        29657              0"; // your shell output
        int position = shellOutput.indexOf(extract); // get the position of the Swap: text
        if (position != -1) {
            String swapLine = shellOutput.substring(position + extract.length()); // remove everything except the swap line
            String numbers = swapLine.trim(); // assuming they are spaces, otherwise do some operations to remove tabs if used

            int firstSpace = numbers.indexOf(' '); // get the first space or change to a tab character if it is used

            String totalNumber = numbers.substring(0, firstSpace); // remove up to the first found after the number

            System.out.println("Total = " + totalNumber);
        } else {
            System.out.println("No '" + extract + "' segment found.");
        }

    }

    public static void main(String[] args) {
        new ShellOutput();
    }
}

Output: Total = 75692


text:
Q: Saving compatibility with old-style links while moving to Symfony2 I'm moving web-app from pure php to Symfony2 and going to save working old links like http://domain.com/index.php?task=help&term_id=2 (which in Symfony2 are like http://domain.com/2/?task=help).
What should I do to do this? (add some rewrite rules to .htaccess in web dir or some other things...)
UPD: Count and position of query params are variable.

A: I would add rewrite rules to htaccess like:
Updated:
RewriteCond %{query_string} ^task=([a-zA-Z]+)&term_id=([0-9]+)$
RewriteRule ^index.php$ /index.php/%2/?task=%1 [R,L]

A: I decided to solve my problem next way:
RewriteCond %{QUERY_STRING} term_id=([0-9]+) [NC]
RewriteRule ^(index.php)?$ /%1/ [R=301,NC,L]


text:
Q: Flutter: to close a webview when you left the page I have a segmented control and, in one of its pages, I have a webview. I want to close my web view automatically when I change page from the segmented control. Some suggestion?

A: you may work on the dispose event of your StateFullWidget and close your webview when your component or page disposed :
@override
void dispose() {
  // close the webview here
  super.dispose();
}

A: No need to do dispose, just use Navigator.pushReplacement will take care of all.


text:
Q: i change the "Listen 80" line to "Listen 8080" in config apache but still it doesn't work my apache is ok but when i update my php,Apache will not start and xampp say "Port 80 in use by "Unable to open process" with PID 4!"  and i change the "Listen 80" line to "Listen 8080" in config apache but apache say yet "Port 80 in use by "Unable to open process" with PID 4!"

A: Reverse whatever you've done and go to xampp folder and search for xampp-control.ini
Look for [ServicePorts] and change the line below it to Apache=8080


text:
Q: material v5 migration: migrate from JSS to Emotion I'm trying to migrate my material-ui project from JSS to Emotion in order to support react18.
I ran the
npx @mui/codemod v5.0.0/jss-to-styled <path>

command successfully.
However, when I try to run my app, I have the following error on all child components but not on the root parent component where theme is defined:

Uncaught ReferenceError: theme is not defined

I can pass theme as a prop to the child components, however the part of the code where i need theme is outside the scope of the component. So, this doesn't fix the issue. Additionally, this error doesn't occur on the parent root component because that's where theme variable is defined:
declare module '@mui/styles/defaultTheme' {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface DefaultTheme extends Theme {}
}
const theme = createTheme(adaptV4Theme({}));

Thus, if I add the code above in all components, I don't have this error anymore and it fixes the issue.
Having said that, I think this is not the correct approach.
Does anyone have any better suggestion? Thank you!
[EDIT]
Here's what my code looks like:
export default function App() {
  return (
    <Router>
      <ThemeProvider theme={theme}>
        <Routes>
          <Route path="/" element={<Home />} />
        </Routes>
      </ThemeProvider>
    </Router>
  );
}

This works for the Home react function component, however it doesn't work for its children components :(
[EDIT 2]
Here's an example of a child component:
import React, { useState, useEffect } from 'react';
import { styled } from '@mui/material/styles';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';

const PREFIX = 'LogIn';

const classes = {
  paper: `${PREFIX}-paper`,
  background: `${PREFIX}-background`,
  avatar: `${PREFIX}-avatar`,
  form: `${PREFIX}-form`,
  submit: `${PREFIX}-submit`
};

const StyledContainer = styled(Container)((
  {
    theme
  }
) => ({
  [`& .${classes.paper}`]: {
    marginTop: theme.spacing(8),
    padding: theme.spacing(4),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: theme.palette.background.paper,
  },

  [`&.${classes.background}`]: {
    display: 'flex',
    alignItems: 'center',
    background:
      'linear-gradient(200.96deg, #ffd194 -29.09%, #4DBD90 51.77%, #062627 129.35%) no-repeat center center fixed',
    position: 'absolute',
    top: '0px',
    right: '0px',
    bottom: '0px',
    left: '0px',
    margin: '0',
    height: '100vh',
    minWidth: '100vw',
    zIndex: '2',
  },

  [`& .${classes.avatar}`]: {
    margin: theme.spacing(1),
    backgroundColor: '#151d29',
    width: 56,
    height: 56,
  },

  [`& .${classes.form}`]: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },

  [`& .${classes.submit}`]: {
    margin: theme.spacing(3, 0, 2),
  }
}));
export const LogIn: React.FC<{ onLogin: Function, onSignup: Function }> = ({ onLogin, onSignup }) => {
...
return (
    <StyledContainer className={classes.background}>
      <Container component="main" maxWidth="xs" sx={{ zIndex: 3 }}>
        <CssBaseline />
        <div className={classes.paper}>
        ...
    );
}
export default LogIn;

A: From the explanation of the problem you described I believe if you wrap your application in the ThemeProvider you should be able to do it only in the parent App component and all you children will have access to the theme.
For example
import { ThemeProvider } from '@mui/material/styles';
import { theme } from './Theme'; // This is where I have my theme, change with yours please

function App() {
  return (
    <Router>
        <ThemeProvider theme={theme}> // Here is where I wrap all my pages and the children components can have access to the theme
            <Routes>
              <Route path={HOME_PAGE} element={<Home />} />
              <Route path={ABOUT_PAGE} element={<About />} />
            </Routes>
        </ThemeProvider>
    </Router>
  );
}

Here is my Theme file.
import { createTheme } from '@mui/material/styles';

export const theme = createTheme({
  palette: {
    primary: {
      main: '#2d9cdb',
      dark: '#2e85d4',
    },
    secondary: {
      main: '#2e85d4',
    },
    text: {
      primary: '#000000',
      secondary: '#2d9cdb',
    },
    ...
        },
  components: {
    MuiAlert: {
      styleOverrides: {
        standardSuccess: {
          backgroundColor: '#55ab68',
          color: '#FFFFFF',
          fontWeight: 'bold',
        },
        standardError: {
          backgroundColor: '#ed4a3a',
          color: '#FFFFFF',
          fontWeight: 'bold',
        },
      }
    }
  }
});

Then for example inside my home page i have an Alert component that uses the theme.
  <Alert severity="error" icon={false}>
    <Typography variant="h4" color="secondary" align="center" >
      Test text
    </Typography>
  </Alert>

Please let me know if it helped.

A: I found the issue!
I added theme as an argument to the arrow function and it is working - which makes sense.
How it was:
const Root = styled('div')(() => ({
  [`& .${classes.chartParent}`]: {
    height: '160px',
  },
  // ...
}));

Fixed code:
const Root = styled('div')(({theme}) => ({
  [`& .${classes.chartParent}`]: {
    height: '160px',
  },
  // ...
}));


text:
Q: How does one count the indexes in an array with JavaScript? I have a JSON object through an AJAX request and I want to count the indexes in the array. However, each array within the array is an array itself. I want to set a variable to this number, so I can print it on a UI element, in reference to the number of records left to load.
Using jQuery, and I'm kind of stumped. There doesn't appear to be anything in jQuery that counts the indexes on an array. :|
I could also use PHP to accomplish the counting, but I wanted to keep it client-side if possible.

A: Look at the length property for your array.


text:
Q: C# canvas going overpainted I have a Canvas in my MainWindow and I draw a line there. When it draws over the width/height of my Canvas, the drawing continues in my MainWindow. Is there a mistake in my code or is that normal?
<Canvas x:Name="coordinateSystem" HorizontalAlignment="Right" Height="580" Margin="0,10,283,0" VerticalAlignment="Top" Width="1024" Cursor="Cross" UseLayoutRounding="False"/>

Here is my function I call everytime when I get a new coordinate for my line:
// xOld, yOld and t are static
// t represents the time
private void drawPoly(double value)
{
    t++;
    Point pOne = new Point(xOld, yOld);
    Point pTwo = new Point(t, value);

    GeometryGroup lineGroup = new GeometryGroup();
    LineGeometry connectorGeometry = new LineGeometry();
    connectorGeometry.StartPoint = pOne;
    connectorGeometry.EndPoint = pTwo;
    lineGroup.Children.Add(connectorGeometry);
    System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
    path.Data = lineGroup;
    path.StrokeThickness = 1;
    path.Stroke = path.Fill = Brushes.Red;

    coordinateSystem.Children.Add(path);

    xOld = t;
    yOld = value;
}

thx
PS: Is there a way to save all drawn points? I want later resize my canvas (zoom out/zoom in) or if the time going to big move my painted line in my canvas and then I need to draw all points again.

A: Canvases do not clip child elements. If you want to stop the child elements from being drawn outside of the Canvas, you'll need to set ClipToBounds to true or set the Clip of the Canvas.