问:
How can I use a Lambda function in creating a Wordle-esque game with Python?
So, I'm a Uni student, and for one of my modules we've been tasked with creating an interactive game or quiz or similar with Python. I thought I'd go with something that's essentially Wordle. My issue is that I can enter an 'A' into the game, but no other letters. If I try repeating the same code albeit with different labels, it just overwrites the functioning 'A' code.

I've been reading and it looks like I'll be able to use a 'lambda' function to get around this problem, but I don't really know how. I'll post my code below, and hopefully one of you wizards can help me.

```<code>from tkinter import *
from tkinter import ttk
GameWindow = Tk()
GameWindow.title ("WORD5 - The 5X5 Word Spelling Game!")
GameWindow.geometry('2850x1000')
GameWindow.configure(bg="plum")
TileFrame=Frame(GameWindow, bg="green")
TileFrame.grid(row=0)
TileLine1Row1 = Label (TileFrame, text="box1", font=("Helvetica", 10), width=10, height=5, borderwidth=1,     relief="solid", bg="plum")
TileLine1Row1.grid(column=1,row=1,padx=15,pady = 10)
#
TileLine1Row2 = Label (TileFrame, text="box2", font=("Helvetica", 10), width=10, height=5,borderwidth=1,     relief="solid", bg="plum")
TileLine1Row2.grid(column=2,row=1,padx=15,pady = 10)
#T
TileLine1Row3 = Label (TileFrame, text="box3", font=("Helvetica", 10), width=10, height=5, borderwidth=1,     relief="solid", bg="plum")
TileLine1Row3.grid(column=3,row=1,padx=15,pady = 10)
#
</code>```

