问:
how to merge two array list in JSON and view in data table rows using asp.net MVC?
text and EmpList having two arraylist how to return two array list in JSON and how to view in data table rows in a single view .i have split the code two $.each(data.EmpList, function (i, item) and $.each(data.test, function (i, item) condition how to merge both array values in a single Row view..

```<code>$("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data.EmpList, function (i, item) {
                            $("#findValue").show();
                            var rows = "<tr>"

                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + item.RoleName  + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                        $.each(data.test, function (i, item) {
                            $("#findValue").show();
                            var rows = "<tr>"
                            + "<td>" + item.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
</code>```

Controller:

```<code>public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            List<ViewRoleModules> test = new List<ViewRoleModules>();
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
                foreach (ViewRoleModules vip in RoleList)
                {
                    test.Add(new ViewRoleModules {
                        RoleName = vip.RoleName
                    });
                }
            }

            var data = new { EmpList = EmpList, test = test };

            return Json(data, JsonRequestBehavior.AllowGet);

        }
</code>```

Here my ouptput screen:

```<code>public class ViewRoleModules
    {
        [Key]
        public int ModuleID { get; set; }
        public int DomainID { get; set; }
        public int ParentModuleID { get; set; }
        public int CompanyTypeID { get; set; }
        public string ModuleName { get; set; }
        public string FolderName { get; set; }
        public string Url { get; set; }
        public int TabOrder { get; set; }
        public string Style { get; set; }
        public string Status { get; set; }
        public string IsTab { get; set; }
        public string ApprovalProcess { get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedDate = DateTime.UtcNow;
        public int ModifiedBy { get; set; }
        public DateTime ModifiedDate = DateTime.UtcNow;

        public string RoleName { get; set; }
        public int RoleID { get; set; }

    }
</code>```

And

```<code>public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            //RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }
</code>```

答:
Current scenario that you are working on, where each module can have multiple roles.EmpList and test are returned as result. Here I have used ModuleId as a common value for linking two lists.

C#:

Controller:

```<code>public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();

            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);

            List<ViewRoleModules> RoleList;
            List<ViewRoleModules> test = new List<ViewRoleModules>();
            foreach (ViewRoleModules emp in EmpList)
            {
                RoleList = type.GetSiteRoleModulesViews(emp.ModuleId);
                foreach (ViewRoleModules vip in RoleList)
                {
                    test.Add(new ViewRoleModules
                    {
                        RoleName = vip.RoleName,
                        ModuleId = vip.ModuleId
                    });
                }
            }

            var data = new { EmpList = EmpList, test = test };

            return Json(data, JsonRequestBehavior.AllowGet);

        }
</code>```

Change made to class GetSiteRoleModulesViews, added ModuleId.

```<code>public List<ViewRoleModules> GetSiteRoleModulesViews(int _ModuleId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", _ModuleId);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            //RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])
                            //*****Included ModuleID Here*****
                            ModuleId = _ModuleId;
                        }
                    );
                }

                return RoleList;
            }
        }
</code>```

JS:

```<code>$("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data.EmpList, function (i, item) {
                            $("#findValue").show();

                            /*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/

                            var Result = $(data.test).filter(function (index, element) {
                                return element.ModuleId == item.ModuleId
                            });

                            var rows = "<tr>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + Result.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
    });
</code>```

Body:
text and EmpList having two arraylist how to return two array list in JSON and how to view in data table rows in a single view .i have split the code two $.each(data.EmpList, function (i, item) and $.each(data.test, function (i, item) condition how to merge both array values in a single Row view..

$("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data.EmpList, function (i, item) {
                            $("#findValue").show();
                            var rows = "
"

                            + "" + item.ModuleName + "	"
                            + "" + item.Url + "	"
                            + "" + item.RoleName  + "	"
                            + "
";
                            $('#example tbody').append(rows);
                        });

                        $.each(data.test, function (i, item) {
                            $("#findValue").show();
                            var rows = "
"
                            + "" + item.RoleName + "	"
                            + "
";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })

Controller:

public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            List<ViewRoleModules> test = new List<ViewRoleModules>();
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
                foreach (ViewRoleModules vip in RoleList)
                {
                    test.Add(new ViewRoleModules {
                        RoleName = vip.RoleName
                    });
                }
            }

            var data = new { EmpList = EmpList, test = test };

            return Json(data, JsonRequestBehavior.AllowGet);

        }

Here my ouptput screen:

public class ViewRoleModules
    {
        [Key]
        public int ModuleID { get; set; }
        public int DomainID { get; set; }
        public int ParentModuleID { get; set; }
        public int CompanyTypeID { get; set; }
        public string ModuleName { get; set; }
        public string FolderName { get; set; }
        public string Url { get; set; }
        public int TabOrder { get; set; }
        public string Style { get; set; }
        public string Status { get; set; }
        public string IsTab { get; set; }
        public string ApprovalProcess { get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedDate = DateTime.UtcNow;
        public int ModifiedBy { get; set; }
        public DateTime ModifiedDate = DateTime.UtcNow;

        public string RoleName { get; set; }
        public int RoleID { get; set; }

    }

And

public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            //RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }

Body:
Current scenario that you are working on, where each module can have multiple roles.EmpList and test are returned as result. Here I have used ModuleId as a common value for linking two lists.

C#:

Controller:

public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();

            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);

            List<ViewRoleModules> RoleList;
            List<ViewRoleModules> test = new List<ViewRoleModules>();
            foreach (ViewRoleModules emp in EmpList)
            {
                RoleList = type.GetSiteRoleModulesViews(emp.ModuleId);
                foreach (ViewRoleModules vip in RoleList)
                {
                    test.Add(new ViewRoleModules
                    {
                        RoleName = vip.RoleName,
                        ModuleId = vip.ModuleId
                    });
                }
            }

            var data = new { EmpList = EmpList, test = test };

            return Json(data, JsonRequestBehavior.AllowGet);

        }

Change made to class GetSiteRoleModulesViews, added ModuleId.

public List<ViewRoleModules> GetSiteRoleModulesViews(int _ModuleId)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", _ModuleId);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            //RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])
                            //*****Included ModuleID Here*****
                            ModuleId = _ModuleId;
                        }
                    );
                }

                return RoleList;
            }
        }

JS:

