问:
Python Windows Service Erroring
I'm currently trying to create a Windows Service using a Python script :

```<code>import win32serviceutil
import time
import sys
import servicemanager
import win32service
import win32event
import win32service
import win32serviceutil
import time
from BIUtilities import script_execution
from abc import ABC,abstractmethod

class PythonService(win32serviceutil.ServiceFramework, ABC):

    _svc_name_ = "Parseltongue"
    _svc_display_name_ = "Parseltongue"
    _svc_description_ = "A service to run python scripts automatically"

    @classmethod
    def parse_command_line(cls):
        win32serviceutil.HandleCommandLine(cls)

    # * DO SOMETHING BEFORE SERVICE STOPS
    @abstractmethod
    def stop(self):
        pass

    # * DO SOMETHING AT SERVICE START
    @abstractmethod
    def start(self):
        pass

    # * MAIN FUNCTIONALITY
    @abstractmethod
    def main(self):
        pass

    # * CONSTRUCTOR
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)

        # * CREATE EVENT FOR SERVICE TO WAIT ON
        self.hWaitStop = win32event.CreateEvent(None, 0, 0,None)

    # * WHEN ASKED TO STOP :
    def SvcStop(self):
        self.stop()

        # * TELL SERVICE WE WILL BE STOPPING
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # * SET EVENT AT STOP
        win32event.SetEvent(self.hWaitStop)

    # * WHEN ASKED TO RUN :
    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)

        # * SET EVENT AT START
        self.start()
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        # * BEGIN LOOP THAT WAITS FOR COMMANDS
        self.main()

class Parseltongue(PythonService):

    _svc_name_ = "Parseltongue"
    _svc_display_name_ = "Parseltongue"
    _svc_description_ = "A service to run python scripts automatically"

    # * SET RUN CONDITION
    def start(self):
        self.isrunning =True

    # * OVERRIDE RUN CONDITION AT STOP
    def stop(self):
        self.isrunning =False

    # * MAIN FUNCTIONALITY
    def main(self):
        while self.isrunning:
            script_execution('test.py')
            time.sleep(5)

def initialize():
    # * FOR RUNNING OUR SCRIPT (THE SCRIPT IS THE ARG)
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonService)
        servicemanager.StartServiceCtrlDispatcher()
    # * EXTRA COMMANDS (install, remove, etc.)
    else:
        win32serviceutil.HandleCommandLine(PythonService)

# * SET SCRIPT RUNNING CONDITONS
if __name__ == '__main__':
    initialize()

</code>```

The above script was converted to an .exe using PyInstaller in the following manner in powershell:

```<code>python -m PyInstaller --runtime-tmpdir=. --onefile --hidden-import win32timezone myscript.py
</code>```

When the command to install the .exe is given, the service is installed correctly. But when I go to start the service, I get the following error:

```<code>Windows could not start the service on Local Computer. For more information, review the System Event Log. If this is a Non-Microsoft service, contact the service vendor, and refer to service specific error code 1
</code>```

And when I check the System Event Log, the following error shows in the log:

```<code>The event logging service encountered an error (5) while enabling publisher {0bf2fb94-7b60-4b4d-9766-e82f658df540} to channel Microsoft-Windows-Kernel-ShimEngine/Operational. This does not affect channel operation, but does affect the ability of the publisher to raise events to the channel. One common reason for this error is that the Provider is using ETW Provider Security and has not granted enable permissions to the Event Log service identity.
</code>```

My initial error with this service was the well-documented 1053 error (service can't run in timely manner). This error was fixed by copying C:\Python310\Lib\site-packages\pywin32_system32\pywintypes37.dll to C:\Python310\Lib\site-packages\win32\pywintypes37.dll and installing C:\Python310\Scripts\pywin32_postinstall.py . Both are solutions suggested here: all python windows service can not start{error 1053}. This fixed my 1053 error, but now the problem outlined above is plaguing me. Any help/insight would be greatly greatly appreciated.

TYIA!

Title: Python Windows Service Erroring

Body:
I'm currently trying to create a Windows Service using a Python script :

import win32serviceutil
import time
import sys
import servicemanager
import win32service
import win32event
import win32service
import win32serviceutil
import time
from BIUtilities import script_execution
from abc import ABC,abstractmethod

class PythonService(win32serviceutil.ServiceFramework, ABC):

    _svc_name_ = "Parseltongue"
    _svc_display_name_ = "Parseltongue"
    _svc_description_ = "A service to run python scripts automatically"

    @classmethod
    def parse_command_line(cls):
        win32serviceutil.HandleCommandLine(cls)

    # * DO SOMETHING BEFORE SERVICE STOPS
    @abstractmethod
    def stop(self):
        pass

    # * DO SOMETHING AT SERVICE START
    @abstractmethod
    def start(self):
        pass

    # * MAIN FUNCTIONALITY
    @abstractmethod
    def main(self):
        pass

    # * CONSTRUCTOR
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)

        # * CREATE EVENT FOR SERVICE TO WAIT ON
        self.hWaitStop = win32event.CreateEvent(None, 0, 0,None)

    # * WHEN ASKED TO STOP :
    def SvcStop(self):
        self.stop()

        # * TELL SERVICE WE WILL BE STOPPING
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # * SET EVENT AT STOP
        win32event.SetEvent(self.hWaitStop)

    # * WHEN ASKED TO RUN :
    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)

        # * SET EVENT AT START
        self.start()
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)

        # * BEGIN LOOP THAT WAITS FOR COMMANDS
        self.main()

class Parseltongue(PythonService):

    _svc_name_ = "Parseltongue"
    _svc_display_name_ = "Parseltongue"
    _svc_description_ = "A service to run python scripts automatically"

    # * SET RUN CONDITION
    def start(self):
        self.isrunning =True

    # * OVERRIDE RUN CONDITION AT STOP
    def stop(self):
        self.isrunning =False

    # * MAIN FUNCTIONALITY
    def main(self):
        while self.isrunning:
            script_execution('test.py')
            time.sleep(5)

def initialize():
    # * FOR RUNNING OUR SCRIPT (THE SCRIPT IS THE ARG)
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonService)
        servicemanager.StartServiceCtrlDispatcher()
    # * EXTRA COMMANDS (install, remove, etc.)
    else:
        win32serviceutil.HandleCommandLine(PythonService)

# * SET SCRIPT RUNNING CONDITONS
if __name__ == '__main__':
    initialize()

The above script was converted to an .exe using PyInstaller in the following manner in powershell:

python -m PyInstaller --runtime-tmpdir=. --onefile --hidden-import win32timezone myscript.py

When the command to install the .exe is given, the service is installed correctly. But when I go to start the service, I get the following error:

Windows could not start the service on Local Computer. For more information, review the System Event Log. If this is a Non-Microsoft service, contact the service vendor, and refer to service specific error code 1

And when I check the System Event Log, the following error shows in the log:

The event logging service encountered an error (5) while enabling publisher {0bf2fb94-7b60-4b4d-9766-e82f658df540} to channel Microsoft-Windows-Kernel-ShimEngine/Operational. This does not affect channel operation, but does affect the ability of the publisher to raise events to the channel. One common reason for this error is that the Provider is using ETW Provider Security and has not granted enable permissions to the Event Log service identity.

