问:
Can multiple threads call methods from same object from custom made ServiceProvider?
I have one question, I'll explain situation. I have Service which has field DAO. And I am making multithreaded application. Every time I make ClientHandler thread I pass it a new instance of Controller in which I have field Service. My question is should I make evry time new Service for evry new Controller I make, or I can make some ServiceProvider so evry thread (and their controller) can use the same instance of Service from that provider. In service I haven't any state (fields) except DAO field. Also I would make in ServiceProvider instatiation of Service with same instance of DAO. I am using Core Java, no beans, frameworks etc.

What is the best practice in this situation and what gives me better performance and thread safety?


来源: stackexchange

问:
Problem with Javascript loading in an image on the computer in a Tauri webapp, error: "Tauri Not allowed to load local resource"

more on the problem

I would like to load an image on the computer using an absolute path in Javascript.

```<code>const image = new Image()
image.onload = function() => redraw();
image.src = absolutePath;
</code>```

When I build the --debug version and run it the console errors: "Tauri Not allowed to load local resource: absolutePath".
After that it (understandably) gives another error:  Failed to execute 'drawImage' [...] The HTMLImageElement provided is in the 'broken' state "

Some more info: (potentially helpful)
I'm using Tauri + Vanilla HTML, JS, CSS + Rust.
I generated and saved the image using a Rust command invoked in the JS and am trying to put that image into a canvas on the HTML using JS. The Rust part saves the image to the same directory the .exe is in.
build.withGlobalTauri is set to true and am using const invoke = window.__TAURI__.invoke for the invoke command.

things i tried

I have tried setting tauri.allowlist.fs.scope = ["**"] in tauri.conf.json but it did not change anything.

I expected that would allow the JS to access to "load [the] local resource"

my desperation

I've been trying to solve this problem for a while and have found little help from the docs or other sources.

ContentLicense: CC BY-SA 4.0

Body:
more on the problem

I would like to load an image on the computer using an absolute path in Javascript.

const image = new Image()
image.onload = function() => redraw();
image.src = absolutePath;

When I build the --debug version and run it the console errors: "Tauri Not allowed to load local resource: absolutePath".
After that it (understandably) gives another error:  Failed to execute 'drawImage' [...] The HTMLImageElement provided is in the 'broken' state "

Some more info: (potentially helpful)
I'm using Tauri + Vanilla HTML, JS, CSS + Rust.
I generated and saved the image using a Rust command invoked in the JS and am trying to put that image into a canvas on the HTML using JS. The Rust part saves the image to the same directory the .exe is in.
build.withGlobalTauri is set to true and am using const invoke = window.__TAURI__.invoke for the invoke command.

things i tried

I have tried setting tauri.allowlist.fs.scope = ["**"] in tauri.conf.json but it did not change anything.

I expected that would allow the JS to access to "load [the] local resource"

my desperation

I've been trying to solve this problem for a while and have found little help from the docs or other sources.


问:
How do I read a file in NodeJS whose URL is stored in my database?
When I try to read a file that is stored in the database, node gives me an error saying:

"error": "ENOENT: no such file or directory, open 'http://localhost:8000/assets/uploadNk2i8BAE81Wp6pFI6TtF-.pdf'"

But, when I visit that link in the browser, I can see the pdf file. So, why is node failing to read the file?

This is my code:

```<code>fs.readFileSync(req.user.resume, 'utf-8', (err,data) => {
            if(err) {
                res.send(err);
            }

            else {
                res.send(data);
            }
        })
</code>```

Body:
When I try to read a file that is stored in the database, node gives me an error saying:

"error": "ENOENT: no such file or directory, open 'http://localhost:8000/assets/uploadNk2i8BAE81Wp6pFI6TtF-.pdf'"

But, when I visit that link in the browser, I can see the pdf file. So, why is node failing to read the file?

This is my code:

fs.readFileSync(req.user.resume, 'utf-8', (err,data) => {
            if(err) {
                res.send(err);
            }

            else {
                res.send(data);
            }
        })


问:
C# WPF 3D file render with all surface details and colors
For my project, I need to render a STEP file that has surfaces with correct colors. And I would like to control that 3D object orientation with an inertial measurement unit. I spent so much time searching and all I can find is obj file render, but it's only capable of mesh rendering with single surface color.

Is there any simple way I can achieve this?

I only can do obj file render, but it will be a solid color, while my model is made from texts and so on.


问:
cin doesnt take another input correctly after a set of input from while
This is the file_processing_tutor.cpp file:

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"

using namespace std;

void outputline(int, const string &, double);
void outputlineDAT(ostream&, const ClientData &);