TileLine1Row4 = Label (TileFrame, text="box4", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine1Row4.grid(column=4,row=1,padx=15,pady = 10)

TileLine1Row5 = Label (TileFrame, text="box5", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")

#Now for the second row of tiles on the game

TileLine2Row1 = Label (TileFrame, text="box6", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row1.grid(column=1,row=2,padx=15,pady = 10)

TileLine2Row2 = Label (TileFrame, text="box7", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row2.grid(column=2,row=2,padx=15,pady = 10)

TileLine2Row3 = Label (TileFrame, text="box8", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row3.grid(column=3,row=2,padx=15,pady = 10)

TileLine2Row4 = Label (TileFrame, text="box9", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row4.grid(column=4,row=2,padx=15,pady = 10)

TileLine2Row5 = Label (TileFrame, text="box10", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row5.grid(column=5,row=2,padx=15,pady = 10)

```<code>#Rows and Columns defined numbers/ rows and columns placings
Trow = 1
Tcolumn = 1
#Defining where the letters go if a letter is pressed on the keyboard
def WhereLettersAreGoing ():
    global Trow
    global Tcolumn
    if Trow == 1:
        if Tcolumn == 1:
            #Add 1 to column count section
            WhereLettersGo = TileLine1Row1
        elif Tcolumn == 2:
            WhereLettersGo = TileLine1Row2
        elif Tcolumn == 3:
            WhereLettersGo = TileLine1Row3
        elif Tcolumn == 4:
            WhereLettersGo = TileLine1Row4
        elif Tcolumn == 5:
            WhereLettersGo = TileLine1Row5
        PutLetterIn (WhereLettersGo)
        Tcolumn = Tcolumn +1
def PutLetterIn (WhereLettersGo):
    WhereLettersGo.configure(text `your text`= "A")
# Define function to get the information about the Button
#Add in a check button?
#Button frame to section it up
ButtonsFrame=Frame(GameWindow, bg="blue")
ButtonsFrame.grid(row=1)

#Now, the buttons are below which represents the letters of the alphabet
#The buttons with letters A B C D E F G & H are on the top row of the letter button rows
#LetterAButton
LetterAButton = Button(ButtonsFrame, text="A", width=7, height=2, borderwidth=5, relief="raised", command = WhereLettersAreGoing)
LetterAButton.grid(column=1, row=4,padx=2,pady = 2)
#LetterBButton
LetterBButton = Button(ButtonsFrame, text="B", width=7, height=2, borderwidth=5, relief="raised")
LetterBButton.grid(column=2, row=4,padx=2,pady = 2)
#LetterCButton
LetterCButton = Button(ButtonsFrame, text="C", width=7, height=2, borderwidth=5, relief="raised")
LetterCButton.grid(column=3, row=4,padx=2,pady = 2)
#LetterDButton
LetterDButton = Button(ButtonsFrame, text="D", width=7, height=2, borderwidth=5, relief="raised")
LetterDButton.grid(column=4, row=4,padx=2,pady = 2)
#LetterEButton
LetterEButton = Button(ButtonsFrame, text="E", width=7, height=2, borderwidth=5, relief="raised")
LetterEButton.grid(column=5, row=4,padx=2,pady = 2)
#LetterFButton
LetterFButton = Button(ButtonsFrame, text="F", width=7, height=2, borderwidth=5, relief="raised")
LetterFButton.grid(column=6, row=4,padx=2,pady = 2)
#LetterGButton
LetterGButton = Button(ButtonsFrame, text="G", width=7, height=2, borderwidth=5, relief="raised")
LetterGButton.grid(column=7, row=4,padx=2,pady = 2)
#LetterHButton
LetterHButton = Button(ButtonsFrame, text="H", width=7, height=2, borderwidth=5, relief="raised")
LetterHButton.grid(column=8, row=4,padx=2,pady = 2)
#The buttons with letters I J K L M N O & P are on the second row of the button rows
#LetterIButton
LetterIButton = Button(ButtonsFrame, text="I", width=7, height=2, borderwidth=5, relief="raised")
LetterIButton.grid(column=1, row=5,padx=2,pady = 2)
#LetterJButton
LetterJButton = Button(ButtonsFrame, text="J", width=7, height=2, borderwidth=5, relief="raised")
LetterJButton.grid(column=2, row=5,padx=2,pady = 2)
#LetterKButton
LetterKButton = Button(ButtonsFrame, text="K", width=7, height=2, borderwidth=5, relief="raised")
LetterKButton.grid(column=3, row=5,padx=2,pady = 2)
#LetterLButton
LetterLButton = Button(ButtonsFrame, text="L", width=7, height=2, borderwidth=5, relief="raised")
LetterLButton.grid(column=4, row=5,padx=2,pady = 2)
#LetterMButton
LetterMButton = Button(ButtonsFrame, text="M", width=7, height=2, borderwidth=5, relief="raised")
LetterMButton.grid(column=5, row=5,padx=2,pady = 2)
#LetterNButton
LetterNButton = Button(ButtonsFrame, text="N", width=7, height=2, borderwidth=5, relief="raised")
LetterNButton.grid(column=6, row=5,padx=2,pady = 2)
#LetterOButton
LetterOButton = Button(ButtonsFrame, text="O", width=7, height=2, borderwidth=5, relief="raised")
LetterOButton.grid(column=7, row=5,padx=2,pady = 2)
#LetterPButton
LetterPButton = Button(ButtonsFrame, text="P", width=7, height=2, borderwidth=5, relief="raised")
LetterPButton.grid(column=8, row=5,padx=2,pady = 2)

#LetterQButton
LetterQButton = Button(ButtonsFrame, text="Q", width=7, height=2, borderwidth=5, relief="raised")
LetterQButton.grid(column=2, row=6,padx=2,pady = 2)
#LetterRButton
LetterRButton = Button(ButtonsFrame, text="R", width=7, height=2, borderwidth=5, relief="raised")
LetterRButton.grid(column=3, row=6,padx=2,pady = 2)
#LetterSButton
LetterSButton = Button(ButtonsFrame, text="S", width=7, height=2, borderwidth=5, relief="raised")
LetterSButton.grid(column=4, row=6,padx=2,pady = 2)
#LetterTButton
LetterTButton = Button(ButtonsFrame, text="T", width=7, height=2, borderwidth=5, relief="raised")
LetterTButton.grid(column=5, row=6,padx=2,pady = 2)
#LetterUButton
LetterUButton = Button(ButtonsFrame, text="U", width=7, height=2, borderwidth=5, relief="raised")
LetterUButton.grid(column=6, row=6,padx=2,pady = 2)
#LetterVButton
LetterVButton = Button(ButtonsFrame, text="V", width=7, height=2, borderwidth=5, relief="raised")
LetterVButton.grid(column=7, row=6,padx=2,pady = 2)

#LetterWButton
LetterWButton = Button(ButtonsFrame, text="W", width=7, height=2, borderwidth=5, relief="raised")
LetterWButton.grid(column=3, row=7,padx=2,pady = 2)
#LetterXButton
LetterXButton = Button(ButtonsFrame, text="X", width=7, height=2, borderwidth=5, relief="raised")
LetterXButton.grid(column=4, row=7,padx=2,pady = 2)
#LetterYButton
LetterYButton = Button(ButtonsFrame, text="Y", width=7, height=2, borderwidth=5, relief="raised")
LetterYButton.grid(column=5, row=7,padx=2,pady = 2)
#LetterZButton
LetterZButton = Button(ButtonsFrame, text="Z", width=7, height=2, borderwidth=5, relief="raised")
LetterZButton.grid(column=6, row=7,padx=2,pady = 2)

#Closing the game window loop
GameWindow.mainloop()
</code>```

Body:
So, I'm a Uni student, and for one of my modules we've been tasked with creating an interactive game or quiz or similar with Python. I thought I'd go with something that's essentially Wordle. My issue is that I can enter an 'A' into the game, but no other letters. If I try repeating the same code albeit with different labels, it just overwrites the functioning 'A' code.

I've been reading and it looks like I'll be able to use a 'lambda' function to get around this problem, but I don't really know how. I'll post my code below, and hopefully one of you wizards can help me.

from tkinter import *
from tkinter import ttk
GameWindow = Tk()
GameWindow.title ("WORD5 - The 5X5 Word Spelling Game!")
GameWindow.geometry('2850x1000')
GameWindow.configure(bg="plum")
TileFrame=Frame(GameWindow, bg="green")
TileFrame.grid(row=0)
TileLine1Row1 = Label (TileFrame, text="box1", font=("Helvetica", 10), width=10, height=5, borderwidth=1,     relief="solid", bg="plum")
TileLine1Row1.grid(column=1,row=1,padx=15,pady = 10)
#
TileLine1Row2 = Label (TileFrame, text="box2", font=("Helvetica", 10), width=10, height=5,borderwidth=1,     relief="solid", bg="plum")
TileLine1Row2.grid(column=2,row=1,padx=15,pady = 10)
#T
TileLine1Row3 = Label (TileFrame, text="box3", font=("Helvetica", 10), width=10, height=5, borderwidth=1,     relief="solid", bg="plum")
TileLine1Row3.grid(column=3,row=1,padx=15,pady = 10)
#

TileLine1Row4 = Label (TileFrame, text="box4", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine1Row4.grid(column=4,row=1,padx=15,pady = 10)

TileLine1Row5 = Label (TileFrame, text="box5", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")

#Now for the second row of tiles on the game

TileLine2Row1 = Label (TileFrame, text="box6", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row1.grid(column=1,row=2,padx=15,pady = 10)

TileLine2Row2 = Label (TileFrame, text="box7", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row2.grid(column=2,row=2,padx=15,pady = 10)

TileLine2Row3 = Label (TileFrame, text="box8", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row3.grid(column=3,row=2,padx=15,pady = 10)

TileLine2Row4 = Label (TileFrame, text="box9", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row4.grid(column=4,row=2,padx=15,pady = 10)

TileLine2Row5 = Label (TileFrame, text="box10", font=("Helvetica", 10), width=10, height=5, borderwidth=1, relief="solid", bg="plum")
TileLine2Row5.grid(column=5,row=2,padx=15,pady = 10)

#Rows and Columns defined numbers/ rows and columns placings
Trow = 1
Tcolumn = 1
#Defining where the letters go if a letter is pressed on the keyboard
def WhereLettersAreGoing ():
    global Trow
    global Tcolumn
    if Trow == 1:
        if Tcolumn == 1:
            #Add 1 to column count section
            WhereLettersGo = TileLine1Row1
        elif Tcolumn == 2:
            WhereLettersGo = TileLine1Row2
        elif Tcolumn == 3:
            WhereLettersGo = TileLine1Row3
        elif Tcolumn == 4:
            WhereLettersGo = TileLine1Row4
        elif Tcolumn == 5:
            WhereLettersGo = TileLine1Row5
        PutLetterIn (WhereLettersGo)
        Tcolumn = Tcolumn +1
def PutLetterIn (WhereLettersGo):
    WhereLettersGo.configure(text `your text`= "A")
# Define function to get the information about the Button
#Add in a check button?
#Button frame to section it up
ButtonsFrame=Frame(GameWindow, bg="blue")
ButtonsFrame.grid(row=1)

#Now, the buttons are below which represents the letters of the alphabet
#The buttons with letters A B C D E F G & H are on the top row of the letter button rows
#LetterAButton
LetterAButton = Button(ButtonsFrame, text="A", width=7, height=2, borderwidth=5, relief="raised", command = WhereLettersAreGoing)
LetterAButton.grid(column=1, row=4,padx=2,pady = 2)
#LetterBButton
LetterBButton = Button(ButtonsFrame, text="B", width=7, height=2, borderwidth=5, relief="raised")
LetterBButton.grid(column=2, row=4,padx=2,pady = 2)
#LetterCButton
LetterCButton = Button(ButtonsFrame, text="C", width=7, height=2, borderwidth=5, relief="raised")
LetterCButton.grid(column=3, row=4,padx=2,pady = 2)
#LetterDButton
LetterDButton = Button(ButtonsFrame, text="D", width=7, height=2, borderwidth=5, relief="raised")
LetterDButton.grid(column=4, row=4,padx=2,pady = 2)
#LetterEButton
LetterEButton = Button(ButtonsFrame, text="E", width=7, height=2, borderwidth=5, relief="raised")
LetterEButton.grid(column=5, row=4,padx=2,pady = 2)
#LetterFButton
LetterFButton = Button(ButtonsFrame, text="F", width=7, height=2, borderwidth=5, relief="raised")
LetterFButton.grid(column=6, row=4,padx=2,pady = 2)
#LetterGButton
LetterGButton = Button(ButtonsFrame, text="G", width=7, height=2, borderwidth=5, relief="raised")
LetterGButton.grid(column=7, row=4,padx=2,pady = 2)
#LetterHButton
LetterHButton = Button(ButtonsFrame, text="H", width=7, height=2, borderwidth=5, relief="raised")
LetterHButton.grid(column=8, row=4,padx=2,pady = 2)
#The buttons with letters I J K L M N O & P are on the second row of the button rows
#LetterIButton
LetterIButton = Button(ButtonsFrame, text="I", width=7, height=2, borderwidth=5, relief="raised")
LetterIButton.grid(column=1, row=5,padx=2,pady = 2)
#LetterJButton
LetterJButton = Button(ButtonsFrame, text="J", width=7, height=2, borderwidth=5, relief="raised")
LetterJButton.grid(column=2, row=5,padx=2,pady = 2)
#LetterKButton
LetterKButton = Button(ButtonsFrame, text="K", width=7, height=2, borderwidth=5, relief="raised")
LetterKButton.grid(column=3, row=5,padx=2,pady = 2)
#LetterLButton
LetterLButton = Button(ButtonsFrame, text="L", width=7, height=2, borderwidth=5, relief="raised")
LetterLButton.grid(column=4, row=5,padx=2,pady = 2)
#LetterMButton
LetterMButton = Button(ButtonsFrame, text="M", width=7, height=2, borderwidth=5, relief="raised")
LetterMButton.grid(column=5, row=5,padx=2,pady = 2)
#LetterNButton
LetterNButton = Button(ButtonsFrame, text="N", width=7, height=2, borderwidth=5, relief="raised")
LetterNButton.grid(column=6, row=5,padx=2,pady = 2)
#LetterOButton
LetterOButton = Button(ButtonsFrame, text="O", width=7, height=2, borderwidth=5, relief="raised")
LetterOButton.grid(column=7, row=5,padx=2,pady = 2)
#LetterPButton
LetterPButton = Button(ButtonsFrame, text="P", width=7, height=2, borderwidth=5, relief="raised")
LetterPButton.grid(column=8, row=5,padx=2,pady = 2)

#LetterQButton
LetterQButton = Button(ButtonsFrame, text="Q", width=7, height=2, borderwidth=5, relief="raised")
LetterQButton.grid(column=2, row=6,padx=2,pady = 2)
#LetterRButton
LetterRButton = Button(ButtonsFrame, text="R", width=7, height=2, borderwidth=5, relief="raised")
LetterRButton.grid(column=3, row=6,padx=2,pady = 2)
#LetterSButton
LetterSButton = Button(ButtonsFrame, text="S", width=7, height=2, borderwidth=5, relief="raised")
LetterSButton.grid(column=4, row=6,padx=2,pady = 2)
#LetterTButton
LetterTButton = Button(ButtonsFrame, text="T", width=7, height=2, borderwidth=5, relief="raised")
LetterTButton.grid(column=5, row=6,padx=2,pady = 2)
#LetterUButton
LetterUButton = Button(ButtonsFrame, text="U", width=7, height=2, borderwidth=5, relief="raised")
LetterUButton.grid(column=6, row=6,padx=2,pady = 2)
#LetterVButton
LetterVButton = Button(ButtonsFrame, text="V", width=7, height=2, borderwidth=5, relief="raised")
LetterVButton.grid(column=7, row=6,padx=2,pady = 2)

#LetterWButton
LetterWButton = Button(ButtonsFrame, text="W", width=7, height=2, borderwidth=5, relief="raised")
LetterWButton.grid(column=3, row=7,padx=2,pady = 2)
#LetterXButton
LetterXButton = Button(ButtonsFrame, text="X", width=7, height=2, borderwidth=5, relief="raised")
LetterXButton.grid(column=4, row=7,padx=2,pady = 2)
#LetterYButton
LetterYButton = Button(ButtonsFrame, text="Y", width=7, height=2, borderwidth=5, relief="raised")
LetterYButton.grid(column=5, row=7,padx=2,pady = 2)
#LetterZButton
LetterZButton = Button(ButtonsFrame, text="Z", width=7, height=2, borderwidth=5, relief="raised")
LetterZButton.grid(column=6, row=7,padx=2,pady = 2)

#Closing the game window loop
GameWindow.mainloop()


来源: stackexchange

问:
Error when using busboy inside of firebase function to send file to google cloud bucket
After initiating my firebase app on the server side in order to handle all the authentication and setting up my firebase functions I learned I can't pass my firebase instance to the front end in order for me to use firebase storage there so I am now trying to pass my file array to my express server.

Originally I was using multer but it seems like firebase and multer don't get along very well so I'm just looking for what might be a good package to use as a substitute for multer any suggestions are welcome. I'll post how I'm passing all my data below so you have a better understanding of my structure.

Even if I can't upload to firebase storage from the backend that isn't an issue because I can easily use a google cloud bucket but the issue with multer still remains. So any suggested libraries?

Client-side upload (Just a basic react-dropzone)

```<code>  const {acceptedFiles, getRootProps, getInputProps} = useDropzone();

  const files = acceptedFiles.map(file => (
    <li key={file.path}>
      {file.path}
    </li>
  ));

  return (
    <Fragment>

      <section class={uploadStyle.uploadBox}>
        <div {...getRootProps({className: 'dropzone'})}>
          <input {...getInputProps()} />
          <p>Click or drop files here</p>
        </div>
        <aside>
          <h4>Files</h4>
          <ul>{files}</ul>
        </aside>
      </section>

      <div class='text-center mt-5'>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
          Upload New Files
        </button>
        {GatherFileName(acceptedFiles)}
      </div>
      <div class='text-center mt-5'>
        <button type="button" class="btn btn-primary" onClick={()=>{fileUpload(acceptedFiles)}}>Submit</button>
      </div>

    </Fragment>

  );
</code>```

fetch request passing data to the server

```<code>let formData = new FormData();
formData.append('files', accepetedfiles);

try{

  const response = await fetch(`http://someUrl`,{
    method:"POST",
    body: formData
  })

  const jsonData = await response.json()

  console.log(jsonData)

}catch(error){

    console.log(error)

}
</code>```

Server-side fire handling (Where I'm stuck. Wont work because I cannot access my formdata)

```<code>try{

    const formData = req.body;
    for(let file = 0;file < files.length;file++){

        let storageRef = ref(storage, `files/${files[file].path}`);
        let uploadTask = await uploadBytesResumable(storageRef, files[file]);

    }

    res.json('no error:\n\nfiles: ' +
        JSON.stringify(files) + '\n\nfile: ' + JSON.stringify(files[0]) +
        '\n\nfiles len: ' + files.length)

}catch(error){
    res.json('error: ' + error + '\n\nfiles: ' + req.body + '\n\nfiles raw: ' + req.body.files)
    res.json('Error: ' + error)
}
</code>```

Update:

Instead of uploading to firebase storage, I'm just going to try and upload to a google cloud bucket as I was doing previously. I switched my code over to using busboy which I tested in a local envirment and it worked without any issues. However if I do not add a header like is suggested on SO I receive Error: Unexpected end of form at Multipart._final which seems to have multiple ways to resolve it.

I've gone ahead and made sure all my packages we're updated and current but still get the same error. So I tried adding a header and am getting the same issue but after adding a few console.logs it seems the line that is causing my crash is where I am detecting a file.

Updated code:

Client-side (same as before)

fetch request passing data to the server

```<code>export default async function UploadToStorage(acceptedFiles,fileVals){//Index are 1-1

  console.log(acceptedFiles)

  try{
      for(let fileCount = 0;fileCount < acceptedFiles.length;fileCount++){
          let boundary = Math.random().toString().substr(8) + "--";

          const formData = new FormData();

          let file = acceptedFiles[fileCount]

          let blob = file.slice(0,file.size)
          let newFile = new File([blob], file.name, {type: "text/plain"});

          formData.append(file.name,newFile)

          const response = await fetch(`https://someUrl`,{
              method:"POST",
              headers: {"Content-Type": 'multipart/form-data;boundary='+boundary},
              body:formData
          })

          const jsonData = await response.json()
          console.log('jsonData: ' + jsonData)

          if(!jsonData){
            return false
          }else{
            return true
          }

      }
  }catch(error){

      console.log(error)

  }

}
</code>```

Server-side fire handling (Where I'm stuck. Crash is at line busboy.on('file' ...)

```<code>app.post('/uploadNewFiles',async(req,res)=>{

    console.log('made it to uploadNewFiles')

    try{

        let buffers = []
        const busboy = Busboy({ headers: req.headers });
        console.log('busboy created')
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            console.log('busboy detected file')
            file.on('data',(data)=>{
                buffers.push(data)
            })

            console.log(buffers)

            file.on('end',()=>{
                buffers = Buffer.concat(buffers)
                console.log(buffers.toString())
            })

            const newFile = bucket.file(filename.filename)

            newFile.save(buffers.toString(),(error=>{
                if(!error){
                    console.log('Upload complete')
                }else{
                    console.log('Upload issue')
                    console.log(error)
                }
            }))

        });
        busboy.on('finish', function() {
            res.json("That's all");
        });
        return req.pipe(busboy);

    }catch(error){
        console.log(error)
        res.json(false)
    }

})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After initiating my firebase app on the server side in order to handle all the authentication and setting up my firebase functions I learned I can't pass my firebase instance to the front end in order for me to use firebase storage there so I am now trying to pass my file array to my express server.

Originally I was using multer but it seems like firebase and multer don't get along very well so I'm just looking for what might be a good package to use as a substitute for multer any suggestions are welcome. I'll post how I'm passing all my data below so you have a better understanding of my structure.

Even if I can't upload to firebase storage from the backend that isn't an issue because I can easily use a google cloud bucket but the issue with multer still remains. So any suggested libraries?

Client-side upload (Just a basic react-dropzone)

  const {acceptedFiles, getRootProps, getInputProps} = useDropzone();

  const files = acceptedFiles.map(file => (

      {file.path}

  ));

  return (
    <Fragment>

          <input {...getInputProps()} />

Click or drop files here

Files

{files}

        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
          Upload New Files
        </button>
        {GatherFileName(acceptedFiles)}

        <button type="button" class="btn btn-primary" onClick={()=>{fileUpload(acceptedFiles)}}>Submit</button>

    </Fragment>

  );

fetch request passing data to the server

let formData = new FormData();
formData.append('files', accepetedfiles);

try{

  const response = await fetch(`http://someUrl`,{
    method:"POST",
    body: formData
  })

  const jsonData = await response.json()

  console.log(jsonData)

}catch(error){

    console.log(error)

}

Server-side fire handling (Where I'm stuck. Wont work because I cannot access my formdata)

try{

    const formData = req.body;
    for(let file = 0;file < files.length;file++){

        let storageRef = ref(storage, `files/${files[file].path}`);
        let uploadTask = await uploadBytesResumable(storageRef, files[file]);

    }

    res.json('no error:\n\nfiles: ' +
        JSON.stringify(files) + '\n\nfile: ' + JSON.stringify(files[0]) +
        '\n\nfiles len: ' + files.length)

}catch(error){
    res.json('error: ' + error + '\n\nfiles: ' + req.body + '\n\nfiles raw: ' + req.body.files)
    res.json('Error: ' + error)
}

Update:

Instead of uploading to firebase storage, I'm just going to try and upload to a google cloud bucket as I was doing previously. I switched my code over to using busboy which I tested in a local envirment and it worked without any issues. However if I do not add a header like is suggested on SO I receive Error: Unexpected end of form at Multipart._final which seems to have multiple ways to resolve it.

I've gone ahead and made sure all my packages we're updated and current but still get the same error. So I tried adding a header and am getting the same issue but after adding a few console.logs it seems the line that is causing my crash is where I am detecting a file.

Updated code:

Client-side (same as before)

fetch request passing data to the server

export default async function UploadToStorage(acceptedFiles,fileVals){//Index are 1-1

  console.log(acceptedFiles)

  try{
      for(let fileCount = 0;fileCount < acceptedFiles.length;fileCount++){
          let boundary = Math.random().toString().substr(8) + "--";

          const formData = new FormData();

          let file = acceptedFiles[fileCount]

          let blob = file.slice(0,file.size)
          let newFile = new File([blob], file.name, {type: "text/plain"});

          formData.append(file.name,newFile)

          const response = await fetch(`https://someUrl`,{
              method:"POST",
              headers: {"Content-Type": 'multipart/form-data;boundary='+boundary},
              body:formData
          })

          const jsonData = await response.json()
          console.log('jsonData: ' + jsonData)

          if(!jsonData){
            return false
          }else{
            return true
          }

      }
  }catch(error){

      console.log(error)

  }

}

Server-side fire handling (Where I'm stuck. Crash is at line busboy.on('file' ...)

app.post('/uploadNewFiles',async(req,res)=>{

    console.log('made it to uploadNewFiles')

    try{

        let buffers = []
        const busboy = Busboy({ headers: req.headers });
        console.log('busboy created')
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            console.log('busboy detected file')
            file.on('data',(data)=>{
                buffers.push(data)
            })

            console.log(buffers)

            file.on('end',()=>{
                buffers = Buffer.concat(buffers)
                console.log(buffers.toString())
            })

            const newFile = bucket.file(filename.filename)

            newFile.save(buffers.toString(),(error=>{
                if(!error){
                    console.log('Upload complete')
                }else{
                    console.log('Upload issue')
                    console.log(error)
                }
            }))

        });
        busboy.on('finish', function() {
            res.json("That's all");
        });
        return req.pipe(busboy);

    }catch(error){
        console.log(error)
        res.json(false)
    }

})


问:
ASP.NET MVC application error - controller method for a GET not found
My ASP.NET MVC app is recording errors (via ELMAH) for GET requests on controller methods that do not support GET.

```<code>[HttpPost]
public ActionResult SaveChoiceSingle(int sessionId, int actionId, int itemNumber, string response)
{
    MultipleChoice.SaveSingleResponse(sessionId, actionId, itemNumber, response);

    return new JsonResult()
               {
                   Data = string.Empty
               };
}
</code>```

The ASP.NET MVC views do not allow a user to send a GET request, so I suspect a client's browser extension is making the GET requests.

What is the "best practice" to send as a response so that it is not logged as an application/server error?

400 Bad Request

404 Not Found

405 Method Not Allowed

Body:
My ASP.NET MVC app is recording errors (via ELMAH) for GET requests on controller methods that do not support GET.

[HttpPost]
public ActionResult SaveChoiceSingle(int sessionId, int actionId, int itemNumber, string response)
{
    MultipleChoice.SaveSingleResponse(sessionId, actionId, itemNumber, response);

    return new JsonResult()
               {
                   Data = string.Empty
               };
}

The ASP.NET MVC views do not allow a user to send a GET request, so I suspect a client's browser extension is making the GET requests.

What is the "best practice" to send as a response so that it is not logged as an application/server error?

400 Bad Request

404 Not Found

405 Method Not Allowed


问:
Delphi 2010 Web Broker
I have a Delphi 7 Web broker app that is working perfectly.  I need to upgrade to Delphi 2010 because the web services in Delphi 7 doesn't work with the web service I need to consume.  When I compile and run it under Delphi 2010 i get "The specified CGI application misbehaved by not returning a complete set of HTTP headers" error. I'm guessing it is related to ansistring but cannot figure it out.

Any ideas on how I can solve this problem.

Thanks

ContentLicense: CC BY-SA 3.0

Title: Delphi 2010 Web Broker


问:
How to read a JavaScript event from QtWebEngine?
I'm trying to read a JavaScript event from a QtWebEngine widget following these answer1,  answer2.

In my code below, when i run the first JavaScript call, it does print the button element correctly:

view->page()->runJavaScript(R"(
    const button = document.getElementById("js-lang-list-button");
    console.log('\ntest:\n', button, "\n\n");
)");
```
<p>However it doesn't print anything from the <code>console.log</code> inside of</p>
<pre class="lang-cpp prettyprint-override"><code>new QWebChannel(qt.webChannelTransport, function (channel) { ... }
</code>```

and the lambda connection never get called when i hover the button.

QObject::connect(&hover_helper, &HoverHelper::hovered, []() {
   qDebug() << "======hovered======" << QTime::currentTime();
});
```
<p>Follow the code:</p>
<pre class="lang-cpp prettyprint-override"><code>//webengine.h
#include <QtWebEngineWidgets>
#include <QFile>

// Subclass to read console.log messages
class WebEnginePage : public QWebEnginePage
{
    Q_OBJECT

public:
    WebEnginePage(QWebEngineProfile* profile, QWebEngineView* parent = 0) {}

protected:
    virtual void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level,
        const QString &message, int lineNumber, const QString &sourceID) {
        qDebug() << "console.log: " << message;
    }
};

static QString getSourceCode(const QString & filename){
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly))
        return {};
    return file.readAll();
}

class HoverHelper: public QObject {
    Q_OBJECT
public:
    using QObject::QObject;
Q_SIGNALS:
    void hovered();
public Q_SLOTS:
    void onHovered(){ Q_EMIT hovered(); }
};
</code>```

.cpp

#include "webengine.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "23654");

    QWebEngineView* view = new QWebEngineView(this);

    // Subclass the page so we can read
    // console.log(...) messages.
    WebEnginePage* page = new WebEnginePage(view->page()->profile(), view);
    view->setPage(page);
    view->page()->setBackgroundColor(Qt::transparent);

    HoverHelper hover_helper;

    QWebChannel channel;
    channel.registerObject("qt_helper", &hover_helper);

    view->page()->setWebChannel(&channel);

    QObject::connect(view, &QWebEngineView::loadFinished, [view]() {

        QStringList source_codes;
        source_codes << getSourceCode(QStringLiteral(":/qtwebchannel/qwebchannel.js"));

        // js-lang-list-button is the search button in the wikipedia page
        // looks like things inside of new QWebChannel isn't getting called
        // as it doesn't print the console.log() message
        source_codes << R"(
            new QWebChannel(qt.webChannelTransport, function (channel)
            {
                const button = document.getElementById("js-lang-list-button");

                console.log('button:', button);
                button.addEventListener('mouseover', myFunction);

                function myFunction()
                {
                    console.log('mouseover');
                    channel.objects.qt_helper.onHovered()
                }
           });
        )";

        // This call is just to check if its finding the element
        view->page()->runJavaScript(R"(
            const button = document.getElementById("js-lang-list-button");
            console.log("\ntest:\n", button, "\n\n");
        )");

        view->page()->runJavaScript(source_codes.join("\n"));
        qDebug() << "loadFinished";
    });

    view->load(QUrl("https://www.wikipedia.com/"));

    // The connection never get called when i hover the
    // search button in the wikipedia page.
    QObject::connect(&hover_helper, &HoverHelper::hovered, []() {
        qDebug() << "======hovered======" << QTime::currentTime();
    });

    view->setGeometry(50, 50, 800, 600);
    view->show();

    return;
}
```

I have checked the value of source_codes and indeed looks like it contain some kind of source on it, i don't understand why things inside of new QWebChannel isn't getting called.

I have also tried loading a profile with the sources to the page instead of loading it through source_codes, but things from new QWebChannel also didn't get called.

I'm using Qt 6.4, Windows 10.

Body:
I'm trying to read a JavaScript event from a QtWebEngine widget following these answer1,  answer2.

In my code below, when i run the first JavaScript call, it does print the button element correctly:

view->page()->runJavaScript(R"(
    const button = document.getElementById("js-lang-list-button");
    console.log('\ntest:\n', button, "\n\n");
)");

However it doesn't print anything from the console.log inside of

new QWebChannel(qt.webChannelTransport, function (channel) { ... }

and the lambda connection never get called when i hover the button.

QObject::connect(&hover_helper, &HoverHelper::hovered, []() {
   qDebug() << "======hovered======" << QTime::currentTime();
});

Follow the code:

//webengine.h
#include <QtWebEngineWidgets>
#include <QFile>

// Subclass to read console.log messages
class WebEnginePage : public QWebEnginePage
{
    Q_OBJECT

public:
    WebEnginePage(QWebEngineProfile* profile, QWebEngineView* parent = 0) {}

protected:
    virtual void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel level,
        const QString &message, int lineNumber, const QString &sourceID) {
        qDebug() << "console.log: " << message;
    }
};

static QString getSourceCode(const QString & filename){
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly))
        return {};
    return file.readAll();
}

class HoverHelper: public QObject {
    Q_OBJECT
public:
    using QObject::QObject;
Q_SIGNALS:
    void hovered();
public Q_SLOTS:
    void onHovered(){ Q_EMIT hovered(); }
};

.cpp

#include "webengine.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "23654");

    QWebEngineView* view = new QWebEngineView(this);

    // Subclass the page so we can read
    // console.log(...) messages.
    WebEnginePage* page = new WebEnginePage(view->page()->profile(), view);
    view->setPage(page);
    view->page()->setBackgroundColor(Qt::transparent);

    HoverHelper hover_helper;

    QWebChannel channel;
    channel.registerObject("qt_helper", &hover_helper);

    view->page()->setWebChannel(&channel);

    QObject::connect(view, &QWebEngineView::loadFinished, [view]() {

        QStringList source_codes;
        source_codes << getSourceCode(QStringLiteral(":/qtwebchannel/qwebchannel.js"));

        // js-lang-list-button is the search button in the wikipedia page
        // looks like things inside of new QWebChannel isn't getting called
        // as it doesn't print the console.log() message
        source_codes << R"(
            new QWebChannel(qt.webChannelTransport, function (channel)
            {
                const button = document.getElementById("js-lang-list-button");

                console.log('button:', button);
                button.addEventListener('mouseover', myFunction);

                function myFunction()
                {
                    console.log('mouseover');
                    channel.objects.qt_helper.onHovered()
                }
           });
        )";

        // This call is just to check if its finding the element
        view->page()->runJavaScript(R"(
            const button = document.getElementById("js-lang-list-button");
            console.log("\ntest:\n", button, "\n\n");
        )");

        view->page()->runJavaScript(source_codes.join("\n"));
        qDebug() << "loadFinished";
    });

    view->load(QUrl("https://www.wikipedia.com/"));

    // The connection never get called when i hover the
    // search button in the wikipedia page.
    QObject::connect(&hover_helper, &HoverHelper::hovered, []() {
        qDebug() << "======hovered======" << QTime::currentTime();
    });

    view->setGeometry(50, 50, 800, 600);
    view->show();

    return;
}

I have checked the value of source_codes and indeed looks like it contain some kind of source on it, i don't understand why things inside of new QWebChannel isn't getting called.

I have also tried loading a profile with the sources to the page instead of loading it through source_codes, but things from new QWebChannel also didn't get called.

I'm using Qt 6.4, Windows 10.


问:
How to remove Widget.Material3.TabLayout bottom divider
For a style using the Widget.Material3.TabLayout

```<code><style name="MyTabLayout" parent="Widget.Material3.TabLayout">
    <item name="tabTextColor">@color/black</item>
    <item name="tabSelectedTextColor">@color/black</item>
    <item name="tabIndicatorFullWidth">true</item>
</style>
</code>```

how does one remove the gray bottom divider that is contiguous to the indicator,

such that only the blue indicator is visible?

Body:
For a style using the Widget.Material3.TabLayout

how does one remove the gray bottom divider that is contiguous to the indicator,

such that only the blue indicator is visible?


问:
loop in df with conditionals
I have this function where I would like to change the variables: “preco_ordem” by df.loc[((df.Ordem ==1), "close")].values or df.loc[((df.Ordem ==-1) , "close")].values and quote for each row value of column df['close'] . if Order = 1 scroll through the close values until finding a value greater or less than the constraints, or inverse if -1.

```<code>import pandas as pd
import numpy as np

#variaveis
cotacao = 27.62
tp = 0.30
sl = 0.20
preco_ordem = 28.51

list_1 = [26.66, 26.7, 26.72, 26.73, 26.74, 26.88, 26.63, 26.56, 26.51, 26.55, 26.54, 26.5, 26.52, 26.59, 26.43, 26.46,
          26.54, 26.51, 26.54, 26.5, 26.51, 26.47, 26.48, 26.41, 26.4, 26.37]
list_2 = [0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0]

df = pd.DataFrame({
    'close': list_1,
    'Ordem': list_2})

def calcular(preco_ordem, cotacao, tp, sl):
    for index, row in df.iterrows():
        #comprado
        if row['Ordem'] == 1:
            #se gain
            if cotacao > (preco_ordem + tp):
                return  (cotacao - preco_ordem)
            #se loss
            if cotacao < (preco_ordem - sl):
                return (cotacao - preco_ordem)
        #vendido
        if row['Ordem'] == -1:
            #se gain
            if cotacao < (preco_ordem - tp):
                return (preco_ordem - cotacao)
            #se loss
            if cotacao > (preco_ordem + sl):
                return (preco_ordem - cotacao)

calcular(preco_ordem, cotacao, tp, sl)
</code>```

expected outcome:

```<code>list_3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
df = pd.DataFrame({
    'close': list_1,
    'Ordem': list_2,
    'resultado': list_3})

df

list_4 = [26.70, 26.51, 26.54]
list_5 = [-0.20, 'Nan', 'Nan']

df2 = pd.DataFrame({
    'close': list_4,
    'resultado': list_5})
df2
</code>```

Title: loop in df with conditionals

Body:
I have this function where I would like to change the variables: “preco_ordem” by df.loc[((df.Ordem ==1), "close")].values or df.loc[((df.Ordem ==-1) , "close")].values and quote for each row value of column df['close'] . if Order = 1 scroll through the close values until finding a value greater or less than the constraints, or inverse if -1.

import pandas as pd
import numpy as np

#variaveis
cotacao = 27.62
tp = 0.30
sl = 0.20
preco_ordem = 28.51

list_1 = [26.66, 26.7, 26.72, 26.73, 26.74, 26.88, 26.63, 26.56, 26.51, 26.55, 26.54, 26.5, 26.52, 26.59, 26.43, 26.46,
          26.54, 26.51, 26.54, 26.5, 26.51, 26.47, 26.48, 26.41, 26.4, 26.37]
list_2 = [0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0]

df = pd.DataFrame({
    'close': list_1,
    'Ordem': list_2})

def calcular(preco_ordem, cotacao, tp, sl):
    for index, row in df.iterrows():
        #comprado
        if row['Ordem'] == 1:
            #se gain
            if cotacao > (preco_ordem + tp):
                return  (cotacao - preco_ordem)
            #se loss
            if cotacao < (preco_ordem - sl):
                return (cotacao - preco_ordem)
        #vendido
        if row['Ordem'] == -1:
            #se gain
            if cotacao < (preco_ordem - tp):
                return (preco_ordem - cotacao)
            #se loss
            if cotacao > (preco_ordem + sl):
                return (preco_ordem - cotacao)

calcular(preco_ordem, cotacao, tp, sl)

expected outcome:

list_3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
df = pd.DataFrame({
    'close': list_1,
    'Ordem': list_2,
    'resultado': list_3})

df

list_4 = [26.70, 26.51, 26.54]
list_5 = [-0.20, 'Nan', 'Nan']

df2 = pd.DataFrame({
    'close': list_4,
    'resultado': list_5})
df2


问:
How can I set the selection caret to a specific point of a contentEditable div with multiple other divs within it?
I hope you are all very well.

Today, I am trying to place the caret at a specific index (this.selectionStart) of a contentEditable element which has other divs and spans within it.

The code to get this.selectionStart is already taken care of, we are now trying to replace  the caret once the selection is gone (due to a re-render of my element)

I have scoured the internet for help but I have only found solutions which work for contentEditable elements which do not contain any other elements.

This is the closest I've come to a working solution I think.

        // this.selectionStart is the index we want the caret to be at
        // this.element is the contenteditable element
        if (this.selectionStart) {
            // We need to set the selection to the correct position

            // get the selection
            var selection = window.getSelection();
            // create a range
            var range = document.createRange();

            // set the range to the correct position
            range.setStart(this.element.childNodes[0], this.selectionStart); // error here
            range.setEnd(this.element.childNodes[0], this.selectionStart);

            // apparently this is needed
            range.collapse(true);
            selection.removeAllRanges();
            selection.addRange(range);
        }
```

This gives us the fun error of Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset 15. (when this.selectionStart is 15)

Please, I beg you, help me if you possibly can.

Thank you so much, this is very, very important.

Body:
I hope you are all very well.

Today, I am trying to place the caret at a specific index (this.selectionStart) of a contentEditable element which has other divs and spans within it.

The code to get this.selectionStart is already taken care of, we are now trying to replace  the caret once the selection is gone (due to a re-render of my element)

I have scoured the internet for help but I have only found solutions which work for contentEditable elements which do not contain any other elements.

This is the closest I've come to a working solution I think.

        // this.selectionStart is the index we want the caret to be at
        // this.element is the contenteditable element
        if (this.selectionStart) {
            // We need to set the selection to the correct position

            // get the selection
            var selection = window.getSelection();
            // create a range
            var range = document.createRange();

            // set the range to the correct position
            range.setStart(this.element.childNodes[0], this.selectionStart); // error here
            range.setEnd(this.element.childNodes[0], this.selectionStart);

            // apparently this is needed
            range.collapse(true);
            selection.removeAllRanges();
            selection.addRange(range);
        }

This gives us the fun error of Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset 15. (when this.selectionStart is 15)

Please, I beg you, help me if you possibly can.

Thank you so much, this is very, very important.


问:
Spring JPA override repository method(s) not consistently called after editing
We have a Spring Boot 2.2.10 application (using Hibernate 5.4.21) with about a half-dozen custom JPA repositories to override base crud repository operations such as 'save'. In general, they work properly.

However, occasionally we have found that after making some edits within the custom repository code inside a method, without changing the interfaces or packages or class names, the custom method fails to be called at all. Other custom repositories continue to function as before.

A recent change in one of our classes triggered this behavior for a custom 'save' method. While making changes in what had *been *working code, it suddenly stopped being invoked for the developer working on the changes (debugger would not stop at breakpoints, log statements would not be printed, and whatever the code was supposed to do would not happen). Reviews of the commits shows no changes other than additional lines of code within the custom method and supporting private methods.

Stranger still, it can sometimes be remedied by changing the log level for the custom implementation package to DEBUG, without restarting the application. This "hackaround" does not always work in the field, leaving us scratching our heads as to why this is happening.

Sometimes a simple "restart the server" will fix the problem, so it does not appear to be environment/settings related. Perform another restart, and the problem might just reappear. This has been confirmed on developer workstations and in the field, where restarting the application might or might not 'fix' the issue for a given run, without any other changes between executions.

Java version does not change the behavior - 1.8 and 11 show the same problem.

Spring boot was updated to 2.5.14 - no change.

Internet searches and StackOverflow q/a have not returned any suggestions that changed the behavior. Reviewing all annotations, method signatures and other aspects of 'working' custom repositories vs. the 'broken' one show no differences.

The entity and related items had unusual case definition - DBConnectionConfig. This was shortened to a more standard ConnectionConfig and all related classes refactored. No change.

There is a separate, custom, non-override method (i.e. it is not in the base CrudRepository interface) and that one ALWAYS works. We tried separating them into separate repository fragments, but still the save() method only sometimes gets invoked.

The next attempt to work around the issue will involve a custom API route to bypass the Spring REST API that is currently used to POST/PATCH the entity, and changes to the related JavaScript front end. Not ideal, and we would rather not have to do this, but we're at our wits end trying to figure out the underlying cause.


问:
How do I add an "add" button that adds another row to a GTK ListStore?
```<code>fn build_table_view() -> (TreeView, ListStore) {
    let list_store = ListStore::new(&[glib::Type::STRING].repeat(4));
    list_store.n_columns();
    let tree_view = TreeView::builder()
        .hexpand(true)
        .vexpand(true)
        .enable_grid_lines(gtk::TreeViewGridLines::Both)
        .model(&list_store)
        .build();

    for (i, title) in ["Website", "Username", "Password"]
        .iter()
        .enumerate()
    {
        let renderer = CellRendererText::builder()
            .editable(true)
            .xalign(0.0)
            .single_paragraph_mode(true)
            .build();

        tree_view.insert_column_with_attributes(
            i.try_into().unwrap(),
            title,
            &renderer,
            &[(&"text", i.try_into().unwrap())],
        );

        let list_store_copy = list_store.clone();
        renderer.connect_edited(move |_renderer, row, text| {
            list_store_copy.set_value(
                &list_store_copy.iter(&row).unwrap(),
                i.try_into().unwrap(),
                &text.to_value()
            );
        });
    }

    let add_button = gtk::Button::with_label("Add");
    //add_button.connect_clicked(clone!())

    list_store.insert_with_values(
        None,
        &[
            (0, &"Test1")
        ],
    );
    (tree_view, list_store)
}

fn build_gtk4_table_ui_v1(application: &Application) {
    let window = ApplicationWindow::new(application);

    window.set_title(Some("Sammy's Safe"));
    window.set_default_size(800, 300);

    let grid = Grid::builder()
        .column_spacing(5)
        .row_spacing(10)
        .build();

    window.set_child(Some(&grid));

    let (tree_view, _list_store) = build_table_view();

    let list_store_copy = _list_store.clone();

    let sw = ScrolledWindow::builder()
        .child(&tree_view)
        .vexpand(false)
        .vexpand_set(false)
        .max_content_height(10)
        .build();

    // column, row, width, height
    grid.attach(&sw, 0, 0, 1, 1);
    window.show();
}
</code>```

I tried following the basic button format that most examples show and just tried including add_button.connect_clicked(move|_, row, text| {list_store.insert_with_values(...)} to no avail. I've been mulling over GTK4 documentation and trying different things with nothing sticking yet. What I want to happen is for the add button to just create a new row with empty strings considering that I got the edit row to already work. A point in the right direction would be great :)

Body:
fn build_table_view() -> (TreeView, ListStore) {
    let list_store = ListStore::new(&[glib::Type::STRING].repeat(4));
    list_store.n_columns();
    let tree_view = TreeView::builder()
        .hexpand(true)
        .vexpand(true)
        .enable_grid_lines(gtk::TreeViewGridLines::Both)
        .model(&list_store)
        .build();

    for (i, title) in ["Website", "Username", "Password"]
        .iter()
        .enumerate()
    {
        let renderer = CellRendererText::builder()
            .editable(true)
            .xalign(0.0)
            .single_paragraph_mode(true)
            .build();

        tree_view.insert_column_with_attributes(
            i.try_into().unwrap(),
            title,
            &renderer,
            &[(&"text", i.try_into().unwrap())],
        );

        let list_store_copy = list_store.clone();
        renderer.connect_edited(move |_renderer, row, text| {
            list_store_copy.set_value(
                &list_store_copy.iter(&row).unwrap(),
                i.try_into().unwrap(),
                &text.to_value()
            );
        });
    }

    let add_button = gtk::Button::with_label("Add");
    //add_button.connect_clicked(clone!())

    list_store.insert_with_values(
        None,
        &[
            (0, &"Test1")
        ],
    );
    (tree_view, list_store)
}

fn build_gtk4_table_ui_v1(application: &Application) {
    let window = ApplicationWindow::new(application);

    window.set_title(Some("Sammy's Safe"));
    window.set_default_size(800, 300);

    let grid = Grid::builder()
        .column_spacing(5)
        .row_spacing(10)
        .build();

    window.set_child(Some(&grid));

    let (tree_view, _list_store) = build_table_view();

    let list_store_copy = _list_store.clone();

    let sw = ScrolledWindow::builder()
        .child(&tree_view)
        .vexpand(false)
        .vexpand_set(false)
        .max_content_height(10)
        .build();

    // column, row, width, height
    grid.attach(&sw, 0, 0, 1, 1);
    window.show();
}

I tried following the basic button format that most examples show and just tried including add_button.connect_clicked(move|_, row, text| {list_store.insert_with_values(...)} to no avail. I've been mulling over GTK4 documentation and trying different things with nothing sticking yet. What I want to happen is for the add button to just create a new row with empty strings considering that I got the edit row to already work. A point in the right direction would be great :)


问:
SPARQL query for "Tree of properties" ( inheritance predicates)
This question was edited to remove an wrong example.

You can see a right way to store and query "subjects for inheritance predicates and inheritance objects" below.
Based on UninformedUser advise.

example.ttl

```<code>@prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:   <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl:    <http://www.w3.org/2002/07/owl#> .
@prefix uri:    <http://uri/> .

uri:Language            rdf:type                rdfs:Class .
uri:English             rdfs:subClassOf         uri:Language .
uri:BritishEnglish      rdfs:subClassOf         uri:English .
uri:Chinese             rdfs:subClassOf         uri:Language .
uri:MandarinChinese     rdfs:subClassOf         uri:Chinese .

uri:know                rdf:type                rdf:Property .
uri:write               rdfs:subPropertyOf      uri:know .
uri:speak               rdfs:subPropertyOf      uri:know .

uri:Alex                uri:speak               uri:English .
uri:John                uri:write               uri:BritishEnglish .
uri:Chen                uri:write               uri:Chinese .
uri:Lin                 uri:speak               uri:MandarinChinese .
</code>```

sparql

```<code>select distinct * { ?p  rdfs:subPropertyOf*    uri:know     .
                    ?s  ?p                     ?o           .
                    ?o  rdfs:subClassOf*       uri:Language . }
</code>```
```<code>s   p   o
http://uri/Alex     http://uri/speak    http://uri/English
http://uri/Lin      http://uri/speak    http://uri/MandarinChinese
http://uri/Chen     http://uri/write    http://uri/Chinese
http://uri/John     http://uri/write    http://uri/BritishEnglish
</code>```

Body:
This question was edited to remove an wrong example.

You can see a right way to store and query "subjects for inheritance predicates and inheritance objects" below.
Based on UninformedUser advise.

example.ttl

@prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:   <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl:    <http://www.w3.org/2002/07/owl#> .
@prefix uri:    <http://uri/> .

uri:Language            rdf:type                rdfs:Class .
uri:English             rdfs:subClassOf         uri:Language .
uri:BritishEnglish      rdfs:subClassOf         uri:English .
uri:Chinese             rdfs:subClassOf         uri:Language .
uri:MandarinChinese     rdfs:subClassOf         uri:Chinese .

uri:know                rdf:type                rdf:Property .
uri:write               rdfs:subPropertyOf      uri:know .
uri:speak               rdfs:subPropertyOf      uri:know .

uri:Alex                uri:speak               uri:English .
uri:John                uri:write               uri:BritishEnglish .
uri:Chen                uri:write               uri:Chinese .
uri:Lin                 uri:speak               uri:MandarinChinese .

sparql

select distinct * { ?p  rdfs:subPropertyOf*    uri:know     .
                    ?s  ?p                     ?o           .
                    ?o  rdfs:subClassOf*       uri:Language . }

s   p   o
http://uri/Alex     http://uri/speak    http://uri/English
http://uri/Lin      http://uri/speak    http://uri/MandarinChinese
http://uri/Chen     http://uri/write    http://uri/Chinese
http://uri/John     http://uri/write    http://uri/BritishEnglish


问:
ASP.NET Core Web API url parameters encoded in controller in .NET Core, .NET 6, .NET 7
What is the right approach for url attributes decoding from HTTP GET requests like:

```<code>Get /reports/{categories}/date/{date}

[Route("reports/{categories}/date/{date}")]
public IEnumerable<Report> GetReports(string categories, string date)
</code>```

Categories is something like Category1\SubCategory, it contains a backslash.

From Swagger, I am getting: Category1\\SubCategory

From a third-party client, I get: Category1%5CSubCategory

Swagger for some reason adds additional backslashes for escaping and third-party client is doing url encoding.

Is there a setting in ASP.NET Core 6, 7 to control the behaviour of parameters regarding special character and encoding?

Body:
What is the right approach for url attributes decoding from HTTP GET requests like:

Get /reports/{categories}/date/{date}

[Route("reports/{categories}/date/{date}")]
public IEnumerable<Report> GetReports(string categories, string date)

Categories is something like Category1\SubCategory, it contains a backslash.

From Swagger, I am getting: Category1\\SubCategory

From a third-party client, I get: Category1%5CSubCategory

Swagger for some reason adds additional backslashes for escaping and third-party client is doing url encoding.

Is there a setting in ASP.NET Core 6, 7 to control the behaviour of parameters regarding special character and encoding?


问:
Expiry Meta data for a S3 object
In my C# code, I am setting the retention date for a S3 object. I want to check if the retention date that I set in C# is right so Is there any way to check in the management console what the retention date has been set to for a particular object. This is what I tried to do

I went to the Management console

clicked on s3 Bucket

selected my test Object

selected edit Meta data from properties.

here I can set the expiry date for the object inside S3 bucket, but I am trying to see the Object Lock retention date that I set through my C# code. This is the screen, I see when I go to Edit MetaData:

any help will be greatly appreciated.

Title: Expiry Meta data for a S3 object


问:
How to add Catalog Categories to side navigation in Martfury Theme, Magento 2.4.2
I am quite new to Magento.
And I'm using **Martfury **theme, but how do I add Catalog **categories **or **smartmenu **in the sidebar shown in the Picture 1.

I tried to add categories here.
Picture 1:
enter image description here

Also to add I've created categories but it's not showing there.
enter image description here

And I've Flushed Magento Cache & Flushed Cache Storage but nothing seems to change.
I've searched for widgets and blocks related to the sidebar but couldn't find it.


问:
ICorRuntimeHost::GetDefaultDomain is deprecated; how do I get the same result in undeprecated CLR hosting code
This problem is about using wholly unmanaged C++ without using deprecated means.

I am hosting the CLR in C++ calling (in order):

CLRCreateInstance to get an ICLRMetaHost* .

The ICLRMetaHost method GetRuntime to get an ICLRRuntimeInfo* for v4.0.30319 .

The ICLRRuntimeInfo method GetInterface to get an ICLRRuntimeHost* .

The Start method of ICLRRuntimeHost to start the host.

Back in the day a different route would have produced a (now deprecated) ICorRuntimeHost* and the result of calling its GetDefaultDomain method would be used to get an _AppDomain* giving unmanaged access to the default AppDomain.

https://learn.microsoft.com/en-us/dotnet/api/system._appdomain

This _AppDomain* is what I want, but ICLRRuntimeHost has no analog of GetDefaultDomain.

The new arrangements for CLR hosting that don't use ICorRuntimeHost don't seem to support getting an _AppDomain* by any means I saw from searching online documentation.

How is the needed _AppDomain* obtained nowadays?


问:
How do I write an AWS lambda function that reads an MQTT message, generates a random number and sends to an SNS topic?
I have attempted to write a Lamda function that will read an incoming MQTT message from an AWS IOT event, generate a random number (either a 0 or a one), and then send a custom message (based upon a zero or a 1 to a specific SNS mesage topic). I am very new at this, so I am probably overlooking many things (so, I've attempted to splice together snippits of code in hopes of getting this correct. Any help would be much appreciated. Thank you!</p>
```<code>import json
import random
import boto3

 expects event parameter to contain:
#   {
{
    "message": " ",
    "sequence": " ",
    "notify_topic_arn": "arn:aws:sns:us-east-1:064389203133:AirPollutionMonitor"
}
#       ,
#
#   }

def lambda_handler(event, context):
# TODO implement
random_number = random.randint(0,1)

if random_number <1:
 # Create an SNS client to send notification
    sns = boto3.client('sns')

    # Format text message from data
    message_text = "CO2 levels are high. Be careful".format(

     str(event['message']),

     str(event['sequence'])

        )

# Publish the formatted message
    response = sns.publish(
            TopicArn = event['notify_topic_arn'],
            Message = message_text

 return response

)
else:
# Create an SNS client to send notification
    sns = boto3.client('sns')

    # Format text message from data
    message_text = "CO2 levels are normal. ".format(

     str(event['message']),

     str(event['sequence'])

        )

 # Publish the formatted message
    response = sns.publish(
            TopicArn = event['notify_topic_arn'],
            Message = message_text

)

 return response

I tried to get this code to run, unfortunately it didn't run as I had hoped. It didn't pick a random number and execute accordingly (based upon choosing a 0 or a 1).
</code>```

Body:
I have attempted to write a Lamda function that will read an incoming MQTT message from an AWS IOT event, generate a random number (either a 0 or a one), and then send a custom message (based upon a zero or a 1 to a specific SNS mesage topic). I am very new at this, so I am probably overlooking many things (so, I've attempted to splice together snippits of code in hopes of getting this correct. Any help would be much appreciated. Thank you!

import json
import random
import boto3

 expects event parameter to contain:
#   {
{
    "message": " ",
    "sequence": " ",
    "notify_topic_arn": "arn:aws:sns:us-east-1:064389203133:AirPollutionMonitor"
}
#       ,
#
#   }

def lambda_handler(event, context):
# TODO implement
random_number = random.randint(0,1)

if random_number <1:
 # Create an SNS client to send notification
    sns = boto3.client('sns')

    # Format text message from data
    message_text = "CO2 levels are high. Be careful".format(

     str(event['message']),

     str(event['sequence'])

        )

# Publish the formatted message
    response = sns.publish(
            TopicArn = event['notify_topic_arn'],
            Message = message_text

 return response

)
else:
# Create an SNS client to send notification
    sns = boto3.client('sns')

    # Format text message from data
    message_text = "CO2 levels are normal. ".format(

     str(event['message']),

     str(event['sequence'])

        )

 # Publish the formatted message
    response = sns.publish(
            TopicArn = event['notify_topic_arn'],
            Message = message_text

)

 return response

I tried to get this code to run, unfortunately it didn't run as I had hoped. It didn't pick a random number and execute accordingly (based upon choosing a 0 or a 1).


问:
trying to make a vertically and diagonally check in tic tac toe
here's what I have as the horizontally, but I'm having a hard time tryna figure out the other too, it would be Appreciative if someone could help

```<code>    public Boolean CheckForWinnerRowsColsDiagonals()
    {
        isDone = false; //assume this to start
        PlayerWon = true; //assume this too
        for (int x = 0; x < 3; ++x)
        {
            if (!gameGrid[x, 0].Equals('N'))
            {
                if (gameGrid[x, 0] == gameGrid[x, 1] && gameGrid[x, 0] == gameGrid[x, 2])
                {
                    isDone = true;
                    if (gameGrid[x, 0].Equals('O'))
                    {
                        PlayerWon = false;
                    }
                    return isDone;
                }
            }
        }
        return isDone;
    }
</code>```

i've tried trying the x to y to get a better understanding and switching the numbers around from (y, 0) (y, 1) (y, 0) (y, 2)

to

(y, 1) (y, 1) (y, 2) (y, 2)

if (gameGrid[x, 0] == gameGrid[x, 1] && gameGrid[x, 0] == gameGrid[x, 2])

although I'm having a hard time on trying to figure it out. but could someone explain

Body:
here's what I have as the horizontally, but I'm having a hard time tryna figure out the other too, it would be Appreciative if someone could help

    public Boolean CheckForWinnerRowsColsDiagonals()
    {
        isDone = false; //assume this to start
        PlayerWon = true; //assume this too
        for (int x = 0; x < 3; ++x)
        {
            if (!gameGrid[x, 0].Equals('N'))
            {
                if (gameGrid[x, 0] == gameGrid[x, 1] && gameGrid[x, 0] == gameGrid[x, 2])
                {
                    isDone = true;
                    if (gameGrid[x, 0].Equals('O'))
                    {
                        PlayerWon = false;
                    }
                    return isDone;
                }
            }
        }
        return isDone;
    }

i've tried trying the x to y to get a better understanding and switching the numbers around from (y, 0) (y, 1) (y, 0) (y, 2)

to

(y, 1) (y, 1) (y, 2) (y, 2)

if (gameGrid[x, 0] == gameGrid[x, 1] && gameGrid[x, 0] == gameGrid[x, 2])

although I'm having a hard time on trying to figure it out. but could someone explain


问:
How to do a function that subtracts a given date from the current date
Here is what I have so far:

```<code>DELIMITER $$
CREATE FUNCTION StudentEnrollTime(startDate date)
RETURNS DATE
BEGIN
    RETURN (CURDATE() - startDate);
END$$
DELIMITER ;
</code>```

I am trying to take in a date given within the functions parameters and subtract it by the current date. What is causing the Error?

Thank you for your help!

I tried to return the CURDATE() - the parameter -> StarDate but MySQL workbench does not like that for some reason...

Body:
Here is what I have so far:

DELIMITER $$
CREATE FUNCTION StudentEnrollTime(startDate date)
RETURNS DATE
BEGIN
    RETURN (CURDATE() - startDate);
END$$
DELIMITER ;

I am trying to take in a date given within the functions parameters and subtract it by the current date. What is causing the Error?

Thank you for your help!

I tried to return the CURDATE() - the parameter -> StarDate but MySQL workbench does not like that for some reason...


问:
Tests in circleci wont pass after upgrading ruby and heroku to 20 from 18
I am currently working on an app that uses ruby on rails on the backend and react.js on the front end.

Since Heroku 18 is ending, I decided to start the upgrade to Heroku 20 which will be available till 2025. Since doing so, I have been banging my head against the wall for 2 days. I have updated my dependancies as I believe fit based on documentation, but now 3 of my tests keep failing (using selenium-webdriver, webdriver, and capybarra). The error thrown shows this:

```<code>Failures:

  1) Posts create post
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/beneficiary/posts/post_spec.rb:7:in `block (2 levels) in <main>'
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'

  2) donor dashboard should have nav elements
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/donor/dashboard_spec.rb:7:in `block (2 levels) in <main>'
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'

  3) Posts create post
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/donor/posts/post_spec.rb:7:in `block (2 levels) in <main>'
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'
</code>```

In the file auth_helper, the format for the fill_in seems to be the issue, but looking at the documentation and confirming the id for user_email to be correct, I don't really understand what is happening at all. I feel like this might be a red herring as it really doesn't seem to be an issue on other tests that use the same method login_as. I tried upping the capybarra timeout time limit as well, and it still seems to fail to the page is certainly loading.

These tests are also passing locally, and only fail when i run them through circleci, which has me baffled and without much understanding of what to try next.

```<code>def login_as(user, password: "password")
  visit root_path

  find('a', text: 'Login').click
  fill_in :user_email, with: user.email
  fill_in :user_password, with: password
  find("input[value='Log in']").click
end
</code>```

The referenced lines in rails_helper are databaseCleaner and example run lines below:

```<code>  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
</code>```

My config.yml is:

```<code># CircleCI 2.0 configuration file
version: 2.1

orbs:
  browser-tools: circleci/browser-tools@1.4.0

jobs:

  build:

    docker:
      # specify the version you desire here
       - image: cimg/ruby:3.0.5-browsers # circleci/ruby:2.7.0-node-browsers
         environment:
          PGHOST: 127.0.0.1
          PGUSER: $HEROKU_APP_NAME
          RAILS_ENV: test
          BUNDLER_VERSION: 2.0.2
      # Specify service dependencies here if necessary
      # CircleCI maintains a library of pre-built images
      # documented at https://circleci.com/docs/2.0/circleci-images/
       - image: circleci/postgres:9.5-alpine
         environment:
          POSTGRES_USER: $HEROKU_APP_NAME
          POSTGRES_DB: $HEROKU_APP_NAME_test
          POSTGRES_PASSWORD: $HEROKU_APP_NAME
       - image: redis:4.0.10

    working_directory: ~/repo

    steps:
      - checkout
      - browser-tools/install-browser-tools

      # Download and cache dependencies
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "Gemfile.lock" }}
          # fallback to using the latest cache if no exact match is found
          - v1-dependencies-

      - run:
          name: Swap node versions
          command: |
            set +e
            wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
            [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
            nvm install v14
            nvm alias default 14.21.1

            echo 'export NVM_DIR="$HOME/.nvm"' >> $BASH_ENV
            echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> $BASH_ENV

      - run:
          name: Configure Bundler
          command: |
            echo 'export BUNDLER_VERSION=$(cat Gemfile.lock | tail -1 | tr -d " ")' >> $BASH_ENV
            source $BASH_ENV
            gem install bundler

      - run:
          name: install dependencies
          command: |
            bundle config set --local path 'vendor/bundle'
            bundle install --jobs=4 --retry=3
      # --path vendor/bundle

      - save_cache:
          paths:
            - ./vendor/bundle
          key: v1-dependencies-{{ checksum "Gemfile.lock" }}

      # Database setup
      - run: bundle exec rails db:create
      - run: bundle exec rails db:schema:load

      # frontend
      - restore_cache:
          keys:
            - sell-more-yarn-cache-{{ .Branch }}-{{ checksum "yarn.lock" }}
            - sell-more-yarn-cache-{{ .Branch }}-
            - sell-more-yarn-cache-

      - run:
          name: Yarn Install
          command: |
            yarn --ignore-engines --cache-folder ~/.cache/yarn

      - save_cache:
          key: sell-more-yarn-cache-{{ .Branch }}-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn

      - run:
          name: Webpacker Pre-Compile
          command: bundle exec rails webpacker:compile

      # run tests!
      - run:
          name: run tests
          command: |
            bundle exec rspec --profile 10 \
              --out test_results/rspec.xml \
              --format progress \
              $(circleci tests glob "spec/**/*_spec.rb" | circleci tests split --split-by=timings)

      # collect reports
      - store_test_results:
          path: /tmp/test-results
      - store_artifacts:
          path: /tmp/test-results
          destination: test-results

workflows:
  version: 2
  build-and-deploy:
    jobs:
      - build

</code>```

Versions:

```<code>    ruby '3.0.5'
    gem 'rails', '~> 6.1'

    group :test do
      gem 'capybara', '~> 3.38'
      gem 'database_cleaner'
      gem 'factory_bot_rails', '~> 6.2.0'
      gem 'rack_session_access'
      gem 'rails-controller-testing'
      gem 'rspec-rails'
      gem 'selenium-webdriver', '~> 4.0'
      gem 'shoulda-callback-matchers', '~> 1.1.1'
      gem 'shoulda-matchers', '~> 4.4'
      gem 'spring-commands-rspec'
      gem 'stripe-ruby-mock', github: 'rebelidealist/stripe-ruby-mock'
      gem 'timecop'
      gem 'webdrivers', '~> 5.2'
      gem 'webmock'
    end
</code>```

Anyone have any ideas to help me get past this as I am falling behind on time and could really use a point in the right direction!

Thanks in advance!

I am expecting these tests to pass as they can locally and should be able to on circleci as they were right before the upgrade.

Body:
I am currently working on an app that uses ruby on rails on the backend and react.js on the front end.

Since Heroku 18 is ending, I decided to start the upgrade to Heroku 20 which will be available till 2025. Since doing so, I have been banging my head against the wall for 2 days. I have updated my dependancies as I believe fit based on documentation, but now 3 of my tests keep failing (using selenium-webdriver, webdriver, and capybarra). The error thrown shows this:

Failures:

  1) Posts create post
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/beneficiary/posts/post_spec.rb:7:in `block (2 levels) in '
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'

  2) donor dashboard should have nav elements
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/donor/dashboard_spec.rb:7:in `block (2 levels) in '
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'

  3) Posts create post
     Failure/Error: fill_in :user_email, with: user.email

     Capybara::ElementNotFound:
       Unable to find visible field :user_email that is not disabled
     # ./spec/support/auth_helper.rb:5:in `login_as'
     # ./spec/features/donor/posts/post_spec.rb:7:in `block (2 levels) in '
     # ./spec/rails_helper.rb:46:in `block (3 levels) in <top (required)>'
     # ./spec/rails_helper.rb:45:in `block (2 levels) in <top (required)>'

In the file auth_helper, the format for the fill_in seems to be the issue, but looking at the documentation and confirming the id for user_email to be correct, I don't really understand what is happening at all. I feel like this might be a red herring as it really doesn't seem to be an issue on other tests that use the same method login_as. I tried upping the capybarra timeout time limit as well, and it still seems to fail to the page is certainly loading.

These tests are also passing locally, and only fail when i run them through circleci, which has me baffled and without much understanding of what to try next.

def login_as(user, password: "password")
  visit root_path

  find('a', text: 'Login').click
  fill_in :user_email, with: user.email
  fill_in :user_password, with: password
  find("input[value='Log in']").click
end

The referenced lines in rails_helper are databaseCleaner and example run lines below:

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

My config.yml is:

# CircleCI 2.0 configuration file
version: 2.1

orbs:
  browser-tools: circleci/browser-tools@1.4.0

jobs:

  build:

    docker:
      # specify the version you desire here
       - image: cimg/ruby:3.0.5-browsers # circleci/ruby:2.7.0-node-browsers
         environment:
          PGHOST: 127.0.0.1
          PGUSER: $HEROKU_APP_NAME
          RAILS_ENV: test
          BUNDLER_VERSION: 2.0.2
      # Specify service dependencies here if necessary
      # CircleCI maintains a library of pre-built images
      # documented at https://circleci.com/docs/2.0/circleci-images/
       - image: circleci/postgres:9.5-alpine
         environment:
          POSTGRES_USER: $HEROKU_APP_NAME
          POSTGRES_DB: $HEROKU_APP_NAME_test
          POSTGRES_PASSWORD: $HEROKU_APP_NAME
       - image: redis:4.0.10

    working_directory: ~/repo

    steps:
      - checkout
      - browser-tools/install-browser-tools

      # Download and cache dependencies
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "Gemfile.lock" }}
          # fallback to using the latest cache if no exact match is found
          - v1-dependencies-

      - run:
          name: Swap node versions
          command: |
            set +e
            wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
            [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
            nvm install v14
            nvm alias default 14.21.1

            echo 'export NVM_DIR="$HOME/.nvm"' >> $BASH_ENV
            echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"' >> $BASH_ENV

      - run:
          name: Configure Bundler
          command: |
            echo 'export BUNDLER_VERSION=$(cat Gemfile.lock | tail -1 | tr -d " ")' >> $BASH_ENV
            source $BASH_ENV
            gem install bundler

      - run:
          name: install dependencies
          command: |
            bundle config set --local path 'vendor/bundle'
            bundle install --jobs=4 --retry=3
      # --path vendor/bundle

      - save_cache:
          paths:
            - ./vendor/bundle
          key: v1-dependencies-{{ checksum "Gemfile.lock" }}

      # Database setup
      - run: bundle exec rails db:create
      - run: bundle exec rails db:schema:load

      # frontend
      - restore_cache:
          keys:
            - sell-more-yarn-cache-{{ .Branch }}-{{ checksum "yarn.lock" }}
            - sell-more-yarn-cache-{{ .Branch }}-
            - sell-more-yarn-cache-

      - run:
          name: Yarn Install
          command: |
            yarn --ignore-engines --cache-folder ~/.cache/yarn

      - save_cache:
          key: sell-more-yarn-cache-{{ .Branch }}-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn

      - run:
          name: Webpacker Pre-Compile
          command: bundle exec rails webpacker:compile

      # run tests!
      - run:
          name: run tests
          command: |
            bundle exec rspec --profile 10 \
              --out test_results/rspec.xml \
              --format progress \
              $(circleci tests glob "spec/**/*_spec.rb" | circleci tests split --split-by=timings)

      # collect reports
      - store_test_results:
          path: /tmp/test-results
      - store_artifacts:
          path: /tmp/test-results
          destination: test-results

workflows:
  version: 2
  build-and-deploy:
    jobs:
      - build

Versions:

    ruby '3.0.5'
    gem 'rails', '~> 6.1'

    group :test do
      gem 'capybara', '~> 3.38'
      gem 'database_cleaner'
      gem 'factory_bot_rails', '~> 6.2.0'
      gem 'rack_session_access'
      gem 'rails-controller-testing'
      gem 'rspec-rails'
      gem 'selenium-webdriver', '~> 4.0'
      gem 'shoulda-callback-matchers', '~> 1.1.1'
      gem 'shoulda-matchers', '~> 4.4'
      gem 'spring-commands-rspec'
      gem 'stripe-ruby-mock', github: 'rebelidealist/stripe-ruby-mock'
      gem 'timecop'
      gem 'webdrivers', '~> 5.2'
      gem 'webmock'
    end

Anyone have any ideas to help me get past this as I am falling behind on time and could really use a point in the right direction!

Thanks in advance!

I am expecting these tests to pass as they can locally and should be able to on circleci as they were right before the upgrade.


问:
How can I fix this error? TypeError: compute_minimal_traces() missing 1 required positional argument: 'event_log'
This is the code: I need help on solving those errors.

I tried to create an instance. I get the following errors. The main goal is to find an pattern from that event_log. Please let me know what other details I need to fix on this.

```<code>import pandas as pd
from sklearn.cluster import KMeans

# Define the phoenixscript class
class phoenixscript:
    def __init__(self):
        pass

    def parse_event_log(event_log):
        # Extract the unique events from the event log
        events = set()
        for trace in event_log:
            # Make sure that trace is a collection of events
            if not isinstance(trace, (list, tuple)):
                continue

            # Iterate over the events in the trace
            for event in trace:
                # Add each element in the event to the set of unique events
                events.update(event)

        # Return the unique events
        return list(events)

    # Define the find_pattern method
    def find_pattern(self, event_log):
        # Parse the event log to extract the relevant information
        events = self.parse_event_log(event_log)

        # Convert the list of strings into a 2-dimensional array
        events_array = [[event] for event in events]

        # Use the K-means clustering algorithm to identify patterns in the data
        kmeans = KMeans(n_clusters=3)
        kmeans.fit(events_array)
        patterns = kmeans.cluster_centers_

        # Return the identified patterns
        return patterns

    # Define the compute_minimal_traces method
    def compute_minimal_traces(self, event_log):
        # Read the event log from the given traces
        events_list = pd.DataFrame(event_log)

        # Use the find_pattern function to identify the minimal number of traces needed
        patterns = self.find_pattern(event_log)
        num_traces = len(patterns)

        # Print the number of minimal traces
        print(num_traces)

        # Return the number of minimal traces
        return num_traces

    # Define the event log
event_log = ([
        ["status-Open", "Workflow", "summary", "summary", "assignee", "Attachment", "Attachment",
         "status-Patch Available",
         "Attachment", "Attachment", "Attachment", "Attachment", "summary", "Fix Version", "resolution",
         "status-Resolved",
         "status-Closed"],
        ["status-Open", "Workflow", "summary", "issuetype", "summary"],
        ["status-Open", "Workflow", "summary", "description", "Fix Version", "labels", "Fix Version", "resolution",
         "status-Resolved"],
        ["status-Open", "Workflow"]])

    # Create an instance of the phoenixscript class
phoenix = phoenixscript()
num_traces = phoenix.compute_minimal_traces(event_log)

    # Print the results
print("The minimal number of traces needed is:", num_traces)
</code>```

I tried to create an instance. I get the following errors.

```<code>Create an instance of the phoenixscript class
phoenix = phoenixscript()

Traceback (most recent call last):
  File "/Users/randeepsingh/Desktop/pythonProjectRDA/main.py", line 8, in <module>
    class phoenixscript:
  File "/Users/randeepsingh/Desktop/pythonProjectRDA/main.py", line 75, in phoenixscript
    num_traces = compute_minimal_traces(event_log)
TypeError: compute_minimal_traces() missing 1 required positional argument: 'event_log'
</code>```

Ignore the following statements(The code doesntworks fine and I get thfv dfe correct result.But if I have a huge list of wofsdbsfgbrds say 150sgdbsgb0, it's not feasible to type and creagsfbsfgbte a dictionary that long.So I made a function which takegsbs thogfbvse words from the list, implements the techsdgbsgdbnisdbfgbque I dicussed above and creates the graph for me which works just ffgdsdfinesbg until here.But wsfgbfghen I try to get the shsfgbsortest distance besgfbsfgbtween two words, I get the following error)

Body:
This is the code: I need help on solving those errors.

I tried to create an instance. I get the following errors. The main goal is to find an pattern from that event_log. Please let me know what other details I need to fix on this.

import pandas as pd
from sklearn.cluster import KMeans

# Define the phoenixscript class
class phoenixscript:
    def __init__(self):
        pass

    def parse_event_log(event_log):
        # Extract the unique events from the event log
        events = set()
        for trace in event_log:
            # Make sure that trace is a collection of events
            if not isinstance(trace, (list, tuple)):
                continue

            # Iterate over the events in the trace
            for event in trace:
                # Add each element in the event to the set of unique events
                events.update(event)

        # Return the unique events
        return list(events)

    # Define the find_pattern method
    def find_pattern(self, event_log):
        # Parse the event log to extract the relevant information
        events = self.parse_event_log(event_log)

        # Convert the list of strings into a 2-dimensional array
        events_array = [[event] for event in events]

        # Use the K-means clustering algorithm to identify patterns in the data
        kmeans = KMeans(n_clusters=3)
        kmeans.fit(events_array)
        patterns = kmeans.cluster_centers_

        # Return the identified patterns
        return patterns

    # Define the compute_minimal_traces method
    def compute_minimal_traces(self, event_log):
        # Read the event log from the given traces
        events_list = pd.DataFrame(event_log)

        # Use the find_pattern function to identify the minimal number of traces needed
        patterns = self.find_pattern(event_log)
        num_traces = len(patterns)

        # Print the number of minimal traces
        print(num_traces)

        # Return the number of minimal traces
        return num_traces

    # Define the event log
event_log = ([
        ["status-Open", "Workflow", "summary", "summary", "assignee", "Attachment", "Attachment",
         "status-Patch Available",
         "Attachment", "Attachment", "Attachment", "Attachment", "summary", "Fix Version", "resolution",
         "status-Resolved",
         "status-Closed"],
        ["status-Open", "Workflow", "summary", "issuetype", "summary"],
        ["status-Open", "Workflow", "summary", "description", "Fix Version", "labels", "Fix Version", "resolution",
         "status-Resolved"],
        ["status-Open", "Workflow"]])

    # Create an instance of the phoenixscript class
phoenix = phoenixscript()
num_traces = phoenix.compute_minimal_traces(event_log)

    # Print the results
print("The minimal number of traces needed is:", num_traces)

I tried to create an instance. I get the following errors.

Create an instance of the phoenixscript class
phoenix = phoenixscript()

Traceback (most recent call last):
  File "/Users/randeepsingh/Desktop/pythonProjectRDA/main.py", line 8, in <module>
    class phoenixscript:
  File "/Users/randeepsingh/Desktop/pythonProjectRDA/main.py", line 75, in phoenixscript
    num_traces = compute_minimal_traces(event_log)
TypeError: compute_minimal_traces() missing 1 required positional argument: 'event_log'

Ignore the following statements(The code doesntworks fine and I get thfv dfe correct result.But if I have a huge list of wofsdbsfgbrds say 150sgdbsgb0, it's not feasible to type and creagsfbsfgbte a dictionary that long.So I made a function which takegsbs thogfbvse words from the list, implements the techsdgbsgdbnisdbfgbque I dicussed above and creates the graph for me which works just ffgdsdfinesbg until here.But wsfgbfghen I try to get the shsfgbsortest distance besgfbsfgbtween two words, I get the following error)


问:
Intermittent 'Can't connect to MySQL server on <mariadb server>'
I am getting an intermittent error message as shown in the subject:

```<code>Can't connect to MySQL server on <mariadb server>
</code>```

Where  is a server on the network.
There are only two webservers that connect to this db server and when this happens, they both give this error message.

All the 3 machines (the webservers and the mariadb server) are CentOS 7 VMs, hosted using KVM. The hosts all connect directly into the same switch.

I have set the max_connections for the mariadb server to 8192:

```<code>MariaDB [(none)]> show variables where variable_name = 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 8192  |
+-----------------+-------+
1 row in set (0.00 sec)
</code>```

/proc/sys/net/core/somaxconn on the mariadb server is set to 10000

The mariadb server uses a filesystem that is hosted on two SATA SDDs, in a RAID0 configuration.

"sar" shows that the mariadb server rarely exceeds 10% of %user, 10% %system, 3% of %iowait or .1% of %steal.

Overall, it doesn't appear to be limited in resources. There are no instances of the "CPU X stuck for Y seconds" in the logs.

There are no firewall issues (iptables and nftables are not configured).

The max_connections was set to 200 before, so I think 8192 should be sufficient.

Note that this only occurs in some circumstances, which probably result in a higher number of concurrent connections, normally, everything works fine (and was working fine with 200 max_connections.

Body:
I am getting an intermittent error message as shown in the subject:

Can't connect to MySQL server on <mariadb server>

Where  is a server on the network.
There are only two webservers that connect to this db server and when this happens, they both give this error message.

All the 3 machines (the webservers and the mariadb server) are CentOS 7 VMs, hosted using KVM. The hosts all connect directly into the same switch.

I have set the max_connections for the mariadb server to 8192:

MariaDB [(none)]> show variables where variable_name = 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 8192  |
+-----------------+-------+
1 row in set (0.00 sec)

/proc/sys/net/core/somaxconn on the mariadb server is set to 10000

The mariadb server uses a filesystem that is hosted on two SATA SDDs, in a RAID0 configuration.

"sar" shows that the mariadb server rarely exceeds 10% of %user, 10% %system, 3% of %iowait or .1% of %steal.

Overall, it doesn't appear to be limited in resources. There are no instances of the "CPU X stuck for Y seconds" in the logs.

There are no firewall issues (iptables and nftables are not configured).

The max_connections was set to 200 before, so I think 8192 should be sufficient.

Note that this only occurs in some circumstances, which probably result in a higher number of concurrent connections, normally, everything works fine (and was working fine with 200 max_connections.


问:
Trigger (py)audio recording with key presses
I am trying to write a script that records audio when certain keys are pressed and stops recording when the keys are released, and saves the audio to a .wav.

The program starts and activates my microphone, but it never seems to actually record and removing my fingers from the Control + Shift keys does not seem to have any affect. At any rate, I do not end up with a .wav file.

```<code>import keyboard
import pyaudio
import wave
import time

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

while True:
    if keyboard.is_pressed('ctrl+shift'):
        print('You Pressed A Key!')
        break

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
</code>```

Body:
I am trying to write a script that records audio when certain keys are pressed and stops recording when the keys are released, and saves the audio to a .wav.

The program starts and activates my microphone, but it never seems to actually record and removing my fingers from the Control + Shift keys does not seem to have any affect. At any rate, I do not end up with a .wav file.

import keyboard
import pyaudio
import wave
import time

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

while True:
    if keyboard.is_pressed('ctrl+shift'):
        print('You Pressed A Key!')
        break

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()