My initial error with this service was the well-documented 1053 error (service can't run in timely manner). This error was fixed by copying C:\Python310\Lib\site-packages\pywin32_system32\pywintypes37.dll to C:\Python310\Lib\site-packages\win32\pywintypes37.dll and installing C:\Python310\Scripts\pywin32_postinstall.py . Both are solutions suggested here: all python windows service can not start{error 1053}. This fixed my 1053 error, but now the problem outlined above is plaguing me. Any help/insight would be greatly greatly appreciated.

TYIA!


来源: stackexchange

问:
Passing data in PreviewProvider SwiftUI, ObservableObject class, ObservedObject
I guys, I have a class with some properties (class ReservationInfo). In my first screen (ReservationFormView) I create an instance of the class(myReservationInfo).
I pass the data with a NavigationLink to the second view (ReservationRecapView). It works all right, but I have a problem with the SwiftUI preview. How can I pass some example data to the preview provider?

```<code>class ReservationInfo: ObservableObject {

    @Published var customerName: String = ""
    @Published var surname : String = ""
    @Published var nPeople : Int = 1
    @Published var date = Date()

}
</code>```
```<code>struct ReservationFormView: View {

    @StateObject var myReservationInfo = ReservationInfo()
    @State private var showSecondView = false

    init() {
        UIStepper.appearance().setDecrementImage(UIImage(systemName: "minus"), for: .normal)
        UIStepper.appearance().setIncrementImage(UIImage(systemName: "plus"), for: .normal)
    }

    var body: some View {
        NavigationView{
            VStack(alignment: .center) {

                Text("Little lemon")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(Color.gray)
                    .multilineTextAlignment(.center)
                    .padding(.bottom, 10.0)

                Label("Reservation Form", systemImage: "fork.knife")
                    .foregroundColor(Color.gray)
                    .padding(.bottom, 30)

                VStack(alignment: .center, spacing: 30.0){

                    TextField("Type your name", text: $myReservationInfo.customerName, onEditingChanged: {print($0)})
                        .onChange(of: myReservationInfo.customerName, perform: { newValue in print(newValue)})
                        .onSubmit {
                            print("submitted")
                        }

                        .underlineTextField()

                    TextField("Type your surname", text: $myReservationInfo.surname)
                        .underlineTextField()

                    HStack(alignment: .center, spacing: 30.0){
                        Label("\(myReservationInfo.nPeople)", systemImage: "person.fill")
                            .font(.title2)
                        Stepper("N di persone", value: $myReservationInfo.nPeople , in: 1...20)
                            .labelsHidden()
                            .accentColor(.blue)
                    }
                    .padding(.top)

                    DatePicker(
                        "Select date",
                        selection: $myReservationInfo.date,
                        in: Date.now...,
                        displayedComponents: [.date, .hourAndMinute]
                    )
                    .onChange(of: myReservationInfo.date, perform: {date in print(date)})
                    .padding(.bottom, 20.0)
                }
                NavigationLink{
                    ReservationRecapView(myReservationInfo: myReservationInfo)
                } label: {
                Text("Avanti")
                    .padding(.horizontal, 70.0)
            }
            .padding(.vertical, 10)
            .background(Color.blue)
            .cornerRadius(10)
            .foregroundColor(.white)

            }

            .padding(.horizontal, 30.0)
            .padding(.bottom, 100.0)
            .environmentObject(myReservationInfo)
        }

    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ReservationFormView()
        }
    }
}

extension Color {
    static let darkPink = Color(red: 208 / 255, green: 45 / 255, blue: 208 / 255)
}

extension View {
    func underlineTextField() -> some View {
        self
            .autocorrectionDisabled(true)
            .overlay(Rectangle().frame(height: 2).padding(.top, 40))
            .foregroundColor(.blue)
    }
}
</code>```
```<code>struct ReservationRecapView: View {

    @ObservedObject var myReservationInfo : ReservationInfo

    var body: some View {
        VStack(alignment: .leading, spacing: 10.0){
            Text(myReservationInfo.customerName)
            Text(myReservationInfo.surname)
            Text("Number of people \(myReservationInfo.nPeople)")
            Text(myReservationInfo.date, style: .date)
            Text(myReservationInfo.date, style: .time)
        }.font(.title2)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ReservationRecapView(myReservationInfo: ReservationInfo())
    }
}
</code>```

I don't know how to pass date in the PreviewProvider

ContentLicense: CC BY-SA 4.0

Body:
I guys, I have a class with some properties (class ReservationInfo). In my first screen (ReservationFormView) I create an instance of the class(myReservationInfo).
I pass the data with a NavigationLink to the second view (ReservationRecapView). It works all right, but I have a problem with the SwiftUI preview. How can I pass some example data to the preview provider?

class ReservationInfo: ObservableObject {

    @Published var customerName: String = ""
    @Published var surname : String = ""
    @Published var nPeople : Int = 1
    @Published var date = Date()

}

struct ReservationFormView: View {

    @StateObject var myReservationInfo = ReservationInfo()
    @State private var showSecondView = false

    init() {
        UIStepper.appearance().setDecrementImage(UIImage(systemName: "minus"), for: .normal)
        UIStepper.appearance().setIncrementImage(UIImage(systemName: "plus"), for: .normal)
    }

    var body: some View {
        NavigationView{
            VStack(alignment: .center) {

                Text("Little lemon")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(Color.gray)
                    .multilineTextAlignment(.center)
                    .padding(.bottom, 10.0)

                Label("Reservation Form", systemImage: "fork.knife")
                    .foregroundColor(Color.gray)
                    .padding(.bottom, 30)

                VStack(alignment: .center, spacing: 30.0){

                    TextField("Type your name", text: $myReservationInfo.customerName, onEditingChanged: {print($0)})
                        .onChange(of: myReservationInfo.customerName, perform: { newValue in print(newValue)})
                        .onSubmit {
                            print("submitted")
                        }

                        .underlineTextField()

                    TextField("Type your surname", text: $myReservationInfo.surname)
                        .underlineTextField()

                    HStack(alignment: .center, spacing: 30.0){
                        Label("\(myReservationInfo.nPeople)", systemImage: "person.fill")
                            .font(.title2)
                        Stepper("N di persone", value: $myReservationInfo.nPeople , in: 1...20)
                            .labelsHidden()
                            .accentColor(.blue)
                    }
                    .padding(.top)

                    DatePicker(
                        "Select date",
                        selection: $myReservationInfo.date,
                        in: Date.now...,
                        displayedComponents: [.date, .hourAndMinute]
                    )
                    .onChange(of: myReservationInfo.date, perform: {date in print(date)})
                    .padding(.bottom, 20.0)
                }
                NavigationLink{
                    ReservationRecapView(myReservationInfo: myReservationInfo)
                } label: {
                Text("Avanti")
                    .padding(.horizontal, 70.0)
            }
            .padding(.vertical, 10)
            .background(Color.blue)
            .cornerRadius(10)
            .foregroundColor(.white)

            }

            .padding(.horizontal, 30.0)
            .padding(.bottom, 100.0)
            .environmentObject(myReservationInfo)
        }

    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ReservationFormView()
        }
    }
}

extension Color {
    static let darkPink = Color(red: 208 / 255, green: 45 / 255, blue: 208 / 255)
}

extension View {
    func underlineTextField() -> some View {
        self
            .autocorrectionDisabled(true)
            .overlay(Rectangle().frame(height: 2).padding(.top, 40))
            .foregroundColor(.blue)
    }
}

struct ReservationRecapView: View {

    @ObservedObject var myReservationInfo : ReservationInfo

    var body: some View {
        VStack(alignment: .leading, spacing: 10.0){
            Text(myReservationInfo.customerName)
            Text(myReservationInfo.surname)
            Text("Number of people \(myReservationInfo.nPeople)")
            Text(myReservationInfo.date, style: .date)
            Text(myReservationInfo.date, style: .time)
        }.font(.title2)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ReservationRecapView(myReservationInfo: ReservationInfo())
    }
}

I don't know how to pass date in the PreviewProvider


问:
How to load pages made in laravel in a wordpress site?
I have a wordpress site, it works with nginx, I am moving the front end to laravel but still using the wordpress admin. I am making this change little by little and at this moment I would only want the home to load laravel and the rest remains Wordpress, is this possible? is there any way?

I'm trying to add pages made in laravel to the wordpress site


问:
I can't read the body of an email
I'm using the laravel-imap package to read my PEC emails from a management system.

For the uninitiated, the PEC is the Certified Electronic Mail, "Posta Elettronica Certificata, (PEC)", it is the system that allows you to send e-mails with legal value equivalent to a registered letter with return receipt.

I can read the Subject thanks to the getSubject() method, I can count the number of attachments but I can't read the body of the email.

I also tried to use the getHTMLBody(), getTextBody() methods but I get nothing, i.e. I get a blank string.

I tried doing a

dd($message->getHTMLBody(true));

but I get null.

This is my code:

```<code>public function mail()
    {
        $oClient = Client::account('default');
        $oClient->connect();
        $folders = $oClient->getFolders();

        /** @var \Webklex\PHPIMAP\Folder $folder */
        foreach ($folders as $folder) {

            /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
            //$messages = $folder->messages()->all()->get();
            $messages = $folder->query()->since(now()->subDays(30))->get();

        }

        foreach($messages as $message){
            echo $message->getSubject().'<br />';
            echo 'Attachments: '.$message->getAttachments()->count().'<br />';
            echo $message->getHTMLBody(true);
        }
    }
</code>```

Can anyone help me please? I'm desperate.

Title: I can't read the body of an email

Body:
I'm using the laravel-imap package to read my PEC emails from a management system.

For the uninitiated, the PEC is the Certified Electronic Mail, "Posta Elettronica Certificata, (PEC)", it is the system that allows you to send e-mails with legal value equivalent to a registered letter with return receipt.

I can read the Subject thanks to the getSubject() method, I can count the number of attachments but I can't read the body of the email.

I also tried to use the getHTMLBody(), getTextBody() methods but I get nothing, i.e. I get a blank string.

I tried doing a

dd($message->getHTMLBody(true));

but I get null.

This is my code:

public function mail()
    {
        $oClient = Client::account('default');
        $oClient->connect();
        $folders = $oClient->getFolders();

        /** @var \Webklex\PHPIMAP\Folder $folder */
        foreach ($folders as $folder) {

            /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
            //$messages = $folder->messages()->all()->get();
            $messages = $folder->query()->since(now()->subDays(30))->get();

        }

        foreach($messages as $message){
            echo $message->getSubject().'
';
            echo 'Attachments: '.$message->getAttachments()->count().'
';
            echo $message->getHTMLBody(true);
        }
    }

Can anyone help me please? I'm desperate.


问:
Python result (list?) to docx for my Warehouse
I can't figure something out
The idea is to create an automatic warehouse label creator "template".
What is suposed to do is create a .docx document (using python-docx) with all the individual locations of an specific shelf within my warehouse (A real warehouse with forklifts and everything), so I can print them out from Microsoft Word.

This is the code I managed to work out so far:

```<code>from docx import Document

document = Document()

try:
    letter = input("Please select the row: ")
    rack = input("Please select the column from the row: ")

    amount_of_locations = input("Please insert the amount of locations in the selected row and column: ")

    amount_of_locations = int(amount_of_locations)

    for result in (range (1, amount_of_locations + 1)):
        label_list = (letter + rack + (" - ") + str(result))
        print(label_list)

except:
    print("Please select a numeric value to define the amount of locations")
    quit()

document.add_heading(label_list)

document.save("Labels For " + str(letter) + str(rack) + ".docx")
</code>```

[I was expecting the Word document to print out a list like the cmd did in this image]
(https://i.stack.imgur.com/cTefw.png)

But word will just "print" this, which is just: letter + rack + (" - ") + amount_of_locations

So basically what I want to happen is that the stuff that appears in cdm to appear exactly the same in word.

Sorry if I'm not using correct terms (Which I'm sure it's the case), but it is one of my first projects and should make the work I'm suposed to manually do a whole of a lot more easy and efficient.

Sorry again and thanks for your time
Any help is gladly appreciated :)

Body:
I can't figure something out
The idea is to create an automatic warehouse label creator "template".
What is suposed to do is create a .docx document (using python-docx) with all the individual locations of an specific shelf within my warehouse (A real warehouse with forklifts and everything), so I can print them out from Microsoft Word.

This is the code I managed to work out so far:

from docx import Document

document = Document()

try:
    letter = input("Please select the row: ")
    rack = input("Please select the column from the row: ")

    amount_of_locations = input("Please insert the amount of locations in the selected row and column: ")

    amount_of_locations = int(amount_of_locations)

    for result in (range (1, amount_of_locations + 1)):
        label_list = (letter + rack + (" - ") + str(result))
        print(label_list)

except:
    print("Please select a numeric value to define the amount of locations")
    quit()

document.add_heading(label_list)

document.save("Labels For " + str(letter) + str(rack) + ".docx")

