问:
popup with jquery ui in asp.net mvc2
I work on a project using ASP.NET MVC 2 (C#). I use the jQueryUI JavaScript library to show a popup window to list the different themes in my database. In my view I use the following code:

```<code><script language="javascript" type="text/javascript">
$(function () {
    $('#dialog').dialog({
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function () {

                              $("#dialog").dialog("close");

            },
            "Cancel": function () { $(this).dialog("close"); }
        }
    });
    $("#show-dialog").button().click(function () {
        $('#dialog').dialog('open');
        return false;
    });
});
</script>

<div id="dialog" title="choisir le thème "  >

<% using (Html.BeginForm())
{ %>
    <p> <span style="color: #0000FF"><strong><em>Titre du document :
    <%=Html.TextBox("Title")  %></em></strong></span>  </p>
    <table>
        <thead>
            <tr>
                <th style="width: 184px">Liste des thèmes </th><th> </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td valign="top" style="width: 184px; height: 131px">
                    <%= Html.ListBoxFor(model => model.SelectedThème, Model.ThèmeList, new { size = "6" })%>
                </td>
            </tr>
        </tbody>
    </table>
     <% } %>
</div>

<span id="show-dialog">thème</span>
<%=Html.TextBox("thème")%>
</code>```

A popup window opens and the list of themes is shown, but when I select a theme the popup should close and the selected theme should be shown in a text box control.
help me please

so my code will :

```<code><script language="javascript" type="text/javascript">
$(function () {
    $('#dialog').dialog({
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function () { $("#thème").val($("#SelectedTheme").val());
                                  $(this).dialog("close"); },
            "Cancel": function () { $(this).dialog("close"); }
        }
    });
    $("#show-dialog").button().click(function () {
        $('#dialog').dialog('open');
        return false;
    });
});

$('#SelectedTheme').change(function () {
    //do whatever you want to do here.
    $("#thème").val($("#SelectedTheme").val());
    $('#dialog').dialog('close');

});

</script>

<div id="dialog" title="choisir le thème "  >

 <% using (Html.BeginForm())
 { %>

  <select id="SelectedTheme" multiple="multiple" name="SelectedTheme">
    <option>item1-in-ThemeList</option>
     <option>item2-in-ThemeList</option>
   </select>

 <% } %>
 </div>

 <fieldset>

 <span id="show-dialog">thème</span>   <%=Html.TextBox("thème")%>
 </fieldset>
</code>```

but when i select a item the popup not close and the value of my text box not change.
help me !!!

答:
Following line

```<code><%= Html.ListBoxFor(model => model.SelectedTheme, Model.ThemeList, new { size = "6" })%>
</code>```

will produce html like this:

```<code><select id="SelectedTheme" multiple="multiple" name="SelectedTheme">
<option>item1-in-ThemeList</option>
<option>item2-in-ThemeList</option>
....
</select>
</code>```

So you would know what to do with following jquery pattern:

```<code>$('#SelectedTheme').live('change', function()
{
    //do whatever you want to do here.
    $("#theme").val($("#SelectedTheme").val());
    $('#dialog').dialog('close');

});
</code>```

Title: popup with jquery ui in asp.net mvc2

Body:
I work on a project using ASP.NET MVC 2 (C#). I use the jQueryUI JavaScript library to show a popup window to list the different themes in my database. In my view I use the following code:

<% using (Html.BeginForm())
{ %>

 Titre du document :
    <%=Html.TextBox("Title")  %>

                Liste des thèmes

                    <%= Html.ListBoxFor(model => model.SelectedThème, Model.ThèmeList, new { size = "6" })%>

     <% } %>

thème
<%=Html.TextBox("thème")%>

A popup window opens and the list of themes is shown, but when I select a theme the popup should close and the selected theme should be shown in a text box control.
help me please

so my code will :

 <% using (Html.BeginForm())
 { %>

  <select id="SelectedTheme" multiple="multiple" name="SelectedTheme">
    <option>item1-in-ThemeList</option>
     <option>item2-in-ThemeList</option>
   </select>

 <% } %>

 <fieldset>

 thème   <%=Html.TextBox("thème")%>
 </fieldset>

but when i select a item the popup not close and the value of my text box not change.
help me !!!

Body:
Following line

<%= Html.ListBoxFor(model => model.SelectedTheme, Model.ThemeList, new { size = "6" })%>

will produce html like this:

<select id="SelectedTheme" multiple="multiple" name="SelectedTheme">
<option>item1-in-ThemeList</option>
<option>item2-in-ThemeList</option>
....
</select>

So you would know what to do with following jquery pattern:

$('#SelectedTheme').live('change', function()
{
    //do whatever you want to do here.
    $("#theme").val($("#SelectedTheme").val());
    $('#dialog').dialog('close');

});


来源: stackexchange

问:
Associate results of query to datagridview under specific cell
Hi i've a datagridview and i want to specify the results of query under the specific field "MEASUREMENT"

```<code>protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-9UN2C31;Initial Catalog=projectdatabase;Integrated Security=True");
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT nome_misurazione FROM measurements INNER JOIN projectmeasurement ON measurements.id_misurazione = projectmeasurement.id_misuraz INNER JOIN project ON project.id_progetto = projectmeasurement.id_progetto INNER JOIN login ON project.id_login = login.id WHERE project.id_progetto = @id_progetto";
    cmd.Parameters.AddWithValue("@id_progetto", myproject.v);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    con.Close();

}
</code>```

Here there is the query result and i want to add it under specific field call MEASUREMENT in datagridview. Gridview Code:

```<code>         <div align ="center"style="margin-top:100px;">
             <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4">
                 <Columns>
                     <asp:BoundField HeaderText="MEASUREMENT" />
                     <asp:ButtonField ButtonType="Button" Text="VIEW">
                     <ControlStyle BackColor="Red" />
                     </asp:ButtonField>
                     <asp:ButtonField ButtonType="Button" Text="DELETE">
                     <ControlStyle BackColor="Red" />
                     </asp:ButtonField>
                 </Columns>
                 <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                 <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                 <RowStyle BackColor="White" ForeColor="#330099" />
                 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                 <SortedAscendingCellStyle BackColor="#FEFCEB" />
                 <SortedAscendingHeaderStyle BackColor="#AF0101" />
                 <SortedDescendingCellStyle BackColor="#F6F0C0" />
                 <SortedDescendingHeaderStyle BackColor="#7E0000" />
             </asp:GridView>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
         </div>
</code>```

答:
Well, if measurement is some PK value, then just left join it in base query you have.

In other words, it probably one value, so a simple join should do the trick.

I mean, I might have say this:

```<code>SELECT ID, FirstName, LastName, Hotel_ID from People
</code>```

Now, of couse I don't want to display Hotel_ID from tblHotels, but I want the Hotel Name, so I would build the query like this:

Note how we use a LEFT JOIN, since the Hotel_ID might be blank (not set).

In effect, the simple above query is a lookup for the Hotel_ID, and now we can use the nice text name in place of the ID.

```<code>SELECT        People.ID, People.Firstname, People.LastName, tblHotels.HotelName
FROM            People LEFT  JOIN
                         tblHotels ON People.Hotel_ID = tblHotels.ID
</code>```

Now, you CAN RUN a whole sql query for each row by using the data row bound event, but I don't think we need to do that.

ContentLicense: CC BY-SA 4.0

Body:
Hi i've a datagridview and i want to specify the results of query under the specific field "MEASUREMENT"

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-9UN2C31;Initial Catalog=projectdatabase;Integrated Security=True");
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT nome_misurazione FROM measurements INNER JOIN projectmeasurement ON measurements.id_misurazione = projectmeasurement.id_misuraz INNER JOIN project ON project.id_progetto = projectmeasurement.id_progetto INNER JOIN login ON project.id_login = login.id WHERE project.id_progetto = @id_progetto";
    cmd.Parameters.AddWithValue("@id_progetto", myproject.v);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    con.Close();

}

Here there is the query result and i want to add it under specific field call MEASUREMENT in datagridview. Gridview Code:

             <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4">
                 <Columns>
                     <asp:BoundField HeaderText="MEASUREMENT" />
                     <asp:ButtonField ButtonType="Button" Text="VIEW">
                     <ControlStyle BackColor="Red" />
                     </asp:ButtonField>
                     <asp:ButtonField ButtonType="Button" Text="DELETE">
                     <ControlStyle BackColor="Red" />
                     </asp:ButtonField>
                 </Columns>
                 <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                 <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                 <RowStyle BackColor="White" ForeColor="#330099" />
                 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                 <SortedAscendingCellStyle BackColor="#FEFCEB" />
                 <SortedAscendingHeaderStyle BackColor="#AF0101" />
                 <SortedDescendingCellStyle BackColor="#F6F0C0" />
                 <SortedDescendingHeaderStyle BackColor="#7E0000" />
             </asp:GridView>
             <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>

Body:
Well, if measurement is some PK value, then just left join it in base query you have.

In other words, it probably one value, so a simple join should do the trick.

I mean, I might have say this:

SELECT ID, FirstName, LastName, Hotel_ID from People

Now, of couse I don't want to display Hotel_ID from tblHotels, but I want the Hotel Name, so I would build the query like this:

Note how we use a LEFT JOIN, since the Hotel_ID might be blank (not set).

In effect, the simple above query is a lookup for the Hotel_ID, and now we can use the nice text name in place of the ID.

SELECT        People.ID, People.Firstname, People.LastName, tblHotels.HotelName
FROM            People LEFT  JOIN
                         tblHotels ON People.Hotel_ID = tblHotels.ID

Now, you CAN RUN a whole sql query for each row by using the data row bound event, but I don't think we need to do that.


问:
How to Combine columns from multiple query results in mySQL?
I need to combine the columns resulting from running two different queries in mySQL.

Query A :

```<code>SELECT us.id as RecruiterID,
       concat(us.first_name," ",us.last_name) as Recruiter,
       count(aj.current_step>6) as Submissions
FROM applied_jobs as aj
LEFT JOIN job_postings as jp ON aj.job_posting_id=jp.id
LEFT JOIN users as us ON aj.applied_by_id=us.id
WHERE aj.created_at BETWEEN CURDATE() AND CURDATE()+1
AND aj.current_step>6
group by Recruiter
</code>```

Query B :

```<code>SELECT concat(us.first_name," ",us.last_name) as Recruiter,
       COUNT(sc.applied_jobs_id) as SELECTIONS
FROM `selected_candidates` as sc
LEFT JOIN applied_jobs as aj ON sc.applied_jobs_id=aj.id
LEFT JOIN users as us ON aj.applied_by_id=us.id
WHERE sc.`created_at` BETWEEN CURDATE() AND CURDATE()+1
GROUP BY Recruiter
</code>```

答:
Even though your question needs a bit of clarity , you could use UNION ALL and in an outer query do the select and add aggregate function SUM in your case grouping by  Recruiter. Note that I added null as selections and null as submissions.

Try:

```<code>select t1.Recruiter,
       sum(t1.Submissions) as submissions,
       sum(t1.selections) as selections
from (

         SELECT
                concat(us.first_name," ",us.last_name) as Recruiter,
                count(aj.current_step>6) as submissions,
                null as selections
         FROM applied_jobs as aj
         LEFT JOIN job_postings as jp ON aj.job_posting_id=jp.id
         LEFT JOIN users as us ON aj.applied_by_id=us.id
         WHERE aj.created_at BETWEEN CURDATE() AND CURDATE()+1
         AND aj.current_step>6
         group by Recruiter

         union all

         SELECT concat(us.first_name," ",us.last_name) as Recruiter,
                null as submissions,
                COUNT(sc.applied_jobs_id) as selections
         FROM `selected_candidates` as sc
         LEFT JOIN applied_jobs as aj ON sc.applied_jobs_id=aj.id
         LEFT JOIN users as us ON aj.applied_by_id=us.id
         WHERE sc.`created_at` BETWEEN CURDATE() AND CURDATE()+1
         GROUP BY Recruiter

    ) as t1
group by t1.Recruiter;
</code>```

Body:
I need to combine the columns resulting from running two different queries in mySQL.

Query A :

SELECT us.id as RecruiterID,
       concat(us.first_name," ",us.last_name) as Recruiter,
       count(aj.current_step>6) as Submissions
FROM applied_jobs as aj
LEFT JOIN job_postings as jp ON aj.job_posting_id=jp.id
LEFT JOIN users as us ON aj.applied_by_id=us.id
WHERE aj.created_at BETWEEN CURDATE() AND CURDATE()+1
AND aj.current_step>6
group by Recruiter

Query B :

SELECT concat(us.first_name," ",us.last_name) as Recruiter,
       COUNT(sc.applied_jobs_id) as SELECTIONS
FROM `selected_candidates` as sc
LEFT JOIN applied_jobs as aj ON sc.applied_jobs_id=aj.id
LEFT JOIN users as us ON aj.applied_by_id=us.id
WHERE sc.`created_at` BETWEEN CURDATE() AND CURDATE()+1
GROUP BY Recruiter

Body:
Even though your question needs a bit of clarity , you could use UNION ALL and in an outer query do the select and add aggregate function SUM in your case grouping by  Recruiter. Note that I added null as selections and null as submissions.

Try:

select t1.Recruiter,
       sum(t1.Submissions) as submissions,
       sum(t1.selections) as selections
from (

         SELECT
                concat(us.first_name," ",us.last_name) as Recruiter,
                count(aj.current_step>6) as submissions,
                null as selections
         FROM applied_jobs as aj
         LEFT JOIN job_postings as jp ON aj.job_posting_id=jp.id
         LEFT JOIN users as us ON aj.applied_by_id=us.id
         WHERE aj.created_at BETWEEN CURDATE() AND CURDATE()+1
         AND aj.current_step>6
         group by Recruiter

         union all

         SELECT concat(us.first_name," ",us.last_name) as Recruiter,
                null as submissions,
                COUNT(sc.applied_jobs_id) as selections
         FROM `selected_candidates` as sc
         LEFT JOIN applied_jobs as aj ON sc.applied_jobs_id=aj.id
         LEFT JOIN users as us ON aj.applied_by_id=us.id
         WHERE sc.`created_at` BETWEEN CURDATE() AND CURDATE()+1
         GROUP BY Recruiter

    ) as t1
group by t1.Recruiter;


问:
Can I run a function when I quit my Node App?
I'm working on a project for school in Node.js on a Raspberry Pi. I have a script that is running and will run for long periods of time controlling some LEDs. Is there a way that I can run a function when I quit the program to turn off all the LEDs I'm using (Stop power to the GPIO)?</p>

答:
You can handle the SIGINT (CTRL-C) signal. Something like:

```<code>function cleanup() {
  // do clean up here
  console.log("clean up");
}

process.on("SIGINT", () => {
  cleanup();
  process.exit(0);
});
</code>```

Body:
You can handle the SIGINT (CTRL-C) signal. Something like:

function cleanup() {
  // do clean up here
  console.log("clean up");
}

process.on("SIGINT", () => {
  cleanup();
  process.exit(0);
});


问:
NSTextAttachment images are not dynamic (light/dark mode)
I have an image that is dynamic for light/dark mode. If I place this image in a UIImageView, the dynamism works: when the user switches from light to dark mode and back, the image changes the version of itself that is displayed. But if I place the same image in an NSAttributedString as an NSTextAttachment and display the string in a label, the dynamism does not work: when the user switches from light to dark mode, the image does not change.

To see the problem in action, paste this code into your viewDidLoad:

```<code>    let size = CGSize(width: 20, height: 20)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image1 = renderer.image {
        UIColor.red.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let image2 = renderer.image {
        UIColor.green.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let asset = UIImageAsset()
    asset.register(image1, with: .init(userInterfaceStyle: .light))
    asset.register(image2, with: .init(userInterfaceStyle: .dark))

    let iv = UIImageView(image: image1)
    iv.frame.origin = .init(x: 100, y: 100)
    self.view.addSubview(iv)

    let text = NSMutableAttributedString(string: "Howdy ", attributes: [
        .foregroundColor: UIColor(dynamicProvider: { traits in
            switch traits.userInterfaceStyle {
            case .light: return .red
            case .dark: return .green
            default: return .red
            }
        })
    ])
    let attachment = NSTextAttachment(image: image1)
    let attachmentCharacter = NSAttributedString(attachment: attachment)
    text.append(attachmentCharacter)

    let label = UILabel()
    label.attributedText = text
    label.sizeToFit()
    label.frame.origin = .init(x: 100, y: 150)
    self.view.addSubview(label)
</code>```

I have deliberately made the text font color dynamic so that you can see that in general color dynamism does work in an attributed string. But not in an attributed string's text attachment!

So: Is this really how iOS behaves, or am I making some mistake in the way I'm configuring the text attachment? If this is how iOS behaves, how are you working around the issue?

[Note that I cannot use an iOS 15 attachment view provider, because I have to be compatible with iOS 13 and 14. So maybe that would solve the problem, but that solution is not open to me.]

答:
Just for the record, here's my rewrite of Larme's suggestion. I made this an extension on UILabel:

```<code>extension UILabel {
    func updateAttachments() {
        guard let attributedString = attributedText else { return }
        let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
        attributedString.enumerateAttribute(.attachment, in: .init(location: 0, length: attributedString.string.utf16.count), options: []) { value, range, stop in
            guard let attachment = value as? NSTextAttachment else { return }
            guard let image = attachment.image else { return }
            guard let asset = image.imageAsset else { return }
            attachment.image = asset.image(with: .current)
            mutableAttributedString.setAttributes([.attachment: attachment], range: range)
        }
        attributedText = mutableAttributedString
    }
}
</code>```

And now, assuming I have a reference to the troublesome UILabel:

```<code>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    guard let previousTraitCollection = previousTraitCollection else { return }
    if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
        label.updateAttachments()
    }
}
</code>```

It would be really nice to inject that override into all UILabels so they could just update themselves, but unfortunately extensions don't work that way, and I can't turn all the UILabels in my app into a UILabel subclass.

Body:
I have an image that is dynamic for light/dark mode. If I place this image in a UIImageView, the dynamism works: when the user switches from light to dark mode and back, the image changes the version of itself that is displayed. But if I place the same image in an NSAttributedString as an NSTextAttachment and display the string in a label, the dynamism does not work: when the user switches from light to dark mode, the image does not change.

To see the problem in action, paste this code into your viewDidLoad:

    let size = CGSize(width: 20, height: 20)
    let renderer = UIGraphicsImageRenderer(size: size)
    let image1 = renderer.image {
        UIColor.red.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let image2 = renderer.image {
        UIColor.green.setFill()
        $0.fill(.init(origin: .zero, size: size))
    }
    let asset = UIImageAsset()
    asset.register(image1, with: .init(userInterfaceStyle: .light))
    asset.register(image2, with: .init(userInterfaceStyle: .dark))

    let iv = UIImageView(image: image1)
    iv.frame.origin = .init(x: 100, y: 100)
    self.view.addSubview(iv)

    let text = NSMutableAttributedString(string: "Howdy ", attributes: [
        .foregroundColor: UIColor(dynamicProvider: { traits in
            switch traits.userInterfaceStyle {
            case .light: return .red
            case .dark: return .green
            default: return .red
            }
        })
    ])
    let attachment = NSTextAttachment(image: image1)
    let attachmentCharacter = NSAttributedString(attachment: attachment)
    text.append(attachmentCharacter)

    let label = UILabel()
    label.attributedText = text
    label.sizeToFit()
    label.frame.origin = .init(x: 100, y: 150)
    self.view.addSubview(label)

I have deliberately made the text font color dynamic so that you can see that in general color dynamism does work in an attributed string. But not in an attributed string's text attachment!

So: Is this really how iOS behaves, or am I making some mistake in the way I'm configuring the text attachment? If this is how iOS behaves, how are you working around the issue?

[Note that I cannot use an iOS 15 attachment view provider, because I have to be compatible with iOS 13 and 14. So maybe that would solve the problem, but that solution is not open to me.]

Body:
Just for the record, here's my rewrite of Larme's suggestion. I made this an extension on UILabel:

extension UILabel {
    func updateAttachments() {
        guard let attributedString = attributedText else { return }
        let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
        attributedString.enumerateAttribute(.attachment, in: .init(location: 0, length: attributedString.string.utf16.count), options: []) { value, range, stop in
            guard let attachment = value as? NSTextAttachment else { return }
            guard let image = attachment.image else { return }
            guard let asset = image.imageAsset else { return }
            attachment.image = asset.image(with: .current)
            mutableAttributedString.setAttributes([.attachment: attachment], range: range)
        }
        attributedText = mutableAttributedString
    }
}

And now, assuming I have a reference to the troublesome UILabel:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    guard let previousTraitCollection = previousTraitCollection else { return }
    if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
        label.updateAttachments()
    }
}

