问:
Issue with using PowerShell command in batch
I download a zip file from my cloud using a PowerShell command.
The command works correctly in PowerShell AND in the command line. However, if I insert the command from the command line into my batch script, only the html is downloaded.
Why does the command work correctly in the command line but not in the batch file?
Im out of ideas :D

```<code>powershell Invoke-WebRequest """https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%2FValheimServer%20Buddelkiste%20Modpack%20v3.4%20-%20Standart.zip&dl=1""" -OutFile """C:\Users\Anonymos\Downloads\servermodpack.zip"""
</code>```

Its works complete fine in cmd and load the ~40 Mb. But in Batch it loads only 9kb (its the Html)

答:
In a batch file - as opposed to the interactive cmd.exe command prompt[1] - you need to to escape % chars. as %% in order to pass them through literally:

```<code>powershell -c "Invoke-WebRequest 'https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%%2FValheimServer%%20Buddelkiste%%20Modpack%%20v3.4%%20-%%20Standart.zip&dl=1' -OutFile C:\Users\Anonymos\Downloads\servermodpack.zip"
</code>```

Note:

I've used -c (-Command), the positionally implied Windows PowerShell CLI (powershell.exe) parameter explicitly for conceptual clarity (in PowerShell (Core) 7+, whose CLI is pwsh, the default is now -f (-File)).

Also, enclosing the entire command line to pass to PowerShell in "..." is generally preferable in order to prevent cmd.exe metacharacters other than % (such as &) from causing problems.

In case the command line requires use of embedded " characters (the solution above avoids this by using embedded '...' quoting), the safest way to escape them is to use "^"" (sic) with powershell.exe, and "" with pwsh.exe - see this answer for details.

[1] In interactive use, % characters cannot technically be escaped, but they're retained as-is unless they're part of a cmd.exe-style environment-variable reference that refers to an existing environment variable, such as %OS%. However, there are ways to treat % literally even in such cases, as discussed in this answer. These techniques are important for invoking cmd.exe command lines programmatically from outside cmd.exe, such as from Node.Js or Python, because such programmatic invocations - perhaps surprisingly - use the rules of interactive cmd.exe sessions, not batch files.

Body:
I download a zip file from my cloud using a PowerShell command.
The command works correctly in PowerShell AND in the command line. However, if I insert the command from the command line into my batch script, only the html is downloaded.
Why does the command work correctly in the command line but not in the batch file?
Im out of ideas :D

powershell Invoke-WebRequest """https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%2FValheimServer%20Buddelkiste%20Modpack%20v3.4%20-%20Standart.zip&dl=1""" -OutFile """C:\Users\Anonymos\Downloads\servermodpack.zip"""

Its works complete fine in cmd and load the ~40 Mb. But in Batch it loads only 9kb (its the Html)

Body:
In a batch file - as opposed to the interactive cmd.exe command prompt[1] - you need to to escape % chars. as %% in order to pass them through literally:

powershell -c "Invoke-WebRequest 'https://sync.luckycloud.de/d/fb56e4a8239a4c6cac7a/files/?p=%%2FValheimServer%%20Buddelkiste%%20Modpack%%20v3.4%%20-%%20Standart.zip&dl=1' -OutFile C:\Users\Anonymos\Downloads\servermodpack.zip"

Note:

I've used -c (-Command), the positionally implied Windows PowerShell CLI (powershell.exe) parameter explicitly for conceptual clarity (in PowerShell (Core) 7+, whose CLI is pwsh, the default is now -f (-File)).

Also, enclosing the entire command line to pass to PowerShell in "..." is generally preferable in order to prevent cmd.exe metacharacters other than % (such as &) from causing problems.

In case the command line requires use of embedded " characters (the solution above avoids this by using embedded '...' quoting), the safest way to escape them is to use "^"" (sic) with powershell.exe, and "" with pwsh.exe - see this answer for details.

[1] In interactive use, % characters cannot technically be escaped, but they're retained as-is unless they're part of a cmd.exe-style environment-variable reference that refers to an existing environment variable, such as %OS%. However, there are ways to treat % literally even in such cases, as discussed in this answer. These techniques are important for invoking cmd.exe command lines programmatically from outside cmd.exe, such as from Node.Js or Python, because such programmatic invocations - perhaps surprisingly - use the rules of interactive cmd.exe sessions, not batch files.


来源: stackexchange

问:
manipulating lists in python
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

```<code>def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

</code>```

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'

答:
```<code>def password(N1, N2, N3):
#takes all three Ns ^ and makes them single digits
N1 = [int(char) for char in str(N1)]
N2 = [int(char) for char in str(N2)]
N3 = [int(char) for char in str(N3)]
#it goes into each variable and finds the max and mins in each section
#W is just the biggest digit out of all of them
W = (N1 + N2 + N3)
W = max(W)
#X is the smallest digit from the first digits given in each N input
X = [N1[0], N2[0], N3[0]]
X = min(X)
#same thing as X just for the second digits this time
Y = [N1[1], N2[1], N3[1]]
Y = min(Y)
#same but for the third digits
Z = [N1[2], N2[2], N3[2]]
Z = min(Z)
#groups all the numbers together into a variable called "password"
password = [W, X, Y, Z]
#Done!
return password
</code>```

ContentLicense: CC BY-SA 4.0

Title: manipulating lists in python

Body:
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'


问:
How can I update/save a Property Change for Child Item from a Hierarchical List View of Items
See the following app screens:

Content View Screen:

Content View with hierarchical list children rows disclosed:

Parent Row Detail View:

Child Row Detail View:

Referencing the above views, here are the steps I do and the resulting problem I’m trying to solve:

Launch the app.

From the Functions (Content View) presented at launch, see that there is one item listed in a list view (1.0 Move Vessel)

Click the yellow (my app accent color) disclosure arrow at the right of the list item.

Two subordinate child list rows appear under the parent list item, 1.1 Move Position and 1.2 Hold Position.

When I tap the parent item (1.0 Move Vessel) in the hierarchy list, I'm successfully able to navigate to a detail view for that tapped item.

Edit the description of the 1.0 Move Vessel item (defaults to test) of the tapped item properties in the detail view using a TextEditor view.

Click yellow Save button at top left of detail view. The app navigates back to the parent Functions (Content View).

Click on the parent 1.0 Move Vessel row again.

See that description was successfully saved and now displayed from the change made in Step 5 and 6.

Repeat steps 5 through 8 again for 1.1 Move Position list row.

See that the edit/change made to the description was not saved and the default test1 description is displayed instead (not what is wanted).

Repeat steps 5 through 8 again for 1.2 Hold Position list row.

See that the edit/change made to the description was not saved and the default test2 description is displayed instead (not what is wanted).

I think I may have a problem in my save code logic and I'm trying to investigate.