[I was expecting the Word document to print out a list like the cmd did in this image]
(https://i.stack.imgur.com/cTefw.png)

But word will just "print" this, which is just: letter + rack + (" - ") + amount_of_locations

So basically what I want to happen is that the stuff that appears in cdm to appear exactly the same in word.

Sorry if I'm not using correct terms (Which I'm sure it's the case), but it is one of my first projects and should make the work I'm suposed to manually do a whole of a lot more easy and efficient.

Sorry again and thanks for your time
Any help is gladly appreciated :)


问:
Automatically set the assignee on an issue using guthub actions
I am trying to add some automation to my github project (the project feature, not a repo). I added a project for my user which I use to manage all my issues. I created a github action that always assigns issues and PRs to this project so I always have an overview over all todos.

Now I want another action. My project uses 4 statuses:

Backlog

Selected for Development

In Progress

Done

I want to automatically assign a user to an issue when the issue is moved into status "In Progress". The assignee should be the current user (= ${{ github.actor }}). So far this works.

on:
  issues:
    types:
      - opened
  pull_request:
    types:
      - opened

permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  add-to-project:
    name: Add to project
    runs-on: ubuntu-latest
    steps:
      - name: Add to project (issues and PRs)
        uses: actions/add-to-project@main
        with:
          project-url: https://github.com/users/sebastian-sommerfeld-io/projects/1
          github-token: ${{ secrets.GH_TOKEN_REPO_AND_PROJECT }}

  assign-issue-to-user:
    name: Assign to user
    runs-on: ubuntu-latest
    steps:
      - name: Assign issue to user
        uses: pozil/auto-assign-issue@v1
        # https://github.com/marketplace/actions/auto-assign-issue
        with:
          assignees: ${{ github.actor }}
          numOfAssignee: 1
          allowSelfAssign: true
          abortIfPreviousAssignees: true
```

Assigning the issue works (job assign-issue-to-user). But the assignee should only be set automatically, if the assignee field is empty (I do not want to override existing assignees) and if the issue is moved into the project status "In Progress". This if condition is the problem I cannot get my head around. The code above just always assigns the user when the issue is created. Regardless of any column change.

Body:
I am trying to add some automation to my github project (the project feature, not a repo). I added a project for my user which I use to manage all my issues. I created a github action that always assigns issues and PRs to this project so I always have an overview over all todos.

Now I want another action. My project uses 4 statuses:

Backlog

Selected for Development

In Progress

Done

I want to automatically assign a user to an issue when the issue is moved into status "In Progress". The assignee should be the current user (= ${{ github.actor }}). So far this works.

on:
  issues:
    types:
      - opened
  pull_request:
    types:
      - opened

permissions:
  contents: read
  issues: write
  pull-requests: write

jobs:
  add-to-project:
    name: Add to project
    runs-on: ubuntu-latest
    steps:
      - name: Add to project (issues and PRs)
        uses: actions/add-to-project@main
        with:
          project-url: https://github.com/users/sebastian-sommerfeld-io/projects/1
          github-token: ${{ secrets.GH_TOKEN_REPO_AND_PROJECT }}

  assign-issue-to-user:
    name: Assign to user
    runs-on: ubuntu-latest
    steps:
      - name: Assign issue to user
        uses: pozil/auto-assign-issue@v1
        # https://github.com/marketplace/actions/auto-assign-issue
        with:
          assignees: ${{ github.actor }}
          numOfAssignee: 1
          allowSelfAssign: true
          abortIfPreviousAssignees: true

Assigning the issue works (job assign-issue-to-user). But the assignee should only be set automatically, if the assignee field is empty (I do not want to override existing assignees) and if the issue is moved into the project status "In Progress". This if condition is the problem I cannot get my head around. The code above just always assigns the user when the issue is created. Regardless of any column change.


问:
renderAllRows: false still renders all rows
I am creating a table and have renderAllRows:false and it still renders all rows, giving me the 'performance tip:

*VM6606 handsontable.full.min.js:61 Performance tip: Handsontable rendered more than 1000 visible rows. Consider limiting the number of rendered rows by specifying the table height and/or turning off the "renderAllRows" option.
*
I don't know why it isn't working, and being a newbie at HOT, I don't know if placement is a problem, or some other issue.  Any help appreciated.

My data set has 18k rows, so I would LOVE to disable it, but it doesn't seem to work.

any ideas why it doesn't work?  Additionally, the readonly:true doesn't work either.

Here's the code:

```<code> HOT_prg_grp = new Handsontable(HOTcontainer, {
      data: data_bucket,
      renderAllRows: false,
      columns: [{ type: 'text', readonly:true },
                { type: 'text', readonly:false }],
      colHeaders: ["Program", "Group"] ,
      afterChange: (changed) => {
        changed?.forEach(([row, col, oldValue, newValue]) => {
          var prg = HOT_prg_grp.getDataAtCell(row, 0);
          chg = [prg, newValue];
          changes.push(chg);
        });
      },
      licenseKey :'blah blah'
    });
  }
</code>```

I would expect the 'renderAllRows: false to work.  also, renderAllRows: False fails.

Body:
I am creating a table and have renderAllRows:false and it still renders all rows, giving me the 'performance tip:

*VM6606 handsontable.full.min.js:61 Performance tip: Handsontable rendered more than 1000 visible rows. Consider limiting the number of rendered rows by specifying the table height and/or turning off the "renderAllRows" option.
*
I don't know why it isn't working, and being a newbie at HOT, I don't know if placement is a problem, or some other issue.  Any help appreciated.

My data set has 18k rows, so I would LOVE to disable it, but it doesn't seem to work.

any ideas why it doesn't work?  Additionally, the readonly:true doesn't work either.

Here's the code:

 HOT_prg_grp = new Handsontable(HOTcontainer, {
      data: data_bucket,
      renderAllRows: false,
      columns: [{ type: 'text', readonly:true },
                { type: 'text', readonly:false }],
      colHeaders: ["Program", "Group"] ,
      afterChange: (changed) => {
        changed?.forEach(([row, col, oldValue, newValue]) => {
          var prg = HOT_prg_grp.getDataAtCell(row, 0);
          chg = [prg, newValue];
          changes.push(chg);
        });
      },
      licenseKey :'blah blah'
    });
  }

I would expect the 'renderAllRows: false to work.  also, renderAllRows: False fails.


问:
Open second dropdown onclick event while other dropdown is open using alpine.js
I'm using Alpine.js to create a dropdown following this tutorial (tutorial)

I'm noticing a behavior when I have one dropdown open (dropdown-1) and click onto another dropdown (dropdown 2) dropdown 1 closes as expected, then dropdown 2 opens and then immediately closes.

Is this expected behavior? and is there a native way within alpine.js to have dropdown 2 open when clicked even though dropdown 1 is closing?

I've checked to make sure they all have unique IDs and they do.

```<code><!-- Sub-Navigation Item -->
        <div
          class="relative"
          @keydown.escape.prevent.stop="close($refs.button)"
          @focusin.window="! $refs.panel.contains($event.target) && close()"
          x-id="['main-menu-dropdown']"
          x-data="{
          open: false,
          toggle(){
            this.open = this.open ? this.close() : true
          },
          close(focusAfter) {
            this.open = false

            focusAfter && focusAfter.focus()
          }
        }"
        >
          <button
            type="button"
            x-ref="button"
            class="parent-dropdown group inline-flex items-center rounded-md text-base font-medium focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2"
            :aria-expanded="open"
            :aria-controls="$id('main-menu-dropdown')"
            @click="toggle()"
          >
            <span>Dropdown 1</span>
          </button>

          <!-- Submenu Panel -->
          <div
            class="absolute z-10 -ml-4 mt-3 w-screen max-w-md transform px-2 sm:px-0 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2"
            style="display:none"
            x-show="open"
            :id="$id('main-menu-dropdown')"
            @click.outside="close($refs.button)"
            x-ref="panel"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 translate-y-1"
            x-transition:enter-end="opacity-100 translate-y-0"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 translate-y-0"
            x-transition:leave-end="opacity-0 translate-y-1"
          >
            <p>submenu</p>
          </div>
          <!-- End Submenu Panel -->
        </div>
<!-- End Sub-Navigation Item -->

<!-- Sub-Navigation Item -->
        <div
          class="relative"
          @keydown.escape.prevent.stop="close($refs.button)"
          @focusin.window="! $refs.panel.contains($event.target) && close()"
          x-id="['main-menu-dropdown']"
          x-data="{
          open: false,
          toggle(){
            this.open = this.open ? this.close() : true
          },
          close(focusAfter) {
            this.open = false

            focusAfter && focusAfter.focus()
          }
        }"
        >
          <button
            type="button"
            x-ref="button"
            class="parent-dropdown group inline-flex items-center rounded-md text-base font-medium focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2"
            :aria-expanded="open"
            :aria-controls="$id('main-menu-dropdown')"
            @click="toggle()"
          >
            <span>Dropdown 2</span>
          </button>

          <!-- Submenu Panel -->
          <div
            class="absolute z-10 -ml-4 mt-3 w-screen max-w-md transform px-2 sm:px-0 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2"
            style="display:none"
            x-show="open"
            :id="$id('main-menu-dropdown')"
            @click.outside="close($refs.button)"
            x-ref="panel"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 translate-y-1"
            x-transition:enter-end="opacity-100 translate-y-0"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 translate-y-0"
            x-transition:leave-end="opacity-0 translate-y-1"
          >
            <p>submenu 2</p>
          </div>
          <!-- End Submenu Panel -->
        </div>