It would be really nice to inject that override into all UILabels so they could just update themselves, but unfortunately extensions don't work that way, and I can't turn all the UILabels in my app into a UILabel subclass.


问:
update Eclipse Android project to next version
I have an android project in Eclipse I started developing in android version 2.2.? (i think).  I want to update the project to run on my 2.3.3 device.  Is there a way to upgrade the project or do I need to create a new one?</p>

答:
So based on your question... I just want to say that an Android 2.2 application will run on your 2.3.3 device without changes.  (i.e., applications are forward compatible)

If you still want to change your platform version, read on.

Right click your project in the Project Explorer pane and select "Properties."  The window that comes up will look like the following and you can select a different platform target.

If your project then reports some property related errors in the Problems pane, you can fix those by right-clicking your project again and selecting the Android Tools --> Fix Project Properties menu item:

There's a uses-sdk element in your AndroidManifest.xml file, the minSdkVersion attribute should always be set to something, especially if you're going to put your application in the Android Market.  The corresponding API levels for Android are well documented.

ContentLicense: CC BY-SA 3.0


问:
Deep Copy Constructor for Linked List in Java
I have a HW assignment and only one small part of it is to make a copy constructor which makes a Deep Copy of the linked list which you have entered in its parameters.

I understand that this means, that the List you have entered remains unchanged, and that the new linked list is isolated from the "old" one. My code gives me a new list which is exactly the same as the old one (the one you enter as a parameter) and this is what I want, but the old one is changed.