Here are the swift files for the Detail View, the View Model, and the Model (I’ve not included the content view code because that code is working ok with the detail view. Again, I think the problem is in my save button and function call code for updating the view model.
NOTE: sorry that I can’t seem to figure out how to get all the code for a file contiguous in the code view. I seem to have some closing braces that don’t appear in the code view. I think you can still follow the code.

```<code>struct FunctionDetailView: View {
    @State var vesselFunction: VesselFunction
    @State var vesselFunctionDescription: String
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var functionViewModel : FunctionViewModel

    var body: some View {

        NavigationView {

            Form {
                Text("Enter description below")
                TextEditor(text: $vesselFunctionDescription)
                    .frame(height: 200)
                    .toolbar {
                        Button {
                            //print(vesselFunction)

                            vesselFunction.funcDescription = vesselFunctionDescription

                            //print(vesselFunction)

                            functionViewModel.updateVesselFunction(vesselFunction: vesselFunction)

                            //print(vesselFunction)

                            presentationMode.wrappedValue.dismiss()
                        } label: {
                            Text("Save")
                        }

                    }
            }
            .padding()
            .navigationTitle(vesselFunction.name)
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct FunctionDetailView_Previews: PreviewProvider {
    static var previews: some View {
        FunctionDetailView(vesselFunction: VesselFunction(id: UUID(), name: "x.x Verb Noun", funcDescription: "Description", children: nil), vesselFunctionDescription: "placeholder")
            .environmentObject(FunctionViewModel())
            .preferredColorScheme(.dark)
    }
}

</code>```

FunctionViewModel.swift

```<code>@MainActor class FunctionViewModel: ObservableObject {

    @Published private(set) var decomp : [VesselFunction] = [
        VesselFunction(id: UUID(), name: "1.0 Move Vessel", funcDescription: "test", children: [
            VesselFunction(id: UUID(), name: "1.1 Move Position", funcDescription: "test1", children: nil),
            VesselFunction(id: UUID(), name: "1.2 Hold Position", funcDescription: "test2", children: nil)
        ])
    ]

    func updateVesselFunction(vesselFunction: VesselFunction) {
        /*
         if let index = decomp.firstIndex(where: { (existingVesselFunction) -> Bool in
         return existingVesselFunction.id == vesselFunction.id
         }) {
         //run this code
         }
         */
        // cleaner version of above
        if let index = decomp.firstIndex(where: { $0.id == vesselFunction.id }) {
            decomp[index] = vesselFunction.updateCompletion()
        }
        /*
         else {
         for item in decomp {
         if item.children != nil {
         if let index = item.children?.firstIndex(where: { $0.id == vesselFunction.id }) {
         item.children![index] = vesselFunction.updateCompletion()
         }
         }
         }
         } */
    }
}
</code>```

FunctionModel.swift

```<code>struct VesselFunction: Identifiable {
    let id : UUID
    let name : String
    var funcDescription : String
    var children : [VesselFunction]?

    init(id: UUID, name: String, funcDescription: String, children: [VesselFunction]?) {
        self.id = id
        self.name = name
        self.funcDescription = funcDescription
        self.children = children
    }

    func updateCompletion() -> VesselFunction {
        return VesselFunction(id: id, name: name, funcDescription: funcDescription, children: children)
    }
}
</code>```

As you can see from the else and for-in loop code commented out at the bottom of the FunctionViewModel code, I was trying to see if I needed to do something like this code to access the children VesselFunction array entries of the decomp published property. With the if let index code that is not commented out, the save function works but only for the top-level decomp array VesselFunction elements, not the nested children arrays elements.

Any help would be appreciated so all decomp array elements, both parent and nested children, can be updated when the TextEditor field is changed and the Save button is pressed in the FunctionDetailView.
NOTE: I am only showing a 1 level deep nested array of children for the decomp property. I actually want to have multiple (at least 3) level of children arrays, so if you have any ideas how to make an updateVesselFunction function work for multiple children array elements, I would appreciate it.

答:
The issue isn't so much your code right now, as it is the architecture of the program. You really need to reorganize the app with MVVM concepts in mind. If you are not sure of them, study Apple’s SwiftUI Tutorials & Stanford’s CS193P. Without a proper architecture, you have gotten lost down a rabbit hole to the extent that I gave up trying to fix the code.

Also, given the structure of your data, I would give serious consideration to using Core Data to model it. Your VesselFunction struct contains an array of VesselFunction, and that it much better modeled as a relationship, rather than having a struct hold an array of the same struct which can hold an array of the same struct. It is a nightmare to deal with as a struct, instead of as a Core Data class.

I would also consider make your FunctionDetailView just display data, and have a separate editing view. This will keep your view separate and easier to manage.

Lastly, you have a lot of redundancy in your naming conventions. Theoretically, you could be trying to access a piece of data at functionViewModel.funcDescription (Not to mention: functionViewModel.children[index].children[subIndex].children[subSubIndex].funcDescription); this can get a bit unwieldy. The further you go down, the worse it will get.

Body:
See the following app screens:

Content View Screen:

Content View with hierarchical list children rows disclosed:

Parent Row Detail View:

Child Row Detail View:

Referencing the above views, here are the steps I do and the resulting problem I’m trying to solve:

Launch the app.

From the Functions (Content View) presented at launch, see that there is one item listed in a list view (1.0 Move Vessel)

Click the yellow (my app accent color) disclosure arrow at the right of the list item.

Two subordinate child list rows appear under the parent list item, 1.1 Move Position and 1.2 Hold Position.

When I tap the parent item (1.0 Move Vessel) in the hierarchy list, I'm successfully able to navigate to a detail view for that tapped item.

Edit the description of the 1.0 Move Vessel item (defaults to test) of the tapped item properties in the detail view using a TextEditor view.

Click yellow Save button at top left of detail view. The app navigates back to the parent Functions (Content View).

Click on the parent 1.0 Move Vessel row again.

See that description was successfully saved and now displayed from the change made in Step 5 and 6.

Repeat steps 5 through 8 again for 1.1 Move Position list row.

See that the edit/change made to the description was not saved and the default test1 description is displayed instead (not what is wanted).

Repeat steps 5 through 8 again for 1.2 Hold Position list row.

See that the edit/change made to the description was not saved and the default test2 description is displayed instead (not what is wanted).

I think I may have a problem in my save code logic and I'm trying to investigate.

Here are the swift files for the Detail View, the View Model, and the Model (I’ve not included the content view code because that code is working ok with the detail view. Again, I think the problem is in my save button and function call code for updating the view model.
NOTE: sorry that I can’t seem to figure out how to get all the code for a file contiguous in the code view. I seem to have some closing braces that don’t appear in the code view. I think you can still follow the code.

struct FunctionDetailView: View {
    @State var vesselFunction: VesselFunction
    @State var vesselFunctionDescription: String
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var functionViewModel : FunctionViewModel

    var body: some View {

        NavigationView {

            Form {
                Text("Enter description below")
                TextEditor(text: $vesselFunctionDescription)
                    .frame(height: 200)
                    .toolbar {
                        Button {
                            //print(vesselFunction)

                            vesselFunction.funcDescription = vesselFunctionDescription

                            //print(vesselFunction)

                            functionViewModel.updateVesselFunction(vesselFunction: vesselFunction)

                            //print(vesselFunction)

                            presentationMode.wrappedValue.dismiss()
                        } label: {
                            Text("Save")
                        }

                    }
            }
            .padding()
            .navigationTitle(vesselFunction.name)
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct FunctionDetailView_Previews: PreviewProvider {
    static var previews: some View {
        FunctionDetailView(vesselFunction: VesselFunction(id: UUID(), name: "x.x Verb Noun", funcDescription: "Description", children: nil), vesselFunctionDescription: "placeholder")
            .environmentObject(FunctionViewModel())
            .preferredColorScheme(.dark)
    }
}

FunctionViewModel.swift

@MainActor class FunctionViewModel: ObservableObject {

    @Published private(set) var decomp : [VesselFunction] = [
        VesselFunction(id: UUID(), name: "1.0 Move Vessel", funcDescription: "test", children: [
            VesselFunction(id: UUID(), name: "1.1 Move Position", funcDescription: "test1", children: nil),
            VesselFunction(id: UUID(), name: "1.2 Hold Position", funcDescription: "test2", children: nil)
        ])
    ]

    func updateVesselFunction(vesselFunction: VesselFunction) {
        /*
         if let index = decomp.firstIndex(where: { (existingVesselFunction) -> Bool in
         return existingVesselFunction.id == vesselFunction.id
         }) {
         //run this code
         }
         */
        // cleaner version of above
        if let index = decomp.firstIndex(where: { $0.id == vesselFunction.id }) {
            decomp[index] = vesselFunction.updateCompletion()
        }
        /*
         else {
         for item in decomp {
         if item.children != nil {
         if let index = item.children?.firstIndex(where: { $0.id == vesselFunction.id }) {
         item.children![index] = vesselFunction.updateCompletion()
         }
         }
         }
         } */
    }
}

FunctionModel.swift

struct VesselFunction: Identifiable {
    let id : UUID
    let name : String
    var funcDescription : String
    var children : [VesselFunction]?

    init(id: UUID, name: String, funcDescription: String, children: [VesselFunction]?) {
        self.id = id
        self.name = name
        self.funcDescription = funcDescription
        self.children = children
    }

    func updateCompletion() -> VesselFunction {
        return VesselFunction(id: id, name: name, funcDescription: funcDescription, children: children)
    }
}

As you can see from the else and for-in loop code commented out at the bottom of the FunctionViewModel code, I was trying to see if I needed to do something like this code to access the children VesselFunction array entries of the decomp published property. With the if let index code that is not commented out, the save function works but only for the top-level decomp array VesselFunction elements, not the nested children arrays elements.

Any help would be appreciated so all decomp array elements, both parent and nested children, can be updated when the TextEditor field is changed and the Save button is pressed in the FunctionDetailView.
NOTE: I am only showing a 1 level deep nested array of children for the decomp property. I actually want to have multiple (at least 3) level of children arrays, so if you have any ideas how to make an updateVesselFunction function work for multiple children array elements, I would appreciate it.


问:
Javascript get Index of Key which contains value
I was wondering if there is a better way to get the Index of Key whose values contain the given value, otherwise it returns Null. In the example below it does what i need, but wasn't sure not sure if there was a simpler way of writing it. I know javascript's syntax is quite powerful and I'm not as familiar with it as others may be.

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

function getValueSetIndex(val) {
let count = 0
  for (const [key, values] of Object.entries(sets)) {
    if (values.includes(val)) {
        return count;
    }
    count += 1
  }
  return null
}

console.log(getValueSetIndex(4))
console.log(getValueSetIndex(20))```

答:
```<code>const keyIndex = (obj, value) => {
  const index = Object.keys(obj).findIndex(key => obj[key].includes(value));
  return index > -1 ? index : null;
}
console.log(keyIndex(sets, 8));
</code>```


问:
How do I edit multiple .txt files in Java
I'm trying to make a GradeManager class in Java for school. I need to:

Enter the students name

Find student file based on name entered (I have 4 students)

Edit grades that are within the file

File example: John,123456789,10,8,7,87,91     (Name,ID,Q1,Q2,Q3,Midterm,Final) and would edit Q1-Final

I don't quite understand how I would be able to get all 4 student files into editStuGrades() without having them all in one file

This is what I got:

```<code>public class GradeManager {
    private static Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        if (commandInput.equalsIgnoreCase("John")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "John.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | ");
                editStuGrade();
            }

        }
        if (commandInput.equalsIgnoreCase("Matthew")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "Matthew.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | " );
                editStuGrade();
            }

        }
    }
    public static void editStuGrade() {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {

        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }
}
</code>```

答:
Start by taking a look at Passing Information to a Method or a Constructor

What you want to (try and do) is to make the core functionality "common".  Let's face it, reading and writing the student data is basically the same for all the students, the only difference is, the source and destination.

To this end, I'd start with a POJO (plain old Java object), for example...

```<code>public class Student {

    private String name;
    private String id;
    private int q1Score;
    private int q2Score;
    private int q3Score;
    private int midTermScore;
    private int finalScore;

    public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
        this.name = name;
        this.id = id;
        this.q1Score = q1Score;
        this.q2Score = q2Score;
        this.q3Score = q3Score;
        this.midTermScore = midTermScore;
        this.finalScore = finalScore;
    }

    public static Student loadByName(String name) throws IOException {
        File file = new File(name + ".txt");
        if (!file.exists()) {
            throw new FileNotFoundException("No record exists for " + name);
        }

        try (Scanner input = new Scanner(file)) {
            input.useDelimiter(",");
            name = input.next();
            String id = input.next();
            int q1Score = input.nextInt();
            int q2Score = input.nextInt();
            int q3Score = input.nextInt();
            int midTermScore = input.nextInt();
            int finalScore = input.nextInt();

            return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
        }
    }

    public void save() throws IOException {
        File file = new File(getName() + ".txt");
        StringJoiner joiner = new StringJoiner(",");
        joiner.add(getName());
        joiner.add(getId());
        joiner.add(Integer.toString(getQ1Score()));
        joiner.add(Integer.toString(getQ2Score()));
        joiner.add(Integer.toString(getQ3Score()));
        joiner.add(Integer.toString(getMidTermScore()));
        joiner.add(Integer.toString(getFinalScore()));

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
            bw.write(joiner.toString());
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getQ1Score() {
        return q1Score;
    }

    public void setQ1Score(int q1Score) {
        this.q1Score = q1Score;
    }

    public int getQ2Score() {
        return q2Score;
    }

    public void setQ2Score(int q2Score) {
        this.q2Score = q2Score;
    }

    public int getQ3Score() {
        return q3Score;
    }

    public void setQ3Score(int q3Score) {
        this.q3Score = q3Score;
    }

    public int getMidTermScore() {
        return midTermScore;
    }

    public void setMidTermScore(int midTermScore) {
        this.midTermScore = midTermScore;
    }

    public int getFinalScore() {
        return finalScore;
    }

    public void setFinalScore(int finalScore) {
        this.finalScore = finalScore;
    }

}
</code>```

nb: You could just use an array, but where's the fun in that

So, the above is just a container for the data we want to manage.  It provides two convince methods for reading and writing the student information, so we don't "repeat" code and introduce possible bugs or maintenance issues along the way (there's only one place we read or write the data)

Next, any methods which need to interact with the student needs to accept an instance of the Student POJO, for example...

```<code>protected void editStuGrade(Student student) throws IOException {
    //...
}
</code>```

Then the rest of the code simply comes down to getting information from the user and feeding it into our workflow...

```<code>public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }
}
</code>```

Runnable example...

```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringJoiner;