<!-- End Sub-Navigation Item -->
</code>```

Body:
I'm using Alpine.js to create a dropdown following this tutorial (tutorial)

I'm noticing a behavior when I have one dropdown open (dropdown-1) and click onto another dropdown (dropdown 2) dropdown 1 closes as expected, then dropdown 2 opens and then immediately closes.

Is this expected behavior? and is there a native way within alpine.js to have dropdown 2 open when clicked even though dropdown 1 is closing?

I've checked to make sure they all have unique IDs and they do.

          <button
            type="button"
            x-ref="button"
            class="parent-dropdown group inline-flex items-center rounded-md text-base font-medium focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2"
            :aria-expanded="open"
            :aria-controls="$id('main-menu-dropdown')"
            @click="toggle()"
          >
            Dropdown 1
          </button>

          <div
            class="absolute z-10 -ml-4 mt-3 w-screen max-w-md transform px-2 sm:px-0 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2"
            style="display:none"
            x-show="open"
            :id="$id('main-menu-dropdown')"
            @click.outside="close($refs.button)"
            x-ref="panel"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 translate-y-1"
            x-transition:enter-end="opacity-100 translate-y-0"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 translate-y-0"
            x-transition:leave-end="opacity-0 translate-y-1"
          >

submenu

          <button
            type="button"
            x-ref="button"
            class="parent-dropdown group inline-flex items-center rounded-md text-base font-medium focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2"
            :aria-expanded="open"
            :aria-controls="$id('main-menu-dropdown')"
            @click="toggle()"
          >
            Dropdown 2
          </button>

          <div
            class="absolute z-10 -ml-4 mt-3 w-screen max-w-md transform px-2 sm:px-0 lg:left-1/2 lg:ml-0 lg:-translate-x-1/2"
            style="display:none"
            x-show="open"
            :id="$id('main-menu-dropdown')"
            @click.outside="close($refs.button)"
            x-ref="panel"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 translate-y-1"
            x-transition:enter-end="opacity-100 translate-y-0"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 translate-y-0"
            x-transition:leave-end="opacity-0 translate-y-1"
          >

submenu 2


问:
Get Commentary from Posts with no MentionElement
I am getting the posts from linkedin but on the response I'm getting the commentary with all the supported elements(TextElement, MentionElement,HastagTemplate).

Can we do some filters on the request in order to only get plain text ?

This is my api endpoint

https://api.linkedin.com/rest/posts?author=urn%3Ali%3Aorganization%3A2127&isDsc=false&q=author&count=100

This is the response I'm getting nowadays

Congratulations to @[Becca Meinz] (urn:li:person:6sc1MHJfcE), Vice President of Best Buy's End-to-End Supply Chain Strategy, for her inclusion on @[Business Insider] (urn:li:organization:683279)'s 100 People Transforming Business list. https://bby.me/wj29an


问:
Trying to use python to authenticate to WebSite
I'm attempting to authenticate to a website to automate some device configuration.
There is no official API so I'm using "WebSpy" in my browser to watch what URLs are targeted and the payloads being sent.

I'm unable to get initial authentication working with a python post request.

The target url is https://xxxxxx.xxx/authenticate.

The payload I see when logging in from a web browser is.

```<code>{ "client_id": xxxxxx,
  "username": <plainText username>,
  "password": <plainText password>,
  "realm": "xxxxx",
  "credential_type": "http://auth0.com/oauth/grant-type/password-realm"}
</code>```

If I replicate all this in a python requests.POST I get back

```<code>{ "error": "invalid request",
  "error_description": "Unknown client."}
</code>```

I should mention the "client_id" I'm sending in my python post is just copied from what I see coming from the browser.

I imagine that client ID should be dynamically generated somehow but I don't see where it's coming from.

I should also mention I see some reference to a \callback URL happening after login within the web browser so I'm guessing that is how/when the auth token is being offered.

Can anyone point me in the right direction on all this?
Thank you in advance.

Body:
I'm attempting to authenticate to a website to automate some device configuration.
There is no official API so I'm using "WebSpy" in my browser to watch what URLs are targeted and the payloads being sent.

I'm unable to get initial authentication working with a python post request.

The target url is https://xxxxxx.xxx/authenticate.

The payload I see when logging in from a web browser is.

{ "client_id": xxxxxx,
  "username": <plainText username>,
  "password": <plainText password>,
  "realm": "xxxxx",
  "credential_type": "http://auth0.com/oauth/grant-type/password-realm"}

If I replicate all this in a python requests.POST I get back

{ "error": "invalid request",
  "error_description": "Unknown client."}

I should mention the "client_id" I'm sending in my python post is just copied from what I see coming from the browser.

I imagine that client ID should be dynamically generated somehow but I don't see where it's coming from.

I should also mention I see some reference to a \callback URL happening after login within the web browser so I'm guessing that is how/when the auth token is being offered.

Can anyone point me in the right direction on all this?
Thank you in advance.


问:
Java URLClassLoader with SSL
I'm refering to this question: Load Class files over the network with Reflections

We successfully loaded the class file, but i thougt, it would be better, if we could use the same thing via SSL. (https://example.com)

I tried to simply add an "s" but I get a "Class not found" exception.

Hope someone can handle that!

ContentLicense: CC BY-SA 3.0

Title: Java URLClassLoader with SSL


问:
MQTT broker connection failure on docker
I am running a docker container for mosquitto mqtt broker like this:

```<code>$ docker run -it -p 1883:1883 -p 9001:9001 -v mosquitto.conf:/mosquitto/config/mosquitto.conf eclipse-mosquitto
</code>```

Next I try to connect to this using a python mqtt client like this:

```<code> import paho.mqtt.client as mqtt
 mqtt_broker = 'localhost'
 client = mqtt.Client("Temperature inside")
 client.connect(mqtt_broker, 1883)
</code>```

I get a ConnectionRefusedError [Errno 61] Connection refused error

What am I doing wrong on the docker side (presumably) or otherwise?

Body:
I am running a docker container for mosquitto mqtt broker like this:

$ docker run -it -p 1883:1883 -p 9001:9001 -v mosquitto.conf:/mosquitto/config/mosquitto.conf eclipse-mosquitto

Next I try to connect to this using a python mqtt client like this:

 import paho.mqtt.client as mqtt
 mqtt_broker = 'localhost'
 client = mqtt.Client("Temperature inside")
 client.connect(mqtt_broker, 1883)

I get a ConnectionRefusedError [Errno 61] Connection refused error

What am I doing wrong on the docker side (presumably) or otherwise?


问:
Null is not an object (evaluating 'ImageCropPicker.openPicker')
I am using this package: https://github.com/ivpusic/react-native-image-crop-picker.
I followed all the installation steps for android.
But as soon as I import

```<code>import ImagePicker from 'react-native-image-crop-picker';
</code>```

into my file, I receive the error saying:

```<code>TypeError: null is not an object (evaluating 'ImageCropPicker.openPicker')
</code>```

Anyone else experience this?
What would the solution be?

Body:
I am using this package: https://github.com/ivpusic/react-native-image-crop-picker.
I followed all the installation steps for android.
But as soon as I import

import ImagePicker from 'react-native-image-crop-picker';

into my file, I receive the error saying:

TypeError: null is not an object (evaluating 'ImageCropPicker.openPicker')

Anyone else experience this?
What would the solution be?


问:
How would I Webscrape / export Google Locations into Excel?
I'm wondering if there's a method for me to export every google result regarding 'location' into an excel file, or a script that could do it?

I'm looking to export the list on the left and it's respective address etc

Thank you


问:
need sudo access when installing homebrew
i type this code in terminal in visual studio code: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

and hit enter and it says "Checking for sudo access (which may request your password)...
Password:
but it doesn't let me type anything.

i am on the administrator account

i cant type anything after password


问:
Java spring configuration class: @Autowired vs final as parameter
I am going over some of the code from the spring project that configuration classes like this:

```<code>@Configuration
@Import(value = {FhirAccessTokenServiceConfig.class, HealthDataServerServiceConfig.class})
public class FhirRouterServiceConfig {

    @Autowired
    private FhirAccessTokenService fhirAccessTokenService;
    @Autowired
    private HealthDataServerService healthDataServerService;

    @Bean
    public FhirRouterService fhirRouterService() {
        return new FhirRouterServiceImpl(fhirAccessTokenService, healthDataServerService);
    }
}
</code>```

When it instantiate the bean object (FhirRouterServiceImpl in this example), it passes two service object as parameter which is autowired.

However, for some configuration classes, it is defined like this. I am going to use same class for example:

```<code>@Configuration
@Import(value = {FhirAccessTokenServiceConfig.class, HealthDataServerServiceConfig.class})
public class FhirRouterServiceConfig {