$("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data.EmpList, function (i, item) {
                            $("#findValue").show();

                            /*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/

                            var Result = $(data.test).filter(function (index, element) {
                                return element.ModuleId == item.ModuleId
                            });

                            var rows = "<tr>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + Result.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
    });


来源: stackexchange

问:
How to partially clear userform in ms access
I have a bound userform with lot of fields in it, I use submit button to let user make entries in shared form. But whenever user clicks on submit button it requery whole form. However, there are around 4-5 fields which should not be cleared on submit button, they should retain the value and rest of the fields should get cleared on every submit button click.

Can this be done in access and how ? below is the simple code is use to submit and requery the record.

```<code>Private Sub SaveBtn_Click()
 RunCommand acCmdSaveRecord
 Me.Requery
 Me.DataForm.Requery
End Sub
</code>```

答:
When you have a "Bound Form" in Access, this means that the Access Form is tied to the underlying data source, which is specified by, and stored in, the "Record Source" property for the form.  In the "SaveBtn_Click()" method you provided above, this code does the following things:

RunCommand acCmdSaveRecord - Saves the current record in the form.

Me.Requery - Requeries the entire form.

Me.DataForm.Requery - Requeries the subform named "DataForm" on your main form.

So when you "Requery" the entire form (depending on how the "Record Source" and other form property settings are setup), the requery operation in some cases moves the cursor to the new record in the data source (...its the default settings for the drag and drop form designer tools in later versions of Access), and I suspect that is why you see the form being "cleared" when you call "Requery."  A couple of items I would point out, just for clarity:

Note 1: "Requery" actually saves the record, so explicitly calling "RunCommand acCmdSaveRecord" should not be necessary if you're going to call "Requery" too.

Note 2: Depending on how the Record Source (and other) form properties are set, Requery in some cases just saves and refreshes the currently selected record, but it doesn't sound like that is how your form is working (based on what you said above), so I'm assuming that is not the case in your form.

Note 3: The subform will also be requeried when you call "Requery" for the main form, so that line of code may also be redundant here.  The reason to call "Me.DataForm.Requery" is if you only want to requery the subform and NOT requery the entire main form.

Note 4: The "DataForm" subform (on your main form) will have a separate data source for it's own "Record Source" property, which is separate from the parent (main) form, so it is important to be aware of that fact, depending on which field values you want to save.

So, that said, there are a couple of options I might suggest, depending on exactly how you want your form to behave:

If you want to keep some of the field values and use those for the NEW RECORD when you hit the requery button, you could always save them off in a variable and then set those controls again after requerying from your variables. Just create a seperate variable for each value you want to save, copy the TextBox control values into each of variables respectively, call requery on the form, and then copy those values back into your TextBox controls after you requery.  That code would be something like the following (depending on the exact names of your TextBox controls, I used the fictitious name "txtMyTextBox" for this example):

Private Sub SaveBtn_Click()
    Dim vValue1 as Variant
    vValue1 = txtMyTextBox
    Me.Requery
    txtMyTextBox = vValue1
End Sub

Or, if you're just trying to create "Default Values" for certain controls, TextBox controls have a "DefaultValue" property you can set to any value you would like to use for the default.  Those can be set from the Property Sheet on the right side of the Access window when the form is opened in Design mode or Layout mode and the TextBox control is selected.  (Press F4 to open the Property Sheet if it's not already open).

But, if you really want to Requery and then go back to the same record you were previously on, you could try the following code:

Private Sub SaveBtn_Click()
    Dim iRecord as Integer
    iRecord = Me.CurrentRecord
    Me.Requery
    DoCmd.GoToRecord , , acGoTo, iRecord
End Sub

Anyway, I hope this all makes sense and you find it helpful.  Please let me know if you have any further questions about this answer.

ContentLicense: CC BY-SA 3.0

Body:
I have a bound userform with lot of fields in it, I use submit button to let user make entries in shared form. But whenever user clicks on submit button it requery whole form. However, there are around 4-5 fields which should not be cleared on submit button, they should retain the value and rest of the fields should get cleared on every submit button click.

Can this be done in access and how ? below is the simple code is use to submit and requery the record.

Private Sub SaveBtn_Click()
 RunCommand acCmdSaveRecord
 Me.Requery
 Me.DataForm.Requery
End Sub


问:
Parent Form can't access Child Form Public Property - Winforms c#
I am feeling kind of stupid at the moment, because everywhere I read this is a normal procedure, and I just cannot find why I am not able to do it also!

So, the situation is the following, I have a Parent Form and a Child Form. The Child Form has a public property. From the Parent Form, i want to access the Child Form public property, and I can't.

My code is the following:

Parent code:

```<code>namespace myProgram.UserInterfaces
{
  public partial class ProjectNew : Form
  {
    public ProjectNew()
    {
        InitializeComponent();
    }

    private void ButtonSelectCustomer_Click(object sender, EventArgs e)
    {
        using (Form f = new ProjectCustomerList())
        {
            this.SuspendLayout();
            f.ShowDialog(this);
        }
        this.Show();
    }
  }
}
</code>```

Child code:

```<code>namespace myProgram.UserInterfaces
{
  public partial class ProjectCustomerList : Form
  {
    public EntCustomer _selectedCustomer = new EntCustomer();

    public EntCustomer SelectedCustomer {
        get
        {
            return _selectedCustomer;
        }
    }

    public ProjectCustomerList()
    {
        InitializeComponent();
    }
    // --- other code ---
  }
}
</code>```

After the using (Form f = new ProjectCustomerList()) i would like to do the following: var sCustomer = f.SelectedCustomer;, but when I do this, Visual Studio doesn't recognize the Child Form public property.

What am I doing wrong? :|

答:
This is normal with inheritance, since f in your case is handled as a simple Form.

You could typecast it to ProjectCustomerList to access the Property.
The is operator is also useful.

```<code>if (f is ProjectCustomerList)
{
    (f as ProjectCustomerList).SelectedCustomer =...;
}
</code>```

or simply

```<code>using (ProjectCustomerList f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}
</code>```

seen var in other comments, works too

```<code>using (var f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}
</code>```

Body:
I am feeling kind of stupid at the moment, because everywhere I read this is a normal procedure, and I just cannot find why I am not able to do it also!

So, the situation is the following, I have a Parent Form and a Child Form. The Child Form has a public property. From the Parent Form, i want to access the Child Form public property, and I can't.

My code is the following:

Parent code:

namespace myProgram.UserInterfaces
{
  public partial class ProjectNew : Form
  {
    public ProjectNew()
    {
        InitializeComponent();
    }

    private void ButtonSelectCustomer_Click(object sender, EventArgs e)
    {
        using (Form f = new ProjectCustomerList())
        {
            this.SuspendLayout();
            f.ShowDialog(this);
        }
        this.Show();
    }
  }
}

Child code:

namespace myProgram.UserInterfaces
{
  public partial class ProjectCustomerList : Form
  {
    public EntCustomer _selectedCustomer = new EntCustomer();

    public EntCustomer SelectedCustomer {
        get
        {
            return _selectedCustomer;
        }
    }

    public ProjectCustomerList()
    {
        InitializeComponent();
    }
    // --- other code ---
  }
}

After the using (Form f = new ProjectCustomerList()) i would like to do the following: var sCustomer = f.SelectedCustomer;, but when I do this, Visual Studio doesn't recognize the Child Form public property.

What am I doing wrong? :|

Body:
This is normal with inheritance, since f in your case is handled as a simple Form.

You could typecast it to ProjectCustomerList to access the Property.
The is operator is also useful.

if (f is ProjectCustomerList)
{
    (f as ProjectCustomerList).SelectedCustomer =...;
}

or simply

using (ProjectCustomerList f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

seen var in other comments, works too

using (var f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}


问:
How to align checkbox and label on prestashop

Hi, I'm working on a prestashop module, and I want to align a checkbox with a label in a smarty template.

I try this for exemple :

```<code><input id="Checkbox1" name="Checkbox1" type="checkbox" value="Admin" />
<label for="Checkbox1">test</label>
</code>```

But on my navigator the label is under the checkbox, and in HTML source, I see a div around my checkbox.

```<code><div class="checker" id="uniform-Checkbox1"><span><input id="Checkbox1" name="Checkbox1" value="Admin" type="checkbox"></span></div>
<label for="Checkbox1">test</label>
</code>```

This code run perfectly in a classic HTML page.
Thanks for help.
I use Prestashop 1.6.1.4 in a docker environment.

答:
Paste following css in your custom css file:

```<code>.checker,
.checker+label {
  display: inline-block;
  vertical-align: middle;
}
</code>```

.checker,
.checker+label {
  display: inline-block;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checker" id="uniform-Checkbox1"><span><input id="Checkbox1" name="Checkbox1" value="Admin" type="checkbox"></span></div>
<label for="Checkbox1">test</label></code>```

Body:
Hi, I'm working on a prestashop module, and I want to align a checkbox with a label in a smarty template.

I try this for exemple :

<input id="Checkbox1" name="Checkbox1" type="checkbox" value="Admin" />
test

But on my navigator the label is under the checkbox, and in HTML source, I see a div around my checkbox.

<input id="Checkbox1" name="Checkbox1" value="Admin" type="checkbox">

test

This code run perfectly in a classic HTML page.
Thanks for help.
I use Prestashop 1.6.1.4 in a docker environment.

Body:
Paste following css in your custom css file:

.checker,
.checker+label {
  display: inline-block;
  vertical-align: middle;
}

.checker,
.checker+label {
  display: inline-block;
  vertical-align: middle;
}

<div class="checker" id="uniform-Checkbox1"><span><input id="Checkbox1" name="Checkbox1" value="Admin" type="checkbox"></span></div>
<label for="Checkbox1">test</label>


问:
Proxypass Apache only if port in host
I have a node app working on port 1234. Because I don't want the port number displayed anywhere, I have a ProxyPass rule in my Apache:

```<code><VirtualHost *:80>
  ProxyPass /node http://example.com:1234
  ProxyPassReverse /node http://example.com:1234
</VirtualHost>
</code>```

It's working perfectly: when I enter http://example.com/node in my browser, the expected page displays.
When I enter http://example.com:1234, too, but I don't want that URL to display in my browser. That's why I put a javascript to change window.location if there is "1234" in the URL...

That's not a good solution, because the page has to load before being redirected and the user sees the port number. I'd like to know if it was possible to redirect immediately example.com:1234 to example.com/node with an Apache rule. I searched all the documentation, but the solution isn't obvious...

答:
If you can't change SSO redirect URL, I would suggest the following:

Run your application on different port (for example 1235)

Create an additional VirtualHost listening on port 1234, and use it for redirecting to :80 with Redirect / http://example.com/

Modify your existing ProxyPass url to go to port 1235

Title: Proxypass Apache only if port in host

Body:
I have a node app working on port 1234. Because I don't want the port number displayed anywhere, I have a ProxyPass rule in my Apache:

<VirtualHost *:80>
  ProxyPass /node http://example.com:1234
  ProxyPassReverse /node http://example.com:1234
</VirtualHost>

It's working perfectly: when I enter http://example.com/node in my browser, the expected page displays.
When I enter http://example.com:1234, too, but I don't want that URL to display in my browser. That's why I put a javascript to change window.location if there is "1234" in the URL...

That's not a good solution, because the page has to load before being redirected and the user sees the port number. I'd like to know if it was possible to redirect immediately example.com:1234 to example.com/node with an Apache rule. I searched all the documentation, but the solution isn't obvious...


问:
How can i make DatePickerFor a readonly?
i have the DatePickerFor and i want to make it readonly I want to force user to pick dates ,not being able to type them.

```<code><td>@(Html.Kendo().DatePickerFor(model => model.DateRecherche).Max(DateTime.Today))</td>
</code>```

Thanks.

答:
Adding the attribute readonly to an input tag will make it read only. You can do this with jQuery like this:

```<code>$(function () {
        $('.k-datepicker input').attr('readonly', 'true');
    });
</code>```

Body:
i have the DatePickerFor and i want to make it readonly I want to force user to pick dates ,not being able to type them.

@(Html.Kendo().DatePickerFor(model => model.DateRecherche).Max(DateTime.Today))

Thanks.

Body:
Adding the attribute readonly to an input tag will make it read only. You can do this with jQuery like this:

$(function () {
        $('.k-datepicker input').attr('readonly', 'true');
    });


问:
How to take unique values from mongodb aggregate pipeline
My current mongodb aggregate pipeline output is

```<code>[
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E003",
        "CustomerName":"Kishore",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    }
];
</code>```

Actual response should be unique based on CustomerID

```<code>[
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E003",
        "CustomerName":"Kishore",
        "CustomerPhone":"919889902----",
    }
];
</code>```

I don't know what operator to use to get unique values from aggregate pipeline.

I am using $project, $sort  for projection of response and $skip and $limit for pagination

答:
group by the value you want :

```<code>db.collection.aggregate([
   {
     $group:{
       _id: "$CustomerID",
       CustomerId: {$first:"$CustomerID"},
       CustomerName: {$first: "$CustomerName"},
       CustomerPhone: {$first: "$CustomerPhone"}
    }
  }
]);
</code>```

I assume that name and phone are the same for the same customer Id, otherwise replace $first with $addToSet in order to get all names and phones

Body:
My current mongodb aggregate pipeline output is

[
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E003",
        "CustomerName":"Kishore",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    }
];

Actual response should be unique based on CustomerID

[
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",
    },
    {
        "CustomerID":"E003",
        "CustomerName":"Kishore",
        "CustomerPhone":"919889902----",
    }
];

I don't know what operator to use to get unique values from aggregate pipeline.

I am using $project, $sort  for projection of response and $skip and $limit for pagination

Body:
group by the value you want :

db.collection.aggregate([
   {
     $group:{
       _id: "$CustomerID",
       CustomerId: {$first:"$CustomerID"},
       CustomerName: {$first: "$CustomerName"},
       CustomerPhone: {$first: "$CustomerPhone"}
    }
  }
]);

I assume that name and phone are the same for the same customer Id, otherwise replace $first with $addToSet in order to get all names and phones


问:
How to write property values of different languages in its native form to a properties file in java by saving the file layout?
I have a localized properties file with a list of key-value pairs.
I want to write property values in japanese,chinese,german etc. to the file and also want to save the already existing file layout with comments and spaces. Need to write these languages in its own native form.

I tried to add a new property ("key = アカウント ナビゲーション コンポーネント") to the existing property file using PropertiesConfigurationLayout. It is possible to add new property in its native form and PropertiesConfigurationLayout helped to save the layout of the file. But the existing keys format will get changed to unicode format.
Useful link : (http://marjavamitjava.com/modifying-property-file-maintaining-order-well-comments/)

This is the code I tried.

Code:

```<code>    File file = new File("base_ch.properties");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setEncoding("UTF-8");
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    Properties props = new Properties();

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

        props.put("key","アカウント ナビゲーション コンポーネント");
        layout.save(out);
        props.store(out, null);
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }
</code>```

base_ch.properties file content before code runs:

```<code># -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = Gültig bis
address.zipcode = 邮政编码:
</code>```

base_ch.properties file content after code runs:

```<code># -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = G\u00FCltig bis
address.zipcode = \u90AE\u653F\u7F16\u7801
#Wed Dec 06 17:40:04 IST 2017
key=アカウント ナビゲーション コンポーネント
</code>```

I want to save the file layout without any change and should retain the existing properties in its native form.
It is able to write various languages to the properties file using various classes, but the file layout will get change in that cases.
PropertiesConfigurationLayout is the only way I found to save the layout.

Can anyone help me?

答:
Got a solution for the question.

Customize PropertiesConfiguration and PropertiesConfigurationLayout classes for to meet the requirement.

Rewrite the escapeValue() method in PropertiesConfiguration in such a way to return the property value itself without escape characters.

Override the save method in PropertiesConfigurationLayout.

The below given is the class which extends PropertiesConfiguration :

```<code>    public class PropertiesConfigurationExtended extends PropertiesConfiguration{

    private static final char[] SEPARATORS = new char[] {'=', ':'};
    private static final char[] WHITE_SPACE = new char[]{' ', '\t', '\f'};
    private static final String ESCAPE = "\\";

    public static class PropertiesWriter extends PropertiesConfiguration.PropertiesWriter{
        private char delimiter;
        /**
         * Constructor.
         */
        public PropertiesWriter(Writer writer, char delimiter)
        {
            super(writer,delimiter);
            this.delimiter = delimiter;
        }
        public void writeProperty(String key, Object value,
                boolean forceSingleLine) throws IOException
        {
            String v;
            if (value instanceof List)
            {
                List values = (List) value;
                if (forceSingleLine)
                {
                    v = makeSingleLineValue(values);
                }
                else
                {
                    writeProperty(key, values);
                    return;
                }
            }
            else
            {
                v = escapeValue(value);
            }

            write(escapeKey(key));
            write(" = ");
            write(v);

            writeln(null);
        }
        /**
         * Rewrite the escapeValue method to avoid escaping of the given property value.
         *
         * @param value the property value
         * @return the same property value
         */
        private String escapeValue(Object value)
        {
            return String.valueOf(value);
        }
    }
}
</code>```

The below given is the class which extends PropertiesConfigurationLayout :

```<code>public class PropertiesConfigurationLayoutExtended extends PropertiesConfigurationLayout{

    public PropertiesConfigurationLayoutExtended(PropertiesConfigurationExtended config) {
        super(config);
    }
    public void save(Writer out) throws ConfigurationException
    {
        try
        {
            char delimiter = getConfiguration().isDelimiterParsingDisabled() ? 0
                    : getConfiguration().getListDelimiter();
            PropertiesConfigurationExtended.PropertiesWriter writer = new PropertiesConfigurationExtended.PropertiesWriter(
                    out, delimiter);
            if (getHeaderComment() != null)
            {
                writer.writeln(getCanonicalHeaderComment(true));
                writer.writeln(null);
            }

            for (Iterator it = getKeys().iterator(); it.hasNext();)
            {
                String key = (String) it.next();
                if (getConfiguration().containsKey(key))
                {
                    // Output blank lines before property
                    for (int i = 0; i < getBlancLinesBefore(key); i++)
                    {
                        writer.writeln(null);
                    }
                    // Output the comment
                    if (getComment(key) != null)
                    {
                        writer.writeln(getCanonicalComment(key, true));
                    }
                    // Output the property and its value
                    boolean singleLine = (isForceSingleLine() || isSingleLine(key))
                            && !getConfiguration().isDelimiterParsingDisabled();
                    writer.writeProperty(key, getConfiguration().getProperty(
                            key), singleLine);
                }
            }
            writer.flush();
        }
        catch (IOException ioex)
        {
            throw new ConfigurationException(ioex);
        }
    }
}
</code>```

The class for writing properties to the file :

```<code>    File file = new File("base_ch.properties");
    PropertiesConfigurationExtended config = new PropertiesConfigurationExtended();
    PropertiesConfigurationLayoutExtended layout = new PropertiesConfigurationLayoutExtended(config);

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        config.setProperty("key","アカウント ナビゲーション コンポーネント");
        layout.save(out, false));
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }
</code>```

Body:
I have a localized properties file with a list of key-value pairs.
I want to write property values in japanese,chinese,german etc. to the file and also want to save the already existing file layout with comments and spaces. Need to write these languages in its own native form.

I tried to add a new property ("key = アカウント ナビゲーション コンポーネント") to the existing property file using PropertiesConfigurationLayout. It is possible to add new property in its native form and PropertiesConfigurationLayout helped to save the layout of the file. But the existing keys format will get changed to unicode format.
Useful link : (http://marjavamitjava.com/modifying-property-file-maintaining-order-well-comments/)

This is the code I tried.

Code:

    File file = new File("base_ch.properties");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setEncoding("UTF-8");
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    Properties props = new Properties();

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");

        props.put("key","アカウント ナビゲーション コンポーネント");
        layout.save(out);
        props.store(out, null);
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }

base_ch.properties file content before code runs:

# -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = Gültig bis
address.zipcode = 邮政编码:

base_ch.properties file content after code runs:

# -----------------------------------------------------------------------
#  All rights reserved.
#  Comments included here
# -----------------------------------------------------------------------
#Tue May 22 13:41:37

account.quote.expiration.time.label = G\u00FCltig bis
address.zipcode = \u90AE\u653F\u7F16\u7801
#Wed Dec 06 17:40:04 IST 2017
key=アカウント ナビゲーション コンポーネント

I want to save the file layout without any change and should retain the existing properties in its native form.
It is able to write various languages to the properties file using various classes, but the file layout will get change in that cases.
PropertiesConfigurationLayout is the only way I found to save the layout.

Can anyone help me?

Body:
Got a solution for the question.

Customize PropertiesConfiguration and PropertiesConfigurationLayout classes for to meet the requirement.

Rewrite the escapeValue() method in PropertiesConfiguration in such a way to return the property value itself without escape characters.

Override the save method in PropertiesConfigurationLayout.

The below given is the class which extends PropertiesConfiguration :

    public class PropertiesConfigurationExtended extends PropertiesConfiguration{

    private static final char[] SEPARATORS = new char[] {'=', ':'};
    private static final char[] WHITE_SPACE = new char[]{' ', '\t', '\f'};
    private static final String ESCAPE = "\\";

    public static class PropertiesWriter extends PropertiesConfiguration.PropertiesWriter{
        private char delimiter;
        /**
         * Constructor.
         */
        public PropertiesWriter(Writer writer, char delimiter)
        {
            super(writer,delimiter);
            this.delimiter = delimiter;
        }
        public void writeProperty(String key, Object value,
                boolean forceSingleLine) throws IOException
        {
            String v;
            if (value instanceof List)
            {
                List values = (List) value;
                if (forceSingleLine)
                {
                    v = makeSingleLineValue(values);
                }
                else
                {
                    writeProperty(key, values);
                    return;
                }
            }
            else
            {
                v = escapeValue(value);
            }

            write(escapeKey(key));
            write(" = ");
            write(v);

            writeln(null);
        }
        /**
         * Rewrite the escapeValue method to avoid escaping of the given property value.
         *
         * @param value the property value
         * @return the same property value
         */
        private String escapeValue(Object value)
        {
            return String.valueOf(value);
        }
    }
}

The below given is the class which extends PropertiesConfigurationLayout :

public class PropertiesConfigurationLayoutExtended extends PropertiesConfigurationLayout{

    public PropertiesConfigurationLayoutExtended(PropertiesConfigurationExtended config) {
        super(config);
    }
    public void save(Writer out) throws ConfigurationException
    {
        try
        {
            char delimiter = getConfiguration().isDelimiterParsingDisabled() ? 0
                    : getConfiguration().getListDelimiter();
            PropertiesConfigurationExtended.PropertiesWriter writer = new PropertiesConfigurationExtended.PropertiesWriter(
                    out, delimiter);
            if (getHeaderComment() != null)
            {
                writer.writeln(getCanonicalHeaderComment(true));
                writer.writeln(null);
            }

            for (Iterator it = getKeys().iterator(); it.hasNext();)
            {
                String key = (String) it.next();
                if (getConfiguration().containsKey(key))
                {
                    // Output blank lines before property
                    for (int i = 0; i < getBlancLinesBefore(key); i++)
                    {
                        writer.writeln(null);
                    }
                    // Output the comment
                    if (getComment(key) != null)
                    {
                        writer.writeln(getCanonicalComment(key, true));
                    }
                    // Output the property and its value
                    boolean singleLine = (isForceSingleLine() || isSingleLine(key))
                            && !getConfiguration().isDelimiterParsingDisabled();
                    writer.writeProperty(key, getConfiguration().getProperty(
                            key), singleLine);
                }
            }
            writer.flush();
        }
        catch (IOException ioex)
        {
            throw new ConfigurationException(ioex);
        }
    }
}

The class for writing properties to the file :

    File file = new File("base_ch.properties");
    PropertiesConfigurationExtended config = new PropertiesConfigurationExtended();
    PropertiesConfigurationLayoutExtended layout = new PropertiesConfigurationLayoutExtended(config);

    try(InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"))
    {
        layout.load(in);
        OutputStreamWriter out =new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        config.setProperty("key","アカウント ナビゲーション コンポーネント");
        layout.save(out, false));
    }
    catch (ConfigurationException | IOException e) {
        e.printStackTrace();
    }


问:
How do I delete a Git branch locally and remotely?
Failed Attempts to Delete a Remote Branch:

$ git branch -d remotes/origin/bugfix
error: branch 'remotes/origin/bugfix' not found.

$ git branch -d origin/bugfix
error: branch 'origin/bugfix' not found.

$ git branch -rd origin/bugfix
Deleted remote branch origin/bugfix (was 2a14ef7).

$ git push
Everything up-to-date

$ git pull
From github.com:gituser/gitproject

* [new branch] bugfix -> origin/bugfix
Already up-to-date.
```