int main() {
    cout << endl << "Phase 1 Writing Data to txt" << endl;
    cout << "Make Sure Input is already ready before running" << endl;
    ofstream outClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::out);
    if(!outClientFile){
        cerr << "File could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << "Enter the account, name, and balance" << endl << "Enter end-of-file to end input." << endl;

    int count_input = 0;
    int account;
    string name;
    double balance;

    while(cin >> account >> name >> balance){
        ++count_input;
        outClientFile << account << ' ' << name << ' ' << balance << endl;
        cout << "? (Input Count = " << count_input << ") " << endl;
    }

    cout << endl << endl << "Phase 2 Reading Data from txt" << endl;
    ifstream inClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::in);

    if(!inClientFile){
        cerr << "File Could not be Opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << left << setw(10) << "Account" << setw(13) << "Name" << "Balance" << endl << fixed << showpoint;
    while(inClientFile >> account >> name >> balance){
        outputline(account, name, balance);
    }

    cout << endl << "Phase 3 Writing 100 Blank Records to Random Access File .Dat" << endl;
    fstream outCredit("C:/Users/User/Desktop/Streaming DT Data/credit.dat", ios::out | ios::in | ios::binary);
    if(!outCredit){
        cerr << "File Could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    ClientData blankClient;
    for(int i = 0; i < 100; ++i){
        outCredit.write(reinterpret_cast <const char *>(&blankClient), sizeof(ClientData));
    }

    cout << endl << "Phase 4 Writing Data Randomly to a Random Access File .Dat" << endl;
    string firstName;
    string lastName;

    cout << "Enter Account Number (1 to 100, 0 to end input)\n?";

    ClientData client;
    cin >> account;

    cout << "Account Input: " << account << endl;

    while(account > 0 && account <= 100){
        cout << "Enter lastname, firstname, balance \n?";
        cin >> lastName >> firstName >> balance;

        client.setAccountNumber(account);
        client.setLastName(lastName);
        client.setFirstName(firstName);
        client.setBalance(balance);

        outCredit.seekp((client.getAccountNumber() - 1) * sizeof(ClientData));
        cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
        cin >> account;
    }
    return 0;
}

void outputline(int account, const string &name, double balance){
    cout << left << setw(10) << account << setw(13) << name << setw(7)
    << setprecision(2) << right << balance << endl;
}
void outputlineDAT(ostream &output, const ClientData &record){
    output << left << setw(10) << record.getAccountNumber() << setw(16)
    << record.getLastName() << setw(11) << record.getFirstName() << setw(10)
    << setprecision(2) << right << fixed << showpoint << record.getBalance() << endl;
}
</code>```

Because I am using Sublime Text 3, I set my input in a file called inputf.in, this is all my raw input:

```<code>100 Jones 24.98
200 Doe 345.67
300 White 0
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.5
3
Barker Doug 0
29
Brown Nancy -24.54
96
Stone Sam 34.98
88
Smith Dave 258.34
33
Dunn Stacey 314.33
0
</code>```

And I see my output as follows from outputf.out:

```<code>Phase 1 Writing Data to txt
Make Sure Input is already ready before running
Enter the account, name, and balance
Enter end-of-file to end input.
? (Input Count = 1)
? (Input Count = 2)
? (Input Count = 3)
? (Input Count = 4)
? (Input Count = 5)
? (Input Count = 6)

Phase 2 Reading Data from txt
Account   Name         Balance
100       Jones          24.98
200       Doe           345.67
300       White           0.00
400       Stone         -42.16
500       Rich          224.62
450       Harmond       412.50

Phase 3 Writing 100 Blank Records to Random Access File .Dat

Phase 4 Writing Data Randomly to a Random Access File .Dat
Enter Account Number (1 to 100, 0 to end input)
?Account Input: 450
</code>```

Problem:
So every output in above was ok, until it reached phase 4 where I get to input new data for account variable, Instead of get the input 3 (which is set from the input) it reoutputs the last account data (450) ignoring the cin input. thus it didn't input anything to a file called credit.dat.

Appreciate any pointers to the issues, Thankyou!

Body:
This is the file_processing_tutor.cpp file:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cstdlib>
#include "ClientData.h"

using namespace std;

void outputline(int, const string &, double);
void outputlineDAT(ostream&, const ClientData &);

int main() {
    cout << endl << "Phase 1 Writing Data to txt" << endl;
    cout << "Make Sure Input is already ready before running" << endl;
    ofstream outClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::out);
    if(!outClientFile){
        cerr << "File could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << "Enter the account, name, and balance" << endl << "Enter end-of-file to end input." << endl;

    int count_input = 0;
    int account;
    string name;
    double balance;

    while(cin >> account >> name >> balance){
        ++count_input;
        outClientFile << account << ' ' << name << ' ' << balance << endl;
        cout << "? (Input Count = " << count_input << ") " << endl;
    }

    cout << endl << endl << "Phase 2 Reading Data from txt" << endl;
    ifstream inClientFile("C:/Users/User/Desktop/Streaming DT Data/test.txt", ios::in);

    if(!inClientFile){
        cerr << "File Could not be Opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << left << setw(10) << "Account" << setw(13) << "Name" << "Balance" << endl << fixed << showpoint;
    while(inClientFile >> account >> name >> balance){
        outputline(account, name, balance);
    }

    cout << endl << "Phase 3 Writing 100 Blank Records to Random Access File .Dat" << endl;
    fstream outCredit("C:/Users/User/Desktop/Streaming DT Data/credit.dat", ios::out | ios::in | ios::binary);
    if(!outCredit){
        cerr << "File Could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    ClientData blankClient;
    for(int i = 0; i < 100; ++i){
        outCredit.write(reinterpret_cast <const char *>(&blankClient), sizeof(ClientData));
    }

    cout << endl << "Phase 4 Writing Data Randomly to a Random Access File .Dat" << endl;
    string firstName;
    string lastName;

    cout << "Enter Account Number (1 to 100, 0 to end input)\n?";

    ClientData client;
    cin >> account;

    cout << "Account Input: " << account << endl;

    while(account > 0 && account <= 100){
        cout << "Enter lastname, firstname, balance \n?";
        cin >> lastName >> firstName >> balance;

        client.setAccountNumber(account);
        client.setLastName(lastName);
        client.setFirstName(firstName);
        client.setBalance(balance);

        outCredit.seekp((client.getAccountNumber() - 1) * sizeof(ClientData));
        cout << "Enter Account Number (1 to 100, 0 to end input)\n?";
        cin >> account;
    }
    return 0;
}

void outputline(int account, const string &name, double balance){
    cout << left << setw(10) << account << setw(13) << name << setw(7)
    << setprecision(2) << right << balance << endl;
}
void outputlineDAT(ostream &output, const ClientData &record){
    output << left << setw(10) << record.getAccountNumber() << setw(16)
    << record.getLastName() << setw(11) << record.getFirstName() << setw(10)
    << setprecision(2) << right << fixed << showpoint << record.getBalance() << endl;
}

Because I am using Sublime Text 3, I set my input in a file called inputf.in, this is all my raw input:

100 Jones 24.98
200 Doe 345.67
300 White 0
400 Stone -42.16
500 Rich 224.62
450 Harmond 412.5
3
Barker Doug 0
29
Brown Nancy -24.54
96
Stone Sam 34.98
88
Smith Dave 258.34
33
Dunn Stacey 314.33
0

And I see my output as follows from outputf.out:

Phase 1 Writing Data to txt
Make Sure Input is already ready before running
Enter the account, name, and balance
Enter end-of-file to end input.
? (Input Count = 1)
? (Input Count = 2)
? (Input Count = 3)
? (Input Count = 4)
? (Input Count = 5)
? (Input Count = 6)

Phase 2 Reading Data from txt
Account   Name         Balance
100       Jones          24.98
200       Doe           345.67
300       White           0.00
400       Stone         -42.16
500       Rich          224.62
450       Harmond       412.50

Phase 3 Writing 100 Blank Records to Random Access File .Dat

Phase 4 Writing Data Randomly to a Random Access File .Dat
Enter Account Number (1 to 100, 0 to end input)
?Account Input: 450

Problem:
So every output in above was ok, until it reached phase 4 where I get to input new data for account variable, Instead of get the input 3 (which is set from the input) it reoutputs the last account data (450) ignoring the cin input. thus it didn't input anything to a file called credit.dat.

Appreciate any pointers to the issues, Thankyou!


问:
ImportError: No module named serial in Linux
I encountered a problem with topic is ImportError: No module named serial by I use it in Linux ubuntu 20.04, and my python version is 3.8.10.

```<code>Traceback (most recent call last):
  File "/home/prawee/catkin_ws/src/ros_myo_2/scripts/myo-rawNode.py", line 9, in <module>
    import serial
ImportError: No module named serial
</code>```

And I have pyserial version 3.5 installed. I have tried repeating the serial install which says this.

```<code>Requirement already satisfied: pyserial in /usr/local/lib/python3.8/dist-packages (3.5)
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
WARNING: There was an error checking the latest version of pip.
</code>```

I wonder if this warning is related to problem?

This problem just happened for the first time. Before this I was able to use it normally. I have tried many ways but still don't understand how to fix it, please help me.

I am stuck in a problem import serial which I hope to be able to fix and use it again the way it used to be.

Body:
I encountered a problem with topic is ImportError: No module named serial by I use it in Linux ubuntu 20.04, and my python version is 3.8.10.

Traceback (most recent call last):
  File "/home/prawee/catkin_ws/src/ros_myo_2/scripts/myo-rawNode.py", line 9, in <module>
    import serial
ImportError: No module named serial

And I have pyserial version 3.5 installed. I have tried repeating the serial install which says this.

Requirement already satisfied: pyserial in /usr/local/lib/python3.8/dist-packages (3.5)
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
WARNING: There was an error checking the latest version of pip.

I wonder if this warning is related to problem?

This problem just happened for the first time. Before this I was able to use it normally. I have tried many ways but still don't understand how to fix it, please help me.

I am stuck in a problem import serial which I hope to be able to fix and use it again the way it used to be.


问:
Numpy array only containing [0,0,0,1] when using imread on png file
Im using matplotlib and numpy to turn a png file (link to image: https://imgpile.com/i/boANTE) into a  2d array using this code:

```<code>import numpy as np
from matplotlib import pyplot as mat_plot

mapimage = mat_plot.imread("map.png")

print(mapimage)
</code>```

when I run this the output looks like this

```<code> [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]

 [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]

 [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]]
</code>```

I don't understand why this is happening as the png file contains coloured pixels but they are not being shown in the 2d array, even though when I open the image with matplotlib and hover over coloured pixels I can see that they should have rgb values other than 0,0,0.

Body:
Im using matplotlib and numpy to turn a png file (link to image: https://imgpile.com/i/boANTE) into a  2d array using this code:

import numpy as np
from matplotlib import pyplot as mat_plot

mapimage = mat_plot.imread("map.png")

print(mapimage)

when I run this the output looks like this

 [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]

 [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]

 [[0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  ...
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]
  [0. 0. 0. 1.]]]

I don't understand why this is happening as the png file contains coloured pixels but they are not being shown in the 2d array, even though when I open the image with matplotlib and hover over coloured pixels I can see that they should have rgb values other than 0,0,0.


问:
MERN stack decoupling to serverless dilemma
First off, I want to say that I’m not a developer. I wanted to learn how to code, so I just started building. Therefore, if my ramblings below sound “off”, this is why.

I created a MERN stack for something that imo is overkill for what I was trying to achieve.

Since then, I’ve started ‘decoupling’ the stack. I’ve moved MongoDB to Atlas, and have configured the serverless REST API/API Gateway to communicate with it.

That leaves me with the frontend.

I want the bare minimum website….A product page (homepage/landing page), login/signup/authorization (cognito), and documentation page (Theneo docs).

The user flow is something like this…..user signup > receives a confirmation email (Nodemailer but I want to change to SES). The user logs in and can change their password, change their api key, or delete their account.

My brain is telling me that the website/frontend could be serverless, just “connect” it to the backend and voilà….mvp!!!  But it’s also telling me don’t ditch the MERN stack you’ve worked so hard on.

Is what I want to achieve possible via serverless? Do I ditch the React webpage, and create and static website? Am I making any sense? Whats the best way to accomplish this?


问:
Postfix mysql check users domain before sending
I want to check the domains belonging to the sender on relation user_id.

main.cf

```<code>virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domain.cf
</code>```

mysql-virtual_domain.cf

```<code>user = ***
password = ***
dbname = ***
hosts = 127.0.0.1
query = SELECT d.domain FROM users AS u LEFT JOIN domains AS d ON u.id = d.user_id
    WHERE u.email='???'
    AND d.domain='%s' AND d.blocked_at IS NULL AND d.active=1