Here is the constructor:

```<code>public SortedLinkedSet(SortedLinkedSet<T> copy) {
    if (copy == null) {
        this.firstNode = null;
    } else{
        SortedLinkedSetNode firstNode1 = new SortedLinkedSetNode(copy.getFirstNode().value);
        this.firstNode = firstNode1;
       // so basically I am chaining elements from "copy" to firstNode1 and then making "this" = to firstNode1.
        while (copy.firstNode.next !=null) {
            firstNode1.add(copy.getFirstNode().next.value);
            this.firstNode = firstNode1;
            copy.firstNode = copy.firstNode.next;
       // at the end of this loop I have a successful new linkedList with the same value, but "copy" has been changed
        }
    }
}
</code>```

If for example I enter a linked list which has the values (1,2,3) -- with this constructor i get back a new linked list with values 1,2,3 but the old one just has 1.. If someone can help me with why this is going wrong it would be great. Thanks

UPDATE : As  Ireeder pointed out, and with a test I did, I am almost sure that the problem is in the statement :
    copy.firstNode = copy.firstNode.next;
i deleted the current code, and did the following test:

```<code>SortedLinkedSetNode firstNode = new SortedLinkedSetNode(copy.getFirstNode().value);
this.firstNode=firstNode;

firstNode.add(copy.getFirstNode().next.value);
this.firstNode = firstNode;

firstNode.add(copy.getFirstNode().next.next.value);
this.firstNode = firstNode;
</code>```