    @Bean
    public FhirRouterService fhirRouterService(final FhirAccessTokenService fhirAccessTokenService, final HealthDataServerService healthDataServerService) {
        return new FhirRouterServiceImpl(fhirAccessTokenService, healthDataServerService);
    }
}
</code>```

Instead of autowiring two services, it uses parameter (final FhirAccessTokenService fhirAccessTokenService for this example) to instantiate the bean.

They both works, but I don't understand the difference and which is better way. I also found that not using @Configuration class at all could be better project structure. Can anybody explain what is happening and what is the best approach?

Body:
I am going over some of the code from the spring project that configuration classes like this:

@Configuration
@Import(value = {FhirAccessTokenServiceConfig.class, HealthDataServerServiceConfig.class})
public class FhirRouterServiceConfig {

    @Autowired
    private FhirAccessTokenService fhirAccessTokenService;
    @Autowired
    private HealthDataServerService healthDataServerService;

    @Bean
    public FhirRouterService fhirRouterService() {
        return new FhirRouterServiceImpl(fhirAccessTokenService, healthDataServerService);
    }
}

When it instantiate the bean object (FhirRouterServiceImpl in this example), it passes two service object as parameter which is autowired.

However, for some configuration classes, it is defined like this. I am going to use same class for example:

@Configuration
@Import(value = {FhirAccessTokenServiceConfig.class, HealthDataServerServiceConfig.class})
public class FhirRouterServiceConfig {

    @Bean
    public FhirRouterService fhirRouterService(final FhirAccessTokenService fhirAccessTokenService, final HealthDataServerService healthDataServerService) {
        return new FhirRouterServiceImpl(fhirAccessTokenService, healthDataServerService);
    }
}

Instead of autowiring two services, it uses parameter (final FhirAccessTokenService fhirAccessTokenService for this example) to instantiate the bean.

They both works, but I don't understand the difference and which is better way. I also found that not using @Configuration class at all could be better project structure. Can anybody explain what is happening and what is the best approach?


问:
Why does document.getElementById("...").value not work on this login page
I raised a question here about how to login to a website (https://www.intellizoom.com/login), where, after inputting the username and password via javascript (tampermonkey), the login button doesn't get enabled. markfila provided the following solution (including my own code):

```<code>setTimeout(function(){
    document.getElementById("email").value = "username@Domain.co.uk";
    document.getElementById("password").value = "password";

    // solution provided my markfila:
    // event needed to enable login button
    let event = new Event("blur");
    document.getElementById("email").dispatchEvent(event);
    document.getElementById("password").dispatchEvent(event);

    // login button now enabled, so use click() to submit
    document.getElementsByClassName("button large primary is-rounded")[0].click();
},100);
</code>```

As a newbie, I'm trying to fully understand what's going on, so I can figure out solutions like this on my own. This is how markfila described it:

... there using some kind of third party library for the ui and its not triggering the event that sets the value attribute. After a bit of messing around it looks like the ui library is setting the value on the blur event.

Reading up about the blur event, if I understand correctly, when an input field is interacted with there is normally a focus event (on entry to the field) and a blur event (on exit from the field). These events can be used to trigger code, including making the login button active.

In an attempt to fully understand this, I've come up with this alternative (albeit less elegant) code that also works successfully:

```<code>setTimeout(function(){
    document.getElementById("password").focus();
    document.getElementById("password").value = "password";
    document.getElementById("email").focus();
    document.getElementById("email").value = "username@Domain.co.uk";
    document.getElementById("password").focus();
    document.getElementsByClassName("button large primary is-rounded")[0].click();
},100);
</code>```

From my testing of the above code, what seems to be happening is that:

the value attribute for each of the two input fields seems to be set only when either (1) the field is focused before calling .value = "..." (as per my revised code) or (2) the blur event is dispatched (as per markfila's code).

the 'Log in' button is only enabled when both the value attribute has been successfully set for both fields, and the blur event is then triggered either by (3) switching focus to a different field (as per my revised code), or (4) dispatching the blur event (as per markfila's code).

How is it that document.getElementById("...").value doesn't actually set .value successfully unless I first focus the field or trigger the blur event?

This was proposed as an answer to this question. Perhaps it's because I'm a newbie, or I've missed something, but whilst it make an interesting read (mostly because it links to this), I really don't understand how it answers my question. AFAIK the issue isn't that the .getAttribute('value') is different from .value.  I know how to make it work (trigger the blur event either directly or by shifting focus to another field - see also here), but I don't understand why setting .value isn't enough.

Also, I've found that manually inputting the username and password activates the 'Log in' button as soon as a valid value is input in for both fields - without exiting the 2nd field, despite (presumably) no blur event being triggered! How can that be?

Body:
I raised a question here about how to login to a website (https://www.intellizoom.com/login), where, after inputting the username and password via javascript (tampermonkey), the login button doesn't get enabled. markfila provided the following solution (including my own code):

setTimeout(function(){
    document.getElementById("email").value = "username@Domain.co.uk";
    document.getElementById("password").value = "password";

    // solution provided my markfila:
    // event needed to enable login button
    let event = new Event("blur");
    document.getElementById("email").dispatchEvent(event);
    document.getElementById("password").dispatchEvent(event);

    // login button now enabled, so use click() to submit
    document.getElementsByClassName("button large primary is-rounded")[0].click();
},100);

As a newbie, I'm trying to fully understand what's going on, so I can figure out solutions like this on my own. This is how markfila described it:

... there using some kind of third party library for the ui and its not triggering the event that sets the value attribute. After a bit of messing around it looks like the ui library is setting the value on the blur event.

Reading up about the blur event, if I understand correctly, when an input field is interacted with there is normally a focus event (on entry to the field) and a blur event (on exit from the field). These events can be used to trigger code, including making the login button active.

In an attempt to fully understand this, I've come up with this alternative (albeit less elegant) code that also works successfully:

setTimeout(function(){
    document.getElementById("password").focus();
    document.getElementById("password").value = "password";
    document.getElementById("email").focus();
    document.getElementById("email").value = "username@Domain.co.uk";
    document.getElementById("password").focus();
    document.getElementsByClassName("button large primary is-rounded")[0].click();
},100);

From my testing of the above code, what seems to be happening is that:

the value attribute for each of the two input fields seems to be set only when either (1) the field is focused before calling .value = "..." (as per my revised code) or (2) the blur event is dispatched (as per markfila's code).

the 'Log in' button is only enabled when both the value attribute has been successfully set for both fields, and the blur event is then triggered either by (3) switching focus to a different field (as per my revised code), or (4) dispatching the blur event (as per markfila's code).

How is it that document.getElementById("...").value doesn't actually set .value successfully unless I first focus the field or trigger the blur event?

This was proposed as an answer to this question. Perhaps it's because I'm a newbie, or I've missed something, but whilst it make an interesting read (mostly because it links to this), I really don't understand how it answers my question. AFAIK the issue isn't that the .getAttribute('value') is different from .value.  I know how to make it work (trigger the blur event either directly or by shifting focus to another field - see also here), but I don't understand why setting .value isn't enough.

Also, I've found that manually inputting the username and password activates the 'Log in' button as soon as a valid value is input in for both fields - without exiting the 2nd field, despite (presumably) no blur event being triggered! How can that be?


问:
E/AudioPlayer(19494): TYPE_SOURCE: java.io.FileNotFoundException: 1670340351487-micro bousta fini.mp3: open failed: ENOENT (No such file or directory)
Im using the VoiceMessage Library to play a file mp3 from an API  json file , when i execute my app it display to me this error :

```<code>E/AudioPlayer(19494): TYPE_SOURCE: java.io.FileNotFoundException: 1670340351487-micro bousta fini.mp3: open failed: ENOENT (No such file or directory)
</code>```

Load Data Method

```<code>Future<void> fetchAudio() async {
HttpClient client = HttpClient();
client.autoUncompress = true;
final HttpClientRequest request = await client.getUrl(Uri.parse("http://api/audio/${widget.id}"));
request.headers
    .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
final HttpClientResponse response = await request.close();
final String content = await response.transform(utf8.decoder).join();
final List data = json.decode(content);
setState(() {
  _loadedAudio = data as List;  ;
});
}
</code>```

and i Call the _loadData inside a ListView Builder like that:

```<code>trailing: IconButton(
                                  icon: Icon(Icons.play_circle_outline),
                                  onPressed: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                Expanded(child: VoiceMessage(
                                                  audioSrc: _loadedAudio[index]['file'],
                                                  played: false, // To show played badge or not.
                                                  me: true, // Set message side.
                                                  onPlay: () {}, // Do something when voice played.
                                                ))
                                        ));
                                  },
</code>```

Also this is a screenshot of my json format

Json Data screenshot

How can I solve it and Thanks

Body:
Im using the VoiceMessage Library to play a file mp3 from an API  json file , when i execute my app it display to me this error :

E/AudioPlayer(19494): TYPE_SOURCE: java.io.FileNotFoundException: 1670340351487-micro bousta fini.mp3: open failed: ENOENT (No such file or directory)

Load Data Method

Future<void> fetchAudio() async {
HttpClient client = HttpClient();
client.autoUncompress = true;
final HttpClientRequest request = await client.getUrl(Uri.parse("http://api/audio/${widget.id}"));
request.headers
    .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
final HttpClientResponse response = await request.close();
final String content = await response.transform(utf8.decoder).join();
final List data = json.decode(content);
setState(() {
  _loadedAudio = data as List;  ;
});
}

and i Call the _loadData inside a ListView Builder like that:

trailing: IconButton(
                                  icon: Icon(Icons.play_circle_outline),
                                  onPressed: () {
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                Expanded(child: VoiceMessage(
                                                  audioSrc: _loadedAudio[index]['file'],
                                                  played: false, // To show played badge or not.
                                                  me: true, // Set message side.
                                                  onPlay: () {}, // Do something when voice played.
                                                ))
                                        ));
                                  },

Also this is a screenshot of my json format

Json Data screenshot

How can I solve it and Thanks


问:
Can VSCode do intellisense when using an external JS script of an HTML page?
I have an HTML page and in that page I have given some elements IDs and I've defined CSS classes and some elements use those classes.

If I load that page in a browser the web dev tools will show those elements and offer code assistance.

I have created a JavaScript file that I am including in my HTML page.

Can VSCode give me intelligent information when I write code in the external JavaScript file in a similar way to the web devs tool does or a node js project does?

Actually, does VSCode do intellisense if the JavaScript IS embedded in the HTML page (this question answered below)?

UPDATE:

I did a test with JavaScript inline in an HTML page and vscode did not show the element in the code complete list or any awareness of it:

It only showed code intelligence with code from other script blocks.

UPDATE 2:

It looks like theres a few parts to this.

There's no awareness of HTML elements, as shown and discovered in web tools in the browser.
There's no awareness of other Javascript libraries in the inline script.
So there's probably no awareness of HTML elements in an external JS and no awareness of JS objects from the main HTML page either.


问:
Running a project in VSCode with Maven, which does run in Intellij, giving deploy error
I have a Java project that is designed to be built with Maven.  I have instructions to use the Intellij IDE, and I know that when a friend uses the same project and follows those instructions, it will build and run successfully.

I could just install Intellij, but my main code editor is VSCode.  So I was hoping that I hoping I could stick with VSCode and run it with this.

I'm working on Windows 10.  I've used the Java code pack to install Java version 17, and I've installed Maven.  When I open the project it looks like this:

In Intellij I'm supposed to be able to right-click the Game.java file and choose to run the main method.  However, I don't seem to be able to do that here.  When I right-click the project in the Maven drop-down, it gives an option to deploy.  But when I click that I get the following error.

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy (default-deploy) on project hw09: Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]
</code>```

I assume this is because the POM file was not set up for a command to deploy, but rather something like a "run" command.  But that isn't an option that Maven seems to give me.

I've also tried running the Game.java file by right-clicking and clicking Run, but it gives this error:

```<code>[Running] cd "c:\Users\blank\Desktop\hw09_local\hw09_local_temp\src\main\java\org\cis1200\" && javac Game.java && java Game
Game.java:13: error: package org.cis1200.mushroom does not exist
        Runnable game = new org.cis1200.mushroom.RunMushroomOfDoom();
                                                ^
1 error
</code>```

I assume it's giving this error because whatever it's using to try to run the program isn't aware of the surrounding file context.  I assume that's what Maven is supposed to do for me.