</code>```

can you suggest how you can perform a similar query to check domains :)

Body:
I want to check the domains belonging to the sender on relation user_id.

main.cf

virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domain.cf

mysql-virtual_domain.cf

user = ***
password = ***
dbname = ***
hosts = 127.0.0.1
query = SELECT d.domain FROM users AS u LEFT JOIN domains AS d ON u.id = d.user_id
    WHERE u.email='???'
    AND d.domain='%s' AND d.blocked_at IS NULL AND d.active=1

can you suggest how you can perform a similar query to check domains :)


问:
Could not install from "angular\core@10.0.14" as it does not contain a package.json file
I am getting this error when I run npm list

```<code>npm ERR! peer dep missing: @angular/compiler@15.0.3, required by @angular/compiler-cli@15.0.3
npm ERR! peer dep missing: @angular/compiler@10.0.14, required by @angular/platform-browser-dynamic@10.0.14
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @angular-builders/custom-webpack@14.1.0
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/animations@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/common@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/forms@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/platform-browser@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/platform-browser-dynamic@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/router@10.0.14
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @angular-devkit/build-angular@14.2.10
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @ngtools/webpack@14.2.10
</code>```

and when I tried to install the missing library using npm install angular/core@10.0.14

I get the following error

```<code>npm ERR! code ENOLOCAL
npm ERR! Could not install from "angular\core@10.0.14" as it does not contain a package.json file.
</code>```

Body:
I am getting this error when I run npm list

npm ERR! peer dep missing: @angular/compiler@15.0.3, required by @angular/compiler-cli@15.0.3
npm ERR! peer dep missing: @angular/compiler@10.0.14, required by @angular/platform-browser-dynamic@10.0.14
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @angular-builders/custom-webpack@14.1.0
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/animations@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/common@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/forms@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/platform-browser@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/platform-browser-dynamic@10.0.14
npm ERR! peer dep missing: @angular/core@10.0.14, required by @angular/router@10.0.14
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @angular-devkit/build-angular@14.2.10
npm ERR! peer dep missing: @angular/compiler-cli@^14.0.0, required by @ngtools/webpack@14.2.10

and when I tried to install the missing library using npm install angular/core@10.0.14

I get the following error

npm ERR! code ENOLOCAL
npm ERR! Could not install from "angular\core@10.0.14" as it does not contain a package.json file.


问:
Adobe Media Encoder - Script to Auto Adjust Layer Length and Trim Comp
I'm completely new to scripting for the Adobe suite, and I'm thinking of going deeper since I work as a Motion Designer.

The point is: I constantly have some jobs where I need to render square videos for ADS, these videos are inside filters, that is, the video I receive is recorded horizontally, so I create two bars, one upper and one lower and animate with the customer's identity.

After making this identity, I usually need to render many videos, where the identity is exactly the same, what changes is the video and its duration.

Therefore, I would like to know if it is possible to create a script in ExtendedScript or in VS Code that asks the Media Encoder to read the Video project in the monitored folder, pull the video layer to the maximum size and mark the output of rendering at the end of this Video layer before rendering the video.

If that's possible, I can simply replace the video file in the folder and drop the project into rendering, which would speed up the workflow considerably.


问:
Android WebView camera clicked image not loading in file input
On my webview app I am able to choose an image from gallery and upload properly but I am not being able to click photo from the camera directly. Whenever I click photo from the camera option and then I click on "Ok", then it comes back to the app from the camera section but the clicked image is not loaded in the file input option for upload. I am not sure what mistake I am committing here. Something with the file path? I am not sure. Everything seems fine to me.

Manifest Permissions

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

MainActivity.java

```<code>webView.setWebChromeClient(new WebChromeClient() {
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg", storageDir);
    }

    public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
        if(mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(null);
        }

        mFilePathCallback = filePath;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if(takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;

            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
            } catch (IOException ex) {
                Log.e(TAG, "Unable to create Image File", ex);
            }

            if(photoFile != null) {
                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }

        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;

        if(takePictureIntent != null) {
            intentArray = new Intent[]{
                takePictureIntent
            };
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
        return true;
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AndroidExampleFolder");

        if(!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }

        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        mCapturedImageURI = Uri.fromFile(file);
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {
            captureIntent
        });
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        openFileChooser(uploadMsg, acceptType);
    }
});