and this Works perfectly(but I knew in advance i'm testing with only 3 element list).How would i do it with a while loop without using such a statement as  :
     copy.firstNode = copy.firstNode.next;
I have to somehow move along the "copy" list ?

答:
First the original to copy from, is called copy, like in do copy this one?

You did have some mix-up with the correct nodes and the code was not kept simple enough.

A recursive solution to simplify things seems appropriate:

```<code>public SortedLinkedSet(SortedLinkedSet<T> original) {
    Objects.requireNotNull(original);
    this.firstNode = copyNodes(orignal.firstNode);
}

private SortedLinkedSetNode copy(SortedLinkedSetNode originalNode) {
    if (originalNode == null) {
        return null;
    }
    SortedLinkedSetNode node = new SortedLinkedSetNode(originalNode.value);
    node.next = copy(originalNode.next);
    return node;
}
</code>```

If the node's value would need deep copying too, that could be done at one place.

A loop would still be simple. One way:

```<code>private SortedLinkedSetNode copy(SortedLinkedSetNode originalNode) {
    SortedLinkedSetNode firstNode = null;
    SortedLinkedSetNode previousNode = null;
    while (originalNode != null) {
        SortedLinkedSetNode node = new SortedLinkedSetNode(originalNode.value);
        if (firstNode == null) {
            firstNode = node;
        } else {
            previousNode.next = node;
        }
        previousNode = node;
        originalNode = originalNode.next;
    }
    return firstNode;
}
</code>```

Body:
I have a HW assignment and only one small part of it is to make a copy constructor which makes a Deep Copy of the linked list which you have entered in its parameters.

I understand that this means, that the List you have entered remains unchanged, and that the new linked list is isolated from the "old" one. My code gives me a new list which is exactly the same as the old one (the one you enter as a parameter) and this is what I want, but the old one is changed.

Here is the constructor:

public SortedLinkedSet(SortedLinkedSet<T> copy) {
    if (copy == null) {
        this.firstNode = null;
    } else{
        SortedLinkedSetNode firstNode1 = new SortedLinkedSetNode(copy.getFirstNode().value);
        this.firstNode = firstNode1;
       // so basically I am chaining elements from "copy" to firstNode1 and then making "this" = to firstNode1.
        while (copy.firstNode.next !=null) {
            firstNode1.add(copy.getFirstNode().next.value);
            this.firstNode = firstNode1;
            copy.firstNode = copy.firstNode.next;
       // at the end of this loop I have a successful new linkedList with the same value, but "copy" has been changed
        }
    }
}

If for example I enter a linked list which has the values (1,2,3) -- with this constructor i get back a new linked list with values 1,2,3 but the old one just has 1.. If someone can help me with why this is going wrong it would be great. Thanks

UPDATE : As  Ireeder pointed out, and with a test I did, I am almost sure that the problem is in the statement :
    copy.firstNode = copy.firstNode.next;
i deleted the current code, and did the following test:

SortedLinkedSetNode firstNode = new SortedLinkedSetNode(copy.getFirstNode().value);
this.firstNode=firstNode;

firstNode.add(copy.getFirstNode().next.value);
this.firstNode = firstNode;

firstNode.add(copy.getFirstNode().next.next.value);
this.firstNode = firstNode;

and this Works perfectly(but I knew in advance i'm testing with only 3 element list).How would i do it with a while loop without using such a statement as  :
     copy.firstNode = copy.firstNode.next;
I have to somehow move along the "copy" list ?

Body:
First the original to copy from, is called copy, like in do copy this one?

You did have some mix-up with the correct nodes and the code was not kept simple enough.

A recursive solution to simplify things seems appropriate:

public SortedLinkedSet(SortedLinkedSet<T> original) {
    Objects.requireNotNull(original);
    this.firstNode = copyNodes(orignal.firstNode);
}

private SortedLinkedSetNode copy(SortedLinkedSetNode originalNode) {
    if (originalNode == null) {
        return null;
    }
    SortedLinkedSetNode node = new SortedLinkedSetNode(originalNode.value);
    node.next = copy(originalNode.next);
    return node;
}

If the node's value would need deep copying too, that could be done at one place.

A loop would still be simple. One way:

private SortedLinkedSetNode copy(SortedLinkedSetNode originalNode) {
    SortedLinkedSetNode firstNode = null;
    SortedLinkedSetNode previousNode = null;
    while (originalNode != null) {
        SortedLinkedSetNode node = new SortedLinkedSetNode(originalNode.value);
        if (firstNode == null) {
            firstNode = node;
        } else {
            previousNode.next = node;
        }
        previousNode = node;
        originalNode = originalNode.next;
    }
    return firstNode;
}


问:
Authorization not found In Php 8
Authorization not found when using below code in php 8 (xampp), it working in php 7(xampp)

Undefined Authorization key.

```<code>require "../vendor_big/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require $_SERVER['DOCUMENT_ROOT'].'/db.php';

$data = (json_decode(file_get_contents("php://input"), true));
$authHeader = apache_request_headers();
// print_r($authHeader);
$secret_key = "bmR0di1zYWxlcy1hcHAtYWR0ZWNoLXJpc2hp";
$jwt = null;
$arr = explode(" ", $authHeader["Authorization"]);
$jwt = $arr[1];
</code>```

output

```<code>Array
(
    [Host] => localhost:8080
    [Connection] => keep-alive
    [sec-ch-ua] => " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
    [sec-ch-ua-mobile] => ?0
    [sec-ch-ua-platform] => "Windows"
    [Upgrade-Insecure-Requests] => 1
    [User-Agent] => Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
    [Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
    [Sec-Fetch-Site] => none
    [Sec-Fetch-Mode] => navigate
    [Sec-Fetch-User] => ?1
    [Sec-Fetch-Dest] => document
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
)
</code>```

how to get authorization?

答: Related table not found in database. When all table added then this issue not appear.</p>

Title: Authorization not found In Php 8

Body:
Authorization not found when using below code in php 8 (xampp), it working in php 7(xampp)

Undefined Authorization key.

require "../vendor_big/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require $_SERVER['DOCUMENT_ROOT'].'/db.php';

$data = (json_decode(file_get_contents("php://input"), true));
$authHeader = apache_request_headers();
// print_r($authHeader);
$secret_key = "bmR0di1zYWxlcy1hcHAtYWR0ZWNoLXJpc2hp";
$jwt = null;
$arr = explode(" ", $authHeader["Authorization"]);
$jwt = $arr[1];

output

Array
(
    [Host] => localhost:8080
    [Connection] => keep-alive
    [sec-ch-ua] => " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
    [sec-ch-ua-mobile] => ?0
    [sec-ch-ua-platform] => "Windows"
    [Upgrade-Insecure-Requests] => 1
    [User-Agent] => Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36
    [Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
    [Sec-Fetch-Site] => none
    [Sec-Fetch-Mode] => navigate
    [Sec-Fetch-User] => ?1
    [Sec-Fetch-Dest] => document
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
)

how to get authorization?


问:
Convert .py to .exe with cmd
I was trying to convert my main.py to a exe file

I followed a tutorial on youtube i did it like it said

first open cmd in the folder

then type in pip install pyinstaller

then type in like this pyinstaller --onefile main.py
but it does'nt convert it shows this

答:
This issue is probably caused because pyinstaller is not in the PATH environment variable.

First, find the full path of pyinstaller.exe - it should be in the Scripts directory of your Python installation (probably C:\Users\[USERNAME]\AppData\Local\Programs\Python\[Python_VER]\Scripts). Copy the full path.

Then open a command prompt (as Administrator) and run the command:

```<code>setx PATH "%PATH%;PYINSTALLER_PATH"
</code>```

where PYINSTALLER_PATH is the full path of pyinstaller you have copied.

Then re-launch command prompt and run the command again.

Title: Convert .py to .exe with cmd

Body:
This issue is probably caused because pyinstaller is not in the PATH environment variable.

First, find the full path of pyinstaller.exe - it should be in the Scripts directory of your Python installation (probably C:\Users\[USERNAME]\AppData\Local\Programs\Python\[Python_VER]\Scripts). Copy the full path.

Then open a command prompt (as Administrator) and run the command:

setx PATH "%PATH%;PYINSTALLER_PATH"

where PYINSTALLER_PATH is the full path of pyinstaller you have copied.

Then re-launch command prompt and run the command again.


问:
Find nearest location based on coordinates in pyspark
I have one dataframe which contains names of stations and its coordinates.
I want for every station the nearest station based on its coordinates.

What i have is 2 functions:

```<code>import math
def dist2(lat1, long1, lat2, long2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lat1, long1, lat2, long2 = map(lambda x: x*pi /180.0, [lat1, long1, lat2, long2])
    # haversine formula
    dlon = long2 - long1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    # Radius of earth in kilometers is 6371
    km = 6371* c
    return km
</code>```
```<code>def find_nearest2(lat, lng):

    min_dist =100000
    min_index = None
    distances = df_onlystations_clean.apply(
    lambda row: dist2(lat, lng, row['lat'], row['lng']),
    axis=1)
    if d < min_dist:
      min_dist = d

    return df_onlystations_clean.loc[min_dist.idxmin(), 'name']
</code>```
```<code>df_onlystations_clean.apply(
    lambda row: find_nearest2(row['lat'], row['lng']),
    axis=1)
</code>```

I always get the same error: 'DataFrame' object has no attribute 'apply'
How can I loop through the df. What I'm doing wrong??

答:
It's because a Spark dataframe is not a Pandas dataframe, you cannot loop over the rows or call the apply method.

You'd have to use Spark udf API to pass a Python user define function on the data.

Body:
I have one dataframe which contains names of stations and its coordinates.
I want for every station the nearest station based on its coordinates.

What i have is 2 functions:

import math
def dist2(lat1, long1, lat2, long2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lat1, long1, lat2, long2 = map(lambda x: x*pi /180.0, [lat1, long1, lat2, long2])
    # haversine formula
    dlon = long2 - long1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    # Radius of earth in kilometers is 6371
    km = 6371* c
    return km

def find_nearest2(lat, lng):

    min_dist =100000
    min_index = None
    distances = df_onlystations_clean.apply(
    lambda row: dist2(lat, lng, row['lat'], row['lng']),
    axis=1)
    if d < min_dist:
      min_dist = d

    return df_onlystations_clean.loc[min_dist.idxmin(), 'name']

df_onlystations_clean.apply(
    lambda row: find_nearest2(row['lat'], row['lng']),
    axis=1)

I always get the same error: 'DataFrame' object has no attribute 'apply'
How can I loop through the df. What I'm doing wrong??


问:
Manage NugetPackage for Solution can't find any online packages
Somehow, the "Manage NuGet Packages for Solution..." Dialog doesn't show any online packages anymore (no items found.):

But the "Manage NuGet Packages..." dialog at the project level works fine.

I already tryed to start Visual Studio (2013 Update 4) with the /Log Parameter but cannot find any errors in the ActivityLog.xml.

Any Ideas?

答:
The package source is missing from your nuget manager.

Without experimenting too much I see two ways to solve it. (as of vs17/2021)

Do as the answer above (remove nuget.config and restart visual studio)

Add nuget as source through menu:Tool->Options->NugetPackageManger->PackageSources and add [name='nuget'], [source='https://api.nuget.org/v3/index.json'] (image below)

For more clarity: I did as 1) and my nuget.config went from

```<code><?xml version="1.0"?>
<configuration>
  <packageSources>
  </packageSources>
</configuration>
</code>```

to

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>
</code>```

so a third option would be to hack the nuget.config manually, and restart visual studio.

Body:
The package source is missing from your nuget manager.

Without experimenting too much I see two ways to solve it. (as of vs17/2021)

Do as the answer above (remove nuget.config and restart visual studio)

Add nuget as source through menu:Tool->Options->NugetPackageManger->PackageSources and add [name='nuget'], [source='https://api.nuget.org/v3/index.json'] (image below)

For more clarity: I did as 1) and my nuget.config went from

<?xml version="1.0"?>
<configuration>
  <packageSources>
  </packageSources>
</configuration>

to

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

so a third option would be to hack the nuget.config manually, and restart visual studio.


问:
Responsive iframe with fixed height
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

```<code><div class="container">
<div class="video-wrapper">
<iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
</div>
</div>
</code>```

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}
```

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

答:
So you need to edit some of the CSS to make it work

Live result on: Codepen.io

```<code>.container {
  max-width: 1240px;
  overflow: hidden;
}

.video-wrapper {
  margin-left: calc((100% - 1240px) / 2);
}

.video {
  width: 1240px;
  height: 700px;
}
</code>```

Explanation:

Set up your container to be responsive, but set overflow to hidden as you don't want a scrollbar when the child element with the iframe gets wider then the container.

Set your video to the correct resolution for a fixed height of 700px, I determend it was 1240px wide by trial and error (you could calculate it).

Now to keep the video in the middle when the screen gets smaller we need to keep in mind that it's not the video that's shrinking but the parent container. So we're just adjusting the view that shows the video. The parts that don't fit in that view need to be equally divided and hidden on the left and right side of the view so that the center of the video is always visible. For that we need to calculate the negative left margin for the video wrapper. Thats the viewport minus the width of the video. Those are the pixels that are not in the view then it needs to be equally divided by 2 (left and right).

Hopefully the explanation makes sense when you take another look at the CSS.

Title: Responsive iframe with fixed height

Body:
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

Body:
So you need to edit some of the CSS to make it work

Live result on: Codepen.io

.container {
  max-width: 1240px;
  overflow: hidden;
}

.video-wrapper {
  margin-left: calc((100% - 1240px) / 2);
}

.video {
  width: 1240px;
  height: 700px;
}

Explanation:

Set up your container to be responsive, but set overflow to hidden as you don't want a scrollbar when the child element with the iframe gets wider then the container.

Set your video to the correct resolution for a fixed height of 700px, I determend it was 1240px wide by trial and error (you could calculate it).

Now to keep the video in the middle when the screen gets smaller we need to keep in mind that it's not the video that's shrinking but the parent container. So we're just adjusting the view that shows the video. The parts that don't fit in that view need to be equally divided and hidden on the left and right side of the view so that the center of the video is always visible. For that we need to calculate the negative left margin for the video wrapper. Thats the viewport minus the width of the video. Those are the pixels that are not in the view then it needs to be equally divided by 2 (left and right).

Hopefully the explanation makes sense when you take another look at the CSS.


问:
How to trigger child elements continuous
depending on which container I click, I would like to add a class to the equal box.
So if I click on the first container -> add class to first box.

In my script I have to write it for each container and duplicate it.. - but I guess there is a way to make it easier? At the end there will be around 100 entries

This HTML:

```<code><div id="row">
  <div class="container">
    <div class="info">A</div>
  </div>
  <div class="container">
    <div class="info">B</div>
  </div>
  <div class="container">
    <div class="info">C</div>
  </div>
  <div class="container">
    <div class="info">D</div>
  </div>
</div>

<div id="row-second">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
</div>
</code>```

This Script:

```<code>    $("#row .container:nth-child(1) div.info").on("click", function() {

      $("#row-second div.box:nth-child(1)").addClass("show");

    });

    $("#row .container:nth-child(2) div.info").on("click", function() {

      $("#row-second div.box:nth-child(2)").addClass("show");

    });
....
</code>```

答:
Something like this should work:

$("#row").on("click", ".container div.info", function() {
  const index = $(this).closest(".container").prevAll(".container").length;
  $(`#row-second div.box:nth-child(${index + 1})`).toggleClass("show");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#row {
  display: flex;
}

.container {
  margin: 5px;
  padding: 5px;
  outline: 1px dotted black;
  cursor: pointer;
  flex: 1 0 2em;
}

#row-second {
  display: flex;
}

#row-second .box {
  margin: 5px;
  padding: 5px;
  outline: 1px dotted black;
  flex: 1 0 2em;
}

.show {
  background-color: #0a0;
  color: white;
}</code>```

A

B

C

D

1

2

3

4

```

Body:
depending on which container I click, I would like to add a class to the equal box.
So if I click on the first container -> add class to first box.

In my script I have to write it for each container and duplicate it.. - but I guess there is a way to make it easier? At the end there will be around 100 entries

This HTML:

A

B

C

D

1

2

3

4

This Script:

    $("#row .container:nth-child(1) div.info").on("click", function() {

      $("#row-second div.box:nth-child(1)").addClass("show");

    });

    $("#row .container:nth-child(2) div.info").on("click", function() {

      $("#row-second div.box:nth-child(2)").addClass("show");

    });
....

Body:
Something like this should work:

$("#row").on("click", ".container div.info", function() {
  const index = $(this).closest(".container").prevAll(".container").length;
  $(`#row-second div.box:nth-child(${index + 1})`).toggleClass("show");
});

#row {
  display: flex;
}

.container {
  margin: 5px;
  padding: 5px;
  outline: 1px dotted black;
  cursor: pointer;
  flex: 1 0 2em;
}

#row-second {
  display: flex;
}