public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }

    public static class Student {

        private String name;
        private String id;
        private int q1Score;
        private int q2Score;
        private int q3Score;
        private int midTermScore;
        private int finalScore;

        public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
            this.name = name;
            this.id = id;
            this.q1Score = q1Score;
            this.q2Score = q2Score;
            this.q3Score = q3Score;
            this.midTermScore = midTermScore;
            this.finalScore = finalScore;
        }

        public static Student loadByName(String name) throws IOException {
            File file = new File(name + ".txt");
            if (!file.exists()) {
                throw new FileNotFoundException("No record exists for " + name);
            }

            try (Scanner input = new Scanner(file)) {
                input.useDelimiter(",");
                name = input.next();
                String id = input.next();
                int q1Score = input.nextInt();
                int q2Score = input.nextInt();
                int q3Score = input.nextInt();
                int midTermScore = input.nextInt();
                int finalScore = input.nextInt();

                return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
            }
        }

        public void save() throws IOException {
            File file = new File(getName() + ".txt");
            StringJoiner joiner = new StringJoiner(",");
            joiner.add(getName());
            joiner.add(getId());
            joiner.add(Integer.toString(getQ1Score()));
            joiner.add(Integer.toString(getQ2Score()));
            joiner.add(Integer.toString(getQ3Score()));
            joiner.add(Integer.toString(getMidTermScore()));
            joiner.add(Integer.toString(getFinalScore()));

            try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
                bw.write(joiner.toString());
            }
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public int getQ1Score() {
            return q1Score;
        }

        public void setQ1Score(int q1Score) {
            this.q1Score = q1Score;
        }

        public int getQ2Score() {
            return q2Score;
        }

        public void setQ2Score(int q2Score) {
            this.q2Score = q2Score;
        }

        public int getQ3Score() {
            return q3Score;
        }

        public void setQ3Score(int q3Score) {
            this.q3Score = q3Score;
        }

        public int getMidTermScore() {
            return midTermScore;
        }

        public void setMidTermScore(int midTermScore) {
            this.midTermScore = midTermScore;
        }

        public int getFinalScore() {
            return finalScore;
        }

        public void setFinalScore(int finalScore) {
            this.finalScore = finalScore;
        }

    }
}
</code>```

Body:
I'm trying to make a GradeManager class in Java for school. I need to:

Enter the students name

Find student file based on name entered (I have 4 students)

Edit grades that are within the file

File example: John,123456789,10,8,7,87,91     (Name,ID,Q1,Q2,Q3,Midterm,Final) and would edit Q1-Final

I don't quite understand how I would be able to get all 4 student files into editStuGrades() without having them all in one file

This is what I got:

public class GradeManager {
    private static Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        if (commandInput.equalsIgnoreCase("John")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "John.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | ");
                editStuGrade();
            }

        }
        if (commandInput.equalsIgnoreCase("Matthew")) {
            String filepath = FileSystems.getDefault().getPath("src", "Assignments", "Matthew.txt").toAbsolutePath().toString();
            File inputFile = new File(filepath);
            Scanner line = new Scanner(inputFile);
            while (line.hasNext()) {
                String rLine = line.nextLine();
                String name = rLine.substring(0, rLine.indexOf(","));
                System.out.println("Name: " + name + " | " );
                editStuGrade();
            }

        }
    }
    public static void editStuGrade() {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {

        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }
}

Body:
Start by taking a look at Passing Information to a Method or a Constructor

What you want to (try and do) is to make the core functionality "common".  Let's face it, reading and writing the student data is basically the same for all the students, the only difference is, the source and destination.

To this end, I'd start with a POJO (plain old Java object), for example...

public class Student {

    private String name;
    private String id;
    private int q1Score;
    private int q2Score;
    private int q3Score;
    private int midTermScore;
    private int finalScore;

    public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
        this.name = name;
        this.id = id;
        this.q1Score = q1Score;
        this.q2Score = q2Score;
        this.q3Score = q3Score;
        this.midTermScore = midTermScore;
        this.finalScore = finalScore;
    }

    public static Student loadByName(String name) throws IOException {
        File file = new File(name + ".txt");
        if (!file.exists()) {
            throw new FileNotFoundException("No record exists for " + name);
        }

        try (Scanner input = new Scanner(file)) {
            input.useDelimiter(",");
            name = input.next();
            String id = input.next();
            int q1Score = input.nextInt();
            int q2Score = input.nextInt();
            int q3Score = input.nextInt();
            int midTermScore = input.nextInt();
            int finalScore = input.nextInt();

            return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
        }
    }

    public void save() throws IOException {
        File file = new File(getName() + ".txt");
        StringJoiner joiner = new StringJoiner(",");
        joiner.add(getName());
        joiner.add(getId());
        joiner.add(Integer.toString(getQ1Score()));
        joiner.add(Integer.toString(getQ2Score()));
        joiner.add(Integer.toString(getQ3Score()));
        joiner.add(Integer.toString(getMidTermScore()));
        joiner.add(Integer.toString(getFinalScore()));

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
            bw.write(joiner.toString());
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getQ1Score() {
        return q1Score;
    }

    public void setQ1Score(int q1Score) {
        this.q1Score = q1Score;
    }

    public int getQ2Score() {
        return q2Score;
    }

    public void setQ2Score(int q2Score) {
        this.q2Score = q2Score;
    }

    public int getQ3Score() {
        return q3Score;
    }

    public void setQ3Score(int q3Score) {
        this.q3Score = q3Score;
    }

    public int getMidTermScore() {
        return midTermScore;
    }

    public void setMidTermScore(int midTermScore) {
        this.midTermScore = midTermScore;
    }

    public int getFinalScore() {
        return finalScore;
    }

    public void setFinalScore(int finalScore) {
        this.finalScore = finalScore;
    }

}

nb: You could just use an array, but where's the fun in that

So, the above is just a container for the data we want to manage.  It provides two convince methods for reading and writing the student information, so we don't "repeat" code and introduce possible bugs or maintenance issues along the way (there's only one place we read or write the data)

Next, any methods which need to interact with the student needs to accept an instance of the Student POJO, for example...

protected void editStuGrade(Student student) throws IOException {
    //...
}

Then the rest of the code simply comes down to getting information from the user and feeding it into our workflow...

public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }
}

Runnable example...

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringJoiner;

public class Main {

    private Scanner command = new Scanner(System.in);

    public static void main(String[] args) throws Exception {
        new Main();
    }

    public Main() {
        System.out.println("Enter a students name: ");
        String commandInput = command.next();
        try {
            Student student = Student.loadByName(commandInput);
            editStuGrade(student);
        } catch (IOException ex) {
            System.out.println("Could not read student record: " + ex.getMessage());
        }
    }

    protected void editStuGrade(Student student) throws IOException {
        System.out.println("Would you like to edit or quit (edit | quit)?");
        String editInput = command.next();
        if (editInput.equalsIgnoreCase("edit")) {
            // Make some changes...
            student.save();
        } else if (editInput.equalsIgnoreCase("quit")) {
            System.exit(0);
        }

    }

    public static class Student {

        private String name;
        private String id;
        private int q1Score;
        private int q2Score;
        private int q3Score;
        private int midTermScore;
        private int finalScore;

        public Student(String name, String id, int q1Score, int q2Score, int q3Score, int midTermScore, int finalScore) {
            this.name = name;
            this.id = id;
            this.q1Score = q1Score;
            this.q2Score = q2Score;
            this.q3Score = q3Score;
            this.midTermScore = midTermScore;
            this.finalScore = finalScore;
        }

        public static Student loadByName(String name) throws IOException {
            File file = new File(name + ".txt");
            if (!file.exists()) {
                throw new FileNotFoundException("No record exists for " + name);
            }

            try (Scanner input = new Scanner(file)) {
                input.useDelimiter(",");
                name = input.next();
                String id = input.next();
                int q1Score = input.nextInt();
                int q2Score = input.nextInt();
                int q3Score = input.nextInt();
                int midTermScore = input.nextInt();
                int finalScore = input.nextInt();

                return new Student(name, id, q1Score, q2Score, q3Score, midTermScore, finalScore);
            }
        }

        public void save() throws IOException {
            File file = new File(getName() + ".txt");
            StringJoiner joiner = new StringJoiner(",");
            joiner.add(getName());
            joiner.add(getId());
            joiner.add(Integer.toString(getQ1Score()));
            joiner.add(Integer.toString(getQ2Score()));
            joiner.add(Integer.toString(getQ3Score()));
            joiner.add(Integer.toString(getMidTermScore()));
            joiner.add(Integer.toString(getFinalScore()));

            try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
                bw.write(joiner.toString());
            }
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public int getQ1Score() {
            return q1Score;
        }

        public void setQ1Score(int q1Score) {
            this.q1Score = q1Score;
        }

        public int getQ2Score() {
            return q2Score;
        }

        public void setQ2Score(int q2Score) {
            this.q2Score = q2Score;
        }

        public int getQ3Score() {
            return q3Score;
        }

        public void setQ3Score(int q3Score) {
            this.q3Score = q3Score;
        }

        public int getMidTermScore() {
            return midTermScore;
        }

        public void setMidTermScore(int midTermScore) {
            this.midTermScore = midTermScore;
        }

        public int getFinalScore() {
            return finalScore;
        }

        public void setFinalScore(int finalScore) {
            this.finalScore = finalScore;
        }

    }
}


问:
Blocking calls with Gevent and WSGI
I've just started working with coroutines and have read up on gevent and greenlets. For a test I served this code through gevents pywsgi module:

```<code>from gevent.pywsgi import WSGIServer
import gevent