How do I properly delete the remotes/origin/bugfix branch both locally and remotely?

答:
It's very simple:

To delete the remote branch

```<code>git push -d origin <branch-name>
</code>```

Or

```<code>git push origin :<branch-name>
</code>```

-- You can also delete tags with this syntax

To forcefully delete local branch

```<code>git branch -D <branch-name>
</code>```

Note: do a git fetch --all --prune on other machines after deleting remote branch, to remove obsolete tracking branches.

Example

to remove local branch

```<code>git branch -D my-local-branch
</code>```

to remove remote branch

```<code>git push origin :my-remote-branch
</code>```

With the new version of git, its also possible to remove branch with

```<code>git push origin --delete <branch_name>
</code>```

TIP:
if you want to see all available branches you can use git branch -a,

and to see just remote branches, you can use git branch -r

ContentLicense: CC BY-SA 4.0

Body:
Failed Attempts to Delete a Remote Branch:

$ git branch -d remotes/origin/bugfix
error: branch 'remotes/origin/bugfix' not found.

$ git branch -d origin/bugfix
error: branch 'origin/bugfix' not found.

$ git branch -rd origin/bugfix
Deleted remote branch origin/bugfix (was 2a14ef7).

$ git push
Everything up-to-date

$ git pull
From github.com:gituser/gitproject