// OUTSIDE onCreate class
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        Uri[] results = null;

        if(resultCode == Activity.RESULT_OK) {
            if(data == null) {
                // If there is not data, then we may have taken a photo
                if(mCameraPhotoPath != null) {
                    results = new Uri[]{
                        Uri.parse(mCameraPhotoPath)
                    };
                }
            } else {
                String dataString = data.getDataString();
                if(dataString != null) {
                    results = new Uri[]{
                        Uri.parse(dataString)
                    };
                }
            }
        }

        mFilePathCallback.onReceiveValue(results);
        mFilePathCallback = null;
    } else if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        if(requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        if(requestCode == FILECHOOSER_RESULTCODE) {
            if(this.mUploadMessage == null) {
                return;
            }

            Uri result = null;

            try {
                if(resultCode == RESULT_OK) {
                    result = data == null ? mCapturedImageURI : data.getData();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_SHORT).show();
            }

            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
}
</code>```

Body:
On my webview app I am able to choose an image from gallery and upload properly but I am not being able to click photo from the camera directly. Whenever I click photo from the camera option and then I click on "Ok", then it comes back to the app from the camera section but the clicked image is not loaded in the file input option for upload. I am not sure what mistake I am committing here. Something with the file path? I am not sure. Everything seems fine to me.

Manifest Permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivity.java

webView.setWebChromeClient(new WebChromeClient() {
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg", storageDir);
    }

    public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
        if(mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(null);
        }

        mFilePathCallback = filePath;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if(takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;

            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
            } catch (IOException ex) {
                Log.e(TAG, "Unable to create Image File", ex);
            }

            if(photoFile != null) {
                mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }

        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;

        if(takePictureIntent != null) {
            intentArray = new Intent[]{
                takePictureIntent
            };
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
        return true;
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMessage = uploadMsg;
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AndroidExampleFolder");

        if(!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }

        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        mCapturedImageURI = Uri.fromFile(file);
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {
            captureIntent
        });
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        openFileChooser(uploadMsg, acceptType);
    }
});

// OUTSIDE onCreate class
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        Uri[] results = null;

        if(resultCode == Activity.RESULT_OK) {
            if(data == null) {
                // If there is not data, then we may have taken a photo
                if(mCameraPhotoPath != null) {
                    results = new Uri[]{
                        Uri.parse(mCameraPhotoPath)
                    };
                }
            } else {
                String dataString = data.getDataString();
                if(dataString != null) {
                    results = new Uri[]{
                        Uri.parse(dataString)
                    };
                }
            }
        }

        mFilePathCallback.onReceiveValue(results);
        mFilePathCallback = null;
    } else if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        if(requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        if(requestCode == FILECHOOSER_RESULTCODE) {
            if(this.mUploadMessage == null) {
                return;
            }

            Uri result = null;

            try {
                if(resultCode == RESULT_OK) {
                    result = data == null ? mCapturedImageURI : data.getData();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_SHORT).show();
            }

            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
}


问:
How to change the default gcc/g++ include and library search path on macOS running on an apple m1 silicon
I've installed the boost library using homebrew on an Apple M1 silicon running macOS Ventura (13.0)

The library and the headers got installed in the directory

```<code>/opt/homebrew/Cellar/boost/1.80.0/
</code>```

and symbolic links got created in directory

/opt/homebrew/lib/ and /opt/homebrew/include pointing to the aforementioned install dir.

The question is: Where I need to create symbolic links to make CMake find the boost specific resources without specifying following command in a every CMake-based C++-project?

```<code>link_directories("/opt/homebrew/lib")
include_directories("/opt/homebrew/include")
</code>```

I guess, I need to find out what is the default CMake include and library search path and afterwards to create there the symbolic links.

The default include and library search path seems to be

```<code>`/Library/Developer/CommandLineTools/usr/include` and `/Library/Developer/CommandLineTools/usr/include`
</code>```

Any help would be appreciated.

Body:
I've installed the boost library using homebrew on an Apple M1 silicon running macOS Ventura (13.0)

The library and the headers got installed in the directory

/opt/homebrew/Cellar/boost/1.80.0/

and symbolic links got created in directory

/opt/homebrew/lib/ and /opt/homebrew/include pointing to the aforementioned install dir.

The question is: Where I need to create symbolic links to make CMake find the boost specific resources without specifying following command in a every CMake-based C++-project?

link_directories("/opt/homebrew/lib")
include_directories("/opt/homebrew/include")

I guess, I need to find out what is the default CMake include and library search path and afterwards to create there the symbolic links.

The default include and library search path seems to be

`/Library/Developer/CommandLineTools/usr/include` and `/Library/Developer/CommandLineTools/usr/include`

Any help would be appreciated.


问:
Does Mono.fromSupplier lead to identical results as using R2DBC
Imagine you have a Postgres database. The driver in use is blocking. To move the resource access into reactive world, you wrap the blocking call in a Mono:

```<code>Mono.fromSupplier { repository.find(id) }
</code>```

According to the r2dbc docs the connection itself is wrapped in a Mono when using the driver:

```<code>Mono.from(connectionFactory.create())
  .flatMapMany(connection -> ..)
  .flatMap(result -> ..)
  .subscribe();
</code>```

Is the resulting behaviour identical to using a reactive driver like R2DBC? If not, what difference does it make?

Body:
Imagine you have a Postgres database. The driver in use is blocking. To move the resource access into reactive world, you wrap the blocking call in a Mono:

Mono.fromSupplier { repository.find(id) }

According to the r2dbc docs the connection itself is wrapped in a Mono when using the driver:

Mono.from(connectionFactory.create())
  .flatMapMany(connection -> ..)
  .flatMap(result -> ..)
  .subscribe();

Is the resulting behaviour identical to using a reactive driver like R2DBC? If not, what difference does it make?


问:
Django Model Data Only To XML
I have this simple model

```<code>class TestData(models.Model):
rcrd_pk = models.AutoField(primary_key=True)
Name = models.CharField(max_length=50)
desc = models.CharField(max_length=300, blank=True, null=True)
</code>```

I want  to get XML of model data.
so I have written this code

```<code>from sms_api.models import TestData
from django.core import serializers
data = TestData.objects.all()
XmlData = serializers.serialize("xml",data)
print (XmlData)
</code>```

This code Export XML like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object model="sms_api.testdata" pk="1">
    <field name="Name" type="CharField">Roqaiah</field>
    <field name="desc" type="CharField">Rogaiah is Old Arabic Name</field>
</object>
<object model="sms_api.testdata" pk="2">
    <field name="Name" type="CharField">Khadeejah</field>
    <field name="desc" type="CharField">Kahdejah is an Arabic Name</field>
</object>
</django-objects>
</code>```

This way exported the Model with datatypes and others unwanted deteails.

I want the ouput to be simple like so

```<code><?xml version="1.0" encoding="utf-8"?>
<django-objects">
<object>
    <Name>Roqaiah</Name>
    <desc>Rogaiah is Old Arabic Name</desc>
</object>
<object>
    <Name>Khadeejah</Name>
    <desc>Kahdejah is an Arabic Name</desc>
</object>
</django-objects>
</code>```

The last Thing if I can change the tags of the xml,
so those tags

```<code><django-objects>
<object>
</code>```

can be

```<code><RowSets>
<Row>
</code>```

Title: Django Model Data Only To XML

Body:
I have this simple model

class TestData(models.Model):
rcrd_pk = models.AutoField(primary_key=True)
Name = models.CharField(max_length=50)
desc = models.CharField(max_length=300, blank=True, null=True)

I want  to get XML of model data.
so I have written this code

from sms_api.models import TestData
from django.core import serializers
data = TestData.objects.all()
XmlData = serializers.serialize("xml",data)
print (XmlData)

This code Export XML like this:

<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object model="sms_api.testdata" pk="1">
    <field name="Name" type="CharField">Roqaiah</field>
    <field name="desc" type="CharField">Rogaiah is Old Arabic Name</field>
</object>
<object model="sms_api.testdata" pk="2">
    <field name="Name" type="CharField">Khadeejah</field>
    <field name="desc" type="CharField">Kahdejah is an Arabic Name</field>
</object>
</django-objects>

This way exported the Model with datatypes and others unwanted deteails.

I want the ouput to be simple like so

<?xml version="1.0" encoding="utf-8"?>
<django-objects">
<object>
    <Name>Roqaiah</Name>
    <desc>Rogaiah is Old Arabic Name</desc>
</object>
<object>
    <Name>Khadeejah</Name>
    <desc>Kahdejah is an Arabic Name</desc>
</object>
</django-objects>

The last Thing if I can change the tags of the xml,
so those tags

<django-objects>
<object>

can be

<RowSets>
<Row>


问:
when I upload my website only show index.php page
I'm trying to upload my website to digital ocean,
but my home only show public/index.php

apache2 000-default.conf

```<code><VirtualHost *:80>
     ServerAdmin admin@domain.com
     DocumentRoot /var/www/html/laravelProject/public
     ServerName Domain.com

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /var/www/html/laravelProject/>

         Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
     </Directory>

   RewriteEngine on
RewriteCond %{SERVER_NAME} =Domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

</code>```

/var/www/html/laravelProject/public/.htaccess

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
        RewriteEngine On
        RewriteBase /
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

</code>```

apache2.conf

```<code><Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
</code>```

tools vision
Ubuntu 20.04
Apache 2.4.4
PHP 8.1.13
Mysql 8

I am try

000-dafault.conf

laravelProject/public/.htaccess

/etc/apache2 vi apache2.conf

sudo a2enmod rewrite

but my website only show index.php.....

Body:
I'm trying to upload my website to digital ocean,
but my home only show public/index.php

apache2 000-default.conf

<VirtualHost *:80>
     ServerAdmin admin@domain.com
     DocumentRoot /var/www/html/laravelProject/public
     ServerName Domain.com

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /var/www/html/laravelProject/>

         Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
     </Directory>

   RewriteEngine on
RewriteCond %{SERVER_NAME} =Domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

/var/www/html/laravelProject/public/.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
        RewriteEngine On
        RewriteBase /
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

apache2.conf

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

tools vision
Ubuntu 20.04
Apache 2.4.4
PHP 8.1.13
Mysql 8

I am try

000-dafault.conf

laravelProject/public/.htaccess

/etc/apache2 vi apache2.conf

sudo a2enmod rewrite

but my website only show index.php.....


问:
Read & Parse a SCORM package to return course content via API in NodeJS
I am currently working on creating an NodeJS API endpoint which helps in

unzip a zipped SCORM package and parse it's content.

Return the course content after parsing the unzipped SCORM package.

I don't know what is the structure of a SCORM package and how to parse a zipped SCORM package return the associated course data.

Thanks in advance for any help.


问:
How to click on flickity slide programatically?
I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ? I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ? I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ?</p>
```<code><section>
    <div class="container">
      <h1>Flickity Slider with Verticle Thumbnail</h1>

      <div class="row">
        <div class="left">
          <div class="carousel carousel-nav" data-flickity='{ "asNavFor": ".carousel-main",  "prevNextButtons": false, "focusOnSelect": true, "contain" : true, "pageDots": false, "contain": true, "setGallerySize": false }'>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
            <div id="bangla" class="carousel-cell"></div>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
          </div>
        </div>
        <div class="right">
          <div class="carousel carousel-main" data-flickity='{ "sync": ".carousel-nav", "prevNextButtons": false , "pageDots": false }'>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
            <div class="carousel-cell">Bangla</div>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
            <div class="carousel-cell"></div>
          </div>
        </div>
      </div>
    </div>
</section>

<Button onclick="document.querySelector('#bangla').click();">Button</Button>
</code>```

Body:
I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ? I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ? I am trying to click on the nav slider by js and change the main slider as like as the mouse click.can anyone help me with this ?

Flickity Slider with Verticle Thumbnail

Bangla

<Button onclick="document.querySelector('#bangla').click();">Button</Button>


问:
How to serve Reactjs specific version number
I am working on Reactjs project, currently i am facing one issue whenever we create any new feature,sometimes there are some breaking changes i need to tell users to logout or refresh application to get new features,if they don't logout they face some issues.
How can I support the old version as well, or is there any other way to solve this problem without breaking the old code</p>


问:
Converting the argument to Control [ CS1503 ]
I have a simple alarm project. I made an operation to create as many alarms as desired, but I am having problems while adding to the new form. The logic of the application is, I start a countdown by creating a new form and adding a timer to it.

I am getting the error

Compiler Error CS1503: the best overloaded method match for 'name' has some invalid arguments

private void button7_Click(object sender, EventArgs e)
{
    Form frm = new Form();
    frm.Controls.Add(new Label() { Text = tiffBoxName + "->CountTime " });
    frm.Controls.Add(new Label() { Text = "|" });
    frm.Controls.Add(count_down(textBox1.Text));
    frm.Show();
}

internal void count_down(string timeLimit)
{
    System.Media.SoundPlayer player = new System.Media.SoundPlayer(ReloadSound);
    int duration = Int32.Parse(timeLimit);
    if (duration == 0)
    {
        countTimer1.Stop();

        player.Play();
        notifyIcon1.ShowBalloonTip(1200);
        Task.Delay(1200);
        notifyIcon1.Visible = false;
    }
    else if (duration > 0)
    {
        duration--;
        labelCount1.Text = duration.ToString();
    }
}
```

The documentation on this did not help me. what can i do to pass the functions and variables to the new form and run them?

Body:
I have a simple alarm project. I made an operation to create as many alarms as desired, but I am having problems while adding to the new form. The logic of the application is, I start a countdown by creating a new form and adding a timer to it.

I am getting the error

Compiler Error CS1503: the best overloaded method match for 'name' has some invalid arguments

private void button7_Click(object sender, EventArgs e)
{
    Form frm = new Form();
    frm.Controls.Add(new Label() { Text = tiffBoxName + "->CountTime " });
    frm.Controls.Add(new Label() { Text = "|" });
    frm.Controls.Add(count_down(textBox1.Text));
    frm.Show();
}

internal void count_down(string timeLimit)
{
    System.Media.SoundPlayer player = new System.Media.SoundPlayer(ReloadSound);
    int duration = Int32.Parse(timeLimit);
    if (duration == 0)
    {
        countTimer1.Stop();

        player.Play();
        notifyIcon1.ShowBalloonTip(1200);
        Task.Delay(1200);
        notifyIcon1.Visible = false;
    }
    else if (duration > 0)
    {
        duration--;
        labelCount1.Text = duration.ToString();
    }
}

The documentation on this did not help me. what can i do to pass the functions and variables to the new form and run them?


问:
Get body from POST in Flask
I am very new to Flask and have the following Flask code:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

@app.route('/test/<email>', methods = ['GET', 'POST'], strict_slashes=False)
def test(email):
    if request.method == 'GET':
        print("USERS_EMAIL: ", email)
        return 'GET REQUEST', 202

    if request.method == 'POST':
        print("USERS_EMAIL: ", email)
        body = request.json['email_subject']
        print("BODY: ", body)
        return '', 201
    return 'ERROR', 400
```
<p>I need to send a JSON object from my react frontend end retrieve it in Flask. I am sending the following body in POSTMAN but I get this error every time (at the bottom of the post):</p>
<p><strong>BODY:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
  "email_subject": "Postman test",
  "title": "Lysenko Ilya Igorevich"
}
</code>```

Things I have tried:

I found these two links (link1, link2) which seemed to be saying two different things, so first I tried both of these options:

body = request.json['body']
```
<pre class="lang-py prettyprint-override"><code>body = request.get_json()
</code>```

neither which worked. I was then wondering whether the name in the square brackets refers not to the body but to the key in the body, so I then tried the following:

body = request.json['email_subject']
```

which did not work either. Any suggestions?

(screenshot of my postman error)

Title: Get body from POST in Flask

Body:
I am very new to Flask and have the following Flask code:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

@app.route('/test/<email>', methods = ['GET', 'POST'], strict_slashes=False)
def test(email):
    if request.method == 'GET':
        print("USERS_EMAIL: ", email)
        return 'GET REQUEST', 202

    if request.method == 'POST':
        print("USERS_EMAIL: ", email)
        body = request.json['email_subject']
        print("BODY: ", body)
        return '', 201
    return 'ERROR', 400

I need to send a JSON object from my react frontend end retrieve it in Flask. I am sending the following body in POSTMAN but I get this error every time (at the bottom of the post):

BODY:

{
  "email_subject": "Postman test",
  "title": "Lysenko Ilya Igorevich"
}

Things I have tried:

I found these two links (link1, link2) which seemed to be saying two different things, so first I tried both of these options:

body = request.json['body']

body = request.get_json()

neither which worked. I was then wondering whether the name in the square brackets refers not to the body but to the key in the body, so I then tried the following:

body = request.json['email_subject']

which did not work either. Any suggestions?

(screenshot of my postman error)


问:
Supervised ML to extract keywords from short texts
I have a lot training data ready and looking for an ML algorithm to replace the current algorithms.
The input is a paragraph containing a short biography of a person and the output is their dates of birth and name.
What algorithm can output a set of keywords based on short texts?</p>


问:
Having issues with the integration of an event into one of the buttons
I'm currently having difficulties with running a code that does the following:

Creates a plot graph when the "Create Obstacle Course" button is manually clicked.

Creates a square that's plotted in the graph which can be moved manually when the "Create Robot" button is clicked

The main issue that I'm having right now is that I keep getting an error message that states TypeError: keypress() missing 1 required positional argument: 'event' whenever I press the "Create Robot" button while running the code. Thus, this results in the movable square not showing up in the plot graph at all. However, there may be more underlying issues present in my code that I'm not aware of yet.

The following code I have now will be pasted below:

```<code>from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)