def hello_world(env, start_response):
    gevent.sleep(5)
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["<b>hello world</b>"]

print 'Serving on 8088...'
WSGIServer(('127.0.0.1', 8888), hello_world).serve_forever()
</code>```

I expected a result where every request would get a 5 second delay before the text is displayed. However, what happens is that every request gets queued up with the call to gevent.sleep() which makes a second request take almost 10 seconds if it was initiated immediately after the first one.

Isn't the serve_forever function spawning new greenlets for every request?

答:
What are you using to make the requests? I suspect the problem lies there.

I tested your code with ab (Apache Benchmark) and got this (output edited):

```<code>$ ab -c 200 -n 200 http://localhost:8888/

Completed 100 requests
Completed 200 requests
Finished 200 requests

Concurrency Level:      200
Time taken for tests:   5.048 seconds
Requests per second:    39.62 [#/sec] (mean)
Time per request:       5048.386 [ms] (mean)
</code>```

The ab command makes 200 concurrent requests to the gevent server. After five seconds, all requests have completed. If the requests were queued, as you suggest, this benchmark would take 1000 seconds.

I suppose it's possible that your system doesn't support greenlets properly, but it seems more likely that the method you are using to test is blocking on each request. I.e. the server is supporting concurrency but your client isn't.

ContentLicense: CC BY-SA 3.0

Title: Blocking calls with Gevent and WSGI

Body:
I've just started working with coroutines and have read up on gevent and greenlets. For a test I served this code through gevents pywsgi module:

from gevent.pywsgi import WSGIServer
import gevent

def hello_world(env, start_response):
    gevent.sleep(5)
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["hello world"]

print 'Serving on 8088...'
WSGIServer(('127.0.0.1', 8888), hello_world).serve_forever()

I expected a result where every request would get a 5 second delay before the text is displayed. However, what happens is that every request gets queued up with the call to gevent.sleep() which makes a second request take almost 10 seconds if it was initiated immediately after the first one.

Isn't the serve_forever function spawning new greenlets for every request?

Body:
What are you using to make the requests? I suspect the problem lies there.

I tested your code with ab (Apache Benchmark) and got this (output edited):

$ ab -c 200 -n 200 http://localhost:8888/

Completed 100 requests
Completed 200 requests
Finished 200 requests

Concurrency Level:      200
Time taken for tests:   5.048 seconds
Requests per second:    39.62 [#/sec] (mean)
Time per request:       5048.386 [ms] (mean)

The ab command makes 200 concurrent requests to the gevent server. After five seconds, all requests have completed. If the requests were queued, as you suggest, this benchmark would take 1000 seconds.

I suppose it's possible that your system doesn't support greenlets properly, but it seems more likely that the method you are using to test is blocking on each request. I.e. the server is supporting concurrency but your client isn't.


问:
No applicable method for 'summarise' applied to an object of class "ts"
```<code>install.packages(c("ggplot2", "ggpubr", "tidyverse", "broom", "AICcmodavg"))
library(ggplot2)
library(ggpubr)
library(tidyverse)
library(broom)
library(AICcmodavg)

my_data <- read.table(file = "clipboard",
                      sep = "\t", header=TRUE)

group_by(my_data, group) %>%
mutate(across(co2, as.numeric)) %>%
suppressWarnings(as.numeric(co2))
summarise (co2, count = n(), mean = mean("CO2", na.rm = TRUE), sd = sd("CO2", na.rm = TRUE))
</code>```

Working my way towards carrying out a one way anova test with a dataset and I keep getting this same error code:

No applicable method for 'summarise' applied to an object of class "ts"

When I run the following line of code:

```<code>summarise (co2, count = n(), mean = mean("CO2", na.rm = TRUE), sd = sd("CO2", na.rm = TRUE))
</code>```

My dataset involves no timeseries (a table of CO2 emissions compared to vegetation type) so I'm not sure why I'm getting this error and what I can do to solve it?
Any help would be much appreciated, thank you!

答:
There are (at least) three problems with your code:

This code is meaningless:

... %>%
  suppressWarnings(as.numeric(co2))
```
<p>This call to <code>suppressWarnings</code> really evaluates to</p>
<pre class="lang-r prettyprint-override"><code>... %>%
  suppressWarnings(., as.numeric(co2))
</code>```

which argument-expands to

... %>%
  suppressWarnings(expr = ., classes = as.numeric(co2))
```
<p>which ... does absolutely nothing. Fortunately, it passes the frame passed to it with no change, so it will not <em>error</em> ... but it also does absolutely nothing to the data, including what you may have originally intended with <code>as.numeric(.)</code>. If you want to convert <code>co2</code> to numeric from something else, this should likely be</p>
<pre class="lang-r prettyprint-override"><code>... %>%
  mutate(co2 = suppressWarnings(as.numeric(co2)))
</code>```

However ... that seems completely redundant given that the line before that is mutate(across(co2, as.numeric)), which does precisely that.

Because you do not continue the pipeline from the suppressWarnings(.) line, your next call is

summarise (co2, ...)
```
<p>If you had differently-named variables, this should fail with <code>object 'somethingelse' not found</code>, but you used <code>co2</code>. That <em>happens</em> to be the name of <code>co2</code> in the <code>datasets</code> package, which is <em>not</em> a <code>data.frame</code>, it is class <code>ts</code>. Type in <code>?co2</code> to see what that data is about, and just <code>co2</code> to see what you were really passing there.</p>
<p>Fix this problem by adding <code>%>%</code> to the previous line. Actually, removing the previous line (and using the fact that the <em>previous</em> previous line does have the <code>%>%</code>), it may be something like:</p>
<pre class="lang-r prettyprint-override"><code>group_by(my_data, group) %>%
  mutate(across(co2, as.numeric)) %>%
  summarise(...)
</code>```

For efficiency, though, doing that mutate within a grouping is inefficient. I suggest instead:

my_data %>%
  mutate(across(co2, ~ suppressWarnings(as.numeric(.)))) %>%
  group_by(group) %>%
  summarise(...)
```
</li>
<li><p>Your <code>summarise</code> call is confuses me.</p>
<pre class="lang-r prettyprint-override"><code>summarise(
  co2,
  count = n(),
  mean = mean("CO2", na.rm = TRUE),
  sd = sd("CO2", na.rm = TRUE)
)
</code>```

co2, assuming it is really a column in the data, will "summarise" to the same number of rows with no aggregation of co2. Perhaps this should be some aggregating function, like min or max? I'll remove this from my suggested code below.

count = n() makes sense, but it returns a single number, so when combined with co2 above, it will repeat this one number nrow(.) times. When we remove co2 above, this will be fine.

mean = mean("CO2", na.rm=TRUE) ... what is the average of a string? Do you mean mean = mean(co2, na.rm=TRUE)?

sd = sd("CO2", na.rm=TRUE) ... ditto.

Ultimately, try this:

my_data %>%
  mutate(across(co2, ~ suppressWarnings(as.numeric(.)))) %>%
  group_by(group) %>%
  summarise(
    count = n(),
    mean = mean(co2, na.rm = TRUE),
    sd = sd(co2, na.rm = TRUE)
  )
```

Body:
install.packages(c("ggplot2", "ggpubr", "tidyverse", "broom", "AICcmodavg"))
library(ggplot2)
library(ggpubr)
library(tidyverse)
library(broom)
library(AICcmodavg)

my_data <- read.table(file = "clipboard",
                      sep = "\t", header=TRUE)

group_by(my_data, group) %>%
mutate(across(co2, as.numeric)) %>%
suppressWarnings(as.numeric(co2))
summarise (co2, count = n(), mean = mean("CO2", na.rm = TRUE), sd = sd("CO2", na.rm = TRUE))

Working my way towards carrying out a one way anova test with a dataset and I keep getting this same error code:

No applicable method for 'summarise' applied to an object of class "ts"

When I run the following line of code:

summarise (co2, count = n(), mean = mean("CO2", na.rm = TRUE), sd = sd("CO2", na.rm = TRUE))

My dataset involves no timeseries (a table of CO2 emissions compared to vegetation type) so I'm not sure why I'm getting this error and what I can do to solve it?
Any help would be much appreciated, thank you!

Body:
There are (at least) three problems with your code:

This code is meaningless:

... %>%
  suppressWarnings(as.numeric(co2))

This call to suppressWarnings really evaluates to

... %>%
  suppressWarnings(., as.numeric(co2))

which argument-expands to

... %>%
  suppressWarnings(expr = ., classes = as.numeric(co2))

which ... does absolutely nothing. Fortunately, it passes the frame passed to it with no change, so it will not error ... but it also does absolutely nothing to the data, including what you may have originally intended with as.numeric(.). If you want to convert co2 to numeric from something else, this should likely be

... %>%
  mutate(co2 = suppressWarnings(as.numeric(co2)))

However ... that seems completely redundant given that the line before that is mutate(across(co2, as.numeric)), which does precisely that.

Because you do not continue the pipeline from the suppressWarnings(.) line, your next call is

summarise (co2, ...)

If you had differently-named variables, this should fail with object 'somethingelse' not found, but you used co2. That happens to be the name of co2 in the datasets package, which is not a data.frame, it is class ts. Type in ?co2 to see what that data is about, and just co2 to see what you were really passing there.

Fix this problem by adding %>% to the previous line. Actually, removing the previous line (and using the fact that the previous previous line does have the %>%), it may be something like:

group_by(my_data, group) %>%
  mutate(across(co2, as.numeric)) %>%
  summarise(...)

For efficiency, though, doing that mutate within a grouping is inefficient. I suggest instead:

my_data %>%
  mutate(across(co2, ~ suppressWarnings(as.numeric(.)))) %>%
  group_by(group) %>%
  summarise(...)

Your summarise call is confuses me.

summarise(
  co2,
  count = n(),
  mean = mean("CO2", na.rm = TRUE),
  sd = sd("CO2", na.rm = TRUE)
)

co2, assuming it is really a column in the data, will "summarise" to the same number of rows with no aggregation of co2. Perhaps this should be some aggregating function, like min or max? I'll remove this from my suggested code below.

count = n() makes sense, but it returns a single number, so when combined with co2 above, it will repeat this one number nrow(.) times. When we remove co2 above, this will be fine.

mean = mean("CO2", na.rm=TRUE) ... what is the average of a string? Do you mean mean = mean(co2, na.rm=TRUE)?

sd = sd("CO2", na.rm=TRUE) ... ditto.

Ultimately, try this:

my_data %>%
  mutate(across(co2, ~ suppressWarnings(as.numeric(.)))) %>%
  group_by(group) %>%
  summarise(
    count = n(),
    mean = mean(co2, na.rm = TRUE),
    sd = sd(co2, na.rm = TRUE)
  )


问:
Tox does not find the requirements file
I have a Python module in which the setup.py script starts as follows:

```<code>import setuptools, pathlib

HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n")

setuptools.setup(
   install_requires=REQUIRES,
   long_description=README,
   ...
)
</code>```

When I run the setup from the command line, like this:

```<code>python setup.py sdist
</code>```

it runs fine. But when I run

```<code>tox
</code>```

I get an error on line 5 in file setup.py:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'
</code>```

even though both the requirements.txt file and the README.md file remain in the same folder as setup.py.

Here is my tox.ini file:

```<code>[tox]
envlist = py39

[testenv]
deps =
    pytest
    -r requirements.txt
commands =
    pytest
</code>```

How can I make tox find my requirements.txt file?

答:
I found the answer myself. The problem was that requirements.txt was not included by my 'MANIFEST.in' file. I changet the file to:

```<code>include pyproject.toml
include *.md
include *.txt
include LICENSE
</code>```

and now tox works.

Title: Tox does not find the requirements file

Body:
I have a Python module in which the setup.py script starts as follows:

import setuptools, pathlib

HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
REQUIRES = (HERE / "requirements.txt").read_text().strip().split("\n")

setuptools.setup(
   install_requires=REQUIRES,
   long_description=README,
   ...
)

When I run the setup from the command line, like this:

python setup.py sdist

it runs fine. But when I run

tox

I get an error on line 5 in file setup.py:

FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'

even though both the requirements.txt file and the README.md file remain in the same folder as setup.py.

Here is my tox.ini file:

[tox]
envlist = py39

[testenv]
deps =
    pytest
    -r requirements.txt
commands =
    pytest

How can I make tox find my requirements.txt file?

Body:
I found the answer myself. The problem was that requirements.txt was not included by my 'MANIFEST.in' file. I changet the file to:

include pyproject.toml
include *.md
include *.txt
include LICENSE

and now tox works.


问:
How to disable an <a> tag in React after clicking it?
How can I disable the below anchor tag in React after it has been clicked? Like the onClick functionality is not working on the anchor tag.</p>
```<code><td align="left">
  <input
    type="file"
    accept=".csv,.xlsx,.xls"
    name="image"
    className="file-upload-input"
    onChange={(e: any) => {
      handleFileChange(e, data.c_id);
    }}
  />

  <a
    href="javascript:;"
    className="btn btn-secondary"
    style={{
      width: "125.62px",
      backgroundColor: "#0b5ed7",
      borderColor: "#0a58ca"
    }}
  >
    <img src={UploadIcon.default} />
    Upload
  </a>
</td>
</code>```

答: try to put a button within  tag ,that way you can conditionally disable it.</p>

Body:
How can I disable the below anchor tag in React after it has been clicked? Like the onClick functionality is not working on the anchor tag.

  <input
    type="file"
    accept=".csv,.xlsx,.xls"
    name="image"
    className="file-upload-input"
    onChange={(e: any) => {
      handleFileChange(e, data.c_id);
    }}
  />

    Upload


问:
ASP.NET MVC View can't see member of an anonymous object viewModel
I am trying to create an anonymous object view model with one member being from the Models folder, and another being from my own custom classes folder:

```<code>var viewModel = new {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(viewModel);
</code>```

In the view, @Model, if you pause/breakpoint, and inspect it with the Visual Studio debugger, contains:

Model [press enter]:

```<code>{ Test1 = {MVC_Test1.Models.Test1}, Test2 = {MVC_Test1.Classes.Test2} }
    Test1: {MVC_Test1.Models.Test1}
    Test2: {MVC_Test1.Classes.Test2}
</code>```

However, if you try the following:

Model.Test1 [press enter]

'Model.Test1' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'

Message: "'object' does not contain a definition for 'Test1'"

What is wrong? Is there a way to refer to a dynamically created view model done this way? Or must I explicitly create a class that instantiates Models.Test1() and Classes.Test2() into one class, and use that instead of the anonymous object?

答:
there is no sense in anonymous model for view, since you will have to create a anomymous input controls, so create a real typed view model</p>
```<code>public class ViewModel
{
public Test1 Test1 {get; set;}
public Test2 Test2 {get; set;}
};

model  = new ViewModel {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(model);
````
</code>```

Body:
I am trying to create an anonymous object view model with one member being from the Models folder, and another being from my own custom classes folder:

var viewModel = new {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(viewModel);

In the view, @Model, if you pause/breakpoint, and inspect it with the Visual Studio debugger, contains:

Model [press enter]:

{ Test1 = {MVC_Test1.Models.Test1}, Test2 = {MVC_Test1.Classes.Test2} }
    Test1: {MVC_Test1.Models.Test1}
    Test2: {MVC_Test1.Classes.Test2}

However, if you try the following:

Model.Test1 [press enter]

'Model.Test1' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'

Message: "'object' does not contain a definition for 'Test1'"

What is wrong? Is there a way to refer to a dynamically created view model done this way? Or must I explicitly create a class that instantiates Models.Test1() and Classes.Test2() into one class, and use that instead of the anonymous object?

Body:
there is no sense in anonymous model for view, since you will have to create a anomymous input controls, so create a real typed view model

public class ViewModel
{
public Test1 Test1 {get; set;}
public Test2 Test2 {get; set;}
};

model  = new ViewModel {
    test1 = new Models.Test1(),
    test2 = new Classes.Test2()
};

return View(model);
````


问:
How to check the number of points <=10 in Cypress
```<code>cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)
</code>```

How to make a check  <=10 ? Maybe to.have.length.most()
DOM

```<code><div id="base-table-[object Object]-body">
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
</div>
</code>```

答:
You can enhance the assertion as follows

cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505')
  .should('have.length.lt', 11)
```

Body:
cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)

How to make a check  <=10 ? Maybe to.have.length.most()
DOM


问:
"npm install -g yo generator-code" gives wierd errors
I open VS Code, and them I show the terminal and it opens up Powershell, so far so good. The application is also started as Administrator. Then I type in:

```<code>npm install -g yo generator-code
</code>```

But it fails. I am unsure what, this is the first time I'm using npm, but it doesn't work, I know that much. When i try yo code, it says that yo is not recognized.
The above command outputs the following "errors":

```<code>npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

changed 869 packages, and audited 870 packages in 1m

59 packages are looking for funding
  run `npm fund` for details

15 vulnerabilities (13 moderate, 2 high)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
</code>```

I saw multiple tutorials on installing this, and none of them detailed what to do if it fails like this. But I assumed i should run npm audit fix. But when running that command it gives the following output:

```<code>npm ERR! code ENOLOCK
npm ERR! audit This command requires an existing lockfile.
npm ERR! audit Try creating one first with: npm i --package-lock-only
npm ERR! audit Original error: loadVirtual requires existing shrinkwrap file

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\admin\AppData\Local\npm-cache\_logs\2022-02-06T21_40_42_240Z-debug.log
</code>```

And in case it helps, here is the contents of the debug.log file mentioned in the output above:

```<code>0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'audit',
0 verbose cli   'fix'
0 verbose cli ]
1 info using npm@8.1.2
2 info using node@v16.13.2
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 2ms
5 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 4ms
6 timing config:load:builtin Completed in 4ms
7 timing config:load:cli Completed in 3ms
8 timing config:load:env Completed in 1ms
9 timing config:load:file:C:\Users\jevar\documents\github\.npmrc Completed in 1ms
10 timing config:load:project Completed in 3ms
11 timing config:load:file:C:\Users\jevar\.npmrc Completed in 0ms
12 timing config:load:user Completed in 0ms
13 timing config:load:file:C:\Users\jevar\AppData\Roaming\npm\etc\npmrc Completed in 1ms
14 timing config:load:global Completed in 1ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:credentials Completed in 1ms
17 timing config:load:setEnvs Completed in 2ms
18 timing config:load Completed in 17ms
19 timing npm:load:configload Completed in 18ms
20 timing npm:load:setTitle Completed in 0ms
21 timing npm:load:setupLog Completed in 0ms
22 timing config:load:flatten Completed in 5ms
23 timing npm:load:cleanupLog Completed in 5ms
24 timing npm:load:configScope Completed in 0ms
25 timing npm:load:projectScope Completed in 0ms
26 timing npm:load Completed in 31ms
27 timing arborist:ctor Completed in 0ms
28 timing command:audit Completed in 6ms
29 verbose stack Error: loadVirtual requires existing shrinkwrap file
29 verbose stack     at Arborist.loadVirtual (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\load-virtual.js:62:18)
29 verbose stack     at async Arborist.audit (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\audit.js:25:18)
29 verbose stack     at async Audit.audit (C:\Program Files\nodejs\node_modules\npm\lib\audit.js:66:5)
30 verbose cwd C:\Users\jevar\documents\github
31 verbose Windows_NT 10.0.19044
32 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "audit" "fix"
33 verbose node v16.13.2
34 verbose npm  v8.1.2
35 error code ENOLOCK
36 error audit This command requires an existing lockfile.
37 error audit Try creating one first with: npm i --package-lock-only
38 error audit Original error: loadVirtual requires existing shrinkwrap file
39 verbose exit 1
</code>```

As I said, this is my first time using npm so I have no idea what this is, or what to do. Thank you in advance!

答:
It looks like I didn't generate the package-lock.json file.
Did you try running the command it says there?

```<code>npm i --package-lock-only
</code>```

Then if it keeps throwing an error, execute the following command:

```<code>npm audit fix
</code>```

If all of that doesn't work, I would recommend you to share the project structure to check the package-lock.json file

I hope I have helped

Body:
I open VS Code, and them I show the terminal and it opens up Powershell, so far so good. The application is also started as Administrator. Then I type in:

npm install -g yo generator-code

But it fails. I am unsure what, this is the first time I'm using npm, but it doesn't work, I know that much. When i try yo code, it says that yo is not recognized.
The above command outputs the following "errors":

npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

changed 869 packages, and audited 870 packages in 1m

59 packages are looking for funding
  run `npm fund` for details

15 vulnerabilities (13 moderate, 2 high)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

I saw multiple tutorials on installing this, and none of them detailed what to do if it fails like this. But I assumed i should run npm audit fix. But when running that command it gives the following output:

npm ERR! code ENOLOCK
npm ERR! audit This command requires an existing lockfile.
npm ERR! audit Try creating one first with: npm i --package-lock-only
npm ERR! audit Original error: loadVirtual requires existing shrinkwrap file

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\admin\AppData\Local\npm-cache\_logs\2022-02-06T21_40_42_240Z-debug.log

And in case it helps, here is the contents of the debug.log file mentioned in the output above:

0 verbose cli [
0 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli   'audit',
0 verbose cli   'fix'
0 verbose cli ]
1 info using npm@8.1.2
2 info using node@v16.13.2
3 timing npm:load:whichnode Completed in 0ms
4 timing config:load:defaults Completed in 2ms
5 timing config:load:file:C:\Program Files\nodejs\node_modules\npm\npmrc Completed in 4ms
6 timing config:load:builtin Completed in 4ms
7 timing config:load:cli Completed in 3ms
8 timing config:load:env Completed in 1ms
9 timing config:load:file:C:\Users\jevar\documents\github\.npmrc Completed in 1ms
10 timing config:load:project Completed in 3ms
11 timing config:load:file:C:\Users\jevar\.npmrc Completed in 0ms
12 timing config:load:user Completed in 0ms
13 timing config:load:file:C:\Users\jevar\AppData\Roaming\npm\etc\npmrc Completed in 1ms
14 timing config:load:global Completed in 1ms
15 timing config:load:validate Completed in 0ms
16 timing config:load:credentials Completed in 1ms
17 timing config:load:setEnvs Completed in 2ms
18 timing config:load Completed in 17ms
19 timing npm:load:configload Completed in 18ms
20 timing npm:load:setTitle Completed in 0ms
21 timing npm:load:setupLog Completed in 0ms
22 timing config:load:flatten Completed in 5ms
23 timing npm:load:cleanupLog Completed in 5ms
24 timing npm:load:configScope Completed in 0ms
25 timing npm:load:projectScope Completed in 0ms
26 timing npm:load Completed in 31ms
27 timing arborist:ctor Completed in 0ms
28 timing command:audit Completed in 6ms
29 verbose stack Error: loadVirtual requires existing shrinkwrap file
29 verbose stack     at Arborist.loadVirtual (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\load-virtual.js:62:18)
29 verbose stack     at async Arborist.audit (C:\Program Files\nodejs\node_modules\npm\node_modules\@npmcli\arborist\lib\arborist\audit.js:25:18)
29 verbose stack     at async Audit.audit (C:\Program Files\nodejs\node_modules\npm\lib\audit.js:66:5)
30 verbose cwd C:\Users\jevar\documents\github
31 verbose Windows_NT 10.0.19044
32 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "audit" "fix"
33 verbose node v16.13.2
34 verbose npm  v8.1.2
35 error code ENOLOCK
36 error audit This command requires an existing lockfile.
37 error audit Try creating one first with: npm i --package-lock-only
38 error audit Original error: loadVirtual requires existing shrinkwrap file
39 verbose exit 1

As I said, this is my first time using npm so I have no idea what this is, or what to do. Thank you in advance!

Body:
It looks like I didn't generate the package-lock.json file.
Did you try running the command it says there?

npm i --package-lock-only

Then if it keeps throwing an error, execute the following command:

npm audit fix

If all of that doesn't work, I would recommend you to share the project structure to check the package-lock.json file

I hope I have helped


问:
How to create quantiles with non-unique bin edges? Python or R
I want to divide my data into quantiles (quintiles to be more specific). However, when using qcut in Pandas or ntile in R, I either get the error that "bin edges must be unique" (qcut) or equal values get assigned to different quintiles (ntile).

Looking at the following data: [1, 8, 2, 1, 8]
I would like the ouput to be:

1 assigned to quintile 1

8 assigned to quintile 5

2 assigned to quintile 3

1 assigned to quintile 1 again

8 assigned to quintile 5 again

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

Do you have any ideas on how I can achieve this?

Thank you very much for your input!

Some data to use:

```<code>import pandas as pd
df = pd.DataFrame({'Date': ['2011-01-01', '2011-01-02', '2011-01-03','2011-01-01', '2011-01-02',
'2011-01-03','2011-01-01', '2011-01-02', '2011-01-03', '2011-01-01','2011-01-02', '2011-01-03',
'2011-01-01', '2011-01-02', '2011-01-03'], 'Name': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'],
'Value':[1, 3, 2, 8, 6, 5, 2, 10, 4, 1, 5, 3, 8, 4, 9]})
</code>```

Code I used in R:

```<code>df = df %>% group_by(Date) %>% mutate(Quint = ntile(Value, 5))
</code>```

This assigned qual values to different bins.

Code I used in Python:

```<code>df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(lambda x: pd.qcut(x, 5, labels=["XS", "S", "M", "L", "XL"]))
</code>```

This resulted in the error of bin edges having to be unique.

答:
A partial answer as it's looking at numpy's descriptions of percentile interpolation methods, and not applying directly to pandas, but in the manual above, you can see the different options for interpolation of the percentiles for a discontinuous dataset.

```<code>import numpy as np

x =  [1, 8, 2, 1, 8]

discontinuous_methods = ['linear',
                         'lower',
                         'higher',
                         'midpoint',
                         'nearest']

for method in discontinuous_methods:
    n = [f'{np.percentile(x, i, interpolation = method):.2f}' for i in [20, 40, 60, 80]]
    print(f'{method:8s} - {n[0]:3s}, {n[1]:3s}, {n[2]:3s}, {n[3]:3s}')

</code>```
```<code>linear   - 1.00, 1.60, 4.40, 8.00
lower    - 1.00, 1.00, 2.00, 8.00
higher   - 1.00, 2.00, 8.00, 8.00
midpoint - 1.00, 1.50, 5.00, 8.00
nearest  - 1.00, 2.00, 2.00, 8.00
</code>```

Body:
I want to divide my data into quantiles (quintiles to be more specific). However, when using qcut in Pandas or ntile in R, I either get the error that "bin edges must be unique" (qcut) or equal values get assigned to different quintiles (ntile).

Looking at the following data: [1, 8, 2, 1, 8]
I would like the ouput to be:

1 assigned to quintile 1

8 assigned to quintile 5

2 assigned to quintile 3

1 assigned to quintile 1 again

8 assigned to quintile 5 again

In this specific case the 1s could also be assigned to quintile 2 instead of 1 (depending on definition). It is just important that equal values are assigned to the same quintile.

Do you have any ideas on how I can achieve this?

Thank you very much for your input!

Some data to use:

import pandas as pd
df = pd.DataFrame({'Date': ['2011-01-01', '2011-01-02', '2011-01-03','2011-01-01', '2011-01-02',
'2011-01-03','2011-01-01', '2011-01-02', '2011-01-03', '2011-01-01','2011-01-02', '2011-01-03',
'2011-01-01', '2011-01-02', '2011-01-03'], 'Name': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'E', 'E', 'E'],
'Value':[1, 3, 2, 8, 6, 5, 2, 10, 4, 1, 5, 3, 8, 4, 9]})