* [new branch] bugfix -> origin/bugfix
Already up-to-date.

How do I properly delete the remotes/origin/bugfix branch both locally and remotely?

Body:
It's very simple:

To delete the remote branch

git push -d origin <branch-name>

Or

git push origin :<branch-name>

-- You can also delete tags with this syntax

To forcefully delete local branch

git branch -D <branch-name>

Note: do a git fetch --all --prune on other machines after deleting remote branch, to remove obsolete tracking branches.

Example

to remove local branch

git branch -D my-local-branch

to remove remote branch

git push origin :my-remote-branch

With the new version of git, its also possible to remove branch with

git push origin --delete <branch_name>

TIP:
if you want to see all available branches you can use git branch -a,

and to see just remote branches, you can use git branch -r


问:
NullPointer Exception Volley android studio
I am working in a Page2 activity in Android Studio and I am using php file pause_in, below is java code using Volley class.It gives me the error:
java.lang.NullPointerException:
Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference.
But after I have added the line for initializing the request,it gives me that:(I have to mention that I used getExtra method to get the variables of email and password from the first screen).

```<code>12-08 12:49:03.446 1346-1370/? W/audio_hw_generic: Not supplying enough
data to HAL, expected position 455229 , only wrote 455040
12-08 12:49:03.446 2245-2245/? D/key: valuee
12-08 12:49:03.514 2245-2245/? W/System.err: org.json.JSONException:
End of input at character 1 of
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.syntaxError(JSONTokener.java:449)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:156)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:173)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:96)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:89)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:67)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:30)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

   com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable
  .run(ExecutorDelivery.java:99)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.handleCallback(Handler.java:751)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Looper.loop(Looper.java:154)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
 android.app.ActivityThread.main(ActivityThread.java:6077)
 12-08 12:49:03.514 2245-2245/? W/System.err:     at
 java.lang.reflect.Method.invoke(Native Method)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
  run(ZygoteInit.java:866)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 12-08 12:49:06.079 1586-1596/? I/ActivityManager: Killing
 3211:com.android.gallery3d/u0a49 (adj 906): empty #17

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Page2 extends AppCompatActivity {

private EditText emailI,passwordI;

DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;

Button pauseIn;
EditText pause;

private RequestQueue requestQueue;
private static final String URL = "http://10.31.16.22/pause_in.php";
private StringRequest request;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2_activity);

    emailI=(EditText)findViewById(R.id.emailiImprovizum);
    passwordI=(EditText)findViewById(R.id.passImprovizum);

    pauseIn = (Button) findViewById(R.id.btnPauseIn);
    pauseIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            request = new StringRequest(Request.Method.POST, URL, new
    Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                         JSONObject jsonObject = new
     JSONObject(response);
                        if
     (jsonObject.names().get(0).equals("success1")) {
                          //  Log.d("dfr","a po bon");
                            Toast.makeText(getApplicationContext(),
      "SUCCESS " + jsonObject.getString("success1"),
      Toast.LENGTH_SHORT).show();

                            Intent intent = getIntent();
                            String e = intent.getStringExtra("Email");
                            String p =
       intent.getStringExtra("Password");

                            emailI.setText(e);
                            passwordI.setText(p);

                            startActivity(new
        Intent(getApplicationContext(), about.class));

                        } else if
       (jsonObject.names().get(0).equals("fail1")) {
                            Toast.makeText(getApplicationContext(),
     "Error" + jsonObject.getString("fail1"),
     Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws
         AuthFailureError {
                    HashMap<String,String> hashMap = new
          HashMap<String, String>();
                    hashMap.put("pause_in","pauseIn");

                    hashMap.put("emailI",emailI.getText().ToString());

               hashMap.put("passwordI",password.getText().ToString());

                    return hashMap;
                }
            };

            requestQueue.add(request);
            Log.d("key","valuee");
        }
    });

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

    drawerLayout = (DrawerLayout) findViewById(R.id.drawableT);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,
    drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close);

actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources()
.getColor(R.color.white));

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    fragmentTransaction =
 getSupportFragmentManager().beginTransaction();

    fragmentTransaction.commit();

    navigationView = (NavigationView)
findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new
 NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item)
  {

            switch (item.getItemId()) {

                case R.id.about_id:
                    Intent i = new Intent(Page2.this, about.class);
                    startActivity(i);

                    break;

                case R.id.id_instructions:

                    Intent i3 = new Intent(Page2.this, about.class);
                    startActivity(i3);

                    break;
            }

            return false;
        }
    });

}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
    }
}

<?php
include_once 'connection.php';

class User1{

private $db;
private $connection;

function __construct() {
        $this -> db = new DB_Connection();
        $this -> connection = $this->db->getConnection();
    }

public function pause($email,$password)
    {
        $pauseIn=time();
        $query = "Select * from users where email='$email' and password
     ='$password'";

        $result = mysqli_query($this->connection, $query);
        if(mysqli_num_rows($result)>0){
        $query2="update users set pause_in='$pauseIn' where
      email='$email' ";
        $inserted = mysqli_query($this -> connection, $query2);
        if($inserted ==1 )
        {
            $json['success1'] = 'welcome';
            echo json_encode($json);
            mysqli_close($this -> connection);
        }
        else{

                $json['fail1'] = ': Email or password is wrong';

            echo json_encode($json);

        }

             }

        }
   }
   $user = new User1();

   if(isset($_POST['email'],$_POST['password'])) {
    $email=$_POST['email'];
    $password=$_POST['password'];

    $user-> pause($email,$password);

        }
        else{

        }
    ?>
</code>```