#row-second .box {
  margin: 5px;
  padding: 5px;
  outline: 1px dotted black;
  flex: 1 0 2em;
}

.show {
  background-color: #0a0;
  color: white;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="row">
  <div class="container">
    <div class="info">A</div>
  </div>
  <div class="container">
    <div class="info">B</div>
  </div>
  <div class="container">
    <div class="info">C</div>
  </div>
  <div class="container">
    <div class="info">D</div>
  </div>
</div>

<div id="row-second">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
</div>


问:
How to package a java web application
Our company has developed a web application based on Struts2 + Spring + Hibernate.
My boss wants me to make a installation CD contains JRE, Tomcat, MySQL, and our product, so that the client can just click sth like installMe.exe and follow the wizard to complete the installation.
I used to deploy web application with war. Just put it under tomcat webapps folder, and start tomcat.
Which software should I choose to complete my boss's task?
Thanks, guys.</p>

答:
You need to create an installer script and tell the installer where to put the files. I have used two, advanced installer which creates an MSI or Nullsoft which is from the guys who created winamp. A lot of open source companies are using it. I'd recommend the fist one, and getting a license to do the more complicated stuff. </p>

<p>The installation of Java is handled automatically with advanced installer. There is even a cool java template you can start from. </p>

Title: How to package a java web application

Body:
You need to create an installer script and tell the installer where to put the files. I have used two, advanced installer which creates an MSI or Nullsoft which is from the guys who created winamp. A lot of open source companies are using it. I'd recommend the fist one, and getting a license to do the more complicated stuff.

The installation of Java is handled automatically with advanced installer. There is even a cool java template you can start from.


问:
Flutter parameters transfering across pages: What about the parameter "key"?
I have made two pages, PersonalPage and InformationPage. I want to transfer some parameters from PersonalPage to InformationPage. Here are my codes.
PersonalPage:

```<code>Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Information(phoneNumber: phoneNumber, nickName: nickName, realName: realName, key: key)
          ),
        );
</code>```

InformationPage:

```<code>class Information extends StatelessWidget {
  String? phoneNumber;
  String? realName;
  String? nickName;
  Information({required Key key, required this.phoneNumber, required this.realName, required this.nickName})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    //Some codes
  }
}
</code>```

In PersonalPage, there is an error in the line including "builder:":

```<code>Undefined name 'key'.
</code>```

It seems that I need to assign key. But I don't know what thing I should put to key. So what should I put to key？ Or can I just take measures to avoid assigning it?
Thanks a lot.

答:
You need to pass Key as the key field is set required.</p>
```<code>Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Information(key: Key('keyName'), phoneNumber: phoneNumber, nickName: nickName, realName: realName, key: key)
          ),
        );
</code>```

Body:
I have made two pages, PersonalPage and InformationPage. I want to transfer some parameters from PersonalPage to InformationPage. Here are my codes.
PersonalPage:

Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Information(phoneNumber: phoneNumber, nickName: nickName, realName: realName, key: key)
          ),
        );