So is there a way to run this project in VSCode?  Or was it simply designed to specifically be run in IntelliJ, and I have to use that?

Body:
I have a Java project that is designed to be built with Maven.  I have instructions to use the Intellij IDE, and I know that when a friend uses the same project and follows those instructions, it will build and run successfully.

I could just install Intellij, but my main code editor is VSCode.  So I was hoping that I hoping I could stick with VSCode and run it with this.

I'm working on Windows 10.  I've used the Java code pack to install Java version 17, and I've installed Maven.  When I open the project it looks like this:

In Intellij I'm supposed to be able to right-click the Game.java file and choose to run the main method.  However, I don't seem to be able to do that here.  When I right-click the project in the Maven drop-down, it gives an option to deploy.  But when I click that I get the following error.

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy (default-deploy) on project hw09: Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]

I assume this is because the POM file was not set up for a command to deploy, but rather something like a "run" command.  But that isn't an option that Maven seems to give me.

I've also tried running the Game.java file by right-clicking and clicking Run, but it gives this error:

[Running] cd "c:\Users\blank\Desktop\hw09_local\hw09_local_temp\src\main\java\org\cis1200\" && javac Game.java && java Game
Game.java:13: error: package org.cis1200.mushroom does not exist
        Runnable game = new org.cis1200.mushroom.RunMushroomOfDoom();
                                                ^
1 error

I assume it's giving this error because whatever it's using to try to run the program isn't aware of the surrounding file context.  I assume that's what Maven is supposed to do for me.

So is there a way to run this project in VSCode?  Or was it simply designed to specifically be run in IntelliJ, and I have to use that?


问:
Angular error TS2304: Cannot find name 'RTCRtpStreamStats'
When I try to integrate 100ms sdk according to the guide, following errors are occured.

```<code>Error: node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:10:57 - error TS2304: Cannot find name 'RTCReceivedRtpStreamStats'.

10 export interface RTCRemoteInboundRtpStreamStats extends RTCReceivedRtpStreamStats {
                                                           ~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:23:40 - error TS2304: Cannot find name 'RTCOutboundRtpStreamStats'.

23 interface MissingOutboundStats extends RTCOutboundRtpStreamStats, MissingCommonStats {
                                          ~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:31:39 - error TS2304: Cannot find name 'RTCInboundRtpStreamStats'.

31 interface MissingInboundStats extends RTCInboundRtpStreamStats, MissingCommonStats {
                                         ~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:40:34 - error TS2304: Cannot find name 'RTCRtpStreamStats'.

40 interface BaseTrackStats extends RTCRtpStreamStats {
                                    ~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video-store/dist/core/schema/notification.d.ts:114:51 - error[0m TS2344: Type 'Type[index]' does not satisfy the constraint 'HMSNotificationTypes'.
  Type 'Type[keyof Type]' is not assignable to type 'HMSNotificationTypes'.
    Type 'Type[string] | Type[number] | Type[symbol]' is not assignable to type 'HMSNotificationTypes'.
      Type 'Type[string]' is not assignable to type 'HMSNotificationTypes'.

114     [index in keyof Type]: HMSNotificationMapping<Type[index]>;
                                                      ~~~~~~~~~~~
src/app/components/partywatch/partywatch.component.ts:75:18 - error TS2339: Property 'playsInline' does not exist on type 'HTMLVideoElement'.

75     videoElement.playsInline = true;
</code>```

RTCRtpStreamStats is defined inside typescript4.0.2, and
typescript4.0.2, @types/webrtc and webrtcmetrics are already installed.
How can I fix these issues?

Body:
When I try to integrate 100ms sdk according to the guide, following errors are occured.

Error: node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:10:57 - error TS2304: Cannot find name 'RTCReceivedRtpStreamStats'.