root = Tk()

def plot():

    fig = Figure(figsize = (5, 5),
                 dpi = 100)
    plot = fig.add_subplot(1, 1, 1)

    x = [ -1.0, 0.0, 3.0, 4.5, 4.0 ,5.0, 6.0, 8.0, 7.0, 7.0, 9.0, 10.0, 12.0, 14.5, 13.0 ]
    y = [ -1.0, 1.0, 2.0, 4.0, 5.0, 6.0, 9.0, 8.0, 9.0, 10.0, 11.0, 13.0, 12.0, 15.0, 13.0 ]

    plot.plot(x, y, color="black", marker="o",   linestyle="")
    #Plots main barrier points

    x = [ 11.0 ]

    y = [ 3.0 ]

    plot.plot(x, y, color="red", marker="o",   linestyle="")
    #Plots goal point

    canvas = FigureCanvasTkAgg(fig, root)
    canvas.get_tk_widget().pack()

    canvas_width = 600
    canvas_height = 400
    w = canvas_width // 2
    h = canvas_height // 2

    canvas = FigureCanvasTkAgg(root, width=w, height=h)
    canvas.pack()

def keypress(event):

      canvas_width = 600
      canvas_height = 400
      w = canvas_width // 2
      h = canvas_height // 2

      canvas = Tk.Canvas(root, width=w, height=h)

      r1 = canvas.create_rectangle(w, h, w + 10, h + 10)
      t = canvas.create_text(w + 20, h + 5, text="")

      x, y = 12, 0

      if event.char == "a": x = -8
      if event.char == "d": x = 8
      if event.char == "w": y = -8
      if event.char == "s": y = 8

      canvas.move(r1, x, y)
      canvas.move(t, x, y)

root.title('Robot Simulation')

root.geometry("500x500")

plot_button = Button(master = root,
                     command = plot,
                     height = 2,
                     width = 25,
                     text = "Create Obstacle Course")

plot_button.pack()

keypress_button = Button(master = root,
                         command = keypress,
                         height = 4,
                         width = 20,
                         text = "Create Robot")

keypress_button.pack()

root.mainloop()
</code>```

Although the keypress code works on its own for me in the provided code below, I can't find a way to integrate it properly into a button click. Any suggestions on what I should do? This code was run on Replit.

Below is the piece of code I tried to integrate into a manual button click:

```<code>import tkinter as tk

root = tk.Tk()

canvas_width = 600
canvas_height = 400
w = canvas_width // 2
h = canvas_height // 2
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
canvas.pack()

r1 = canvas.create_rectangle(w, h, w + 40, h + 10)
t = canvas.create_text(w + 20, h + 5, text="Hello")

def keypress(event):
    """The 4 key press"""
    x, y = 0, 0
    if event.char == "a":
        x = -10
    if event.char == "d":
        x = 10
    if event.char == "w":
        y = -10
    if event.char == "s":
        y = 10
    canvas.move(r1, x, y)
    canvas.move(t, x, y)

root.bind("<Key>", keypress)
root.mainloop()
</code>```

Body:
I'm currently having difficulties with running a code that does the following:

Creates a plot graph when the "Create Obstacle Course" button is manually clicked.

Creates a square that's plotted in the graph which can be moved manually when the "Create Robot" button is clicked

The main issue that I'm having right now is that I keep getting an error message that states TypeError: keypress() missing 1 required positional argument: 'event' whenever I press the "Create Robot" button while running the code. Thus, this results in the movable square not showing up in the plot graph at all. However, there may be more underlying issues present in my code that I'm not aware of yet.

The following code I have now will be pasted below:

from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)

root = Tk()

def plot():

    fig = Figure(figsize = (5, 5),
                 dpi = 100)
    plot = fig.add_subplot(1, 1, 1)

    x = [ -1.0, 0.0, 3.0, 4.5, 4.0 ,5.0, 6.0, 8.0, 7.0, 7.0, 9.0, 10.0, 12.0, 14.5, 13.0 ]
    y = [ -1.0, 1.0, 2.0, 4.0, 5.0, 6.0, 9.0, 8.0, 9.0, 10.0, 11.0, 13.0, 12.0, 15.0, 13.0 ]

    plot.plot(x, y, color="black", marker="o",   linestyle="")
    #Plots main barrier points

    x = [ 11.0 ]

    y = [ 3.0 ]

    plot.plot(x, y, color="red", marker="o",   linestyle="")
    #Plots goal point

    canvas = FigureCanvasTkAgg(fig, root)
    canvas.get_tk_widget().pack()

    canvas_width = 600
    canvas_height = 400
    w = canvas_width // 2
    h = canvas_height // 2

    canvas = FigureCanvasTkAgg(root, width=w, height=h)
    canvas.pack()

def keypress(event):

      canvas_width = 600
      canvas_height = 400
      w = canvas_width // 2
      h = canvas_height // 2

      canvas = Tk.Canvas(root, width=w, height=h)

      r1 = canvas.create_rectangle(w, h, w + 10, h + 10)
      t = canvas.create_text(w + 20, h + 5, text="")

      x, y = 12, 0

      if event.char == "a": x = -8
      if event.char == "d": x = 8
      if event.char == "w": y = -8
      if event.char == "s": y = 8

      canvas.move(r1, x, y)
      canvas.move(t, x, y)

root.title('Robot Simulation')

root.geometry("500x500")

plot_button = Button(master = root,
                     command = plot,
                     height = 2,
                     width = 25,
                     text = "Create Obstacle Course")

plot_button.pack()

keypress_button = Button(master = root,
                         command = keypress,
                         height = 4,
                         width = 20,
                         text = "Create Robot")

keypress_button.pack()

root.mainloop()

Although the keypress code works on its own for me in the provided code below, I can't find a way to integrate it properly into a button click. Any suggestions on what I should do? This code was run on Replit.

Below is the piece of code I tried to integrate into a manual button click:

import tkinter as tk

root = tk.Tk()

canvas_width = 600
canvas_height = 400
w = canvas_width // 2
h = canvas_height // 2
canvas = tk.Canvas(root, width=canvas_width, height=canvas_height)
canvas.pack()

r1 = canvas.create_rectangle(w, h, w + 40, h + 10)
t = canvas.create_text(w + 20, h + 5, text="Hello")

def keypress(event):
    """The 4 key press"""
    x, y = 0, 0
    if event.char == "a":
        x = -10
    if event.char == "d":
        x = 10
    if event.char == "w":
        y = -10
    if event.char == "s":
        y = 10
    canvas.move(r1, x, y)
    canvas.move(t, x, y)

root.bind("<Key>", keypress)
root.mainloop()


问:
Postgresql recursive query, getting a table with non duplicates but also a view with extra informations (for a left join)
I would like to get in one calculations two tables (if possible something like views) out of a recursive query.
I have recursive query, and in this query new items where calculated. These new items have (an unknown number of) new calculated values.

My example only generates the ids of natural numbers. In each iteration it creates a new id and some values for it.

Now it is my target to get a view for the ids and a view for the extra_values, so that i dont break the second Normal Form.

Here is my example on dbfiddle.

```<code>CREATE TABLE IF NOT EXISTS public.extra_info
(
    id integer,
  sub_id integer,
  value integer
);