答:
You haven't initialised the RequestQueue object in you class.

```<code>RequestQueue queue = Volley.newRequestQueue(getContext());
</code>```

Try it...

Body:
I am working in a Page2 activity in Android Studio and I am using php file pause_in, below is java code using Volley class.It gives me the error:
java.lang.NullPointerException:
Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference.
But after I have added the line for initializing the request,it gives me that:(I have to mention that I used getExtra method to get the variables of email and password from the first screen).

12-08 12:49:03.446 1346-1370/? W/audio_hw_generic: Not supplying enough
data to HAL, expected position 455229 , only wrote 455040
12-08 12:49:03.446 2245-2245/? D/key: valuee
12-08 12:49:03.514 2245-2245/? W/System.err: org.json.JSONException:
End of input at character 1 of
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.syntaxError(JSONTokener.java:449)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:156)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
org.json.JSONObject.<init>(JSONObject.java:173)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:96)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.example.a.mysql_php_register_login.Page2$1$1.
onResponse(Page2.java:89)
12-08 12:49:03.514 2245-2245/? W/System.err:     at
com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:67)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

com.android.volley.toolbox.StringRequest.
deliverResponse(StringRequest.java:30)
12-08 12:49:03.514 2245-2245/? W/System.err:     at

   com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable
  .run(ExecutorDelivery.java:99)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.handleCallback(Handler.java:751)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Handler.dispatchMessage(Handler.java:95)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  android.os.Looper.loop(Looper.java:154)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
 android.app.ActivityThread.main(ActivityThread.java:6077)
 12-08 12:49:03.514 2245-2245/? W/System.err:     at
 java.lang.reflect.Method.invoke(Native Method)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.
  run(ZygoteInit.java:866)
  12-08 12:49:03.514 2245-2245/? W/System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 12-08 12:49:06.079 1586-1596/? I/ActivityManager: Killing
 3211:com.android.gallery3d/u0a49 (adj 906): empty #17

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class Page2 extends AppCompatActivity {

private EditText emailI,passwordI;

DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;

Button pauseIn;
EditText pause;

private RequestQueue requestQueue;
private static final String URL = "http://10.31.16.22/pause_in.php";
private StringRequest request;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2_activity);

    emailI=(EditText)findViewById(R.id.emailiImprovizum);
    passwordI=(EditText)findViewById(R.id.passImprovizum);

    pauseIn = (Button) findViewById(R.id.btnPauseIn);
    pauseIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            request = new StringRequest(Request.Method.POST, URL, new
    Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                         JSONObject jsonObject = new
     JSONObject(response);
                        if
     (jsonObject.names().get(0).equals("success1")) {
                          //  Log.d("dfr","a po bon");
                            Toast.makeText(getApplicationContext(),
      "SUCCESS " + jsonObject.getString("success1"),
      Toast.LENGTH_SHORT).show();

                            Intent intent = getIntent();
                            String e = intent.getStringExtra("Email");
                            String p =
       intent.getStringExtra("Password");

                            emailI.setText(e);
                            passwordI.setText(p);

                            startActivity(new
        Intent(getApplicationContext(), about.class));

                        } else if
       (jsonObject.names().get(0).equals("fail1")) {
                            Toast.makeText(getApplicationContext(),
     "Error" + jsonObject.getString("fail1"),
     Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws
         AuthFailureError {
                    HashMap<String,String> hashMap = new
          HashMap<String, String>();
                    hashMap.put("pause_in","pauseIn");

                    hashMap.put("emailI",emailI.getText().ToString());

               hashMap.put("passwordI",password.getText().ToString());

                    return hashMap;
                }
            };

            requestQueue.add(request);
            Log.d("key","valuee");
        }
    });

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

    drawerLayout = (DrawerLayout) findViewById(R.id.drawableT);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this,
    drawerLayout, toolbar,
            R.string.drawer_open, R.string.drawer_close);