InformationPage:

class Information extends StatelessWidget {
  String? phoneNumber;
  String? realName;
  String? nickName;
  Information({required Key key, required this.phoneNumber, required this.realName, required this.nickName})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    //Some codes
  }
}

In PersonalPage, there is an error in the line including "builder:":

Undefined name 'key'.

It seems that I need to assign key. But I don't know what thing I should put to key. So what should I put to key？ Or can I just take measures to avoid assigning it?
Thanks a lot.

Body:
You need to pass Key as the key field is set required.

Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => Information(key: Key('keyName'), phoneNumber: phoneNumber, nickName: nickName, realName: realName, key: key)
          ),
        );


问:
jib gradle plugin does't run tests
I have a skaffold + jib + jib-maven-plugin setup that I use for development.

I run skaffold dev and it builds the project, container image and deploys to my local k8s cluster. Whenever I touch the source code it rebuilds and redeploys containers. The rebuilds trigger maven goals to compile & run unit tests.

This works fine, but is a bit slow since maven recompiles all sources everytime sth changes so I thought I'd give gradle setup a shot and test its incremental compilation capabilities for my project.

It works great, but there's one thing I am bit confused about, that is that jib gradle plugin seems not to be running the test tasks for my sources at all.

```<code>$> gradle jibDockerBuild --dry-run

:my-module:generateMainEffectiveLombokConfig1 SKIPPED
:my-module:compileJava SKIPPED
:my-module:processResources SKIPPED
:my-module:classes SKIPPED
:my-module:jibDockerBuild SKIPPED
</code>```

If I run gradle build the tests tasks are triggered:

```<code>$> gradle build --dry-run
:my-module:generateMainEffectiveLombokConfig1 SKIPPED
:my-module:compileJava SKIPPED
:my-module:processResources SKIPPED
:my-module:classes SKIPPED
:my-module:jar SKIPPED
:my-module:assemble SKIPPED
:my-module:generateTestEffectiveLombokConfig1 SKIPPED
:my-module:compileTestJava SKIPPED
:my-module:processTestResources SKIPPED
:my-module:testClasses SKIPPED
:my-module:test SKIPPED
:my-module:check SKIPPED
:my-module:build SKIPPED
</code>```

I trawled through jib and skaffold documentation and github issues, but I couldn't find anything related to running unit tests as part of the container image creation using jib.

I would think that running unit tests should be mandatory part of building an image and that either gradle jibDockerBuild would run it implicitly just like gradle build does or that skaffold via its integration with jib would somehow trigger those by perhaps running gradle test before jibDockerBuild, but it seems not to be the case.

So the question is how do I make sure my unit tests run when using skaffold with jib and gradle and what's the reason why it doesn't happen automatically....

答:
You can compose testing together with jibDockerBuild by either invoking them together with gradle test jibDockerBuild or by defining a dependency in your configuration with jibDockerBuild.dependsOn test.

As to why it's not done by default -- user requirements differ. For example, you could be building an image prior to running integration tests using it. It's much easier to combine tasks than separate/disable them.

Title: jib gradle plugin does't run tests

Body:
I have a skaffold + jib + jib-maven-plugin setup that I use for development.

I run skaffold dev and it builds the project, container image and deploys to my local k8s cluster. Whenever I touch the source code it rebuilds and redeploys containers. The rebuilds trigger maven goals to compile & run unit tests.

This works fine, but is a bit slow since maven recompiles all sources everytime sth changes so I thought I'd give gradle setup a shot and test its incremental compilation capabilities for my project.

It works great, but there's one thing I am bit confused about, that is that jib gradle plugin seems not to be running the test tasks for my sources at all.

$> gradle jibDockerBuild --dry-run

:my-module:generateMainEffectiveLombokConfig1 SKIPPED
:my-module:compileJava SKIPPED
:my-module:processResources SKIPPED
:my-module:classes SKIPPED
:my-module:jibDockerBuild SKIPPED

If I run gradle build the tests tasks are triggered:

$> gradle build --dry-run
:my-module:generateMainEffectiveLombokConfig1 SKIPPED
:my-module:compileJava SKIPPED
:my-module:processResources SKIPPED
:my-module:classes SKIPPED
:my-module:jar SKIPPED
:my-module:assemble SKIPPED
:my-module:generateTestEffectiveLombokConfig1 SKIPPED
:my-module:compileTestJava SKIPPED
:my-module:processTestResources SKIPPED
:my-module:testClasses SKIPPED
:my-module:test SKIPPED
:my-module:check SKIPPED
:my-module:build SKIPPED

I trawled through jib and skaffold documentation and github issues, but I couldn't find anything related to running unit tests as part of the container image creation using jib.

I would think that running unit tests should be mandatory part of building an image and that either gradle jibDockerBuild would run it implicitly just like gradle build does or that skaffold via its integration with jib would somehow trigger those by perhaps running gradle test before jibDockerBuild, but it seems not to be the case.

So the question is how do I make sure my unit tests run when using skaffold with jib and gradle and what's the reason why it doesn't happen automatically....


问:
Python Turtle Enumerate
Is anyone able to explain this code? My friend wrote it and I don’t understand anything about the line defining “diff”</p>
```<code>import math
import turtle
import random

t = turtle.Turtle()
screen = turtle.Screen()
t.shape("turtle")
t.speed(0)
t.tracer(100)

COLOR = [18.0, 0.0, 41.0]
COLOR_2 = [0.0, 172.0, 219.0]
WIDTH = screen.window_width()
HEIGHT = screen.window_height()

diff = [(hue - COLOR[index]) / HEIGHT for index, hue in enumerate(COLOR_2)]
</code>```

答: If you wanted to evenly distribute values from COLOR to COLOR_2 over HEIGHT steps, this would compute how much to change each component at each step.  For example, if HEIGHT were 2, it would compute [-9.0, 86.0, 89.0].