CREATE OR REPLACE FUNCTION public.calc_stuff(id integer, ar integer[])
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
 declare
  rand integer;
  i integer;
 Begin
    RAISE NOTICE 'ar: %', ar;
    rand = random() * 5 + 1::integer;
    FOR i in 1..rand
    LOOP
        INSERT INTO extra_info SELECT id+1 AS id, i AS sub_id, random() * 1000 + 1::integer AS value;
    END LOOP;
    RETURN id+1;
 END

$BODY$;

DELETE FROM extra_info;
CREATE MATERIALIZED VIEW my_ids AS (
  WITH RECURSIVE rec_part AS(
    SELECT 1 AS id
    UNION
    SELECT calc_stuff(rp.id, array_agg(ei.value) OVER (PARTITION BY rp.id))
       FROM rec_part rp
      LEFT JOIN extra_info ei
         ON rp.id = ei.id
       WHERE rp.id < 20
  )
SELECT id FROM rec_part
)
</code>```

Here should be a problem, because my values (in my case) depend on the old values, and here the query can not handle the new values in extra_info.

How would you solve the problem? Is there only the way to handle the iteration with a function and a while loop or a recursive function and add the values in two tables?

(And can i handle in one function two temporary tables?)

Another problem i have, where i handle the iteration for my own. I would add in the function there a static table for the extra values.

Thank you very much,

Best regards, Ludwig Rahlff

Body:
I would like to get in one calculations two tables (if possible something like views) out of a recursive query.
I have recursive query, and in this query new items where calculated. These new items have (an unknown number of) new calculated values.

My example only generates the ids of natural numbers. In each iteration it creates a new id and some values for it.

Now it is my target to get a view for the ids and a view for the extra_values, so that i dont break the second Normal Form.

Here is my example on dbfiddle.

CREATE TABLE IF NOT EXISTS public.extra_info
(
    id integer,
  sub_id integer,
  value integer
);

CREATE OR REPLACE FUNCTION public.calc_stuff(id integer, ar integer[])
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
 declare
  rand integer;
  i integer;
 Begin
    RAISE NOTICE 'ar: %', ar;
    rand = random() * 5 + 1::integer;
    FOR i in 1..rand
    LOOP
        INSERT INTO extra_info SELECT id+1 AS id, i AS sub_id, random() * 1000 + 1::integer AS value;
    END LOOP;
    RETURN id+1;
 END

$BODY$;

DELETE FROM extra_info;
CREATE MATERIALIZED VIEW my_ids AS (
  WITH RECURSIVE rec_part AS(
    SELECT 1 AS id
    UNION
    SELECT calc_stuff(rp.id, array_agg(ei.value) OVER (PARTITION BY rp.id))
       FROM rec_part rp
      LEFT JOIN extra_info ei
         ON rp.id = ei.id
       WHERE rp.id < 20
  )
SELECT id FROM rec_part
)

Here should be a problem, because my values (in my case) depend on the old values, and here the query can not handle the new values in extra_info.

How would you solve the problem? Is there only the way to handle the iteration with a function and a while loop or a recursive function and add the values in two tables?

(And can i handle in one function two temporary tables?)

Another problem i have, where i handle the iteration for my own. I would add in the function there a static table for the extra values.

Thank you very much,

Best regards, Ludwig Rahlff


问:
I'm getting Incorrect values for sectors and levels on my Python Plotly Sunburst chart. What am I doing wrong?
I have a dataset of approx 13k unique users in a Pandas dataframe, with each user assigned a group for 5 different business areas -> 'businessArea1', 'businessArea2', 'businessArea3', 'businessArea4'and  'businessArea5' along with an unique 'id' column. I'd like to have a sunburst chart that contains the total 13k users broken down by the values of the 3 groups that are on that level, for example group1 = 8k, group2 = 5k. Then for the next level, the groups with parents on the higher level should add up to the total of the parents total.

Currently I'm getting totally wrong values for the root level I'm getting 5k. What's happening to the rest?

```<code>p_df = p_df[['BusinessArea1','BusinessArea2', 'BusinessArea3',
'BusinessArea4',
'BusinessArea5']].value_counts().reset_index(name='Total')

fig1 = px.sunburst(p_df, path=['BusinessArea1','BusinessArea2',
'BusinessArea3','BusinessArea4', `'BusinessArea5'], values='Total')
fig1.update_layout(
title_text="Business Areas 1 - 5",
font_size=10,
width=900,
height=900,
)
fig1.show()
</code>```

I was expecting to have the values of each sector to be accurate to how many of those groups are on that level. The total for these groups should be the total for the overall number of users - 13k.

Table

Body:
I have a dataset of approx 13k unique users in a Pandas dataframe, with each user assigned a group for 5 different business areas -> 'businessArea1', 'businessArea2', 'businessArea3', 'businessArea4'and  'businessArea5' along with an unique 'id' column. I'd like to have a sunburst chart that contains the total 13k users broken down by the values of the 3 groups that are on that level, for example group1 = 8k, group2 = 5k. Then for the next level, the groups with parents on the higher level should add up to the total of the parents total.

Currently I'm getting totally wrong values for the root level I'm getting 5k. What's happening to the rest?

p_df = p_df[['BusinessArea1','BusinessArea2', 'BusinessArea3',
'BusinessArea4',
'BusinessArea5']].value_counts().reset_index(name='Total')

fig1 = px.sunburst(p_df, path=['BusinessArea1','BusinessArea2',
'BusinessArea3','BusinessArea4', `'BusinessArea5'], values='Total')
fig1.update_layout(
title_text="Business Areas 1 - 5",
font_size=10,
width=900,
height=900,
)
fig1.show()

I was expecting to have the values of each sector to be accurate to how many of those groups are on that level. The total for these groups should be the total for the overall number of users - 13k.

Table


问:
Twilio: The phone hangs up by itself at the end of the first send
So what I'm trying to accomplish is simple, I'm setting up a decision tree between the user and the responder by analyzing what the user is saying (yes or no).

Using Twilio , ngrok to expose my server port and AssamblyIa for audio to text stream transcription I have a problem with sending data to Twilio.

this is what the exchange looks like:

```<code>app.post("/", async (req, res) => {
  console.log("this is lapeste:" + req.headers.host);
  assembly = new WebSocket(
    "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=8000",
    { headers: { authorization: "MY-API-KEY" } }
  );

  res.set("Content-Type", "text/xml");
  res.send(
    `<Response>
       <Start>
         <Stream url='wss://${req.headers.host}' />
       </Start>
       <Say voice="Polly.Celine" language="fr-FR">
          BlaBla
       </Say>
       <Pause length='5'/>
       <Say voice="Polly.Celine" language="fr-FR">
        BlaBla Bla again
       </Say>
     </Response>`
  );
});
</code>```

After processing the <Response>...</Response>, the Twilio phone hangup right after the last <say>.

Thank you for reading me. :)

What did you try and what were you expecting?:

I sent a first < response > to Twilio hoping to be able to send others but it hangs up directly after the first. :(

Body:
So what I'm trying to accomplish is simple, I'm setting up a decision tree between the user and the responder by analyzing what the user is saying (yes or no).

Using Twilio , ngrok to expose my server port and AssamblyIa for audio to text stream transcription I have a problem with sending data to Twilio.

this is what the exchange looks like:

app.post("/", async (req, res) => {
  console.log("this is lapeste:" + req.headers.host);
  assembly = new WebSocket(
    "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=8000",
    { headers: { authorization: "MY-API-KEY" } }
  );

  res.set("Content-Type", "text/xml");
  res.send(
    `<Response>
       <Start>
         <Stream url='wss://${req.headers.host}' />
       </Start>
       <Say voice="Polly.Celine" language="fr-FR">
          BlaBla
       </Say>
       <Pause length='5'/>
       <Say voice="Polly.Celine" language="fr-FR">
        BlaBla Bla again
       </Say>
     </Response>`
  );
});

After processing the <Response>...</Response>, the Twilio phone hangup right after the last <say>.

Thank you for reading me. :)

What did you try and what were you expecting?:

I sent a first < response > to Twilio hoping to be able to send others but it hangs up directly after the first. :(


问:
When i change fragment, my Listview hold the items but my spinner inside the items get resetted
I'm new to kotlin and to android, I'm writing an app that has a fragment that contains a ListView (the LV's items have 2 spinner inside) and another fragment that send data to populate the ListView (and comes back with popBackStack), my problem is that when I edit the value of the spinner through the app, if I add another exercise the previous spinner get resetted

List View Adapter

```<code>class EsLViewAdapter(var esArray: ArrayList<Esercizio>, var context: Context) : BaseAdapter() {
override fun getCount(): Int {
return esArray.size
    }

override fun getItem(p0: Int): Any {
val esInserito = EsInserito(esArray.get(p0).id, esArray.get(p0).name, esArray.get(p0).settore, esArray.get(p0).kcal)
return esInserito
    }

override fun getItemId(p0: Int): Long {
return esArray.get(p0).id.toLong()
    }

override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val convertView : View
if (p1 == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_es_scheda, p2, false);
        }
 else
 convertView = p1
 val currentItem : EsInserito = getItem(p0) as EsInserito
 val tVN : TextView = convertView.findViewById(R.id.textViewName)
 tVN.setText(currentItem.name)

 val spSerie : Spinner = convertView.findViewById(R.id.serie)
 val spRipetizioni : Spinner = convertView.findViewById(R.id.ripetizioni)
 val serie : Array<Int> = arrayOf(1, 2, 3, 4, 5)
 val ripetizioni : Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
 val serieAdapter = ArrayAdapter<Int>(context, android.R.layout.simple_spinner_item, serie)
 val ripetizioniAdapter = ArrayAdapter<Int>(context, android.R.layout.simple_spinner_item, ripetizioni)
 serieAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
 ripetizioniAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
 spSerie.adapter = serieAdapter
 spRipetizioni.adapter = ripetizioniAdapter
 spSerie.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
 override fun onNothingSelected(parent: AdapterView<*>?) {
 spSerie.post(Runnable {
 spSerie.setSelection(0)
 serieAdapter.notifyDataSetChanged()
                 })
            }
 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
 spSerie.post(Runnable {
 spSerie.setSelection(position)
 serieAdapter.notifyDataSetChanged()
                 })
             }
         }
 spRipetizioni.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
 override fun onNothingSelected(parent: AdapterView<*>?) {
 spRipetizioni.setSelection(0, true)
 ripetizioniAdapter.notifyDataSetChanged()
             }
 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
 spRipetizioni.setSelection(position, true)
 ripetizioniAdapter.notifyDataSetChanged()
             }
         }
 return convertView
     }
 }