actionBarDrawerToggle.getDrawerArrowDrawable().setColor(getResources()
.getColor(R.color.white));

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    fragmentTransaction =
 getSupportFragmentManager().beginTransaction();

    fragmentTransaction.commit();

    navigationView = (NavigationView)
findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new
 NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item)
  {

            switch (item.getItemId()) {

                case R.id.about_id:
                    Intent i = new Intent(Page2.this, about.class);
                    startActivity(i);

                    break;

                case R.id.id_instructions:

                    Intent i3 = new Intent(Page2.this, about.class);
                    startActivity(i3);

                    break;
            }

            return false;
        }
    });

}

@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
    }
}

<?php
include_once 'connection.php';

class User1{

private $db;
private $connection;

function __construct() {
        $this -> db = new DB_Connection();
        $this -> connection = $this->db->getConnection();
    }

public function pause($email,$password)
    {
        $pauseIn=time();
        $query = "Select * from users where email='$email' and password
     ='$password'";

        $result = mysqli_query($this->connection, $query);
        if(mysqli_num_rows($result)>0){
        $query2="update users set pause_in='$pauseIn' where
      email='$email' ";
        $inserted = mysqli_query($this -> connection, $query2);
        if($inserted ==1 )
        {
            $json['success1'] = 'welcome';
            echo json_encode($json);
            mysqli_close($this -> connection);
        }
        else{

                $json['fail1'] = ': Email or password is wrong';

            echo json_encode($json);

        }

             }

        }
   }
   $user = new User1();

   if(isset($_POST['email'],$_POST['password'])) {
    $email=$_POST['email'];
    $password=$_POST['password'];

    $user-> pause($email,$password);

        }
        else{

        }
    ?>

Body:
You haven't initialised the RequestQueue object in you class.

RequestQueue queue = Volley.newRequestQueue(getContext());

Try it...


问:
Automatic update a Windows application
How do I develop my Windows application so it will auto update on the client machine, like Firefox, Skype, etc.?

Is there any simple approach or any open source library which help me to do it just following some steps or a few lines of code?

答:
try microsoft clickonce technology

(in MSDN)

Title: Automatic update a Windows application

ContentLicense: CC BY-SA 2.5