Code I used in R:

df = df %>% group_by(Date) %>% mutate(Quint = ntile(Value, 5))

This assigned qual values to different bins.

Code I used in Python:

df['Quintiles'] = df.groupby(by=["Date"])['Value'].transform(lambda x: pd.qcut(x, 5, labels=["XS", "S", "M", "L", "XL"]))

This resulted in the error of bin edges having to be unique.

Body:
A partial answer as it's looking at numpy's descriptions of percentile interpolation methods, and not applying directly to pandas, but in the manual above, you can see the different options for interpolation of the percentiles for a discontinuous dataset.

import numpy as np

x =  [1, 8, 2, 1, 8]

discontinuous_methods = ['linear',
                         'lower',
                         'higher',
                         'midpoint',
                         'nearest']

for method in discontinuous_methods:
    n = [f'{np.percentile(x, i, interpolation = method):.2f}' for i in [20, 40, 60, 80]]
    print(f'{method:8s} - {n[0]:3s}, {n[1]:3s}, {n[2]:3s}, {n[3]:3s}')

linear   - 1.00, 1.60, 4.40, 8.00
lower    - 1.00, 1.00, 2.00, 8.00
higher   - 1.00, 2.00, 8.00, 8.00
midpoint - 1.00, 1.50, 5.00, 8.00
nearest  - 1.00, 2.00, 2.00, 8.00