</code>```

Fragment that has the listview

```<code> class AddSchedeFragment : Fragment(){
 lateinit var addEs : Button
 lateinit var save : Button
 var esArray : ArrayList<Esercizio> = ArrayList()
 lateinit var lVAdapter : EsLViewAdapter
 lateinit var listView : ListView
 private lateinit var esVM : EserciziViewModel
 private lateinit var bundle : Bundle
 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
 val view = inflater.inflate(R.layout.fragment_add_scheda, container, false)
 esVM = ViewModelProvider(requireActivity()).get(EserciziViewModel::class.java)
         //button setup
 addEs = view.findViewById(R.id.btnAddEsercizio)
 addEs.setOnClickListener(object : View.OnClickListener {
 override fun onClick(view: View?) {
 val frag = EsChoice()
                 (activity as MainActivity).setCurrentFragment(frag)
             }
         })
 save = view.findViewById(R.id.btnSave)
 save.setOnClickListener(object : View.OnClickListener{
 override fun onClick(view: View?) {

             }
         })
         //listView setup
 listView = view.findViewById(R.id.esList)
 lVAdapter = EsLViewAdapter(esArray, this.requireContext())
 listView.adapter = lVAdapter
 observe()
 return view
     }
 fun observe(){
 esVM.mutableLiveData.observe(viewLifecycleOwner, {
 esArray.add(it)
         })
     }
 override fun onResume() {
 super.onResume()
     }
 fun addItem(item : Esercizio){
 esArray.add(item)
 lVAdapter.notifyDataSetChanged()
     }
 }
</code>```

Fragment that let me choose the data

```<code>class EsChoice : Fragment() {
 lateinit var gridLayout : RecyclerView
 private lateinit var esVM : EserciziViewModel
 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
 val view = inflater.inflate(R.layout.fragment_choose_ex, container, false)
 esVM = ViewModelProvider(requireActivity()).get(EserciziViewModel::class.java)
 val esArray : ArrayList<Esercizio> = ArrayList()
 val db = SchedeDatabaseHandler(this.requireContext())
 val cur = db.showAll(db.readableDatabase)
 if(cur.position < -1) error("CURSORE NON FUNZIONANTE")
 gridLayout = view.findViewById(R.id.exerciseGrid)
 gridLayout.layoutManager = GridLayoutManager(this.requireContext(), 2)
 if(cur.moveToFirst()) {
 do {
 esArray.add(Esercizio(cur.getInt(0), cur.getString(1), cur.getString(2), cur.getInt(3)))
 while (cur.moveToNext())
         }
 val adapter = EserciziAdapter(this.requireContext(), esArray)
 gridLayout.adapter = adapter
 gridLayout.addOnItemTouchListener(GridRViewTouchListener(this.requireContext(), gridLayout, object : GridRViewTouchListener.ClickListener{
 override fun onClick(view : View, position : Int){
 esVM.setData(esArray[position])
                //val frag = AddSchedeFragment()
                 //(activity as MainActivity).setCurrentFragment(frag)
 activity?.supportFragmentManager?.popBackStack()
             }
         }))
 return view
     }
 }
</code>```

My Fragment

I kind of think that the problem is that the ListViewAdapter.getView() build the spinner each time from scratch but I don't know what to do to fix it

I tried to use onSaveInstance with onResume but I didn't make any progress

Body:
I'm new to kotlin and to android, I'm writing an app that has a fragment that contains a ListView (the LV's items have 2 spinner inside) and another fragment that send data to populate the ListView (and comes back with popBackStack), my problem is that when I edit the value of the spinner through the app, if I add another exercise the previous spinner get resetted

List View Adapter

class EsLViewAdapter(var esArray: ArrayList<Esercizio>, var context: Context) : BaseAdapter() {
override fun getCount(): Int {
return esArray.size
    }

override fun getItem(p0: Int): Any {
val esInserito = EsInserito(esArray.get(p0).id, esArray.get(p0).name, esArray.get(p0).settore, esArray.get(p0).kcal)
return esInserito
    }

override fun getItemId(p0: Int): Long {
return esArray.get(p0).id.toLong()
    }

override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val convertView : View
if (p1 == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_es_scheda, p2, false);
        }
 else
 convertView = p1
 val currentItem : EsInserito = getItem(p0) as EsInserito
 val tVN : TextView = convertView.findViewById(R.id.textViewName)
 tVN.setText(currentItem.name)

 val spSerie : Spinner = convertView.findViewById(R.id.serie)
 val spRipetizioni : Spinner = convertView.findViewById(R.id.ripetizioni)
 val serie : Array<Int> = arrayOf(1, 2, 3, 4, 5)
 val ripetizioni : Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
 val serieAdapter = ArrayAdapter<Int>(context, android.R.layout.simple_spinner_item, serie)
 val ripetizioniAdapter = ArrayAdapter<Int>(context, android.R.layout.simple_spinner_item, ripetizioni)
 serieAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
 ripetizioniAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
 spSerie.adapter = serieAdapter
 spRipetizioni.adapter = ripetizioniAdapter
 spSerie.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
 override fun onNothingSelected(parent: AdapterView<*>?) {
 spSerie.post(Runnable {
 spSerie.setSelection(0)
 serieAdapter.notifyDataSetChanged()
                 })
            }
 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
 spSerie.post(Runnable {
 spSerie.setSelection(position)
 serieAdapter.notifyDataSetChanged()
                 })
             }
         }
 spRipetizioni.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
 override fun onNothingSelected(parent: AdapterView<*>?) {
 spRipetizioni.setSelection(0, true)
 ripetizioniAdapter.notifyDataSetChanged()
             }
 override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
 spRipetizioni.setSelection(position, true)
 ripetizioniAdapter.notifyDataSetChanged()
             }
         }
 return convertView
     }
 }

Fragment that has the listview

 class AddSchedeFragment : Fragment(){
 lateinit var addEs : Button
 lateinit var save : Button
 var esArray : ArrayList<Esercizio> = ArrayList()
 lateinit var lVAdapter : EsLViewAdapter
 lateinit var listView : ListView
 private lateinit var esVM : EserciziViewModel
 private lateinit var bundle : Bundle
 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
 val view = inflater.inflate(R.layout.fragment_add_scheda, container, false)
 esVM = ViewModelProvider(requireActivity()).get(EserciziViewModel::class.java)
         //button setup
 addEs = view.findViewById(R.id.btnAddEsercizio)
 addEs.setOnClickListener(object : View.OnClickListener {
 override fun onClick(view: View?) {
 val frag = EsChoice()
                 (activity as MainActivity).setCurrentFragment(frag)
             }
         })
 save = view.findViewById(R.id.btnSave)
 save.setOnClickListener(object : View.OnClickListener{
 override fun onClick(view: View?) {

             }
         })
         //listView setup
 listView = view.findViewById(R.id.esList)
 lVAdapter = EsLViewAdapter(esArray, this.requireContext())
 listView.adapter = lVAdapter
 observe()
 return view
     }
 fun observe(){
 esVM.mutableLiveData.observe(viewLifecycleOwner, {
 esArray.add(it)
         })
     }
 override fun onResume() {
 super.onResume()
     }
 fun addItem(item : Esercizio){
 esArray.add(item)
 lVAdapter.notifyDataSetChanged()
     }
 }

Fragment that let me choose the data

class EsChoice : Fragment() {
 lateinit var gridLayout : RecyclerView
 private lateinit var esVM : EserciziViewModel
 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
 val view = inflater.inflate(R.layout.fragment_choose_ex, container, false)
 esVM = ViewModelProvider(requireActivity()).get(EserciziViewModel::class.java)
 val esArray : ArrayList<Esercizio> = ArrayList()
 val db = SchedeDatabaseHandler(this.requireContext())
 val cur = db.showAll(db.readableDatabase)
 if(cur.position < -1) error("CURSORE NON FUNZIONANTE")
 gridLayout = view.findViewById(R.id.exerciseGrid)
 gridLayout.layoutManager = GridLayoutManager(this.requireContext(), 2)
 if(cur.moveToFirst()) {
 do {
 esArray.add(Esercizio(cur.getInt(0), cur.getString(1), cur.getString(2), cur.getInt(3)))
 while (cur.moveToNext())
         }
 val adapter = EserciziAdapter(this.requireContext(), esArray)
 gridLayout.adapter = adapter
 gridLayout.addOnItemTouchListener(GridRViewTouchListener(this.requireContext(), gridLayout, object : GridRViewTouchListener.ClickListener{
 override fun onClick(view : View, position : Int){
 esVM.setData(esArray[position])
                //val frag = AddSchedeFragment()
                 //(activity as MainActivity).setCurrentFragment(frag)
 activity?.supportFragmentManager?.popBackStack()
             }
         }))
 return view
     }
 }

My Fragment

I kind of think that the problem is that the ListViewAdapter.getView() build the spinner each time from scratch but I don't know what to do to fix it

I tried to use onSaveInstance with onResume but I didn't make any progress


问:
FastAPI Socket Emit multiple Values
I am using SocketIO with FastAPI to emit server event(upon button click on the browser side).
Below is my Server code:

```<code>@sio.on('my_event')
async def servermessage():
    data = "Hello"
    mydata = 5
    await sio.emit("response", data, mydata)