问:
"Unable to get workspace root" when exporting Eclipse plug-ins
I am writing an Eclipse plug-in and trying to package and export it. In Eclipse, I used File -> Export... -> Deployable plug-ins ans fragments -> Select my plug-in and set the Directory. But it shows the following error:

```<code>'Export Plug-ins' has encountered a problem.
An internal error occurred during: "Export Plug-ins".
Unable to get workspace root
</code>```

This error has been shown every time even when I try to export an hello world plug-in. What causes this error and what is the correct step to configure and export the plug-in?

Thanks!

答: Getting workspace root errors are mostly related to resources plugin, try adding org.eclipse.core.resources plugin as a dependency and try exporting again. If you can give more detail about the problem we can be more helpful.</p>

Body:
I am writing an Eclipse plug-in and trying to package and export it. In Eclipse, I used File -> Export... -> Deployable plug-ins ans fragments -> Select my plug-in and set the Directory. But it shows the following error:

'Export Plug-ins' has encountered a problem.
An internal error occurred during: "Export Plug-ins".
Unable to get workspace root

This error has been shown every time even when I try to export an hello world plug-in. What causes this error and what is the correct step to configure and export the plug-in?

Thanks!


问:
Find the value of one column based on maximum value in another column per group
I have a query which gives me three columns: an ID, the day of week of event and count of how many events each day of week has, i.e.

```<code>ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3
</code>```

I get this by using query

```<code>SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
</code>```

I would like to reduce this query to only return the day of week for each user with the maximum count. At the same time, I would like to change the column with counts to instead show the frequency of events for that weekday. For the example above I would like to change the output to be

```<code>ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7
</code>```

Thankful if anyone got an idea

答:
To get the expected result set you could do your calculation in outer query like</p>

```<code>SELECT ID,
SUBSTRING_INDEX(GROUP_CONCAT(Day_Name ORDER BY Cnt DESC),',',1) Day_Name,
MAX(Cnt)/SUM(Cnt) Frequency
FROM(
    SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
    FROM EVENT AS E
    INNER JOIN PERSON AS P
    ON P.ID_2 = E.ID_2
    WHERE E.EVENT_DATE > '2016-01-01'
    AND E.EVENT_STATUS LIKE '%OCCURED%'
    GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
) t
GROUP BY ID
</code>```

Body:
I have a query which gives me three columns: an ID, the day of week of event and count of how many events each day of week has, i.e.

ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3

I get this by using query

SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)

I would like to reduce this query to only return the day of week for each user with the maximum count. At the same time, I would like to change the column with counts to instead show the frequency of events for that weekday. For the example above I would like to change the output to be

ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7

Thankful if anyone got an idea

Body:
To get the expected result set you could do your calculation in outer query like

SELECT ID,
SUBSTRING_INDEX(GROUP_CONCAT(Day_Name ORDER BY Cnt DESC),',',1) Day_Name,
MAX(Cnt)/SUM(Cnt) Frequency
FROM(
    SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
    FROM EVENT AS E
    INNER JOIN PERSON AS P
    ON P.ID_2 = E.ID_2
    WHERE E.EVENT_DATE > '2016-01-01'
    AND E.EVENT_STATUS LIKE '%OCCURED%'
    GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
) t
GROUP BY ID


问:
Javascript event listener remove
How can I remove the eventlistener when a page navigates to another page in a single page app?

I'm facing this issue when revisiting that page, not when eventlistener is called

```<code>if (window.addEventListener) {
  window.addEventListener("message", listenMessage, false);
  // console.log("false");
} else {
  window.attachEvent("onmessage", listenMessage);
  //console.log("true");
}
var listenMessage = function(msg) {
/**/
}
</code>```

答:
I think you should use a Layout Page and ,your first page and other page should based on this Layout Page.
After that you can describe a global variable
Before navigation you should change this variable's value.
Check your variable's value and use that method:</p>

```<code>document.getElementById("Your_Element_Id").removeEventListener("Your_Listener", your Function);
</code>```

Title: Javascript event listener remove

Body:
How can I remove the eventlistener when a page navigates to another page in a single page app?

I'm facing this issue when revisiting that page, not when eventlistener is called

if (window.addEventListener) {
  window.addEventListener("message", listenMessage, false);
  // console.log("false");
} else {
  window.attachEvent("onmessage", listenMessage);
  //console.log("true");
}
var listenMessage = function(msg) {
/**/
}

Body:
I think you should use a Layout Page and ,your first page and other page should based on this Layout Page.
After that you can describe a global variable
Before navigation you should change this variable's value.
Check your variable's value and use that method:

document.getElementById("Your_Element_Id").removeEventListener("Your_Listener", your Function);


问:
Add UI element dynamically on Button click
I made a simple Form with a TableLayoutPanel and a button below it.
Is it possible to create another TableLayoutPanel below the one I already have on each button click?
And how can i fill it with data?

I searched for many hours but didn't find anything.

Here is a screenshot of my form, if it helps you:

I want the other tables to appear on the lower half of the split.

Thanks in advance, Jan

答:
Of course you can.  You may want to consider adding the TableLayoutPanels to a FlowLayoutPanel so that they will wrap and scroll automatically.

Just create the control, setup the columns and rows, then add it to some container:

```<code>TableLayoutPanel tlp = new TableLayoutPanel();
// setup "tlp" with your desired properties
tlp.XXX = YYY
// ...
flowLayoutPanel1.Controls.Add(tlp);
</code>```

Body:
Of course you can.  You may want to consider adding the TableLayoutPanels to a FlowLayoutPanel so that they will wrap and scroll automatically.

Just create the control, setup the columns and rows, then add it to some container:

TableLayoutPanel tlp = new TableLayoutPanel();
// setup "tlp" with your desired properties
tlp.XXX = YYY
// ...
flowLayoutPanel1.Controls.Add(tlp);


问:
Where are files uploaded by Valums?! (i have to store them in mysql database with PHP)
when i upload several files using Valmus Uploader, how can i "work with them", ie. store in mysql database, crop or resize, etc...

but, where are those files, and how can i access them?

tnx in adv!!!

答:
ok, all i had to do is to set that action file is php.php, from server directory
;-)

tnx to all!


问:
How can I extract the week number from java.util.Date in scala
I already tried to use:
getWeek
getCalendarDate
and I don't want to use Calendar package (because I am using a specific software that don't allow me to use it)
Thanks in advance,</p>

答:
```<code>import java.util.Calendar
import java.util.GregorianCalendar

val calendar = new GregorianCalendar()

calendar.setTime(sail_dt)
calendar.get(Calendar.WEEK_OF_YEAR)
</code>```

Finally I managed to find a SCALA code to cope with my problem. Thank you all.

Body:
import java.util.Calendar
import java.util.GregorianCalendar

val calendar = new GregorianCalendar()

calendar.setTime(sail_dt)
calendar.get(Calendar.WEEK_OF_YEAR)

Finally I managed to find a SCALA code to cope with my problem. Thank you all.


问:
How to use prefixes for inline styles. React
For example.

```<code>        return {
        transform: 'rotateY(' + d.rotateY + 'rad) '
        + ' translateX(' + translateX + 'px)'
        + ' translateZ(' + d.translateZ + 'px)'
        + ' rotateY(' + d.rotateYAround + 'deg)',
        ...
</code>```

How to use 'ms' prefix ?

答:
Per the React docs:

Vendor prefixes other than ms should begin with a capital letter. This is why WebkitTransition has an uppercase "W".