问:
Check if Bot and Member are in the same channel
I cant really figure out how to do this without iterating through all voicechannels and compare the user ids, but this is veeeery slow. Is there a better way? I want to know this, because my Music Bot should add a song to the queue if the User who wrote the command is in the same voice channel as the Bot</p>

答:
```<code>if (ctx.guild.voice_client.channel == ctx.message.author.voice.channel):
</code>```


问:
Keeping dependency inject component out of main code base
I have a MVC app that uses ninject to inject service dependencies into controllers and it works well.  However I also have some domain objects that require these services in their constructors and I want to resolve these dependencies using ninject, but don't want to reference ninject directly in my domain objects assembly.  I have read lots of questions and answers here but its still not clear to me the best way to go about this.  For example I have a ShoppingCart domain object that needs an instance of a IProductCatalogService passed to its constructor.  What is the best pattern to create an instance of a shopping cart?  I could have a reference to the root kernel and call out to that, but that would mean having references to ninject throughout my domain assembly.  Should I wrap access to the kernel in a factory class?

Any thoughts or suggestions welcome!

答:
It is usually considered bad practice to have services in domain objects.  I think you need to rethink exactly what you are attempting to achieve.  Why does a ShoppingCart need to consume Product Catalog Services?

From a Domain perspective I would assume that a ShoppingCart would consist of many 'items', have properties like total etc and potentially would be passed to an ordering service.  Your controller actions would update the Shopping Cart domain by adding items, removing items, etc, etc.

