问:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 4914: character maps to <undefined>
I'm using ArtUshak's wiki_tool_python scripts codes to dump images from an Vietnamese wiki at Fandom.com, in this case: https://lhmn.fandom.com/vi.

At the moment I decided to dump the images, using predefined text file from a previous code.
Because most of the files on that wiki have at least, an Vietnamese character on it's name, I have to use --confine-encoding UTF-8 option to properly get all of the files, using list-images --confine-encoding UTF-8 https://lhmn.fandom.com/vi. After that, using the result I got from using list-images, I copies all the files list on to a text file, calling it images.txt.

download-images, using the previous file created, I get it to run the command to dump the images: download-images images.txt .\data\download

(The download-images command do not accept --confine-encoding UTF-8 option)

Then this happen and the script stop:

Traceback (most recent call last):
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 1198, in <module>
    cli(obj={})
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 829, in __call__
    return self.main(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 782, in main
    rv = self.invoke(ctx)
         ^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 610, in invoke
    return callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 652, in download_images
    with click.progressbar(list(read_image_list(list_file))) as bar:
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 37, in read_image_list
    url_line = next(file_iterator)
               ^^^^^^^^^^^^^^^^^^^
  File "F:\VMN - TC21TH\PYTHON\Lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 4914: character maps to <undefined>
```

It supposed to get all the files from the previously defined list and download them to the path .\data\download.

Body:
I'm using ArtUshak's wiki_tool_python scripts codes to dump images from an Vietnamese wiki at Fandom.com, in this case: https://lhmn.fandom.com/vi.

At the moment I decided to dump the images, using predefined text file from a previous code.
Because most of the files on that wiki have at least, an Vietnamese character on it's name, I have to use --confine-encoding UTF-8 option to properly get all of the files, using list-images --confine-encoding UTF-8 https://lhmn.fandom.com/vi. After that, using the result I got from using list-images, I copies all the files list on to a text file, calling it images.txt.

download-images, using the previous file created, I get it to run the command to dump the images: download-images images.txt .\data\download

(The download-images command do not accept --confine-encoding UTF-8 option)

Then this happen and the script stop:

Traceback (most recent call last):
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 1198, in <module>
    cli(obj={})
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 829, in __call__
    return self.main(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 782, in main
    rv = self.invoke(ctx)
         ^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\core.py", line 610, in invoke
    return callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\AppData\Local\pypoetry\Cache\virtualenvs\wiki-tool-python-UGT00s18-py3.11\Lib\site-packages\click\decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 652, in download_images
    with click.progressbar(list(read_image_list(list_file))) as bar:
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ADMIN\Downloads\wiki_tool\wiki_tool_python-master\wiki_tool_python\wikitool.py", line 37, in read_image_list
    url_line = next(file_iterator)
               ^^^^^^^^^^^^^^^^^^^
  File "F:\VMN - TC21TH\PYTHON\Lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 4914: character maps to <undefined>

It supposed to get all the files from the previously defined list and download them to the path .\data\download.


来源: stackexchange

问:
How to combine declarative mappings from different packages?
before I start contriving a minimal example with a lot of sqlalchemy boilerplate stuff, maybe I can explain the concept theoretically.

I have a package "foo" that defines some tables in a database schema "foo_db" in the standard ORM manner:

```<code>class FooTable(Base):
    __tablename__ = 'foo_data'
    id = Column(Integer, primary_key=True)
</code>```

The package is typically used stand-alone with its own database schema, "foo_db."

A separate package "bar" has its own schema "bar_db" with its own tables, but it also needs to use the tables of "foo" on "foo_db," and it has foreign keys into foo_db's tables (both schemas obviously are on the same server):

```<code>from foo.models import Base, FooTable

class BarTable(Base):
    __tablename__ = 'bar_data'
    id = Column(Integer, primary_key=True)
    foo_id = Column(ForeignKey('foo_db.foo_data.id'))
    foo = relationship(FooTable)
</code>```

When I try to use this code I get errors like these:

```<code>(MySQLdb._exceptions.ProgrammingError) (1146, "Table 'bar_db.foo_data' doesn't exist")
</code>```

The only way I found to get around this is to literally re-define FooTable in package bar:

```<code>class FooTable(Base):
    __tablename__ = 'foo_data'
    __table_args__ = {'schema': 'foo_db'}
    id = Column(Integer, primary_key=True)
</code>```

This is very obviously not how it should be done. Any suggestions?

ContentLicense: CC BY-SA 4.0

Body:
before I start contriving a minimal example with a lot of sqlalchemy boilerplate stuff, maybe I can explain the concept theoretically.

I have a package "foo" that defines some tables in a database schema "foo_db" in the standard ORM manner:

class FooTable(Base):
    __tablename__ = 'foo_data'
    id = Column(Integer, primary_key=True)

The package is typically used stand-alone with its own database schema, "foo_db."

A separate package "bar" has its own schema "bar_db" with its own tables, but it also needs to use the tables of "foo" on "foo_db," and it has foreign keys into foo_db's tables (both schemas obviously are on the same server):

from foo.models import Base, FooTable

class BarTable(Base):
    __tablename__ = 'bar_data'
    id = Column(Integer, primary_key=True)
    foo_id = Column(ForeignKey('foo_db.foo_data.id'))
    foo = relationship(FooTable)

When I try to use this code I get errors like these:

(MySQLdb._exceptions.ProgrammingError) (1146, "Table 'bar_db.foo_data' doesn't exist")

The only way I found to get around this is to literally re-define FooTable in package bar:

class FooTable(Base):
    __tablename__ = 'foo_data'
    __table_args__ = {'schema': 'foo_db'}
    id = Column(Integer, primary_key=True)

This is very obviously not how it should be done. Any suggestions?


问:
How can I accomplish the "i dont knw if the naming is right" but accordion modals
hello react native developers, I'm trying to create what's attached in the images

while clicking on it should toggle like:


问:
Cant update pdf file using pdf-lib nodejs
How to update pdf file in nodejs using the pdf-lib?

documentation https://pdf-lib.js.org/

```<code>  const pdfDoc = await PDFDocument.load(
    readFileSync(
      './UserAccount.pdf',
    ),
  );
  const form = pdfDoc.getForm();
  const applicationFor = form
    .getTextField('username')
    .setText('New Username');
  const pdfBytes = await pdfDoc.save();
  download(pdfBytes, 'pdf-lib_form_creation_example.pdf', 'application/pdf');
  return pdfBytes;
};
</code>```

here is the text field property that I want to update on pdf

Body:
How to update pdf file in nodejs using the pdf-lib?

documentation https://pdf-lib.js.org/

  const pdfDoc = await PDFDocument.load(
    readFileSync(
      './UserAccount.pdf',
    ),
  );
  const form = pdfDoc.getForm();
  const applicationFor = form
    .getTextField('username')
    .setText('New Username');
  const pdfBytes = await pdfDoc.save();
  download(pdfBytes, 'pdf-lib_form_creation_example.pdf', 'application/pdf');
  return pdfBytes;
};

here is the text field property that I want to update on pdf


问:
Binding multicast address to a socket
I'm trying to make a multicast application. I'm using Winsock 2 and I don't know how to prepare a multicast address for send and receive. I think the multicast address should be bound to a socket but I don't know exactly how.

When I look up on the multicast programming guide of Microsoft Winsock website, they used something like struct group_req or ip_mreq(6). I don't know how to bind it to a socket

What can I do next? :

```<code>group_req prepare_addr(SOCKADDR_STORAGE& mcastaddr) {
    group_req result{};
    DWORD interface_index{};
    GetBestInterfaceEx((sockaddr*)&mcastaddr, &interface_index);
    result.gr_group = mcastaddr;
    result.gr_interface = interface_index;

</code>```

Title: Binding multicast address to a socket

Body:
I'm trying to make a multicast application. I'm using Winsock 2 and I don't know how to prepare a multicast address for send and receive. I think the multicast address should be bound to a socket but I don't know exactly how.

When I look up on the multicast programming guide of Microsoft Winsock website, they used something like struct group_req or ip_mreq(6). I don't know how to bind it to a socket

What can I do next? :

group_req prepare_addr(SOCKADDR_STORAGE& mcastaddr) {
    group_req result{};
    DWORD interface_index{};
    GetBestInterfaceEx((sockaddr*)&mcastaddr, &interface_index);
    result.gr_group = mcastaddr;
    result.gr_interface = interface_index;


问:
tkinter empty variable for entry inserted into database
so i wrote this code to connect to the database and insert or return some data from it
but i when i want to insert there's no data to be inserted into database, I mean the row is created in the table but it's an empty row and the problem should be from somewhere like usersign.get()

```<code>from tkinter import *
import mysql.connector
import time
def MainWindow():
    global tk
    tk = Tk()
    tk.geometry('300x340')
    tk.title("Login")
    label = Label(tk, text="Enter Your Credentials", fg="black")
    label.pack(side="top", pady="15px")
    label2 = Label(tk, text="Username")
    label2.pack(expand=True)
    userlog = StringVar()
    userentry = Entry(tk, width=20, textvariable=userlog)
    userentry.pack(expand=True)
    label3 = Label(tk, text="Password")
    label3.pack()
    passlog = StringVar()
    passentry = Entry(tk, width=20, textvariable=passlog)
    passentry.pack()
    login = Button(tk, text="Login", bg="gray")
    login.pack(pady="15px")
    forgot = Button(tk, text="Forgot password", bg="white", command=lambda: forgotpassword())
    forgot.pack()
    btn2 = Button(tk, text="Sign Up", bg="white", command=Signup)
    btn2.pack(expand=True)
    tk.mainloop()
def Withdraw():
    tk2.withdraw()
    tk.deiconify()
def forgotpassword():
    global tk2
    tk.withdraw()
    tk2 = Tk()
    tk2.geometry('300x340')
    tk2.title("Forgot Password")
    lbl = Label(tk2, text="Username")
    lbl.pack(side="top", expand=True)
    userforgot = StringVar()
    usr = Entry(tk2, width=20, textvariable=userforgot)
    usr.pack(expand=True)
    lbl2 = Label(tk2, text="Phone Number")
    lbl2.pack(expand=True)
    phoneforgot = StringVar()
    phone = Entry(tk2, width=20, textvariable=phoneforgot)
    phone.pack(expand=True)
    btn = Button(tk2, text="Forgot Password", bg="white", command=PassRecovery())
    btn.pack(expand=True)
def PassRecovery():
    #connectes to database
    #checks if datas match or not
    # if so, creates a label showing the data
    Btn = Button(tk2, text="Return to login window", command=lambda: Withdraw())
    Btn.pack(expand=True)
def Signup():
    global tk3, usersign, passsign, phonesign
    # the problem is that globalization is happening before the assignment of variables
    tk.withdraw()
    tk3 = Tk()
    tk3.geometry('300x340')
    tk3.title("Sign Up")
    lbl = Label(tk3, text="Username")
    lbl.pack(expand=True)
    usersign = StringVar()
    ent1 = Entry(tk3, textvariable=usersign, width=20)
    ent1.pack(expand=True)
    lbl2 = Label(tk3, text="Password")
    lbl2.pack(expand=True)
    passsign = StringVar()
    ent2 = Entry(tk3, textvariable=passsign, width=20)
    ent2.pack(expand=True)
    print(passsign.get())
    phonesign = StringVar()
    lbl3 = Label(tk3, text="Phone Number")
    lbl3.pack(expand=True)
    ent3 = Entry(tk3, textvariable=phonesign, width=20)
    ent3.pack(expand=True)
    btn = Button(tk3, text="Sign Up", command=lambda: InsertData())
    btn.pack(expand=True)
    print(usersign.get())
def InsertData():
    db = mysql.connector.connect(host="localhost", user="root", password="Balarooch1386")
    cursor = db.cursor()
    cursor.execute("use usercredentials")
    cursor.execute("insert into data values (%s, %s, %s)", (usersign.get(), passsign.get(), phonesign.get()))
    db.commit()
    labl = Label(tk3, text="Signed Up Successfully")
    labl.pack(expand=True)
    print(usersign.get())
    # tk3.withdraw()
    # tk.deiconify()
MainWindow()
#issue : no data to insert into table
</code>```

i tried putting all the functions in MainWindow() but it didn't work

Body:
so i wrote this code to connect to the database and insert or return some data from it
but i when i want to insert there's no data to be inserted into database, I mean the row is created in the table but it's an empty row and the problem should be from somewhere like usersign.get()

from tkinter import *
import mysql.connector
import time
def MainWindow():
    global tk
    tk = Tk()
    tk.geometry('300x340')
    tk.title("Login")
    label = Label(tk, text="Enter Your Credentials", fg="black")
    label.pack(side="top", pady="15px")
    label2 = Label(tk, text="Username")
    label2.pack(expand=True)
    userlog = StringVar()
    userentry = Entry(tk, width=20, textvariable=userlog)
    userentry.pack(expand=True)
    label3 = Label(tk, text="Password")
    label3.pack()
    passlog = StringVar()
    passentry = Entry(tk, width=20, textvariable=passlog)
    passentry.pack()
    login = Button(tk, text="Login", bg="gray")
    login.pack(pady="15px")
    forgot = Button(tk, text="Forgot password", bg="white", command=lambda: forgotpassword())
    forgot.pack()
    btn2 = Button(tk, text="Sign Up", bg="white", command=Signup)
    btn2.pack(expand=True)
    tk.mainloop()
def Withdraw():
    tk2.withdraw()
    tk.deiconify()
def forgotpassword():
    global tk2
    tk.withdraw()
    tk2 = Tk()
    tk2.geometry('300x340')
    tk2.title("Forgot Password")
    lbl = Label(tk2, text="Username")
    lbl.pack(side="top", expand=True)
    userforgot = StringVar()
    usr = Entry(tk2, width=20, textvariable=userforgot)
    usr.pack(expand=True)
    lbl2 = Label(tk2, text="Phone Number")
    lbl2.pack(expand=True)
    phoneforgot = StringVar()
    phone = Entry(tk2, width=20, textvariable=phoneforgot)
    phone.pack(expand=True)
    btn = Button(tk2, text="Forgot Password", bg="white", command=PassRecovery())
    btn.pack(expand=True)
def PassRecovery():
    #connectes to database
    #checks if datas match or not
    # if so, creates a label showing the data
    Btn = Button(tk2, text="Return to login window", command=lambda: Withdraw())
    Btn.pack(expand=True)
def Signup():
    global tk3, usersign, passsign, phonesign
    # the problem is that globalization is happening before the assignment of variables
    tk.withdraw()
    tk3 = Tk()
    tk3.geometry('300x340')
    tk3.title("Sign Up")
    lbl = Label(tk3, text="Username")
    lbl.pack(expand=True)
    usersign = StringVar()
    ent1 = Entry(tk3, textvariable=usersign, width=20)
    ent1.pack(expand=True)
    lbl2 = Label(tk3, text="Password")
    lbl2.pack(expand=True)
    passsign = StringVar()
    ent2 = Entry(tk3, textvariable=passsign, width=20)
    ent2.pack(expand=True)
    print(passsign.get())
    phonesign = StringVar()
    lbl3 = Label(tk3, text="Phone Number")
    lbl3.pack(expand=True)
    ent3 = Entry(tk3, textvariable=phonesign, width=20)
    ent3.pack(expand=True)
    btn = Button(tk3, text="Sign Up", command=lambda: InsertData())
    btn.pack(expand=True)
    print(usersign.get())
def InsertData():
    db = mysql.connector.connect(host="localhost", user="root", password="Balarooch1386")
    cursor = db.cursor()
    cursor.execute("use usercredentials")
    cursor.execute("insert into data values (%s, %s, %s)", (usersign.get(), passsign.get(), phonesign.get()))
    db.commit()
    labl = Label(tk3, text="Signed Up Successfully")
    labl.pack(expand=True)
    print(usersign.get())
    # tk3.withdraw()
    # tk.deiconify()
MainWindow()
#issue : no data to insert into table

i tried putting all the functions in MainWindow() but it didn't work


问:
Max size for BluetoothRemoteGATTCharacteristic.writeValueWithResponse()
I'm using Web Bluetooth on Chrome to send data to a BLE device running micropython using the following code...

```<code>var value = new TextEncoder('utf-8').encode(str);
for (i=0; i<value.byteLength; i+=self.DATA_BUFFER_SIZE) {
  await self.dataCharacteristic.writeValueWithResponse(value.slice(i, i + self.DATA_BUFFER_SIZE));
}
</code>```

The micropython BLE device has its receive buffer set to 512 bytes, and on most computers, the above code works fine with self.DATA_BUFFER_SIZE set to 512 as well. But on one computer, I could not get the above code to work unless self.DATA_BUFFER_SIZE is reduced to 20. If set to anything higher than 20, writeValueWithResponse() will not complete. There are no error messages on the developer console, the await simply never completes.

Tested successfully with 512...

Various macbooks

Various Win 10 laptops

Desktops and laptops running Ubuntu 20.04 and 22.04

Android phone

Fire tablet

Failed unless set to 20...

A single laptop running Ubuntu 22.04, Chrome 108.0.5359.124, Qualcomm atheros qca9377

Can anyone advice...

Is this a bug in Chrome / Linux qca9377 driver / hardware?

Are there any ways for me to detect the largest safe buffer size for writeValueWithResponse?

Body:
I'm using Web Bluetooth on Chrome to send data to a BLE device running micropython using the following code...

var value = new TextEncoder('utf-8').encode(str);
for (i=0; i<value.byteLength; i+=self.DATA_BUFFER_SIZE) {
  await self.dataCharacteristic.writeValueWithResponse(value.slice(i, i + self.DATA_BUFFER_SIZE));
}

The micropython BLE device has its receive buffer set to 512 bytes, and on most computers, the above code works fine with self.DATA_BUFFER_SIZE set to 512 as well. But on one computer, I could not get the above code to work unless self.DATA_BUFFER_SIZE is reduced to 20. If set to anything higher than 20, writeValueWithResponse() will not complete. There are no error messages on the developer console, the await simply never completes.

Tested successfully with 512...

Various macbooks

Various Win 10 laptops

Desktops and laptops running Ubuntu 20.04 and 22.04

Android phone

Fire tablet

Failed unless set to 20...

A single laptop running Ubuntu 22.04, Chrome 108.0.5359.124, Qualcomm atheros qca9377

Can anyone advice...

Is this a bug in Chrome / Linux qca9377 driver / hardware?

Are there any ways for me to detect the largest safe buffer size for writeValueWithResponse?


问:
How do I create an NSView from a nib in Swift
I am trying to use Swift 5.7.2 to create a macOS menu bar application. Ultimately, I have an NSMenu filled with a handful of NSMenuItems that have submenus with custom views. I have code that creates this menu then use the following to set the view of the submenu item:

```<code>subMenuItem.view = SubMenuView(frame: NSRect(x: 0.0, y: 0.0, width: 160.0, height: 37.0))
</code>```

The SubMenuView looks like this:

I have tried turning the nib into an NSView a handful of different ways but none have worked. This is what I end up getting:

My code for the SubMenuView.swift file is below:

```<code>import Cocoa

class SubMenuView: NSView {

    @IBOutlet var parentView: NSView!

    @IBOutlet var label: NSTextField!

    @IBAction func set(_ sender: NSButton) {

    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}
</code>```

Above, parentView is linked to the background of the SubMenuView, label is linked to the text input, and set is linked to the button. I know that it has something to do with setting the constraints in the init function but can't seem to get it to work. What is the best way of going about this?

Body:
I am trying to use Swift 5.7.2 to create a macOS menu bar application. Ultimately, I have an NSMenu filled with a handful of NSMenuItems that have submenus with custom views. I have code that creates this menu then use the following to set the view of the submenu item:

subMenuItem.view = SubMenuView(frame: NSRect(x: 0.0, y: 0.0, width: 160.0, height: 37.0))

The SubMenuView looks like this:

I have tried turning the nib into an NSView a handful of different ways but none have worked. This is what I end up getting:

My code for the SubMenuView.swift file is below:

import Cocoa

class SubMenuView: NSView {

    @IBOutlet var parentView: NSView!

    @IBOutlet var label: NSTextField!

    @IBAction func set(_ sender: NSButton) {

    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

Above, parentView is linked to the background of the SubMenuView, label is linked to the text input, and set is linked to the button. I know that it has something to do with setting the constraints in the init function but can't seem to get it to work. What is the best way of going about this?


问:
Hydration failed because the initial UI does not match what was rendered on the server (Next.js v12.3.1)
```<code>import { Container } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import Layout from '../../components/Layout/Layout'

const CartScreen = () => {

  const cart = useSelector(state => state.cart)
  const { cartItems } = cart

  console.log(cartItems)

  return (
    <Layout>
      <Container>

        <div>
          <h1>Shopping Cart</h1>
          {cartItems && cartItems.length === 0 && <p>Your cart is empty </p>}
        </div>

      </Container>
    </Layout>
  )
}

export default CartScreen
</code>```

This code gives me that Hydration Error only when 'cart' is empty

I don't know how to use useEffect on this and I use redux toolkit.

Body:
import { Container } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import Layout from '../../components/Layout/Layout'

const CartScreen = () => {

  const cart = useSelector(state => state.cart)
  const { cartItems } = cart

  console.log(cartItems)

  return (
    <Layout>
      <Container>

Shopping Cart

          {cartItems && cartItems.length === 0 &&
Your cart is empty
}

      </Container>
    </Layout>
  )
}

export default CartScreen

This code gives me that Hydration Error only when 'cart' is empty

I don't know how to use useEffect on this and I use redux toolkit.


问:
My quiz app is not moving to the next question
I am currently making a quiz app. I think there might be a problem with my logic. My quiz is not moving to the next question.

Each quiz has four options. Out of four options if the correct one is clicked then the "Correct" message is shown otherwise "Incorrect" message is displayed. Then the user can move to next question.

I am pasting my JavaScript code below. I cannot move to the next item in my array.

```<code>const questions = [
  {
    questionText: "Commonly used data types DO NOT include:",
    options: ["1. strings", "2. booleans", "3. alerts", "4. numbers"],
    answer: "3. alerts",
  },
  {
    questionText: "Arrays in JavaScript can be used to store ______.",
    options: [
      "1. numbers and strings",
      "2. other arrays",
      "3. booleans",
      "4. all of the above",
    ],
    answer: "4. all of the above",
  },
  {
    questionText:
      "String values must be enclosed within _____ when being assigned to variables.",
    options: ["1. commas", "2. curly brackets", "3. quotes", "4. parentheses"],
    answer: "3. quotes",
  },
  {
    questionText:
      "A very useful tool used during development and debugging for printing content to the debugger is:",
    options: [
      "1. JavaScript",
      "2. terminal/bash",
      "3. for loops",
      "4. console.log",
    ],
    answer: "4. console.log",
  },
  {
    questionText:
      "Which of the following is a statement that can be used to terminate a loop, switch or label statement?",
    options: ["1. break", "2. stop", "3. halt", "4. exit"],
    answer: "1. break",
  },
];

let currentItem = 0;
let myscore = 0;
let timeleft = 50;
let answer = false;

const startBtn = document.querySelector('.start-btn');
const timeEl = document.querySelector('#time');
const scoreEl = document.querySelector('.score-btn');
const quizContainer = document.querySelector(".quiz-container");
const container = document.querySelector(".container");
const finish = document.querySelector('.finish');
const scores = document.querySelector('.scores');
const result = document.querySelector('.result');

startBtn.addEventListener('click',function(){
  container.classList.add('inactive-container');
  quizContainer.classList.add('active-quiz-container');
  displayQuestion(0);
  setTimer();
})

// countdown
function setTimer(){

  let downloadTimer = setInterval(function(){

  if(timeleft <= 0){
    clearInterval(downloadTimer);
    timeEl.innerHTML = `Time:Finished`;
    quizContainer.classList.remove('active-quiz-container');
    finish.classList.add('active-finish');
  } else {
      if(timeleft < 10){
        timeEl.innerHTML = `Time: 0${timeleft} sec`;
      }
      else{
        timeEl.innerHTML = `Time: ${timeleft} sec`;
      }

  }
  timeleft -= 1;
}, 1000);
}

// display quiz

function displayQuestion(index){
    const item = questions[index];
    quizContainer.innerHTML = `<div class="questions">
      <h3 class="question-text">${item.questionText}</h3>
      <button class="option-btn">
         ${item.options[0]}
      </button>
      <button class="option-btn">
        ${item.options[1]}
      </button>
      <button class="option-btn">
       ${item.options[2]}
      </button>
      <button class="option-btn">
        ${item.options[3]}
      </button>

      <div class="answer">
        <p>${item.answer}</p>
      </div>
      <div class="result">
        <p></p>
      </div>
    </div>`

    const btns = document.querySelectorAll('.option-btn');
    const result = document.querySelector('.result');
    btns.forEach((btn)=>{
      btn.addEventListener('click',function(e){
        if((e.currentTarget.innerText) === item.answer){
            result.innerText = "Correct!"
            result.classList.add('show-result');
            myscore += 5;
            answer = true;
        }
        else{
          result.innerText ="Incorrect!"
          result.classList.add('show-result');
          timeleft -= 10;
        }

      })
    })
    nextQuestion();
  }
  function nextQuestion(){

    if(answer){
      currentItem ++;
      displayQuestion(currentItem);
    }
  }
</code>```

Body:
I am currently making a quiz app. I think there might be a problem with my logic. My quiz is not moving to the next question.

Each quiz has four options. Out of four options if the correct one is clicked then the "Correct" message is shown otherwise "Incorrect" message is displayed. Then the user can move to next question.

I am pasting my JavaScript code below. I cannot move to the next item in my array.

const questions = [
  {
    questionText: "Commonly used data types DO NOT include:",
    options: ["1. strings", "2. booleans", "3. alerts", "4. numbers"],
    answer: "3. alerts",
  },
  {
    questionText: "Arrays in JavaScript can be used to store ______.",
    options: [
      "1. numbers and strings",
      "2. other arrays",
      "3. booleans",
      "4. all of the above",
    ],
    answer: "4. all of the above",
  },
  {
    questionText:
      "String values must be enclosed within _____ when being assigned to variables.",
    options: ["1. commas", "2. curly brackets", "3. quotes", "4. parentheses"],
    answer: "3. quotes",
  },
  {
    questionText:
      "A very useful tool used during development and debugging for printing content to the debugger is:",
    options: [
      "1. JavaScript",
      "2. terminal/bash",
      "3. for loops",
      "4. console.log",
    ],
    answer: "4. console.log",
  },
  {
    questionText:
      "Which of the following is a statement that can be used to terminate a loop, switch or label statement?",
    options: ["1. break", "2. stop", "3. halt", "4. exit"],
    answer: "1. break",
  },
];

let currentItem = 0;
let myscore = 0;
let timeleft = 50;
let answer = false;

const startBtn = document.querySelector('.start-btn');
const timeEl = document.querySelector('#time');
const scoreEl = document.querySelector('.score-btn');
const quizContainer = document.querySelector(".quiz-container");
const container = document.querySelector(".container");
const finish = document.querySelector('.finish');
const scores = document.querySelector('.scores');
const result = document.querySelector('.result');

startBtn.addEventListener('click',function(){
  container.classList.add('inactive-container');
  quizContainer.classList.add('active-quiz-container');
  displayQuestion(0);
  setTimer();
})

// countdown
function setTimer(){

  let downloadTimer = setInterval(function(){

  if(timeleft <= 0){
    clearInterval(downloadTimer);
    timeEl.innerHTML = `Time:Finished`;
    quizContainer.classList.remove('active-quiz-container');
    finish.classList.add('active-finish');
  } else {
      if(timeleft < 10){
        timeEl.innerHTML = `Time: 0${timeleft} sec`;
      }
      else{
        timeEl.innerHTML = `Time: ${timeleft} sec`;
      }

  }
  timeleft -= 1;
}, 1000);
}

// display quiz

function displayQuestion(index){
    const item = questions[index];
    quizContainer.innerHTML = `

${item.questionText}

      <button class="option-btn">
         ${item.options[0]}
      </button>
      <button class="option-btn">
        ${item.options[1]}
      </button>
      <button class="option-btn">
       ${item.options[2]}
      </button>
      <button class="option-btn">
        ${item.options[3]}
      </button>

${item.answer}

`

    const btns = document.querySelectorAll('.option-btn');
    const result = document.querySelector('.result');
    btns.forEach((btn)=>{
      btn.addEventListener('click',function(e){
        if((e.currentTarget.innerText) === item.answer){
            result.innerText = "Correct!"
            result.classList.add('show-result');
            myscore += 5;
            answer = true;
        }
        else{
          result.innerText ="Incorrect!"
          result.classList.add('show-result');
          timeleft -= 10;
        }

      })
    })
    nextQuestion();
  }
  function nextQuestion(){

    if(answer){
      currentItem ++;
      displayQuestion(currentItem);
    }
  }


问:
The "jspdf" library, when inserting the same image, loads it into the browser again each time. How to fix it?
Using the jspdf library, I am creating a pdf file. It has headers. Site logo in headers. I noticed that for each sheet of the pdf file, the library reloads the logo (logo requests are visible in the Network tab). This slows down the formation of the pdf file. And in general, not very good, the picture is the same, why upload it several times.

Is it possible to make the image load not for each sheet of the pdf file, but once for the entire pdf file?

Here is the code to insert the image:

```<code>let doc = new jsPDF('p', 'pt');
...
let pageCount = doc.internal.getNumberOfPages();
...
let logoImg = new Image();
logoImg.src = logoImgPath;
...
for (let i = 1; i <= pageCount; i++) {
    // This line inserts an image into a pdf sheet. In the Network tab in the browser, I noticed that the picture is loaded for each sheet. Is there any way to make that the image is loaded only once - for the entire pdf file?
    doc.addImage(logoImg, 'png', 10, 10, 100, 80);
}
</code>```

Body:
Using the jspdf library, I am creating a pdf file. It has headers. Site logo in headers. I noticed that for each sheet of the pdf file, the library reloads the logo (logo requests are visible in the Network tab). This slows down the formation of the pdf file. And in general, not very good, the picture is the same, why upload it several times.

Is it possible to make the image load not for each sheet of the pdf file, but once for the entire pdf file?

Here is the code to insert the image:

let doc = new jsPDF('p', 'pt');
...
let pageCount = doc.internal.getNumberOfPages();
...
let logoImg = new Image();
logoImg.src = logoImgPath;
...
for (let i = 1; i <= pageCount; i++) {
    // This line inserts an image into a pdf sheet. In the Network tab in the browser, I noticed that the picture is loaded for each sheet. Is there any way to make that the image is loaded only once - for the entire pdf file?
    doc.addImage(logoImg, 'png', 10, 10, 100, 80);
}


问:
Filtering a string URI before parsing in reactor-netty HttpServer
Assume we have dependencies as described here.

pom.xml

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-bom</artifactId>
            <version>2022.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>io.projectreactor.netty</groupId>
        <artifactId>reactor-netty-core</artifactId>
    </dependency>
    <dependency>
        <groupId>io.projectreactor.netty</groupId>
        <artifactId>reactor-netty-http</artifactId>
    </dependency>
</dependencies>
</code>```

and simple HttpServer application

```<code>import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;

public class Application {

    public static void main(String[] args) {
        DisposableServer server =
                HttpServer.create()
                          .host("localhost")
                          .port(8080)
                          .bindNow();

        server.onDispose()
              .block();
    }
}
</code>```

URI parsing is a very dangerous operation in our time.

How can I access the URI string before it will be parsed with HttpOperations.resolvePath method?
It is very important to apply some filters and rules in this place to protect against malicious requests.

Lifecycle callbacks don't help me. Filtering with nginx or HttpLoadBalancer add a very high latency so they are not suitable. I expect low latency.

Thank you!

Body:
Assume we have dependencies as described here.

pom.xml

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-bom</artifactId>
            <version>2022.0.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>io.projectreactor.netty</groupId>
        <artifactId>reactor-netty-core</artifactId>
    </dependency>
    <dependency>
        <groupId>io.projectreactor.netty</groupId>
        <artifactId>reactor-netty-http</artifactId>
    </dependency>
</dependencies>

and simple HttpServer application

import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;

public class Application {

    public static void main(String[] args) {
        DisposableServer server =
                HttpServer.create()
                          .host("localhost")
                          .port(8080)
                          .bindNow();

        server.onDispose()
              .block();
    }
}

URI parsing is a very dangerous operation in our time.

How can I access the URI string before it will be parsed with HttpOperations.resolvePath method?
It is very important to apply some filters and rules in this place to protect against malicious requests.

Lifecycle callbacks don't help me. Filtering with nginx or HttpLoadBalancer add a very high latency so they are not suitable. I expect low latency.

Thank you!


问:
Angular Materials-Data not displaying which is from database, error not defined
I am using mat-table for my project. Here is my html code:

    <ng-container matColumnDef="Item">
        Item
        {{Menu.item}}
    </ng-container>

    <ng-container matColumnDef="Price">
        Price
        {{Menu.price}}
    </ng-container>

Token Number: 01

            Clicked on {{Menu.item}} which is {{Menu.price}}/-

        <button mat-stroked-button color="primary">Cancel</button>
        <button mat-flat-button color="primary">Print</button>

Token Number: 02

        <button mat-stroked-button color="primary">Cancel</button>
        <button mat-flat-button color="primary">Print</button>

```
<p>and here is my ts file code</p>
```  displayedColumns: string[] = ['Item', 'Price'];

  Menu1: menu1[] = [
    // {
    //   item: 'idly',
    //   price: 20.
    // },
    // {
    //   item: 'vada',
    //   price: 90.
    // },
    // {
    //   item: 'vada',
    //   price: 90.
    // },
  ];

  constructor(private morningService: MorningService) { }

datasource=this.Menu1

  ngOnInit(): void {
    this.morningService.getAllMenu()
      .subscribe({
        next: (menu) => {
          this.Menu1=menu;
        },
        error: (Response) => {
          console.log(Response);
        }

      });

    // this.Menu1.push()
  }

  // datasource = this.Menu1
  clickedRows = new  Set<menu1>

```
<p>This is my service file</p>
```export class MorningService {
  url: string = environment.baseApiUrl

  constructor(private http: HttpClient) { }

  getAllMenu(): Observable<menu1[]> {
    return this.http.get<menu1[]>(this.url +'/api/Menu');
  }
}
```

The data is coming from the sql which I have been integrated with.

I have tried hard-coding the data which is working fine... but when I want it statically it is going blank.

Body:
I am using mat-table for my project. Here is my html code:

    <ng-container matColumnDef="Item">
        Item
        {{Menu.item}}
    </ng-container>

    <ng-container matColumnDef="Price">
        Price
        {{Menu.price}}
    </ng-container>

Token Number: 01

            Clicked on {{Menu.item}} which is {{Menu.price}}/-

        <button mat-stroked-button color="primary">Cancel</button>
        <button mat-flat-button color="primary">Print</button>

Token Number: 02

        <button mat-stroked-button color="primary">Cancel</button>
        <button mat-flat-button color="primary">Print</button>

and here is my ts file code

  displayedColumns: string[] = ['Item', 'Price'];

  Menu1: menu1[] = [
    // {
    //   item: 'idly',
    //   price: 20.
    // },
    // {
    //   item: 'vada',
    //   price: 90.
    // },
    // {
    //   item: 'vada',
    //   price: 90.
    // },
  ];

  constructor(private morningService: MorningService) { }

datasource=this.Menu1

  ngOnInit(): void {
    this.morningService.getAllMenu()
      .subscribe({
        next: (menu) => {
          this.Menu1=menu;
        },
        error: (Response) => {
          console.log(Response);
        }

      });

    // this.Menu1.push()
  }

  // datasource = this.Menu1
  clickedRows = new  Set<menu1>

This is my service file

export class MorningService {
  url: string = environment.baseApiUrl

  constructor(private http: HttpClient) { }

  getAllMenu(): Observable<menu1[]> {
    return this.http.get<menu1[]>(this.url +'/api/Menu');
  }
}

The data is coming from the sql which I have been integrated with.

I have tried hard-coding the data which is working fine... but when I want it statically it is going blank.


问:
Why jit can destroy performance on Linux server?
We have a Postgresql development server on Windows and a production server on Ubuntu Linux. The Postgresql release versions are slightly different, the newer in on linux (Postgresql 14.5).

One database was exported from development and imported in production, so they are the same. We noticed that some queries are 100 times slower on Ubuntu server. Too much to blame a different hardware. The critical queries are like the following:

```<code>SELECT a.field1,
...
a.field_n,
CASE (EXISTS (
SELECT b."waterBodyCode"
  FROM "GAP_ecologico_SWB_1" b
  WHERE a.field1 = b.field1_b AND ...))
  WHEN true
    THEN 'Yes'
        ELSE 'No'
  END AS "attributableQE"
FROM "SWB_ecological_quality_elements" a
ORDER BY a.field1, ...;
</code>```

I know we can rewrite the query in a better and more efficient way but before doing that we would like to understand the root cause of the poor performance on Ubuntu.

SWB_ecological_quality_elements and swaterBodyCode are views. What we suspect is that on Windows server the inner query is executed using indexing or caching while on Ubuntu  a full scan is done. The postgresql.conf files are quite similar, what can we check ?

UPDATE 1

I tuned the memory as suggested by PgTune but it was useless, same poor performance. I executed the query with Analyze, the timing result looks weird but I'm not an expert.

```<code>"  Functions: 1499"
"  Options: Inlining true, Optimization true, Expressions true,         Deforming true"
"  Timing: Generation 101.424 ms, Inlining 103.476 ms, Optimization 10402.780 ms, Emission 6866.288 ms, Total 17473.968 ms"
"Execution Time: 18005.457 ms"
</code>```

UPDATE 2

Setting jit to false cause an incredible performance boost on the query execute on the Linux server. Don't know anything about jit and cannot figure out why it behaves so differently on Windows (Postgresql 14.4) and on Linux (Postgresql 14.5), but others noticed its weird effects as can be read here: Handling performance problems with jit in postgres 12.
Any explanation ?

Body:
We have a Postgresql development server on Windows and a production server on Ubuntu Linux. The Postgresql release versions are slightly different, the newer in on linux (Postgresql 14.5).

One database was exported from development and imported in production, so they are the same. We noticed that some queries are 100 times slower on Ubuntu server. Too much to blame a different hardware. The critical queries are like the following:

SELECT a.field1,
...
a.field_n,
CASE (EXISTS (
SELECT b."waterBodyCode"
  FROM "GAP_ecologico_SWB_1" b
  WHERE a.field1 = b.field1_b AND ...))
  WHEN true
    THEN 'Yes'
        ELSE 'No'
  END AS "attributableQE"
FROM "SWB_ecological_quality_elements" a
ORDER BY a.field1, ...;

I know we can rewrite the query in a better and more efficient way but before doing that we would like to understand the root cause of the poor performance on Ubuntu.

SWB_ecological_quality_elements and swaterBodyCode are views. What we suspect is that on Windows server the inner query is executed using indexing or caching while on Ubuntu  a full scan is done. The postgresql.conf files are quite similar, what can we check ?

UPDATE 1

I tuned the memory as suggested by PgTune but it was useless, same poor performance. I executed the query with Analyze, the timing result looks weird but I'm not an expert.

"  Functions: 1499"
"  Options: Inlining true, Optimization true, Expressions true,         Deforming true"
"  Timing: Generation 101.424 ms, Inlining 103.476 ms, Optimization 10402.780 ms, Emission 6866.288 ms, Total 17473.968 ms"
"Execution Time: 18005.457 ms"

UPDATE 2

Setting jit to false cause an incredible performance boost on the query execute on the Linux server. Don't know anything about jit and cannot figure out why it behaves so differently on Windows (Postgresql 14.4) and on Linux (Postgresql 14.5), but others noticed its weird effects as can be read here: Handling performance problems with jit in postgres 12.
Any explanation ?


问:
How to use same .arb file for multiple language codes with Flutter?
Countries like Norway have a lot of different language codes. Is there a way to use the same translation/.arb file for multiple language codes or do I have to create 7 identical files? Which will be a pain to update later.

Examples of language codes for Norwegian:
[no, no_NO, nb, nb_NO, nb_SJ, nn, nn_NO]


问:
How to use date_format when using JPQL/JPA to do the sum group by month from column date
I have to get the total price in month from a date(LocalDate) yy-mm-dd with jpql query but i can't do it
with jpql  with function : function('date_format',p.date,'%Y-%m')

```<code>//in the table of entity i have:
public class Reservation {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private double price;
@ManyToOne @JoinColumn(name="userId" )
public User  user;
private LocalDate date;
private boolean confirmed;}
</code>```

the class where i will put the result

```<code>public class MonthIncomes {
private LocalDate date ;
private double price;

     public MonthIncomes (LocalDate date,double price){

           this. date=  date;
           this.price = price;

         }

//what i do in repository

public interface ReservationRepo extends JpaRepository<Reservation, Long> {
@Query(value = "select new com.food.dto.MonthIncomes( function('date_format',date,'%Y-%m'),SUM(p.price)) from Reservation p group by function('date_format',p.date,'%Y-%m')" )

public List<MonthIncomes> getIncomeByMonth();}`
</code>```

Body:
I have to get the total price in month from a date(LocalDate) yy-mm-dd with jpql query but i can't do it
with jpql  with function : function('date_format',p.date,'%Y-%m')

//in the table of entity i have:
public class Reservation {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private double price;
@ManyToOne @JoinColumn(name="userId" )
public User  user;
private LocalDate date;
private boolean confirmed;}

the class where i will put the result

public class MonthIncomes {
private LocalDate date ;
private double price;

     public MonthIncomes (LocalDate date,double price){

           this. date=  date;
           this.price = price;

         }

//what i do in repository

public interface ReservationRepo extends JpaRepository<Reservation, Long> {
@Query(value = "select new com.food.dto.MonthIncomes( function('date_format',date,'%Y-%m'),SUM(p.price)) from Reservation p group by function('date_format',p.date,'%Y-%m')" )

public List<MonthIncomes> getIncomeByMonth();}`


问:
Prevent Knockout binding with invalid value
In one of my blades, there was an infoBox that was no longer needed. I deleted it in the js file. But I forgot to check the corresponding HTML file, which contains its original date binding.

Html looks like this:

```<code><div data-bind="pcControl: myInfoBox"></div>
</code>```

So myInfoBox is no longer a valid expression because it's deleted. And this div causes the blade to crash. But the error is not detected until I launch a local instance.

My question is how I can check against cases like this(invalid binding value) with a simple build cmd or something, without actually launch a local instance to see the KO error.

I set the "npm run build" cmd to contain following contents:

```<code>"build": "msbuild.exe ./MyExtension.csproj /m /p:RunBundlerInDevMode=true /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly"
</code>```

Body:
In one of my blades, there was an infoBox that was no longer needed. I deleted it in the js file. But I forgot to check the corresponding HTML file, which contains its original date binding.

Html looks like this:

So myInfoBox is no longer a valid expression because it's deleted. And this div causes the blade to crash. But the error is not detected until I launch a local instance.

My question is how I can check against cases like this(invalid binding value) with a simple build cmd or something, without actually launch a local instance to see the KO error.

I set the "npm run build" cmd to contain following contents:

"build": "msbuild.exe ./MyExtension.csproj /m /p:RunBundlerInDevMode=true /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly"


问:
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use technicians.set() instead
I keep getting this very same type error even though I am using set. Can someone maybe point out what I'm doing wrong in my api endpoint?

views.py

```<code>@require_http_methods(["GET", "POST"])
def api_requerimientos(request):
    if request.method == "GET":
        requerimientos = FormularioCliente.objects.all()
        return JsonResponse(
            {"requerimientos": requerimientos},
            encoder=FormularioClienteEncoder,
        )
    elif request.method == "POST":
        print("POST REQUEST HIT")
        try:
            content = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("Invalid JSON in request body")

        requerimiento = FormularioCliente(**content)  # Create a new FormularioCliente object
        if "technicians" in content and isinstance(content["technicians"], list):
            try:
                technicians_id_list = content["technicians"]
                technicians = Technician.objects.filter(employee_number__in=technicians_id_list)
                requerimiento.technicians.set(technicians)
                requerimiento.save()
                print('requerimiento:', requerimiento)
            except Technician.DoesNotExist:
                pass
        requerimiento.save()  # Save the object to the database
</code>```

models.py

```<code>class FormularioCliente(models.Model):

    empresa = models.CharField(max_length=21, null=True, unique=True)
    titulo = models.CharField(max_length=66)
    descripcion = models.CharField(max_length=66)
    enlace = models.URLField(null=True)
    tipo = models.CharField(max_length=17, choices=TIPO_REQUIRIMIENTO, default="tecnologia")
    date = models.DateField(null=True, auto_now_add=True)
    time = models.TimeField(null=True, auto_now_add=True)
    entrega = models.DateField(null=True)
    finished = models.CharField(max_length=19, choices=TIPO_FINALIZACION, default="Abierto")
    technicians = models.ManyToManyField(Technician, blank=True)
    special_hours = models.SmallIntegerField(default=0)
    regular_hours = models.PositiveSmallIntegerField(default=1)
    total_hours = models.SmallIntegerField(default=1)
    importancia = models.PositiveSmallIntegerField(default=1)
    file = models.FileField(upload_to='files', blank=True)
    updated = models.DateField(auto_now=True)

    def __str__(self):
        return f'{self.titulo}: {self.descripcion} @ {self.date}'

    def technicians_as_json(self):
        return list(self.technicians.all().values())
</code>```
```<code>class Technician(models.Model):
    name = models.TextField()
    employee_number = models.SmallIntegerField(unique=True, primary_key=True)

    def __str__(self):
        return self.name + " - " + str(self.employee_number)
</code>```

encoders.py

```<code>class TechnicianEncoder(ModelEncoder):
    model = Technician
    properties = ["name", "employee_number"]

class FormularioClienteEncoder(ModelEncoder):
    model = FormularioCliente
    properties = [
        "id",
        "empresa",
        "titulo",
        "descripcion",
        # "user",
        "enlace",
        # "tipo",
        # "File",
        "tipo",
        "date",
        "time",
        "entrega",
        "finished",
        "technicians",  # <-- Add this
        "special_hours",
        "regular_hours",
        "total_hours",
        "importancia",
        "updated",
    ]

    encoders = {"technicians": TechnicianEncoder()}
</code>```

I also tried to loop through technicians queryset and add it to the instance one by one as well via the add() method but that also didn't work.

I even tried this:

```<code>techs = list(requerimiento.technicians.filter(employee_number__in=technicians_id_list).all())

requerimiento.technicians.set(techs)

</code>```

None of it worked

Body:
I keep getting this very same type error even though I am using set. Can someone maybe point out what I'm doing wrong in my api endpoint?

views.py

@require_http_methods(["GET", "POST"])
def api_requerimientos(request):
    if request.method == "GET":
        requerimientos = FormularioCliente.objects.all()
        return JsonResponse(
            {"requerimientos": requerimientos},
            encoder=FormularioClienteEncoder,
        )
    elif request.method == "POST":
        print("POST REQUEST HIT")
        try:
            content = json.loads(request.body)
        except json.JSONDecodeError:
            return HttpResponseBadRequest("Invalid JSON in request body")

        requerimiento = FormularioCliente(**content)  # Create a new FormularioCliente object
        if "technicians" in content and isinstance(content["technicians"], list):
            try:
                technicians_id_list = content["technicians"]
                technicians = Technician.objects.filter(employee_number__in=technicians_id_list)
                requerimiento.technicians.set(technicians)
                requerimiento.save()
                print('requerimiento:', requerimiento)
            except Technician.DoesNotExist:
                pass
        requerimiento.save()  # Save the object to the database

models.py

class FormularioCliente(models.Model):

    empresa = models.CharField(max_length=21, null=True, unique=True)
    titulo = models.CharField(max_length=66)
    descripcion = models.CharField(max_length=66)
    enlace = models.URLField(null=True)
    tipo = models.CharField(max_length=17, choices=TIPO_REQUIRIMIENTO, default="tecnologia")
    date = models.DateField(null=True, auto_now_add=True)
    time = models.TimeField(null=True, auto_now_add=True)
    entrega = models.DateField(null=True)
    finished = models.CharField(max_length=19, choices=TIPO_FINALIZACION, default="Abierto")
    technicians = models.ManyToManyField(Technician, blank=True)
    special_hours = models.SmallIntegerField(default=0)
    regular_hours = models.PositiveSmallIntegerField(default=1)
    total_hours = models.SmallIntegerField(default=1)
    importancia = models.PositiveSmallIntegerField(default=1)
    file = models.FileField(upload_to='files', blank=True)
    updated = models.DateField(auto_now=True)

    def __str__(self):
        return f'{self.titulo}: {self.descripcion} @ {self.date}'

    def technicians_as_json(self):
        return list(self.technicians.all().values())

class Technician(models.Model):
    name = models.TextField()
    employee_number = models.SmallIntegerField(unique=True, primary_key=True)

    def __str__(self):
        return self.name + " - " + str(self.employee_number)

encoders.py

class TechnicianEncoder(ModelEncoder):
    model = Technician
    properties = ["name", "employee_number"]

class FormularioClienteEncoder(ModelEncoder):
    model = FormularioCliente
    properties = [
        "id",
        "empresa",
        "titulo",
        "descripcion",
        # "user",
        "enlace",
        # "tipo",
        # "File",
        "tipo",
        "date",
        "time",
        "entrega",
        "finished",
        "technicians",  # <-- Add this
        "special_hours",
        "regular_hours",
        "total_hours",
        "importancia",
        "updated",
    ]

    encoders = {"technicians": TechnicianEncoder()}

I also tried to loop through technicians queryset and add it to the instance one by one as well via the add() method but that also didn't work.

I even tried this:

techs = list(requerimiento.technicians.filter(employee_number__in=technicians_id_list).all())

requerimiento.technicians.set(techs)

None of it worked


问:
gstreamer failed queueing buffer while recording video on ubuntu 20.04
I am new to the gst-launch-1.0 tool. In our project, we have upgraded Ubuntu 18.04 kernel 4.15.0-142-generic to Ubuntu 20.04 is 5.4.0-135-generic. gst-launch-1.0 version is 1.14.5(GStreamer 1.14.5), it is the same for both Operating Systems```</p>
<p>We are using the gst-launch-1.0 for video recording, I was an able to record a video with the below command on ubuntu 18.04, but the same command is not working on Ubuntu 20.04:</p>
```Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
/GstPipeline:pipeline0/GstV4l2Src:v4l2src0.GstPad:src: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)BGR, colorimetry=(string)sRGB, interlace-mode=(string)progressive
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:src: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)I420, interlace-mode=(string)progressive
Redistribute latency...
/GstPipeline:pipeline0/GstX264Enc:x264enc0.GstPad:sink: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)I420, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:sink: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)BGR, colorimetry=(string)sRGB, interlace-mode=(string)progressive
```
<p>After setting export GST_DEBUG=5 below is last part of the log:</p>
```0:00:01.113209286  1373 0x55b5f70d2d20 DEBUG         v4l2bufferpool gstv4l2bufferpool.c:1464:gst_v4l2_buffer_pool_release_buffer:<v4l2src0:pool:src> release buffer 0x7f124417e360
0:00:01.113238267  1373 0x55b5f70d2d20 ERROR          v4l2allocator gstv4l2allocator.c:1269:gst_v4l2_allocator_qbuf:<v4l2src0:pool:src:allocator> failed queueing buffer 0: Invalid request descriptor
0:00:01.113260991  1373 0x55b5f70d2d20 ERROR         v4l2bufferpool gstv4l2bufferpool.c:1196:gst_v4l2_buffer_pool_qbuf:<v4l2src0:pool:src> could not queue a buffer 0
0:00:01.113281859  1373 0x55b5f70d2d20 DEBUG        GST_PERFORMANCE gstbufferpool.c:1309:default_release_buffer:<v4l2src0:pool:src> discarding buffer 0x7f124417e360: memory tag set
0:00:01.113306708  1373 0x55b5f70d2d20 DEBUG             GST_MEMORY gstmemory.c:88:_gst_memory_free: free memory 0x7f1244178150
0:00:01.113328592  1373 0x55b5f70d2d20 DEBUG               fdmemory gstfdmemory.c:74:gst_fd_mem_free: 0x7f1244178150: freed
0:00:01.113352970  1373 0x55b5f70d2d20 DEBUG             GST_MEMORY gstmemory.c:88:_gst_memory_free: free memory 0x55b5f7122600
0:00:01.113373026  1373 0x55b5f70d2d20 DEBUG               fdmemory gstfdmemory.c:74:gst_fd_mem_free: 0x55b5f7122600: freed
0:00:01.113412613  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4323:gst_pad_chain_data_unchecked:<x264enc0:sink> calling chainfunction &gst_video_encoder_chain with buffer buffer: 0x55b5f712dc60, pts 0:00:00.234978960, dts 99:99:99.999999999, dur 0:00:00.033333333, size 233632, offset 3, offset_end 4, flags 0x0
0:00:01.114983356  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4329:gst_pad_chain_data_unchecked:<x264enc0:sink> called chainfunction &gst_video_encoder_chain with buffer 0x55b5f712dc60, returned ok
0:00:01.115015593  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4329:gst_pad_chain_data_unchecked:<videoconvert0:sink> called chainfunction &gst_base_transform_chain with buffer 0x55b5f712d900, returned ok
0:00:01.115046926  1373 0x55b5f70d2d20 DEBUG                basesrc gstbasesrc.c:2519:gst_base_src_get_range:<v4l2src0> calling create offset 18446744073709551615 length 4096, time 0
0:00:01.115070231  1373 0x55b5f70d2d20 DEBUG         v4l2bufferpool gstv4l2bufferpool.c:1386:gst_v4l2_buffer_pool_acquire_buffer:<v4l2src0:pool:src> acquire
```

Please suggest the changes required in gst-launch-1.0 command option to record the video.

Body:
I am new to the gst-launch-1.0 tool. In our project, we have upgraded Ubuntu 18.04 kernel 4.15.0-142-generic to Ubuntu 20.04 is 5.4.0-135-generic. gst-launch-1.0 version is 1.14.5(GStreamer 1.14.5), it is the same for both Operating Systems```

We are using the gst-launch-1.0 for video recording, I was an able to record a video with the below command on ubuntu 18.04, but the same command is not working on Ubuntu 20.04:

Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
/GstPipeline:pipeline0/GstSplitMuxSink:splitmuxsink0/GstFileSink:sink: async = false
/GstPipeline:pipeline0/GstV4l2Src:v4l2src0.GstPad:src: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)BGR, colorimetry=(string)sRGB, interlace-mode=(string)progressive
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:src: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)I420, interlace-mode=(string)progressive
Redistribute latency...
/GstPipeline:pipeline0/GstX264Enc:x264enc0.GstPad:sink: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)I420, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:sink: caps = video/x-raw, width=(int)394, height=(int)392, framerate=(fraction)30/1, format=(string)BGR, colorimetry=(string)sRGB, interlace-mode=(string)progressive

After setting export GST_DEBUG=5 below is last part of the log:

0:00:01.113209286  1373 0x55b5f70d2d20 DEBUG         v4l2bufferpool gstv4l2bufferpool.c:1464:gst_v4l2_buffer_pool_release_buffer:<v4l2src0:pool:src> release buffer 0x7f124417e360
0:00:01.113238267  1373 0x55b5f70d2d20 ERROR          v4l2allocator gstv4l2allocator.c:1269:gst_v4l2_allocator_qbuf:<v4l2src0:pool:src:allocator> failed queueing buffer 0: Invalid request descriptor
0:00:01.113260991  1373 0x55b5f70d2d20 ERROR         v4l2bufferpool gstv4l2bufferpool.c:1196:gst_v4l2_buffer_pool_qbuf:<v4l2src0:pool:src> could not queue a buffer 0
0:00:01.113281859  1373 0x55b5f70d2d20 DEBUG        GST_PERFORMANCE gstbufferpool.c:1309:default_release_buffer:<v4l2src0:pool:src> discarding buffer 0x7f124417e360: memory tag set
0:00:01.113306708  1373 0x55b5f70d2d20 DEBUG             GST_MEMORY gstmemory.c:88:_gst_memory_free: free memory 0x7f1244178150
0:00:01.113328592  1373 0x55b5f70d2d20 DEBUG               fdmemory gstfdmemory.c:74:gst_fd_mem_free: 0x7f1244178150: freed
0:00:01.113352970  1373 0x55b5f70d2d20 DEBUG             GST_MEMORY gstmemory.c:88:_gst_memory_free: free memory 0x55b5f7122600
0:00:01.113373026  1373 0x55b5f70d2d20 DEBUG               fdmemory gstfdmemory.c:74:gst_fd_mem_free: 0x55b5f7122600: freed
0:00:01.113412613  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4323:gst_pad_chain_data_unchecked:<x264enc0:sink> calling chainfunction &gst_video_encoder_chain with buffer buffer: 0x55b5f712dc60, pts 0:00:00.234978960, dts 99:99:99.999999999, dur 0:00:00.033333333, size 233632, offset 3, offset_end 4, flags 0x0
0:00:01.114983356  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4329:gst_pad_chain_data_unchecked:<x264enc0:sink> called chainfunction &gst_video_encoder_chain with buffer 0x55b5f712dc60, returned ok
0:00:01.115015593  1373 0x55b5f70d2d20 DEBUG         GST_SCHEDULING gstpad.c:4329:gst_pad_chain_data_unchecked:<videoconvert0:sink> called chainfunction &gst_base_transform_chain with buffer 0x55b5f712d900, returned ok
0:00:01.115046926  1373 0x55b5f70d2d20 DEBUG                basesrc gstbasesrc.c:2519:gst_base_src_get_range:<v4l2src0> calling create offset 18446744073709551615 length 4096, time 0
0:00:01.115070231  1373 0x55b5f70d2d20 DEBUG         v4l2bufferpool gstv4l2bufferpool.c:1386:gst_v4l2_buffer_pool_acquire_buffer:<v4l2src0:pool:src> acquire

Please suggest the changes required in gst-launch-1.0 command option to record the video.


问:
When checking the country code in iOS, do I have to check both two and three letter codes?
Background

In my app I use CallKit, only to check if there is an ongoing call, and after adding that feature, my app got rejected because CallKit has been blocked in China:

Recently, the Chinese Ministry of Industry and Information Technology (MIIT) requested that CallKit functionality be deactivated in all apps available on the China App Store.

I looked for a way to fix this, apparently it's OK to check the phone's country code and just not use CallKit if it's in China.

My question

In all examples I found for doing this – e.g. Disabling Callkit from China Store Best Approach – the phone's country code was compared against both "CN" and "CHN".

Why compare to three letter codes in addition to two letter codes?
I mean, the country code comes from iOS, it ought to be well defined what comes from that source.

I have tried comparing both two and three letter codes, but so far only come across two letter codes and I've only seen two letter codes in the docs – but I couldn't find a definite answer in the docs either.


问:
insert value txt file into mysql laravel 6
how can I insert value from my input file.txt like this to MySQL, these [example image] (https://i.stack.imgur.com/v16fi.png).
and I just need atm_id, name_atm, ip, and status agent_connection
my code is like

```<code>`   $data = $request->file('file');
        $filetmp = $data->getRealPath();
        $filedata = file_get_contents($filetmp);
        $lines = explode("\n", $filedata);
        $lines=array_slice($lines,
        array_keys(
         array_filter($lines,
          function($item){
          return strpos($item,'PAR') ;
          }))[0]
         );
        $arrays = array_map(function($array) {
            $columns = ['atm_id', 'name_atm', 'ip', 'agent_connection',];
            return array_combine($columns, array_map('trim', $array));
        }, array_chunk($lines, 5));
        dd($arrays);`
</code>```

I expect I can insert just

atm_id = AT8502 atm_name = example ip = 10.51.7.50 agent_connection = complete

as much as data on txt file.

Body:
how can I insert value from my input file.txt like this to MySQL, these [example image] (https://i.stack.imgur.com/v16fi.png).
and I just need atm_id, name_atm, ip, and status agent_connection
my code is like

`   $data = $request->file('file');
        $filetmp = $data->getRealPath();
        $filedata = file_get_contents($filetmp);
        $lines = explode("\n", $filedata);
        $lines=array_slice($lines,
        array_keys(
         array_filter($lines,
          function($item){
          return strpos($item,'PAR') ;
          }))[0]
         );
        $arrays = array_map(function($array) {
            $columns = ['atm_id', 'name_atm', 'ip', 'agent_connection',];
            return array_combine($columns, array_map('trim', $array));
        }, array_chunk($lines, 5));
        dd($arrays);`

I expect I can insert just

atm_id = AT8502 atm_name = example ip = 10.51.7.50 agent_connection = complete

as much as data on txt file.


问:
Python- ModuleNotFoundError: No module named 'PCM'
I am doing a voice detection project on Python3.10. However, I cannot run my code it said: "ModuleNotFoundError: No module named 'PCM" (line 7)  I tried to pip install PCM and pip install confusion-matrix again and again but it's still the same. I don't know how to fix it; hopefully, someone can help me. Thank you very much!

Here is my code

```<code>####### IMPORTS #############
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report
from PCM.PCM import plot_confusion_matrix
import pickle

##### Loading saved csv ##############
df = pd.read_pickle("final_audio_data_csv/audio_data.csv")

####### Making our data training-ready
X = df["feature"].values
X = np.concatenate(X, axis=0).reshape(len(X), 40)

y = np.array(df["class_label"].tolist())

####### train test split ############
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

##### Training ############

logit_reg = LogisticRegression(max_iter=10000)
logit_reg.fit(X_train, y_train)
score = logit_reg.score(X_test, y_test)
print("Model Score: \n")
print(score)

#### Evaluating our model ###########
print("Model Classification Report: \n")

y_pred = logit_reg.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(classification_report(y_test, y_pred))
plot_confusion_matrix(cm, classes=["Does not have WW", "Has WW"])

#### Save the model
pickle.dump(logit_reg, open('saved_model/WWD_ML.txt', 'wb'))

'''
To load the model again run this:

>>> model = pickle.load(open('saved_model/WWD_ML.txt', 'rb'))
>>> model.predict(<-- your matrix -->) # to predict
'''
</code>```

here is my terminal

```<code>PS C:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master> & C:/Users/adamn/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/adamn/Documents/voice detection/WakeWordDetection-master/WakeWordDetection-master/UsingML.py"
Traceback (most recent call last):
  File "c:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master\UsingML.py", line 7, in <module>
    from PCM.PCM import plot_confusion_matrix
ModuleNotFoundError: No module named 'PCM'
PS C:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master>
</code>```

Body:
I am doing a voice detection project on Python3.10. However, I cannot run my code it said: "ModuleNotFoundError: No module named 'PCM" (line 7)  I tried to pip install PCM and pip install confusion-matrix again and again but it's still the same. I don't know how to fix it; hopefully, someone can help me. Thank you very much!

Here is my code

####### IMPORTS #############
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report
from PCM.PCM import plot_confusion_matrix
import pickle

##### Loading saved csv ##############
df = pd.read_pickle("final_audio_data_csv/audio_data.csv")

####### Making our data training-ready
X = df["feature"].values
X = np.concatenate(X, axis=0).reshape(len(X), 40)

y = np.array(df["class_label"].tolist())

####### train test split ############
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

##### Training ############

logit_reg = LogisticRegression(max_iter=10000)
logit_reg.fit(X_train, y_train)
score = logit_reg.score(X_test, y_test)
print("Model Score: \n")
print(score)

#### Evaluating our model ###########
print("Model Classification Report: \n")

y_pred = logit_reg.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(classification_report(y_test, y_pred))
plot_confusion_matrix(cm, classes=["Does not have WW", "Has WW"])

#### Save the model
pickle.dump(logit_reg, open('saved_model/WWD_ML.txt', 'wb'))

'''
To load the model again run this:

>>> model = pickle.load(open('saved_model/WWD_ML.txt', 'rb'))
>>> model.predict(<-- your matrix -->) # to predict
'''

here is my terminal

PS C:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master> & C:/Users/adamn/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/adamn/Documents/voice detection/WakeWordDetection-master/WakeWordDetection-master/UsingML.py"
Traceback (most recent call last):
  File "c:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master\UsingML.py", line 7, in <module>
    from PCM.PCM import plot_confusion_matrix
ModuleNotFoundError: No module named 'PCM'
PS C:\Users\adamn\Documents\voice detection\WakeWordDetection-master\WakeWordDetection-master>


问:
CIImage pixelBuffer always return nil
I am doing some task to apply filter effect in to my WebRTC call, follow this tutorial:
https://developer.apple.com/documentation/vision/applying_matte_effects_to_people_in_images_and_video

Here is my code to convert:

```<code>func capturer(_ capturer: RTCVideoCapturer, didCapture frame: RTCVideoFrame) {
    let pixelBufferr = frame.buffer as! RTCCVPixelBuffer
    let pixelBufferRef = pixelBufferr.pixelBuffer

    if #available(iOS 15.0, *) {
      DispatchQueue.global().async {
        if let output = GreetingProcessor.shared.processVideoFrame(
          foreground: pixelBufferRef,
          background: self.vbImage) {
          print("new output: \(output) => \(output.pixelBuffer) + \(self.buffer(from: output))")
          guard let px = output.pixelBuffer else { return }
          let rtcPixelBuffer = RTCCVPixelBuffer(pixelBuffer: px)
          let i420buffer = rtcPixelBuffer.toI420()
          let newFrame = RTCVideoFrame(buffer: i420buffer, rotation: frame.rotation, timeStampNs: frame.timeStampNs)
          self.videoSource.capturer(capturer, didCapture: newFrame)
        }
      }
    }
  }
</code>```

THen here is how I apply effect:

```<code>func blendImages(
    background: CIImage,
    foreground: CIImage,
    mask: CIImage,
    isRedMask: Bool = false
  ) -> CIImage? {
    // scale mask
    let maskScaleX = foreground.extent.width / mask.extent.width
    let maskScaleY = foreground.extent.height / mask.extent.height
    let maskScaled = mask.transformed(by: __CGAffineTransformMake(maskScaleX, 0, 0, maskScaleY, 0, 0))

    // scale background
    let backgroundScaleX = (foreground.extent.width / background.extent.width)
    let backgroundScaleY = (foreground.extent.height / background.extent.height)
    let backgroundScaled = background.transformed(
      by: __CGAffineTransformMake(backgroundScaleX, 0, 0, backgroundScaleY, 0, 0))

    let blendFilter = isRedMask ? CIFilter.blendWithRedMask() : CIFilter.blendWithMask()
    blendFilter.inputImage = foreground
    blendFilter.backgroundImage = backgroundScaled
    blendFilter.maskImage = maskScaled

    return blendFilter.outputImage
  }
</code>```

The problem is output.pixelBuffer always nil, so I can not create RTCFrame to pass it again to delegate

Can someone help?

Title: CIImage pixelBuffer always return nil

Body:
I am doing some task to apply filter effect in to my WebRTC call, follow this tutorial:
https://developer.apple.com/documentation/vision/applying_matte_effects_to_people_in_images_and_video

Here is my code to convert:

func capturer(_ capturer: RTCVideoCapturer, didCapture frame: RTCVideoFrame) {
    let pixelBufferr = frame.buffer as! RTCCVPixelBuffer
    let pixelBufferRef = pixelBufferr.pixelBuffer

    if #available(iOS 15.0, *) {
      DispatchQueue.global().async {
        if let output = GreetingProcessor.shared.processVideoFrame(
          foreground: pixelBufferRef,
          background: self.vbImage) {
          print("new output: \(output) => \(output.pixelBuffer) + \(self.buffer(from: output))")
          guard let px = output.pixelBuffer else { return }
          let rtcPixelBuffer = RTCCVPixelBuffer(pixelBuffer: px)
          let i420buffer = rtcPixelBuffer.toI420()
          let newFrame = RTCVideoFrame(buffer: i420buffer, rotation: frame.rotation, timeStampNs: frame.timeStampNs)
          self.videoSource.capturer(capturer, didCapture: newFrame)
        }
      }
    }
  }

THen here is how I apply effect:

func blendImages(
    background: CIImage,
    foreground: CIImage,
    mask: CIImage,
    isRedMask: Bool = false
  ) -> CIImage? {
    // scale mask
    let maskScaleX = foreground.extent.width / mask.extent.width
    let maskScaleY = foreground.extent.height / mask.extent.height
    let maskScaled = mask.transformed(by: __CGAffineTransformMake(maskScaleX, 0, 0, maskScaleY, 0, 0))

    // scale background
    let backgroundScaleX = (foreground.extent.width / background.extent.width)
    let backgroundScaleY = (foreground.extent.height / background.extent.height)
    let backgroundScaled = background.transformed(
      by: __CGAffineTransformMake(backgroundScaleX, 0, 0, backgroundScaleY, 0, 0))

    let blendFilter = isRedMask ? CIFilter.blendWithRedMask() : CIFilter.blendWithMask()
    blendFilter.inputImage = foreground
    blendFilter.backgroundImage = backgroundScaled
    blendFilter.maskImage = maskScaled

    return blendFilter.outputImage
  }

The problem is output.pixelBuffer always nil, so I can not create RTCFrame to pass it again to delegate

Can someone help?


问:
In unity dots physics,is there any way to scale mesh collider?
In traditional physics engine,we can scale the mesh collider by changing the scale in Transform property.
What about in dots physics,I've tried adding the scale property but it doesn't work.

In traditional physics engine,we can scale the mesh collider by changing the scale in Transform property.
What about in dots physics,I've tried adding the scale property but it doesn't work.


问:
How to present horizontal data vertically in a datagrid either using backend SQL or in frontend vb.net
I have a data as follows :

```<code>No1 Name1 No2 Name2 No3 Name3
232 Sanp  453 Awerk 374 Wash
</code>```

I bring this to data table with following query:

```<code>select No1,Name1,No2,Name2,No3,Name3 from tbl_info
</code>```

Since I have 50 such columns I don't want to show it horizontally. There will be single record.
Need to display data in data grid in below format vertically for better view:

```<code>No1   232
Name1 Sanp
No2   453
Name2 Awerk
No3   374
Name3 Wash
</code>```

Body:
I have a data as follows :

No1 Name1 No2 Name2 No3 Name3
232 Sanp  453 Awerk 374 Wash

I bring this to data table with following query:

select No1,Name1,No2,Name2,No3,Name3 from tbl_info

Since I have 50 such columns I don't want to show it horizontally. There will be single record.
Need to display data in data grid in below format vertically for better view:

No1   232
Name1 Sanp
No2   453
Name2 Awerk
No3   374
Name3 Wash


问:
substract with phpspreedshet
I have a php front end for a database with expenses on a project.
I use phpspreadsheet to create reports from this database and until now everything worked great.
In the excel table I export three columns from the database table: type of expense, amount, date of expense.

The total amount for each type of expenses is entered in the table as a positive number and the quantities that are subtracted are entered as negative numbers - example: category of expense: travel costs, amount: 100, date | travel costs, amount: -10, date | travel costs, amount: -25, date, etc. In the excel template that I use with phpspreadsheet I created a fourth column 'balance'. In this column I substract the negative initial values from the starting amount that is positive and I end up with a excel table having four columns: travel costs, amount: 100, date, balance:100 | travel costs, amount: -10, date, balance:90 | travel costs, amount: -25, date, balance: 65 etc.

Until now it was simple because I knew the types of expenses - they were entered by me in the database so the users can only select between these predefined values and I got a sheet with multiple tables for each type of expense:

```<code>    $sql="SELECT type_expense, , date, amount FROM expenses where acronym = '" . $_SESSION['idproject'] . "' ORDER BY type_expense";
$rsSql=db_query($sql,$conn);

$baseRow = 17;
$r=0;
$sum=0;
while ($data2 = db_fetch_array($rsSql)){

    $row = $baseRow + $r;
    $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1);

if($data2['type_expense']=='travel costs'){

    $spreadsheet->getActiveSheet()->setCellValue('A' . $row, $r + 1)
        ->setCellValue('B' . $row, $data2['type_expense'])
        ->setCellValue('C' . $row, $data2['amount'])
        ->setCellValue('D' . $row, $data2['date']);

        $sum=$sum+$data2['amount'];

        $spreadsheet->getActiveSheet()->setCellValue('E'. $row , $sum);

        $r= $r+1;

    }

    }

$spreadsheet->getActiveSheet()->removeRow($baseRow - 1, 1);
</code>```

I use the same code for populating tables in the predefined sheet for the other two type of expenses: personnel cost and other expenses.

The problem is that now users need to define their own types of expenses so the code above could not work because I don't know how they define the type expense so I can use it in the if conditional inside the loop.
Also the sheet will be overcrowded with tables so I need to create a single table that define type of expense, date, amount and balance for all type of expenses - type of expense: travel costs, date, amount: 100, balance: 100 | type of expense: travel costs, date, amount: -10, balance: 90 | type of expense: personnel costs, amount: 10, date, balance:10 | type of expense: personnel costs, date, amount: -5, balance:5, etc

I tried with a conditional for all type of expenses as positive (this is the initial amount from where all the values are subtracted) but I get 0 in all the rows form the balance column.

I really need a suggestion where to go from here in order to have a single table with subtraction on each type of expenses.

Title: substract with phpspreedshet

Body:
I have a php front end for a database with expenses on a project.
I use phpspreadsheet to create reports from this database and until now everything worked great.
In the excel table I export three columns from the database table: type of expense, amount, date of expense.

The total amount for each type of expenses is entered in the table as a positive number and the quantities that are subtracted are entered as negative numbers - example: category of expense: travel costs, amount: 100, date | travel costs, amount: -10, date | travel costs, amount: -25, date, etc. In the excel template that I use with phpspreadsheet I created a fourth column 'balance'. In this column I substract the negative initial values from the starting amount that is positive and I end up with a excel table having four columns: travel costs, amount: 100, date, balance:100 | travel costs, amount: -10, date, balance:90 | travel costs, amount: -25, date, balance: 65 etc.

Until now it was simple because I knew the types of expenses - they were entered by me in the database so the users can only select between these predefined values and I got a sheet with multiple tables for each type of expense:

    $sql="SELECT type_expense, , date, amount FROM expenses where acronym = '" . $_SESSION['idproject'] . "' ORDER BY type_expense";
$rsSql=db_query($sql,$conn);

$baseRow = 17;
$r=0;
$sum=0;
while ($data2 = db_fetch_array($rsSql)){

    $row = $baseRow + $r;
    $spreadsheet->getActiveSheet()->insertNewRowBefore($row, 1);

if($data2['type_expense']=='travel costs'){

    $spreadsheet->getActiveSheet()->setCellValue('A' . $row, $r + 1)
        ->setCellValue('B' . $row, $data2['type_expense'])
        ->setCellValue('C' . $row, $data2['amount'])
        ->setCellValue('D' . $row, $data2['date']);

        $sum=$sum+$data2['amount'];

        $spreadsheet->getActiveSheet()->setCellValue('E'. $row , $sum);

        $r= $r+1;

    }

    }

$spreadsheet->getActiveSheet()->removeRow($baseRow - 1, 1);

I use the same code for populating tables in the predefined sheet for the other two type of expenses: personnel cost and other expenses.

The problem is that now users need to define their own types of expenses so the code above could not work because I don't know how they define the type expense so I can use it in the if conditional inside the loop.
Also the sheet will be overcrowded with tables so I need to create a single table that define type of expense, date, amount and balance for all type of expenses - type of expense: travel costs, date, amount: 100, balance: 100 | type of expense: travel costs, date, amount: -10, balance: 90 | type of expense: personnel costs, amount: 10, date, balance:10 | type of expense: personnel costs, date, amount: -5, balance:5, etc

I tried with a conditional for all type of expenses as positive (this is the initial amount from where all the values are subtracted) but I get 0 in all the rows form the balance column.

I really need a suggestion where to go from here in order to have a single table with subtraction on each type of expenses.


问:
Unexplainable behavior of .push_back for a vector<char> in functions
I am quite new to C++ and during solving a Codewars Kata I faced following problem.
I want to define a Variable of type std::vector with the name tmp2 in a function.
Add a char via push_back and return the value.

When I set a breakpoint at return(tmp2) and debug the code (MSVS2022), the debugger shows tmp2 as empty.

If I do the same operation in a void function the debugger shows tmp with 'c' as content

Here is my code:

```<code>#include <vector>
//turn on debugger
//set a breakpoint at return(tmp2) in function test2() and inspect tmp2

void test()
{
    std::vector<char> tmp;
    tmp.push_back('c'); //tmp holds 'c'
}

std::vector<char> test2()
{
    std::vector<char> tmp2;
    tmp2.push_back('c');
    return(tmp2);//tmp2 does not contain 'c'
}

int main()
{
    test();
    std::vector<char> x = test2();
}
</code>```

Could someone please tell me, where I am wrong?
Thanks in advance.

Regs
Marcus

I have tried to clean my project.
But I cannot find out where I am wrong.
An explanation would be very helpful.

Body:
I am quite new to C++ and during solving a Codewars Kata I faced following problem.
I want to define a Variable of type std::vector with the name tmp2 in a function.
Add a char via push_back and return the value.

When I set a breakpoint at return(tmp2) and debug the code (MSVS2022), the debugger shows tmp2 as empty.

If I do the same operation in a void function the debugger shows tmp with 'c' as content

Here is my code:

#include <vector>
//turn on debugger
//set a breakpoint at return(tmp2) in function test2() and inspect tmp2

void test()
{
    std::vector<char> tmp;
    tmp.push_back('c'); //tmp holds 'c'
}

std::vector<char> test2()
{
    std::vector<char> tmp2;
    tmp2.push_back('c');
    return(tmp2);//tmp2 does not contain 'c'
}

int main()
{
    test();
    std::vector<char> x = test2();
}

Could someone please tell me, where I am wrong?
Thanks in advance.

Regs
Marcus

I have tried to clean my project.
But I cannot find out where I am wrong.
An explanation would be very helpful.


问:
Any solution regarding sending a file to IBM MQ
Good afternoon all, I have an issue with IBM MQ, I'm supposed to use JMS to connect to a defined queue then send an XML file to the defined queue. Any help with this problem is gladly appreciated.

In this image it shows that no message is received even though in eclipse IDE it states other wise:

I have a coded application that should work it sends and receives a message the problem is that when I check my IBM MQ explorer and my linux MQ server  nothing appears so I'm not sure if its the server configurations that are wrong.

Here is the code I was referring to :

package mqtest;
import javax.jms.Destination;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class JmsIOPutGet {

    // System exit status value (assume unset value to be 1)
    private static int status = 1;

    // Create variables for the connection to MQ
    private static final String HOST = "13.246.126.217"; // Host name or IP address
    private static final int PORT = 1416; // Listener port for your queue manager
    private static final String CHANNEL = "DEV.APP.SVRCONN"; // Channel name
    private static final String QMGR = "qm5"; // Queue manager name
    private static final String APP_USER = "mqm"; // Windows user name that application uses to connect to MQ
    private static final String APP_PASSWORD = "Kion2018"; // Windows user password associated with APP_USER
    private static final String QUEUE_NAME = "Q2"; // Queue that the application uses to put and get messages to and from

    /**
     * Main method
     *
     * @param args
     */
    public static void main(String[] args) {

        // Variables
        JMSContext context = null;
        Destination destination = null;
        JMSProducer producer = null;
        JMSConsumer consumer = null;

        try {
            // Create a connection factory
            JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
            JmsConnectionFactory cf = ff.createConnectionFactory();

            // Set the properties
            cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, HOST);
            cf.setIntProperty(WMQConstants.WMQ_PORT, PORT);
            cf.setStringProperty(WMQConstants.WMQ_CHANNEL, CHANNEL);
            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
            cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, QMGR);
            cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "JmsPutGet (JMS)");
            cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
            cf.setStringProperty(WMQConstants.USERID, APP_USER);
            cf.setStringProperty(WMQConstants.PASSWORD, APP_PASSWORD);
            //cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "*TLS12");

            // Create JMS objects
            context = cf.createContext();
            destination = context.createQueue("queue:///" + QUEUE_NAME);

            // Read given file
            File myObj = new File("C:\\Users\\Lesego\\OneDrive\\Documents\\Test Files\\application.xml");
            Scanner myReader = new Scanner(myObj);
            String msg = "";
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                msg = msg + data;
            }
            myReader.close();
            TextMessage message = context.createTextMessage(msg);
            producer = context.createProducer();
            producer.send(destination, message);
            System.out.println("Sent message:\n" + message);

            consumer = context.createConsumer(destination); // autoclosable
            String receivedMessage = consumer.receiveBody(String.class, 15000); // in ms or 15 seconds

            System.out.println("\nReceived message:\n" + receivedMessage);

            recordSuccess();
        } catch (JMSException jmsex) {
            recordFailure(jmsex);
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
            e.printStackTrace();
        }

        System.exit(status);

    } // end main()

    /**
     * Record this run as successful.
     */
    private static void recordSuccess() {
        System.out.println("SUCCESS");
        status = 0;
        return;
    }

    /**
     * Record this run as failure.
     *
     * @param ex
     */
    private static void recordFailure(Exception ex) {
        if (ex != null) {
            if (ex instanceof JMSException) {
                processJMSException((JMSException) ex);
            } else {
                System.out.println(ex);
            }
        }
        System.out.println("FAILURE");
        status = -1;
        return;
    }

    /**
     * Process a JMSException and any associated inner exceptions.
     *
     * @param jmsex
     */
    private static void processJMSException(JMSException jmsex) {
        System.out.println(jmsex);
        Throwable innerException = jmsex.getLinkedException();
        if (innerException != null) {
            System.out.println("Inner exception(s):");
        }
        while (innerException != null) {
            System.out.println(innerException);
            innerException = innerException.getCause();
        }
        return;
    }
```


问:
How do you prevent that a button is clicked too fast again?
I need to detect a mouse click to create a wait for a button so you can't spam. Is there a better way, and if not can you tell me how?

I don't know whether to search for a button pause or a mouse click, or if it would be the right way.


问:
How to update xamarin app apk automatically?
I want to update my xamarin app automatically by clicking update button from my settings page. for testing purpose, i've added the apk file in the assets folder. but the launcher didn't work. I've followed this solution but didn't work. Help plz?

This my update button click code

```<code>            var cacheFile = Path.Combine(FileSystem.CacheDirectory, "App.apk");

            using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApp.Assets.App.apk"))
            using (var file = new FileStream(cacheFile, FileMode.Create, FileAccess.Write))
            {
                resource.CopyTo(file);
            }

            await Launcher.OpenAsync
                       (new OpenFileRequest()
                       {
                           File = new ReadOnlyFile(cacheFile)
                       }
             );
</code>```

AndroidManifest.xml

```<code>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

</code>```

Body:
I want to update my xamarin app automatically by clicking update button from my settings page. for testing purpose, i've added the apk file in the assets folder. but the launcher didn't work. I've followed this solution but didn't work. Help plz?

This my update button click code

            var cacheFile = Path.Combine(FileSystem.CacheDirectory, "App.apk");

            using (var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApp.Assets.App.apk"))
            using (var file = new FileStream(cacheFile, FileMode.Create, FileAccess.Write))
            {
                resource.CopyTo(file);
            }

            await Launcher.OpenAsync
                       (new OpenFileRequest()
                       {
                           File = new ReadOnlyFile(cacheFile)
                       }
             );

AndroidManifest.xml

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />


问:
Livewire how to revert input changes?
let say I got $foo in my component and I bind this property to an input wire:model="foo.{{ $index }}.column", I will do some checking everytime when user make changes on this input, how can I stop the update process or revert the input back to previous value? Method below wont work because after updating method it will still go to updated method, but I cant get previous value in updated method</p>
```<code>public $foo = [];

public function updatingFoo($value, $key)
{
    //checking
    if(true) {
       $previousValue = Arr::get($this->foo, $key);
       Arr::set($this->foo, $key, $previousValue);
    }
}
</code>```

Title: Livewire how to revert input changes?

Body:
let say I got $foo in my component and I bind this property to an input wire:model="foo.{{ $index }}.column", I will do some checking everytime when user make changes on this input, how can I stop the update process or revert the input back to previous value? Method below wont work because after updating method it will still go to updated method, but I cant get previous value in updated method

public $foo = [];

public function updatingFoo($value, $key)
{
    //checking
    if(true) {
       $previousValue = Arr::get($this->foo, $key);
       Arr::set($this->foo, $key, $previousValue);
    }
}