10 export interface RTCRemoteInboundRtpStreamStats extends RTCReceivedRtpStreamStats {
                                                           ~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:23:40 - error TS2304: Cannot find name 'RTCOutboundRtpStreamStats'.

23 interface MissingOutboundStats extends RTCOutboundRtpStreamStats, MissingCommonStats {
                                          ~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:31:39 - error TS2304: Cannot find name 'RTCInboundRtpStreamStats'.

31 interface MissingInboundStats extends RTCInboundRtpStreamStats, MissingCommonStats {
                                         ~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video/dist/interfaces/webrtc-stats.d.ts:40:34 - error TS2304: Cannot find name 'RTCRtpStreamStats'.

40 interface BaseTrackStats extends RTCRtpStreamStats {
                                    ~~~~~~~~~~~~~~~~~
node_modules/@100mslive/hms-video-store/dist/core/schema/notification.d.ts:114:51 - error[0m TS2344: Type 'Type[index]' does not satisfy the constraint 'HMSNotificationTypes'.
  Type 'Type[keyof Type]' is not assignable to type 'HMSNotificationTypes'.
    Type 'Type[string] | Type[number] | Type[symbol]' is not assignable to type 'HMSNotificationTypes'.
      Type 'Type[string]' is not assignable to type 'HMSNotificationTypes'.

114     [index in keyof Type]: HMSNotificationMapping<Type[index]>;
                                                      ~~~~~~~~~~~
src/app/components/partywatch/partywatch.component.ts:75:18 - error TS2339: Property 'playsInline' does not exist on type 'HTMLVideoElement'.

75     videoElement.playsInline = true;

RTCRtpStreamStats is defined inside typescript4.0.2, and
typescript4.0.2, @types/webrtc and webrtcmetrics are already installed.
How can I fix these issues?


问:
MacOS Cocoa: Is it possible to modify/add my own button or modify alpha of third party app's window?
I am trying to add my own button on top of the window of third party app's windows OR modify the alpha (kCGWindowAlpha I think) of third party app windows in MacOS. I don't need this app to be sandboxed.

I have been able to get details of third party windows using:

```<code>@IBAction func printWindows(_ sender: NSButton?) {
        let runningApps = NSWorkspace.shared.runningApplications
        print("runningApps: \(runningApps)")
        if let info = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[ String : Any]] {
            for dict in info {
                print("dict: \(dict)")
                print("type: \(type(of:dict))")
                print("kCGWindowOwnerName: \(dict[kCGWindowOwnerName as String])")
            }
        }
    }
</code>```

This gives me a lot of details of all the app windows opened. However, I am unable to figure out how I can use that info to modify the third party window. Can you direct me in the right direction on how I can achieve something like this?

So far, I have seen this code which lets me get screenshots of windows:

https://github.com/sassman/son-of-grab/blob/main/Controller.m

Is this something which Services are for? My reading of Services indicates that it's inly meant for clipboard/pasteboard stuff:

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/providing.html

Is this something which can be achieved via Accessibility APIs?

Body:
I am trying to add my own button on top of the window of third party app's windows OR modify the alpha (kCGWindowAlpha I think) of third party app windows in MacOS. I don't need this app to be sandboxed.

I have been able to get details of third party windows using:

@IBAction func printWindows(_ sender: NSButton?) {
        let runningApps = NSWorkspace.shared.runningApplications
        print("runningApps: \(runningApps)")
        if let info = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[ String : Any]] {
            for dict in info {
                print("dict: \(dict)")
                print("type: \(type(of:dict))")
                print("kCGWindowOwnerName: \(dict[kCGWindowOwnerName as String])")
            }
        }
    }

This gives me a lot of details of all the app windows opened. However, I am unable to figure out how I can use that info to modify the third party window. Can you direct me in the right direction on how I can achieve something like this?

So far, I have seen this code which lets me get screenshots of windows:

https://github.com/sassman/son-of-grab/blob/main/Controller.m

Is this something which Services are for? My reading of Services indicates that it's inly meant for clipboard/pasteboard stuff:

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/providing.html

Is this something which can be achieved via Accessibility APIs?


问:
How can I check the messages that I received from whatsapp business API?
We are using an integration with whatsapp business API and it is working great, but we need to check if we have a new message or if the user have replied, we try it to use the whatsapp business app, but we can't access to the app and it seems like that whatsapp doesn't allow to use the App and API with the same number, then is there any way to check the messages like an app or dashboard?

I have been investigating in internet but I cannot find any solutions for that


问:
how to cretae zip file using zipfile in python?

import os
from zipfile import ZipFile
from os.path import basename

src = "C:\git\mytest"

full_path=[]

for root, dirs, files in os.walk(src, topdown=False):
    for name in files:
        full_path.append(os.path.join(root, name))

with ZipFile('output.zip', 'w') as zipObj:
    for item in full_path:
        zipObj.write(item, basename(item))

```

Trying to create a zip file with containing some file of a specific folder.

In specific folder has some files. then it will add to zip file

In the mentioned code, one zipfile is created but there is no file. I am not getting the exact reason

Body:
import os
from zipfile import ZipFile
from os.path import basename

src = "C:\git\mytest"

full_path=[]

for root, dirs, files in os.walk(src, topdown=False):
    for name in files:
        full_path.append(os.path.join(root, name))

with ZipFile('output.zip', 'w') as zipObj:
    for item in full_path:
        zipObj.write(item, basename(item))

Trying to create a zip file with containing some file of a specific folder.

In specific folder has some files. then it will add to zip file

In the mentioned code, one zipfile is created but there is no file. I am not getting the exact reason


问:
Using Volttron aggregation agent
I'm trying to get the aggregate agent to work with timescale db.
https://volttron.readthedocs.io/en/main/developing-volttron/developing-agents/specifications/aggregate.html

I have a file aggregation.config

```<code>{
    "connection": {
        "type": "postgresql",
        "params": {
            "dbname": "volttrondb",

            "host": "127.0.0.1",
            "port": 5432,
            "user": "user",
            "password": "password",
            "timescale_dialect": true
        }
    },
   "aggregations":[
        # list of aggregation groups each with unique aggregation_period and
        # list of points that needs to be collected
        {
        "aggregation_period": "1h",
        "use_calendar_time_periods": true,
        "utc_collection_start_time":"2016-03-01T01:15:01.000000",
        "points": [
            {
             "topic_names": ["campus/building/fake/EKG_Cos", "campus/building/fake/EKG_Sin"],
             "aggregation_topic_name":"campus/building/fake/avg_of_EKG_Cos_EKG_Sin",
             "aggregation_type": "avg",
             "min_count": 2
            }
        ]
        }
    ]
}
</code>```

And run the following command
vctl install services/core/SQLAggregateHistorian/ --tag  aggregate-historian -c config/aggregation.config --start

It starts correctly - the vctl status shows it running and there are no errors in the log.

I do not see the point campus/building/fake/avg_of_EKG_Cos_EKG_Sin in the topics table.

Any suggestions?

Title: Using Volttron aggregation agent

Body:
I'm trying to get the aggregate agent to work with timescale db.
https://volttron.readthedocs.io/en/main/developing-volttron/developing-agents/specifications/aggregate.html

I have a file aggregation.config

{
    "connection": {
        "type": "postgresql",
        "params": {
            "dbname": "volttrondb",

            "host": "127.0.0.1",
            "port": 5432,
            "user": "user",
            "password": "password",
            "timescale_dialect": true
        }
    },
   "aggregations":[
        # list of aggregation groups each with unique aggregation_period and
        # list of points that needs to be collected
        {
        "aggregation_period": "1h",
        "use_calendar_time_periods": true,
        "utc_collection_start_time":"2016-03-01T01:15:01.000000",
        "points": [
            {
             "topic_names": ["campus/building/fake/EKG_Cos", "campus/building/fake/EKG_Sin"],
             "aggregation_topic_name":"campus/building/fake/avg_of_EKG_Cos_EKG_Sin",
             "aggregation_type": "avg",
             "min_count": 2
            }
        ]
        }
    ]
}

And run the following command
vctl install services/core/SQLAggregateHistorian/ --tag  aggregate-historian -c config/aggregation.config --start

It starts correctly - the vctl status shows it running and there are no errors in the log.

I do not see the point campus/building/fake/avg_of_EKG_Cos_EKG_Sin in the topics table.

Any suggestions?


问:
Subtle difference in Forward Propagation results
I am attempting code a neural network from scratch. I am using performance by tensorflow (keras) as a ceiling (for now). Comparing an implementation of 'Forward Propagation' using the same dataset, weights, and biases (and other hyperparameters), I am noticing a very small difference in loss where ideally they should be the same.

I believe this difference aggregates as multiple passes are made. I would appreciate an insight on this matter.

The programming language I am using is Python 3.5 and data structures are implemented through the package numpy with much of data being of type numpy.float64.


问:
Canny edge detector, but only for the object I want

I want to detect only the tray edges in this picture. I tried with the Canny edge detector. It detects edges in the whole picture. What can I do to just detect the tray? I used the code here.

I just want it to detect the tray.

NEW UPDATE
Detected edges need to be recognized.

NEW NEW UPDATE
Template Matching

Imlementing Template Matching

https://docs.opencv.org/4.x/d4/dc6/tutorial_py_template_matching.html
(I used the code here)

exampleImages


问:
Excel vba to generate a list of files and sizes in subfolders
Hello I have inherited some excel vba code which produces a list of files which are less than 100 days old and captures the file sizes that sit in a specific folder and sub folders.   When running the code, it tries to access some sub folders which I don't have access to and it crashes can anyone assist? I would also like it to ignore subfolders that start 02-Recs.

thanks

Sub getfiles()

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object, sf
    Dim i As Integer, colFolders As New Collection, ws As Worksheet

    Set ws = ActiveSheet
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.getfolder("F:\test\")

    colFolders.Add oFolder          'start with this folder

    Do While colFolders.Count > 0      'process all folders
        Set oFolder = colFolders(1)    'get a folder to process
        colFolders.Remove 1            'remove item at index 1

        For Each oFile In oFolder.Files
            If oFile.DateLastModified > Now - 100 Then
                ws.Cells(i + 1, 1) = oFolder.Path
                ws.Cells(i + 1, 2) = oFile.Name
                ws.Cells(i + 1, 3) = "RO"
                ws.Cells(i + 1, 4) = oFile.DateLastModified
                ws.Cells(i + 1, 5) = oFile.Size / 1024 ^ 2
                i = i + 1
            End If
        Next oFile

        'add any subfolders to the collection for processing
        For Each sf In oFolder.subfolders
            colFolders.Add sf 'add to collection for processing
        Next sf
    Loop

End Sub
```


问:
How to do a create endpoint with relationship with fastapi and sqlmodel?
In models, have a User that can have many roles and Role that can have many users (many-to-many):

class UsersRoles(SQLModel, table=True):
    user_id: int = Field(foreign_key='users.id', primary_key=True)
    role_id: int = Field(foreign_key='roles.id', primary_key=True)

class User(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    email: str = Field(unique=True, index=True)
    roles: list['Role'] = Relationship(back_populates='users', link_model=UsersRoles)

class Role(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str = Field(unique=True)
    users: list['User'] = Relationship(back_populates='roles', link_model=UsersRoles)
```
<p>In the <strong>api</strong>, declare the endpoint:</p>
<pre class="lang-py prettyprint-override"><code>@router.post('/user')
def create_user(user: User) -> User:
    with get_session() as session:
        session.add(user)
        session.commit()
        session.refresh(user)
        return user
</code>```

Then I want to create the User with roles and call the endpoint:

role = Role(name='admin')
user = User(name='Jane', email='test@xyz.com', roles=[role])

# payload = {
#   'name': 'Jane',
#   'email': 'test@xyz.com',
#   'roles': ['admin']
# }
payload = user.json()
response = requests.post('http://localhost:8000/user', json=payload)
```
<p><strong>Error:</strong> Get what looks like a SqlAlchemy error:</p>
```state = <sqlalchemy.orm.state.InstanceState object at 0x0000016B1F3B6BF0>
child = {'name': 'user'}
initiator = <sqlalchemy.orm.attributes.AttributeEvent object at 0x0000016B1F2FF780>

    def emit_backref_from_collection_append_event(state, child, initiator):
        if child is None:
            return

>       child_state, child_dict = instance_state(child), instance_dict(child)
E       AttributeError: 'dict' object has no attribute '_sa_instance_state'
```

How can I make this work?

The same thing happens whether the role already exists in the DB or not.

Works if the payload (user) doesn't have roles in it.

The error comes up before the controller code gets executed, ie, in api doesn't even reach the first line inside create_user(...).

Body:
In models, have a User that can have many roles and Role that can have many users (many-to-many):

class UsersRoles(SQLModel, table=True):
    user_id: int = Field(foreign_key='users.id', primary_key=True)
    role_id: int = Field(foreign_key='roles.id', primary_key=True)

class User(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    email: str = Field(unique=True, index=True)
    roles: list['Role'] = Relationship(back_populates='users', link_model=UsersRoles)

class Role(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str = Field(unique=True)
    users: list['User'] = Relationship(back_populates='roles', link_model=UsersRoles)

In the api, declare the endpoint:

@router.post('/user')
def create_user(user: User) -> User:
    with get_session() as session:
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

Then I want to create the User with roles and call the endpoint:

role = Role(name='admin')
user = User(name='Jane', email='test@xyz.com', roles=[role])

# payload = {
#   'name': 'Jane',
#   'email': 'test@xyz.com',
#   'roles': ['admin']
# }
payload = user.json()
response = requests.post('http://localhost:8000/user', json=payload)

Error: Get what looks like a SqlAlchemy error:

state = <sqlalchemy.orm.state.InstanceState object at 0x0000016B1F3B6BF0>
child = {'name': 'user'}
initiator = <sqlalchemy.orm.attributes.AttributeEvent object at 0x0000016B1F2FF780>

    def emit_backref_from_collection_append_event(state, child, initiator):
        if child is None:
            return

>       child_state, child_dict = instance_state(child), instance_dict(child)
E       AttributeError: 'dict' object has no attribute '_sa_instance_state'

How can I make this work?

The same thing happens whether the role already exists in the DB or not.

Works if the payload (user) doesn't have roles in it.

The error comes up before the controller code gets executed, ie, in api doesn't even reach the first line inside create_user(...).


问:
Automated BCC for all the email accounts on the company using Outlook Add-ins
I'm trying to fill out automatically the BCC for every email sent within the domain of our office using any kind of language.

I created and Outlook Add-in and I was thinking maybe put a button there and when it's clicked your BCC is always filled with one email. Please let me know any ideas how I can get this done.

Thank you!


问:
How do I resolve this error in the encoder of my VAE?
I was trying to create a VAE which has an input of different images that are in different folders, but when I try to run the VAE I get an error:

```<code>from skimage.io import imread
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd import Variable
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
import os
import ast
import numpy as np
import pywt
import matplotlib.pyplot as plt
from PIL import Image as PImage
os.chdir('D:/bob/')
SAVEDIR = "D:/bob/wavelets/image/output/"
IMAGEDIR="D:/bob/wavelets/dataset"

device="cpu"
class VAE(nn.Module):
    def __init__(self, x_dim, h_dim, z_dim):
        super(VAE, self).__init__()

        # Encoder
        self.fc1 = nn.Linear(x_dim, h_dim)
        self.fc2_mu = nn.Linear(h_dim, z_dim)
        self.fc2_logvar = nn.Linear(h_dim, z_dim)

        # Decoder
        self.fc3 = nn.Linear(z_dim, h_dim)
        self.fc4 = nn.Linear(h_dim, x_dim)

    def encoder(self, x):
        h = F.relu(self.fc1(x))
        return self.fc2_mu(h), self.fc2_logvar(h)

    def sampling(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return eps.mul(std).add_(mu) # return z sample

    def decoder(self, z):
        h = F.relu(self.fc3(z))
        return F.sigmoid(self.fc4(h))

    def forward(self, x):
        mu, logvar = self.encoder(x.view(-1, 4096))
        z = self.sampling(mu, logvar)
        return self.decoder(z), mu,

vae = VAE(x_dim=4096, h_dim=400, z_dim=20).to(device)
optimizer = optim.Adam(vae.parameters(), lr=0.001)

# reconstruction error + KL divergence losses
def loss_function(recon_x, x, mu, logvar):
    BCE = F.binary_cross_entropy(recon_x, x.view(-1, 4096), reduction='sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + KLD
dirpath = os.listdir(IMAGEDIR)
def train(epoch):
    vae.train()
    train_loss = 0
    for subdir in dirpath:
        full_subdir= IMAGEDIR + '/' + subdir + '/'
        imageList = os.listdir(full_subdir)
        for image in imageList:
            fullpath = full_subdir + image
            inputImage = imread(fullpath)[:,:]
            optimizer.zero_grad()
            recon_batch, mu, logvar = vae(inputImage)
            loss = loss_function(recon_batch, inputImage, mu, logvar)
            loss.backward()
            train_loss += loss.item()
            optimizer.step()
train(7)
</code>```

When I try to run the code, this is the error I get:
ValueError: Type must be a sub-type of ndarray type
This comes from the line that says: mu, logvar = self.encoder(x.view(-1, 4096)) in the forward function. Does anyone have any solutions as to how I can resolve this issue so my code will run properly? Thanks!

Body:
I was trying to create a VAE which has an input of different images that are in different folders, but when I try to run the VAE I get an error:

from skimage.io import imread
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd import Variable
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
from PIL import Image
import os
import ast
import numpy as np
import pywt
import matplotlib.pyplot as plt
from PIL import Image as PImage
os.chdir('D:/bob/')
SAVEDIR = "D:/bob/wavelets/image/output/"
IMAGEDIR="D:/bob/wavelets/dataset"

device="cpu"
class VAE(nn.Module):
    def __init__(self, x_dim, h_dim, z_dim):
        super(VAE, self).__init__()

        # Encoder
        self.fc1 = nn.Linear(x_dim, h_dim)
        self.fc2_mu = nn.Linear(h_dim, z_dim)
        self.fc2_logvar = nn.Linear(h_dim, z_dim)

        # Decoder
        self.fc3 = nn.Linear(z_dim, h_dim)
        self.fc4 = nn.Linear(h_dim, x_dim)

    def encoder(self, x):
        h = F.relu(self.fc1(x))
        return self.fc2_mu(h), self.fc2_logvar(h)

    def sampling(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return eps.mul(std).add_(mu) # return z sample

    def decoder(self, z):
        h = F.relu(self.fc3(z))
        return F.sigmoid(self.fc4(h))

    def forward(self, x):
        mu, logvar = self.encoder(x.view(-1, 4096))
        z = self.sampling(mu, logvar)
        return self.decoder(z), mu,

vae = VAE(x_dim=4096, h_dim=400, z_dim=20).to(device)
optimizer = optim.Adam(vae.parameters(), lr=0.001)

# reconstruction error + KL divergence losses
def loss_function(recon_x, x, mu, logvar):
    BCE = F.binary_cross_entropy(recon_x, x.view(-1, 4096), reduction='sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + KLD
dirpath = os.listdir(IMAGEDIR)
def train(epoch):
    vae.train()
    train_loss = 0
    for subdir in dirpath:
        full_subdir= IMAGEDIR + '/' + subdir + '/'
        imageList = os.listdir(full_subdir)
        for image in imageList:
            fullpath = full_subdir + image
            inputImage = imread(fullpath)[:,:]
            optimizer.zero_grad()
            recon_batch, mu, logvar = vae(inputImage)
            loss = loss_function(recon_batch, inputImage, mu, logvar)
            loss.backward()
            train_loss += loss.item()
            optimizer.step()
train(7)

When I try to run the code, this is the error I get:
ValueError: Type must be a sub-type of ndarray type
This comes from the line that says: mu, logvar = self.encoder(x.view(-1, 4096)) in the forward function. Does anyone have any solutions as to how I can resolve this issue so my code will run properly? Thanks!


问:
protobuf-net unable to import
I'm trying protobuf-net contract-first but for some reason I'm getting the following errors when I try to import user_session_2.proto because it depends on shared_1.proto. They are both in different directories. How do I deal with that issue?

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="protobuf-net" Version="3.1.25" />
    <PackageReference Include="protobuf-net.BuildTools" Version="3.1.25">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <AdditionalFiles Include="Protos\common\shared_1.proto" />
    <AdditionalFiles Include="Protos\WebAPI\user_session_2.proto" />
  </ItemGroup>

</Project>

</code>```

Protos/common/shared_1.proto

```<code>syntax = "proto2";

package shared_1;

...
</code>```

Protos/WebAPI/user_session_2.proto

```<code>syntax = "proto2";

package user_session_2;

import "common/shared_1.proto";

...
</code>```

Title: protobuf-net unable to import

Body:
I'm trying protobuf-net contract-first but for some reason I'm getting the following errors when I try to import user_session_2.proto because it depends on shared_1.proto. They are both in different directories. How do I deal with that issue?

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="protobuf-net" Version="3.1.25" />
    <PackageReference Include="protobuf-net.BuildTools" Version="3.1.25">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <AdditionalFiles Include="Protos\common\shared_1.proto" />
    <AdditionalFiles Include="Protos\WebAPI\user_session_2.proto" />
  </ItemGroup>

</Project>

Protos/common/shared_1.proto

syntax = "proto2";

package shared_1;

...

Protos/WebAPI/user_session_2.proto

syntax = "proto2";

package user_session_2;

import "common/shared_1.proto";

...


问:
Need to put prefix div or span inside react-textarea-autosize
I have a requirement. Where I can place prefix div or span inside react-textarea-autosize. Please check screenshot for better clarity. Hi There(in screenshot), should be prefix div or span.
enter image description here

I am trying to set data-prefix, but it is not working.


问:
How to create Microsoft Teams Apps with bots dynamically?
We would like to have an ability to programmatically create Microsoft Teams apps so that they can be installed into the same Microsoft Teams tenant. Since there is no way to pass any data from the app manifest to the bot endpoint we have to create separate bot for each app which will have an endpoint like so /api/messages/:id. This way we can differentiate between the apps/bots on the backend.

We weren't able to find bot Azure APIs to accomplish this easily, aside from low level resource APIs or Azure CLI to create app registry and the bot.

Is this the best way to approach this problem? Any suggestions?


问:
Change SSRS Report Server Instance Name
I am setting up SSRS on a windows 2019 server with SQL Server 2019 installed.  Once SSRS is installed and it prompts for first configuration is there anyway to change the default value of Report server Instance of "SSRS" to a different value?  See image.  I have tried a few things like amending  tag in the rsreportserver.config and tried changing the name of the install folder C:<install path>\SSRS but it is locked by a process and I tried stopping all SQL Server services etc but that did not work.

Can this default instance name be changed?

Title: Change SSRS Report Server Instance Name


问:
Should I serialize a data and save it in host/server computer to resume/pause upload to AWS S3 Bucket?
According to AWS Docs, we must serialize and de-serialize the pause result so that, if I resume the upload, I can pick up where I left off:

On a successful upload pause, PauseResult.getInfoToResume() returns an instance of PersistableUpload that can be used to resume the upload operation at a later time.

```<code>// Retrieve the persistable upload from the pause result.
PersistableUpload persistableUpload = pauseResult.getInfoToResume();

// Create a new file to store the information.
File f = new File("resume-upload");
if( !f.exists() ) f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);

// Serialize the persistable upload to the file.
persistableUpload.serialize(fos);
fos.close();
</code>```

Taking into account that my project is organized as follows (Standard Spring Boot Project):

```<code>Project Name
|__src
   |__main
      |__java
      |  |__com.blabla.projectname
      |
      |_____resources
</code>```

Would I have temporary files within the deployed project if I deployed my web application using the method described in the AWS Docs?

```<code>Project Name
|__src
   |__main
      |__java
      |  |__com.blabla.projectname
      |
      |_____resources
            |__temporal_file.tmp
</code>```

When uploading a file to an AWS S3 bucket, I experienced the identical issue with PutObjectRequest(String bucketName, String key, File file). This method requires file and file has to exist on disk.

I later discovered that I'm not bounded to the method above since it has a overloaded method
PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata).
Now, rather than explicitly referencing a file, I use MultipartFile.getInputStream(). This way, I can do this without the file really being on the disk.

Returning to my question, is there a way to pause and resume without serializing? Since I'm new to this and really couldn't find anything decent on the internet, I had to ask it here.

I sincerely appreciate your assistance in advance.

Body:
According to AWS Docs, we must serialize and de-serialize the pause result so that, if I resume the upload, I can pick up where I left off:

On a successful upload pause, PauseResult.getInfoToResume() returns an instance of PersistableUpload that can be used to resume the upload operation at a later time.

// Retrieve the persistable upload from the pause result.
PersistableUpload persistableUpload = pauseResult.getInfoToResume();

// Create a new file to store the information.
File f = new File("resume-upload");
if( !f.exists() ) f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);

// Serialize the persistable upload to the file.
persistableUpload.serialize(fos);
fos.close();

Taking into account that my project is organized as follows (Standard Spring Boot Project):

Project Name
|__src
   |__main
      |__java
      |  |__com.blabla.projectname
      |
      |_____resources

Would I have temporary files within the deployed project if I deployed my web application using the method described in the AWS Docs?

Project Name
|__src
   |__main
      |__java
      |  |__com.blabla.projectname
      |
      |_____resources
            |__temporal_file.tmp

When uploading a file to an AWS S3 bucket, I experienced the identical issue with PutObjectRequest(String bucketName, String key, File file). This method requires file and file has to exist on disk.

I later discovered that I'm not bounded to the method above since it has a overloaded method
PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata).
Now, rather than explicitly referencing a file, I use MultipartFile.getInputStream(). This way, I can do this without the file really being on the disk.

Returning to my question, is there a way to pause and resume without serializing? Since I'm new to this and really couldn't find anything decent on the internet, I had to ask it here.

I sincerely appreciate your assistance in advance.


问:
Navigating to item in Xamarin.Forms from a view that has a custom renderer causes blank black/white screen in iOS
When navigating to an item in a Flyout menu from a view that contains a custom renderer, the screen turns into blank black/white screen where the white was the flyout menu, and the black is the detail (see attached). We are using Prism navigation to navigate via the flyout menu.

Screenshot of blank black and white sections

This happens only in iOS.

Expected behavior was to navigate to a different screen/view but, instead, it gave us what you see in the screenshot above. In addition, we have to force-close the app because we get stuck.

At first, we thought that it was a Flyout issue but it appears to be a navigation issue.

Anybody know what may be causing this anomalous behavior?