If you really need to consider this option, is to use commonservicelocator.  This will separate out your (direct) dependency on ninject.


问:
Remove all but the first four characters on each line
So I have a text file in Vscode that contains several lines of text like so:

1801: Joseph Marie Jacquard, a French merchant and inventor invent a loom that uses punched wooden cards to automatically weave fabric designs. Early computers would use similar punch cards.

So now I'm trying to isolate the year number/the first 4 characters of each line. I'm new to regex, and I know how to get the first 4 characters (I used ^.{4}) but how would I be able to find all EXCEPT for the first 4 characters so that I can replace them with nothing and be left with just the year numbers?

答:
Find: (?<=^\d{4}).*
Replace: with nothing

regex101 Demo

(?<=^\d{4}) if a line starts ^ with 4 digits , (?<=...) is a positive lookbehind

.* match everything else up to line terminators, so the :  will be included in the match

Since you never matched the 4 digits, a lookbehind/lookahead isn't part of any match necessarily, that you want to keep, you don't have to worry about any capture groups or replacements.


问:
Exporting SQL query result to csv or Excel
I want to write the result of a SQL query to a csv or Excel file and save it in a particular folder. I have following requests:

I would like to know, if this can be achieved using a Java program which can be reused for any SQL query result.

I would also like to know, if this can be used for different databases (Oracle, MySQL, SQL Server, etc.).

I plan to attach the saved file to an email. Is it possible to export SQL query results to an email directly?.

答:
this work for exort to csv and txt</p>
```<code>public void ExportTxt(){
        FileWriter texto = null;
        ResultSet rs2 = null;
        ResultSet rs = null;
        try {
            texto = new FileWriter("texto.txt");
            PrintWriter pw = new PrintWriter(texto);
            Statement consulta = conn.createStatement();
            Statement consulta2 = conn.createStatement();
            String query = "SELECT * FROM coches";
            rs = consulta.executeQuery(query);
            int i=1;
            pw.println("----------------");
            while (rs.next()) {
                pw.println(i + ",Coche: Matricula:" + rs.getString("matricula") + ", Marca:" + rs.getString("marca") + ", Modelo:" + rs.getString("modelo"));
                String query2 = "SELECT * FROM reparaciones WHERE coche = '" + rs.getString("matricula") + "'";
                rs2 = consulta2.executeQuery(query2);
                pw.println("----------------");
                while(rs2.next()){
                    pw.println(rs2.getRow() + ",Reparacion: Fecha entrada:" + rs2.getString("fecha_entrada") + ", Fecha salida:" + rs2.getString("fecha_salida"));
                }
                i++;
            }
            rs.close();
            rs2.close();
            consulta.close();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                texto.close();
            } catch (IOException ex) {
                Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void ExportCSV(){
        PrintWriter pw = null;
        try {
            File archivo = new File("excel.csv");
            pw = new PrintWriter((new FileWriter(archivo)));
            Statement consulta = conn.createStatement();
            String query = "SELECT * FROM clientes";
            ResultSet rs = consulta.executeQuery(query);
            pw.println("id;nombre;apellidos;direccion;nif;telefono");
            while(rs.next()){
                pw.println(rs.getInt("id") + ";" + rs.getString("nombre") + ";" + rs.getString("Apellidos") + ";" + rs.getString("direccion") + ";" + rs.getString("nif") + ";" + rs.getString("telefono"));
            }
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            pw.close();
        }
    }
</code>```