Title: Python Turtle Enumerate

Body:
Is anyone able to explain this code? My friend wrote it and I don’t understand anything about the line defining “diff”

import math
import turtle
import random

t = turtle.Turtle()
screen = turtle.Screen()
t.shape("turtle")
t.speed(0)
t.tracer(100)

COLOR = [18.0, 0.0, 41.0]
COLOR_2 = [0.0, 172.0, 219.0]
WIDTH = screen.window_width()
HEIGHT = screen.window_height()

diff = [(hue - COLOR[index]) / HEIGHT for index, hue in enumerate(COLOR_2)]


答:
You can use this to identify the element/div being clicked.

You can then use .index() to get where it is within its parent - there's a small issue here in that you have row > container > info so each info index will be 0 - so you need to get the .container's index.

Then use $("#row-second div.box").eq(idx) to find the corresponding box

Added $(".show").removeClass("show"); as the name "show" implies you want to show just the one being clicked and hide the others; obviously remove this if your use-case is to leave them shown.

Updated snippet:

 $("#row .container div.info").on("click", function() {
    var idx = $(this).closest(".container").index();
    $(".show").removeClass("show");
    $("#row-second div.box").eq(idx).addClass("show");
 })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#row div { cursor: pointer; }

#row-second div { display:none; }

#row-second div.show { display:block; }</code>```

A

B

C

D

1

2

3

4

```

Title: How to trigger child elements continuous

Body:
You can use this to identify the element/div being clicked.

You can then use .index() to get where it is within its parent - there's a small issue here in that you have row > container > info so each info index will be 0 - so you need to get the .container's index.

Then use $("#row-second div.box").eq(idx) to find the corresponding box

Added $(".show").removeClass("show"); as the name "show" implies you want to show just the one being clicked and hide the others; obviously remove this if your use-case is to leave them shown.

Updated snippet:

 $("#row .container div.info").on("click", function() {
    var idx = $(this).closest(".container").index();
    $(".show").removeClass("show");
    $("#row-second div.box").eq(idx).addClass("show");
 })

#row div { cursor: pointer; }

#row-second div { display:none; }

#row-second div.show { display:block; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="row">
  <div class="container">
    <div class="info">A</div>
  </div>
  <div class="container">
    <div class="info">B</div>
  </div>
  <div class="container">
    <div class="info">C</div>
  </div>
  <div class="container">
    <div class="info">D</div>
  </div>
</div>

<hr>

<div id="row-second">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
</div>


问:
How to skin all ASP.Net validators?
I want all of the validators in an ASP.Net 3.5 website to have a CssClass value of "error".  My initial thought was to do this in a theme skin like so:

```<code><asp:CompareValidator runat="server"
    CssClass="error" />
<asp:CustomValidator runat="server"
    CssClass="error" />
<asp:RequiredFieldValidator runat="server"
    CssClass="error" />
<belCommon:ZipCodeValidator runat="server"
    CssClass="error" />
<belCommon:PhoneNumberValidator runat="server"
    CssClass="error" />
</code>```

This is only a partial listing of validators that I use. Ideally, I would like to do something like this:

```<code><asp:BaseValidator runat="server"
    CssClass="error" />
</code>```

And because all validators inherit from BaseValidator, I would expect that this would work, but it doesn't.  Is there a way to accomplish this without adding every single validator control to the skin explicitly?

Update:

I found a different approach using javascript:

```<code>Sys.Application.add_init(function(sender, args)
{
    if (Page_Validators != null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            Page_Validators[i].className = "error";
        }
    }
});
</code>```

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans.  This script checks to see if it exists and then loops through and sets the class name.  I added this to the master page and its working so far.

答:
I'd be tempted to iterate over the controls of the page in the server pageload method and to apply the css class there:

```<code>foreach (object obj in this.Controls)
{
  if (obj is BaseValidator)
  {
     ((BaseValidator)obj).CssClass = "error";
  }
}
</code>```

This may not be the best way to do this and I've not had the opportunity to test it but hopefully it might help you along the way.

OwnerDisplayName: jrummell

ContentLicense: CC BY-SA 2.5

Title: How to skin all ASP.Net validators?

Body:
I want all of the validators in an ASP.Net 3.5 website to have a CssClass value of "error".  My initial thought was to do this in a theme skin like so:

<asp:CompareValidator runat="server"
    CssClass="error" />
<asp:CustomValidator runat="server"
    CssClass="error" />
<asp:RequiredFieldValidator runat="server"
    CssClass="error" />
<belCommon:ZipCodeValidator runat="server"
    CssClass="error" />
<belCommon:PhoneNumberValidator runat="server"
    CssClass="error" />

This is only a partial listing of validators that I use. Ideally, I would like to do something like this:

<asp:BaseValidator runat="server"
    CssClass="error" />

And because all validators inherit from BaseValidator, I would expect that this would work, but it doesn't.  Is there a way to accomplish this without adding every single validator control to the skin explicitly?

Update:

I found a different approach using javascript:

Sys.Application.add_init(function(sender, args)
{
    if (Page_Validators != null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            Page_Validators[i].className = "error";
        }
    }
});

ASP.Net generates a javascript variable called Page_Validators, which is an array of the validation spans.  This script checks to see if it exists and then loops through and sets the class name.  I added this to the master page and its working so far.

LastEditorDisplayName: jrummell

Body:
I'd be tempted to iterate over the controls of the page in the server pageload method and to apply the css class there:

foreach (object obj in this.Controls)
{
  if (obj is BaseValidator)
  {
     ((BaseValidator)obj).CssClass = "error";
  }
}

This may not be the best way to do this and I've not had the opportunity to test it but hopefully it might help you along the way.

OwnerDisplayName: Lazarus


问:
RabbitMQ: can both consuming and publishing be done in one thread?
can both consuming and publishing be done in one Python thread using RabbitMQ channels?</p>

答:
Kombu is a common python library for working with RabbitMQ (Celery uses it under the hood).  It is worth pointing out here that the answer to your question for the simplest use of Kombu that I tried is "No - you can't receive and publish on the same consumer callback thread."

Specifically if there are several messages in the queue for a consumer that has registered a callback for that topic and that callback does some processing and publishes the results then the publishing of the result will cause the 2nd message in the queue to hit the callback before it has returned from the publish from 1st message - so you end up with a recursive call to the callback.  If you have n message on the queue your call stack will end up n message deep before it unwinds.  Obviously that explodes pretty quickly.

One solution (not necessarily the best) is to have the callback just post the message into a simple queue internal to the consumer that could be processed on the main process thread (i.e. off the callback thread)

```<code>def process_message(self, body: str, message: Message):
    # Queue the message for processing off this thread:
    print("Start process_message ----------------")
    self.do_process_message(body, message) if self.publish_on_callback else self.queue.put((body, message))#
    print("End process_message ------------------")

def do_process_message(self, body: str, message: Message):
    # Deserialize and "Process" the message:
    print(f"Process message: {body}")
    # ... msg processing code...

    # Publish a processing output:
    processing_output = self.get_processing_output()
    print(f"Publishing processing output: {processing_output}")
    self.rabbit_msg_transport.publish(Topics.ProcessingOutputs, processing_output)

    # Acknowledge the message:
    message.ack()

def run_message_loop(self):
    while True:
        print("Waiting for incoming message")
        self.rabbit_connection.drain_events()
        while not self.queue.empty():
            body, message = self.queue.get(block=False)
            self.do_process_message(body, message)