</code>```

Below is the equivalent Javascript code to catch the above emit from server:

```<code>socket.on('response', function () {
        document.getElementById("test").innerHTML=data;
        document.getElementById("mytest").innerHTML=mydata;
});
</code>```

However nothing gets printed in the browser? Am I missing something?

Title: FastAPI Socket Emit multiple Values

Body:
I am using SocketIO with FastAPI to emit server event(upon button click on the browser side).
Below is my Server code:

@sio.on('my_event')
async def servermessage():
    data = "Hello"
    mydata = 5
    await sio.emit("response", data, mydata)

Below is the equivalent Javascript code to catch the above emit from server:

socket.on('response', function () {
        document.getElementById("test").innerHTML=data;
        document.getElementById("mytest").innerHTML=mydata;
});

However nothing gets printed in the browser? Am I missing something?


问:
How to avoid form resubmission -servlet,jsp-
when i logged in using the post method, the form data will be sent to owner-controller servlet and finally redirect to viewStaff.jsp page.

the problem is, if i'm using request dispatcher, whenever i reload the viewStaff.jsp page, the browser will ask me to confirm form resubmission. where am I doing wrong? however if i use response.sendRedirect method, i can't pass some necessary data to viewStaff.jsp page, unless if i'm using session.

therefore, how do i prevent confirm form resubmission if i'm using request dispatcher?

```<code>//this is the method that will handle the request and response object, and forward it to viewStaff.jsp

public void viewStaff(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher rd = request.getRequestDispatcher("/owners/viewStaff.jsp");
        rd.forward(request, response);
    }

//this is the method that will handle login error. if there are no error, then it will call the viewStaff method

public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String username = "";
        String password = "";

        String username_err = "";
        String password_err = "";

        username = request.getParameter("username");
        password = request.getParameter("password");

        if(username.isEmpty()) {
            username_err = "please enter username";
        }

        if(password.isEmpty()) {
            password_err = "please enter password";
        }

        if(!username.isEmpty()&&!password.isEmpty()) {
            viewStaff(request, response);
        } else {
            request.setAttribute("username_err", username_err);
            request.setAttribute("password_err", password_err);
            RequestDispatcher rd = request.getRequestDispatcher("/owners/login.jsp");
            rd.forward(request, response);
        }
    }
</code>```

//this is the actual post method

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String action = "";
        action = request.getParameter("action");

        if(action.equals("login")) {
            login(request,response);
        }

    }
</code>```

//this is my login.jsp

```<code>
<c:set var="username_err" value="${requestScope.username_err}" />
<c:set var="password_err" value="${requestScope.password_err}" />
<c:set var="username" value="${param.username}" />
<c:set var="password" value="${param.password}" />
<main class="form-signin">
    <form action="owner-controller?action=login" method="POST">
        <h1 class="h3 mb-3 fw-normal">
            Please sign in |
            <p class="fw-lighter">owner</p>
        </h1>

        <div class="form-floating">
            <input type="text" name="username"
                class="form-control <c:if test="${not empty username_err}">is-invalid</c:if> "
                value="${param.username}" id="floatingInput"
                placeholder="Username"> <label for="floatingInput">Username</label>
        </div>
        <span style="color: red;">
            <!-- username error here -->
        </span>

        <div class="form-floating">
            <input type="password" name="password" class="form-control <c:if test="${not empty password_err}">is-invalid</c:if>"
                id="floatingPassword" placeholder="Password"> <label
                for="floatingPassword">Password</label>
        </div>

        <span style="color: red;">
            <!-- password error here -->
        </span>

        <div class="checkbox mb-3">
            <label> <input type="checkbox" value="remember-me">
                Remember me
            </label>
        </div>
        <button class="w-100 btn btn-lg btn-primary" type="submit">Sign
            in</button>
    </form>
    <a href="owner-controller?action=login">click here to invoke GET method</a>
</main>

</code>```

enter image description here

i did try using session attribute and it works, i don't have to confirm form resubmission. but somehow i want to know why request dispatcher does not work?

Body:
when i logged in using the post method, the form data will be sent to owner-controller servlet and finally redirect to viewStaff.jsp page.

the problem is, if i'm using request dispatcher, whenever i reload the viewStaff.jsp page, the browser will ask me to confirm form resubmission. where am I doing wrong? however if i use response.sendRedirect method, i can't pass some necessary data to viewStaff.jsp page, unless if i'm using session.

therefore, how do i prevent confirm form resubmission if i'm using request dispatcher?

//this is the method that will handle the request and response object, and forward it to viewStaff.jsp

public void viewStaff(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher rd = request.getRequestDispatcher("/owners/viewStaff.jsp");
        rd.forward(request, response);
    }

//this is the method that will handle login error. if there are no error, then it will call the viewStaff method

public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String username = "";
        String password = "";

        String username_err = "";
        String password_err = "";

        username = request.getParameter("username");
        password = request.getParameter("password");

        if(username.isEmpty()) {
            username_err = "please enter username";
        }

        if(password.isEmpty()) {
            password_err = "please enter password";
        }

        if(!username.isEmpty()&&!password.isEmpty()) {
            viewStaff(request, response);
        } else {
            request.setAttribute("username_err", username_err);
            request.setAttribute("password_err", password_err);
            RequestDispatcher rd = request.getRequestDispatcher("/owners/login.jsp");
            rd.forward(request, response);
        }
    }

//this is the actual post method

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String action = "";
        action = request.getParameter("action");

        if(action.equals("login")) {
            login(request,response);
        }

    }

//this is my login.jsp

<c:set var="username_err" value="${requestScope.username_err}" />
<c:set var="password_err" value="${requestScope.password_err}" />
<c:set var="username" value="${param.username}" />
<c:set var="password" value="${param.password}" />

    <form action="owner-controller?action=login" method="POST">

            Please sign in |

owner

            <input type="text" name="username"
                class="form-control <c:if test="${not empty username_err}">is-invalid</c:if> "
                value="${param.username}" id="floatingInput"
                placeholder="Username"> Username

            <input type="password" name="password" class="form-control <c:if test="${not empty password_err}">is-invalid</c:if>"
                id="floatingPassword" placeholder="Password"> Password

             <input type="checkbox" value="remember-me">
                Remember me

        <button class="w-100 btn btn-lg btn-primary" type="submit">Sign
            in</button>
    </form>
    click here to invoke GET method

enter image description here

i did try using session attribute and it works, i don't have to confirm form resubmission. but somehow i want to know why request dispatcher does not work?


问:
ckeditor 5 removes empty tags - and I don't want it to
I'm using FA to render icons, eg

and ckeditor 5 removes them.

Any ideas how to prevent this behaviour?

NB - I'm using ckeditor v5. I've tried:

```<code>htmlSupport: {
allow: [
    { name: /<i[^>]*><\/i>/g },
    { name: "i", classes: ["fa-thin", "fa-regular", "fa-light", "fa-solid", "fa-brands"] }
    ]
}
</code>```

Body:
I'm using FA to render icons, eg

and ckeditor 5 removes them.

Any ideas how to prevent this behaviour?

NB - I'm using ckeditor v5. I've tried:

htmlSupport: {
allow: [
    { name: /]*><\/i>/g },
    { name: "i", classes: ["fa-thin", "fa-regular", "fa-light", "fa-solid", "fa-brands"] }
    ]
}