Body:
this work for exort to csv and txt

public void ExportTxt(){
        FileWriter texto = null;
        ResultSet rs2 = null;
        ResultSet rs = null;
        try {
            texto = new FileWriter("texto.txt");
            PrintWriter pw = new PrintWriter(texto);
            Statement consulta = conn.createStatement();
            Statement consulta2 = conn.createStatement();
            String query = "SELECT * FROM coches";
            rs = consulta.executeQuery(query);
            int i=1;
            pw.println("----------------");
            while (rs.next()) {
                pw.println(i + ",Coche: Matricula:" + rs.getString("matricula") + ", Marca:" + rs.getString("marca") + ", Modelo:" + rs.getString("modelo"));
                String query2 = "SELECT * FROM reparaciones WHERE coche = '" + rs.getString("matricula") + "'";
                rs2 = consulta2.executeQuery(query2);
                pw.println("----------------");
                while(rs2.next()){
                    pw.println(rs2.getRow() + ",Reparacion: Fecha entrada:" + rs2.getString("fecha_entrada") + ", Fecha salida:" + rs2.getString("fecha_salida"));
                }
                i++;
            }
            rs.close();
            rs2.close();
            consulta.close();
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                texto.close();
            } catch (IOException ex) {
                Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void ExportCSV(){
        PrintWriter pw = null;
        try {
            File archivo = new File("excel.csv");
            pw = new PrintWriter((new FileWriter(archivo)));
            Statement consulta = conn.createStatement();
            String query = "SELECT * FROM clientes";
            ResultSet rs = consulta.executeQuery(query);
            pw.println("id;nombre;apellidos;direccion;nif;telefono");
            while(rs.next()){
                pw.println(rs.getInt("id") + ";" + rs.getString("nombre") + ";" + rs.getString("Apellidos") + ";" + rs.getString("direccion") + ";" + rs.getString("nif") + ";" + rs.getString("telefono"));
            }
        } catch (IOException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            pw.close();
        }
    }


问:
How do i make a form around a div box
I created a small box div containing an image and a text beside each other. But I don't know how I can add a form around it that when I hover on any part of the box it would click on submit.

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="trust-box">
  <img src="https://images.pexels.com/photos/34299/herbs-flavoring-seasoning-cooking.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="trust" width="50" height="50">
  <span>Portis Wallet</span>
</div></code>```

And again how do I make the image and the text align horizontally inside the box? The div box image.

答:
Research mouseenter for adding an event listener for hovering. For aligning your elements you can make use of flexbox. See the snippet below:

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  border: 1px solid black;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="trust-box">
  <img src="https://images.pexels.com/photos/34299/herbs-flavoring-seasoning-cooking.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="trust" width="50" height="50">
  <span>Portis Wallet</span>
</div></code>```

More on flexbox here.

Title: How do i make a form around a div box

Body:
I created a small box div containing an image and a text beside each other. But I don't know how I can add a form around it that when I hover on any part of the box it would click on submit.

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  text-align: center;
}

  Portis Wallet

And again how do I make the image and the text align horizontally inside the box? The div box image.

Body:
Research mouseenter for adding an event listener for hovering. For aligning your elements you can make use of flexbox. See the snippet below:

.trust-box {
  width: 200px;
  height: 80px;
  margin: 20px;
  background: #fff;
  color: #000;
  border-radius: 5px;
  border: 1px solid black;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}

<div class="trust-box">
  <img src="https://images.pexels.com/photos/34299/herbs-flavoring-seasoning-cooking.jpg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="trust" width="50" height="50">
  <span>Portis Wallet</span>
</div>

More on flexbox here.


问:
How to check the last character of a string in C#?
I want to find the last character of a string in C# and then put it in an if statement.

Then if the last character is equal to 'A', 'B' or 'C' a certain action should be performed.

How do I get the last character of a string in C#?

答:
Since C# 8.0, you can use new syntactic forms for System.Index and System.Range hence addressing specific characters in a string becomes trivial. Example for your scenario:

```<code>var lastChar = aString[^1..]; // aString[Range.StartAt(new Index(1, fromEnd: true))

if (lastChar == "A" || lastChar == "B" || lastChar == "C")
    // perform action here
</code>```

Full explanation here: Ranges (Microsoft Docs)

Body:
Since C# 8.0, you can use new syntactic forms for System.Index and System.Range hence addressing specific characters in a string becomes trivial. Example for your scenario:

var lastChar = aString[^1..]; // aString[Range.StartAt(new Index(1, fromEnd: true))

if (lastChar == "A" || lastChar == "B" || lastChar == "C")
    // perform action here

Full explanation here: Ranges (Microsoft Docs)


问:
AWS SSM - store multiple parameters using terraform and json file
We have a couple of legacy applications we're migrating to ec2 and these use a bunch of application configuration parameters. I need to be able to store each config as an individual parameter per application.

I'm trying the following but clearly not doing it right as it appends all values to a single parameter per application:

```<code>locals {
  application = {
    "application1" = { app_shortcode = "app1"},
    "application2" = { app_shortcode = "app2"}
}

resource "aws_ssm_parameter" "application_parameters" {
  for_each = local.application
  name     = each.key
  value    = jsonencode(file("${path.module}/${each.key}/ssm_param.json"))
}
</code>```

my app1's ssm_param.json is something like

```<code>{
    "app1_config1": "config_value_1",
    "app1_config2": "config_value_2",
    "app1_config3": "config_value_3"
}
</code>```

and app2's ssm_param.jsonis

```<code>{
    "app2_config_a": "config_value_a",
    "app2_config_b": "config_value_b",
    "app2_config_c": "config_value_c"
}
</code>```

The current output is a single parameter like this for each application:
"{\r\n    \"app2_config_a\": \"config_value_a\",\r\n    \"app2_config_b\": \"config_value_b\"\r\n, \r\n    \"app2_config_c\": \"config_value_c\"\r\n}"

Looking for suggestions please.

答:
I solved this by using a slightly different approach (not quite the same as my initial one but this works for me for now):

used a ssm_params.yaml as below (the project team was kind enough to give me the config settings as yaml output)

```<code>parameter:
    app1:
      name: app1_config1
      description: "application config test"
      type: "String"
      value: "some_randoM_value"
    app1:
      name: app_config2
      description: "another test"
      type: "SecureString"
      value: "some_random123_value###"
    app2:
      name: app_config_2
      description: "config test"
      type: "String"
      value: "some_randoM_value_2"
</code>```

```<code>locals {
params             = yamldecode(file("${path.module}/ssm_params.yaml"))
}

resource "aws_ssm_parameter" "app_params" {
  for_each = local.params.parameter
  name     = each.value.name
  type     = each.value.type
  value    = each.value.value
}
</code>```

Body:
We have a couple of legacy applications we're migrating to ec2 and these use a bunch of application configuration parameters. I need to be able to store each config as an individual parameter per application.

I'm trying the following but clearly not doing it right as it appends all values to a single parameter per application:

locals {
  application = {
    "application1" = { app_shortcode = "app1"},
    "application2" = { app_shortcode = "app2"}
}

resource "aws_ssm_parameter" "application_parameters" {
  for_each = local.application
  name     = each.key
  value    = jsonencode(file("${path.module}/${each.key}/ssm_param.json"))
}

my app1's ssm_param.json is something like

{
    "app1_config1": "config_value_1",
    "app1_config2": "config_value_2",
    "app1_config3": "config_value_3"
}

and app2's ssm_param.jsonis

{
    "app2_config_a": "config_value_a",
    "app2_config_b": "config_value_b",
    "app2_config_c": "config_value_c"
}

The current output is a single parameter like this for each application:
"{\r\n    \"app2_config_a\": \"config_value_a\",\r\n    \"app2_config_b\": \"config_value_b\"\r\n, \r\n    \"app2_config_c\": \"config_value_c\"\r\n}"

Looking for suggestions please.

Body:
I solved this by using a slightly different approach (not quite the same as my initial one but this works for me for now):

used a ssm_params.yaml as below (the project team was kind enough to give me the config settings as yaml output)

parameter:
    app1:
      name: app1_config1
      description: "application config test"
      type: "String"
      value: "some_randoM_value"
    app1:
      name: app_config2
      description: "another test"
      type: "SecureString"
      value: "some_random123_value###"
    app2:
      name: app_config_2
      description: "config test"
      type: "String"
      value: "some_randoM_value_2"

locals {
params             = yamldecode(file("${path.module}/ssm_params.yaml"))
}

resource "aws_ssm_parameter" "app_params" {
  for_each = local.params.parameter
  name     = each.value.name
  type     = each.value.type
  value    = each.value.value
}