</code>```

In this snippet above process_message is the callback.  If publish_on_callback is True you'll see recursion in the callback n deep for n message on rabbit queue.  If publish_on_callback is False it runs correctly without recursion in the callback.

Another approach is to use a second Connection for the Producer Exchange - separate from the Connection used for the Consumer.  This also works so that callback from consuming a message and publishing the result completes before the callback is again fired for the next message on queue.

Body:
Kombu is a common python library for working with RabbitMQ (Celery uses it under the hood).  It is worth pointing out here that the answer to your question for the simplest use of Kombu that I tried is "No - you can't receive and publish on the same consumer callback thread."

Specifically if there are several messages in the queue for a consumer that has registered a callback for that topic and that callback does some processing and publishes the results then the publishing of the result will cause the 2nd message in the queue to hit the callback before it has returned from the publish from 1st message - so you end up with a recursive call to the callback.  If you have n message on the queue your call stack will end up n message deep before it unwinds.  Obviously that explodes pretty quickly.

One solution (not necessarily the best) is to have the callback just post the message into a simple queue internal to the consumer that could be processed on the main process thread (i.e. off the callback thread)

def process_message(self, body: str, message: Message):
    # Queue the message for processing off this thread:
    print("Start process_message ----------------")
    self.do_process_message(body, message) if self.publish_on_callback else self.queue.put((body, message))#
    print("End process_message ------------------")

def do_process_message(self, body: str, message: Message):
    # Deserialize and "Process" the message:
    print(f"Process message: {body}")
    # ... msg processing code...

    # Publish a processing output:
    processing_output = self.get_processing_output()
    print(f"Publishing processing output: {processing_output}")
    self.rabbit_msg_transport.publish(Topics.ProcessingOutputs, processing_output)

    # Acknowledge the message:
    message.ack()

def run_message_loop(self):
    while True:
        print("Waiting for incoming message")
        self.rabbit_connection.drain_events()
        while not self.queue.empty():
            body, message = self.queue.get(block=False)
            self.do_process_message(body, message)

In this snippet above process_message is the callback.  If publish_on_callback is True you'll see recursion in the callback n deep for n message on rabbit queue.  If publish_on_callback is False it runs correctly without recursion in the callback.

Another approach is to use a second Connection for the Producer Exchange - separate from the Connection used for the Consumer.  This also works so that callback from consuming a message and publishing the result completes before the callback is again fired for the next message on queue.


问:
why is undetected Chromedriver not working?
```<code>import undetected_chromedriver as uc
driver = uc.Chrome()
</code>```

The undetected Chromedriver isnt working after google chrome update.
I cannnot use normal chromedriver as some block access
Kindly provide some solution , is it related the the chrome update , what to do now ?

See the following Error -

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 269, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\imdec\Desktop\script.py", line 12, in <module>
    driver = uc.Chrome()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\site-packages\undetected_chromedriver\__init__.py", line 356, in __init__
    self.browser_pid = start_detached(
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\site-packages\undetected_chromedriver\dprocess.py", line 35, in start_detached
    ).start()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
</code>```

答:
"why is undetected Chromedriver not working?"

Because it is trying to create child processes, and your script is not multiprocessing-safe. This may be the fault of the author of the library you're using for not mentioning it in the documentation. When a child process starts, it must import the main script, and if your main script then tries to create another child process (by calling uc.Chrome again for example), you end up with an infinite recursion. Python prevents this infinite recursion by throwing an error, which actually describes quite exactly what the solution is to this problem: protect any multiprocessing calls in your main script from execution on import by using the special __name__ variable which is set to "__main__" only in the original instance, and will be set to "__mp_main__" in child processes.

import undetected_chromedriver as uc
if __name__ == "__main__":
    driver = uc.Chrome()
```

Body:
import undetected_chromedriver as uc
driver = uc.Chrome()

The undetected Chromedriver isnt working after google chrome update.
I cannnot use normal chromedriver as some block access
Kindly provide some solution , is it related the the chrome update , what to do now ?

See the following Error -

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 269, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\imdec\Desktop\script.py", line 12, in <module>
    driver = uc.Chrome()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\site-packages\undetected_chromedriver\__init__.py", line 356, in __init__
    self.browser_pid = start_detached(
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\site-packages\undetected_chromedriver\dprocess.py", line 35, in start_detached
    ).start()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\context.py", line 327, in _Popen
    return Popen(process_obj)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\imdec\AppData\Local\Programs\Python\Python310\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RuntimeError('''
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.


问:
Can't execute npm install
When I am executing npm install this error shows. Any advice about this?

```<code>PS C:\Users\alex\Downloads\team> npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: frontend@0.0.0
npm ERR! Found: @angular/compiler@13.1.3
npm ERR! node_modules/@angular/compiler
npm ERR! @angular/compiler@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler@"13.0.3" from @angular/compiler-cli@13.0.3
npm ERR! node_modules/@angular/compiler-cli
npm ERR! dev @angular/compiler-cli@"~13.0.0" from the root project
npm ERR! peer @angular/compiler-cli@"^13.0.0" from @angular-devkit/build-angular@13.2.2
npm ERR! node_modules/@angular-devkit/build-angular
npm ERR! dev @angular-devkit/build-angular@"^13.2.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! See C:\Users\ for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\
</code>```

Here is Package.json file:

```<code>{
  "name": "frontend",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^13.1.0",
    "@angular/cdk": "^13.1.0",
    "@angular/common": "~13.1.0",
    "@angular/compiler": "~13.1.0",
    "@angular/core": "~13.1.0",
    "@angular/forms": "~13.1.0",
    "@angular/platform-browser": "~13.1.0",
    "@angular/platform-browser-dynamic": "~13.1.0",
    "@angular/router": "~13.1.0",
    "@types/jquery": "^3.5.13",
    "bootstrap": "^5.1.3",
    "bootstrap4-toggle": "^3.6.1",
    "colors": "^1.4.0",
    "jquery": "^3.6.0",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.2.0",
    "@angular/cli": "~13.0.4",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "^3.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.4.3"
  }
}
</code>```

答:
ERESOLVE issues with npm@7 and npm@8 are common because they are more strict about peer dependencies than npm@6. Often, the easiest resolution is to pass the --legacy-peer-deps flag to npm (e.g., npm i --legacy-peer-deps) or else use npm@6.

The "correct" solution is to figure out which of your dependencies need to be updated in package.json to avoid the peer dependency conflict, but that is sometimes not possible with dependencies that are unmaintained. In that case, the solution is to find or create something else to get rid of the unmaintained dependency.

However, 9 times out of 10, someone just wants to get the stuff installed and hope it works, in which case --legacy-peer-deps will do that. Just make sure you have good test coverage because you're using a different peer dependency version than that specified by a package so something somewhere might not work.

To see if the problem will affect your production app, do npm install --production. If it doesn't give you an ERESOLVE error, then the problem is in your dev dependencies only, which is less of a concern typically.

Title: Can't execute npm install

Body:
When I am executing npm install this error shows. Any advice about this?

PS C:\Users\alex\Downloads\team> npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: frontend@0.0.0
npm ERR! Found: @angular/compiler@13.1.3
npm ERR! node_modules/@angular/compiler
npm ERR! @angular/compiler@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler@"13.0.3" from @angular/compiler-cli@13.0.3
npm ERR! node_modules/@angular/compiler-cli
npm ERR! dev @angular/compiler-cli@"~13.0.0" from the root project
npm ERR! peer @angular/compiler-cli@"^13.0.0" from @angular-devkit/build-angular@13.2.2
npm ERR! node_modules/@angular-devkit/build-angular
npm ERR! dev @angular-devkit/build-angular@"^13.2.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! See C:\Users\ for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\

Here is Package.json file:

{
  "name": "frontend",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "^13.1.0",
    "@angular/cdk": "^13.1.0",
    "@angular/common": "~13.1.0",
    "@angular/compiler": "~13.1.0",
    "@angular/core": "~13.1.0",
    "@angular/forms": "~13.1.0",
    "@angular/platform-browser": "~13.1.0",
    "@angular/platform-browser-dynamic": "~13.1.0",
    "@angular/router": "~13.1.0",
    "@types/jquery": "^3.5.13",
    "bootstrap": "^5.1.3",
    "bootstrap4-toggle": "^3.6.1",
    "colors": "^1.4.0",
    "jquery": "^3.6.0",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.2.0",
    "@angular/cli": "~13.0.4",
    "@angular/compiler-cli": "~13.0.0",
    "@types/jasmine": "~3.10.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.10.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "^3.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "typescript": "~4.4.3"
  }
}


问:
How to enhance the speed of my C++ program in reading delimited text files?
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

```<code>int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}
</code>```

C# program:

```<code>    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }
</code>```

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.

答:
If you know the max line length you can your stdio+fgets and null terminated strings, it will rock.

For c# if it will fit in memory (probably not if it takes 34 sec) I'd be curious to see how IO.File.WriteAllText("out.txt",IO.File.ReadAllText("in.txt").Replace("|","#")); performs!

Body:
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}

C# program:

    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.