So your inline styles would look like this:

return {
  msTransform: 'rotateY(' + d.rotateY + 'rad) ' +
    ' translateX(' + translateX + 'px)' +
    ' translateZ(' + d.translateZ + 'px)' +
    ' rotateY(' + d.rotateYAround + 'deg)',
  ...,

  transform: 'rotateY(' + d.rotateY + 'rad) ' +
    ' translateX(' + translateX + 'px)' +
    ' translateZ(' + d.translateZ + 'px)' +
    ' rotateY(' + d.rotateYAround + 'deg)',
  ...
}```

Although I would recommend something that adds prefixes automatically. You might want to look into using a library such as styled-components rather than using inline styles.

Per the styled-components docs:

The CSS rules are automatically vendor prefixed, so you don't have to think about it.

Body:
For example.

        return {
        transform: 'rotateY(' + d.rotateY + 'rad) '
        + ' translateX(' + translateX + 'px)'
        + ' translateZ(' + d.translateZ + 'px)'
        + ' rotateY(' + d.rotateYAround + 'deg)',
        ...

How to use 'ms' prefix ?

Body:
Per the React docs:

Vendor prefixes other than ms should begin with a capital letter. This is why WebkitTransition has an uppercase "W".

So your inline styles would look like this:

return {
  msTransform: 'rotateY(' + d.rotateY + 'rad) ' +
    ' translateX(' + translateX + 'px)' +
    ' translateZ(' + d.translateZ + 'px)' +
    ' rotateY(' + d.rotateYAround + 'deg)',
  ...,

  transform: 'rotateY(' + d.rotateY + 'rad) ' +
    ' translateX(' + translateX + 'px)' +
    ' translateZ(' + d.translateZ + 'px)' +
    ' rotateY(' + d.rotateYAround + 'deg)',
  ...
}

Although I would recommend something that adds prefixes automatically. You might want to look into using a library such as styled-components rather than using inline styles.

Per the styled-components docs:

The CSS rules are automatically vendor prefixed, so you don't have to think about it.


问:
typescript: any difference between number[] and [number,number]?
I'm just learning Typescript and trying to understand best practices for types and interfaces. I am playing with an example using GPS coordinates and want to know if one approach is better than another.

```<code>let gps1 : number[];
let gps2 : [number, number]
interface Coordinate {
   0: number,
   1: number
}
let gps3 : Coordinate;
</code>```

I suppose the bigger question is if there is a value in typing an array of fixed size & type. Because Typescript does not allow me to easily test if a value is of a certain type on runtime, correct? (i.e. unserialized from a JSON string)

```<code>gps3 = [1,3]
let check = gps3 instanceof Coordinate;  // doesn't work
</code>```

答:
Maybe I'm a bit late but best practise would probably be using ECMA6 Proxy.

```<code>    latLngLiteral = new Proxy({},{
        set: function(obj, prop, val) {
            //only these two properties can be set
            if(['lng','lat'].indexOf(prop) == -1) {
                throw new ReferenceError('Key must be "lat" or "lng"!');
            }

            //the dec format only accepts numbers
            if(isNaN(val)) {
                throw new TypeError('Value must be numeric');
            }

            //latitude is in range between 0 and 90
            if(prop == 'lat'  && !(-90 < val && val < 90)) {
                throw new RangeError('Position is out of range!');
            }
            //longitude is in range between 0 and 180
            else if(prop == 'lng' && !(-180 < val && val < 180)) {
                throw new RangeError('Position is out of range!');
            }

            obj[prop] = val;

            return true;
        }
    });
</code>```

Body:
I'm just learning Typescript and trying to understand best practices for types and interfaces. I am playing with an example using GPS coordinates and want to know if one approach is better than another.

let gps1 : number[];
let gps2 : [number, number]
interface Coordinate {
   0: number,
   1: number
}
let gps3 : Coordinate;

I suppose the bigger question is if there is a value in typing an array of fixed size & type. Because Typescript does not allow me to easily test if a value is of a certain type on runtime, correct? (i.e. unserialized from a JSON string)

gps3 = [1,3]
let check = gps3 instanceof Coordinate;  // doesn't work

Body:
Maybe I'm a bit late but best practise would probably be using ECMA6 Proxy.

    latLngLiteral = new Proxy({},{
        set: function(obj, prop, val) {
            //only these two properties can be set
            if(['lng','lat'].indexOf(prop) == -1) {
                throw new ReferenceError('Key must be "lat" or "lng"!');
            }

            //the dec format only accepts numbers
            if(isNaN(val)) {
                throw new TypeError('Value must be numeric');
            }

            //latitude is in range between 0 and 90
            if(prop == 'lat'  && !(-90 < val && val < 90)) {
                throw new RangeError('Position is out of range!');
            }
            //longitude is in range between 0 and 180
            else if(prop == 'lng' && !(-180 < val && val < 180)) {
                throw new RangeError('Position is out of range!');
            }

            obj[prop] = val;

            return true;
        }
    });


问:
How to scan a formatted string using fscanf()?
I have this file with multiple lines. Each line follows a format of

```<code>`userID:$An Integer$$String:`
</code>```

For example:

```<code>pyc1:$1$$Tnq7a6/C1wwyKyt0V/.BP/:
pyc2:$6$$Tnq7a6/C1wwyKyt0V/.BP/:
</code>```

How should I use fscanf() to retrieve the userID, the integer, and the string between $$ and :`?

This is what I have now, but it is not working.

```<code>int main(){
    FILE * file = fopen("shadow.txt", "r");
    char line[256] = {0};
    char userID[30] = {0};
    int hashType;
    char hash[256] = {0};
    int result = fscanf(file, "%s :$ %d $$ %s :", userID, &hashType, hash);
    printf("%s\n", userID );
    printf("%d\n", hashType );
    printf("%s\n", hash );

}
</code>```

I don't know much about the format I should specify for fscanf() to achieve this. Please help.

答:
Try this:

```<code>while(ret = fscanf(file," %[^:] : $ %d $$ %[^:] :",userID,&hashtype,hash))
{

    if(ret == EOF)
    {
        break;
    }

    printf("value of ret: %d\n",ret);
    printf("%s , %d , %s",userid,id,str);

    // . . .

}
</code>```

here, int ret is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input

Body:
I have this file with multiple lines. Each line follows a format of

`userID:$An Integer$$String:`

For example:

pyc1:$1$$Tnq7a6/C1wwyKyt0V/.BP/:
pyc2:$6$$Tnq7a6/C1wwyKyt0V/.BP/:

How should I use fscanf() to retrieve the userID, the integer, and the string between $$ and :`?

This is what I have now, but it is not working.

int main(){
    FILE * file = fopen("shadow.txt", "r");
    char line[256] = {0};
    char userID[30] = {0};
    int hashType;
    char hash[256] = {0};
    int result = fscanf(file, "%s :$ %d $$ %s :", userID, &hashType, hash);
    printf("%s\n", userID );
    printf("%d\n", hashType );
    printf("%s\n", hash );

}

I don't know much about the format I should specify for fscanf() to achieve this. Please help.

Body:
Try this:

while(ret = fscanf(file," %[^:] : $ %d $$ %[^:] :",userID,&hashtype,hash))
{

    if(ret == EOF)
    {
        break;
    }

    printf("value of ret: %d\n",ret);
    printf("%s , %d , %s",userid,id,str);

    // . . .

}

here, int ret is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input