问:
for each 10 minutes sequelize table summary for my table
```<code>const group = sequelize.define("Group", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const room = sequelize.define("Room", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const user = sequelize.define("User", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const UserData = {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    first_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
    last_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
}

const summaryOfUserData = {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    first_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
    last_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
}

Group.belongsTo(room, { constraints: true, onDelete: "CASCADE" });
userData.belongsTo(user, { constraints: true, onDelete: "CASCADE" });
userData.belongsTo(group, { constraints: true, onDelete: "CASCADE" });
summaryOfUserData.belongsTo(user, { constraints: true, onDelete: "CASCADE" });
summaryOfUserData.belongsTo(room, { constraints: true, onDelete: "CASCADE" });

for example
    user table ->
      id: 1 , name: messi;
      id: 2 , name: Alex;

    room table ->
      id 1, name: song;
      id: 2, name: game;

    group table ->
      id 1, name: singers, roomId: 1;
      id 2, name: rappers, roomId: 1;
      id: 3, name: war game players, roomId: 2;
      id: 4, name: car racing players, roomId: 2;

    user data ->
      id: 1, userId: 1,  first_seen: 1671431773, last_seen: 1671431833, GroupId: 1;
      id: 2, userId: 1, first_seen: 1671431774, last_seen: 1671431834, GroupId: 1;
      id: 3, userId: 1,  first_seen: 1671431775, last_seen: 1671431835, GroupId: 2;

      id: 4, userId: 1,  first_seen: 1671431776, last_seen: 1671431836, GroupId: 3;
      id: 5, userId: 1,  first_seen: 1671431777, last_seen: 1671431837, GroupId: 4;

      id: 6, userId: 1,  first_seen: 1671431778, last_seen: 1671431838, GroupId: 2;
      id: 7, userId: 1, first_seen: 1671431779, last_seen: 1671431839, GroupId: 2;
</code>```

Every 10 minutes, before each user changes their room, I want to detect the room and add the first and last time seen in the room to the SummaryOfUserData table.
for example

```<code>  summarry of user data
    id: 1, userId: 1,  first_seen: 1671431773, last_seen: 1671431835, RoomId: 1;
    id: 1, userId: 1,  first_seen: 1671431776, last_seen: 1671431837, RoomId: 2;
    id: 1, userId: 1,  first_seen: 1671431778, last_seen: 1671431839, RoomId: 1;
</code>```

how can i do this please can you help me?

I believe you can help me

I'll throw random because stack overflow doesn't allow me to post the question, it says explain a little more

Body:
const group = sequelize.define("Group", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const room = sequelize.define("Room", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const user = sequelize.define("User", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
});

const UserData = {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    first_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
    last_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
}

const summaryOfUserData = {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    first_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
    last_seen: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
}

Group.belongsTo(room, { constraints: true, onDelete: "CASCADE" });
userData.belongsTo(user, { constraints: true, onDelete: "CASCADE" });
userData.belongsTo(group, { constraints: true, onDelete: "CASCADE" });
summaryOfUserData.belongsTo(user, { constraints: true, onDelete: "CASCADE" });
summaryOfUserData.belongsTo(room, { constraints: true, onDelete: "CASCADE" });

for example
    user table ->
      id: 1 , name: messi;
      id: 2 , name: Alex;

    room table ->
      id 1, name: song;
      id: 2, name: game;

    group table ->
      id 1, name: singers, roomId: 1;
      id 2, name: rappers, roomId: 1;
      id: 3, name: war game players, roomId: 2;
      id: 4, name: car racing players, roomId: 2;

    user data ->
      id: 1, userId: 1,  first_seen: 1671431773, last_seen: 1671431833, GroupId: 1;
      id: 2, userId: 1, first_seen: 1671431774, last_seen: 1671431834, GroupId: 1;
      id: 3, userId: 1,  first_seen: 1671431775, last_seen: 1671431835, GroupId: 2;

      id: 4, userId: 1,  first_seen: 1671431776, last_seen: 1671431836, GroupId: 3;
      id: 5, userId: 1,  first_seen: 1671431777, last_seen: 1671431837, GroupId: 4;

      id: 6, userId: 1,  first_seen: 1671431778, last_seen: 1671431838, GroupId: 2;
      id: 7, userId: 1, first_seen: 1671431779, last_seen: 1671431839, GroupId: 2;

Every 10 minutes, before each user changes their room, I want to detect the room and add the first and last time seen in the room to the SummaryOfUserData table.
for example

  summarry of user data
    id: 1, userId: 1,  first_seen: 1671431773, last_seen: 1671431835, RoomId: 1;
    id: 1, userId: 1,  first_seen: 1671431776, last_seen: 1671431837, RoomId: 2;
    id: 1, userId: 1,  first_seen: 1671431778, last_seen: 1671431839, RoomId: 1;

how can i do this please can you help me?

I believe you can help me

I'll throw random because stack overflow doesn't allow me to post the question, it says explain a little more


来源: stackexchange

问:
Setting the download attribute for link using javascript works partially
I want to change the download attribute of a link, that gets triggered after a click by the user, then a timer runs for 10 seconds, then the file gets downloaded automatically.
When the users click the Click here button, the download attribute gets changed , but when it automatically downloads after a time, the download attribute is not being set.
This is the code.

```<code>const download = document.querySelector('.download-btn');
const countdown = document.querySelector('.countdown');
const pleaseWaitText = document.querySelector('.pleaseWait-text');
const manualDownloadText = document.querySelector('.manualDownload-text');
const manualDownloadLink = document.querySelector('.manualDownload-link');
var timeLeft = 10;

download.addEventListener('click', () => {
download.style.display = "none";
countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

var downloadTimer = setInterval(function timeCount() {
timeLeft--;
countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

if (timeLeft <= 0) {
  clearInterval(downloadTimer);

  pleaseWaitText.style.display = "block";
  let download_href = "https://tuqut.com/jsdn12enda21.pdf";

  window.location.href = download_href;
  manualDownloadLink.href = download_href;
  manualDownloadLink.setAttribute("download", "work.pdf");

  setTimeout(() => {
    pleaseWaitText.style.display = "none";
    manualDownloadText.style.display = "block";
  }, 1000);
}
}, 1000);
});
</code>```

This is the html code

```<code><div class="download-container">
<a href="#" class="download-btn">Download files <i class="fas fa-
download"></i></a>
<div class="countdown"></div>
<div class="pleaseWait-text">Please wait ...</div>
<div class="manualDownload-text">
If the download didn't start automatically, <a href="#" class="manualDownload-link" target="_top" download="work.pdf">click here</a>
</div>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change the download attribute of a link, that gets triggered after a click by the user, then a timer runs for 10 seconds, then the file gets downloaded automatically.
When the users click the Click here button, the download attribute gets changed , but when it automatically downloads after a time, the download attribute is not being set.
This is the code.

const download = document.querySelector('.download-btn');
const countdown = document.querySelector('.countdown');
const pleaseWaitText = document.querySelector('.pleaseWait-text');
const manualDownloadText = document.querySelector('.manualDownload-text');
const manualDownloadLink = document.querySelector('.manualDownload-link');
var timeLeft = 10;

download.addEventListener('click', () => {
download.style.display = "none";
countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

var downloadTimer = setInterval(function timeCount() {
timeLeft--;
countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

if (timeLeft <= 0) {
  clearInterval(downloadTimer);

  pleaseWaitText.style.display = "block";
  let download_href = "https://tuqut.com/jsdn12enda21.pdf";

  window.location.href = download_href;
  manualDownloadLink.href = download_href;
  manualDownloadLink.setAttribute("download", "work.pdf");

  setTimeout(() => {
    pleaseWaitText.style.display = "none";
    manualDownloadText.style.display = "block";
  }, 1000);
}
}, 1000);
});

This is the html code

Download files

Please wait ...

If the download didn't start automatically, click here


问:
How can we set hibernate filter conditions from queries.properties file?
I am trying to fetch the queries from my properties file. Native query is working fine, but I need to change filter conditions from properties file also.

query.properties file contains :

```<code>userQuery=SELECT * FROM USER limit 1
</code>```

and in my repository

```<code>@Value("${userQuery}")
String query1;
</code>```
```<code>Query query = getEntityManager().createNativeQuery(query1);
return query.getResultList();
</code>```

This is working fine, but in my filter (see below) I want to take filter condition from query.properties file itself.

```<code>@FilterDefs(value = {
        @FilterDef(name = "getData", parameters = {
                @ParamDef(name = "firstName", type = "java.lang.String")
        })})

@Filters(value = {
        @Filter(name = "getData", condition = "first_name in(:firstName)")})
</code>```

query.properties

```<code>userQuery=SELECT * FROM USER limit 1

filterQuery=first_name in(:firstName)
</code>```

Body:
I am trying to fetch the queries from my properties file. Native query is working fine, but I need to change filter conditions from properties file also.

query.properties file contains :

userQuery=SELECT * FROM USER limit 1

and in my repository

@Value("${userQuery}")
String query1;

Query query = getEntityManager().createNativeQuery(query1);
return query.getResultList();

This is working fine, but in my filter (see below) I want to take filter condition from query.properties file itself.

@FilterDefs(value = {
        @FilterDef(name = "getData", parameters = {
                @ParamDef(name = "firstName", type = "java.lang.String")
        })})

@Filters(value = {
        @Filter(name = "getData", condition = "first_name in(:firstName)")})

query.properties

userQuery=SELECT * FROM USER limit 1

filterQuery=first_name in(:firstName)


问:
Twitter api stream api rules: listen to a stream by a mention of two accounts where one is a constant and the other account can be any account
How can I create twitter api stream rules to  listen to a stream by a mentions of two accounts, where one is a constant and the other account can be any account?

For example I would like to listen to a stream from @example account and @<any other account>, but the rule is the @example account must be mentioned plus any other account. I know how to listen to a mention of an account, but how do I enforce the rule as described above?


问:
How to add 5 and more things in a select drop-down in smart filters in jet engine in WordPress?
I am using Jet smart filters in WordPress and I am using a select filter (dropdown menu) for it. It has 5 options for bedrooms, 1,2,3,4, and 5+, I want it to filter exactly 1, 2, 3, 4 bedrooms and for 5+ for all the apartments having bedrooms greater than and equal to 5.

Here are my settings:

Here is my filter type

Here are the filters manual input, this data is number in database

Here is my 3rd settings for the filter I have used comparison operator equals to for this

What should I do for 5+ bedrooms.

I am expecting exact number of bedrooms for 1-4 bedrooms and for 5+ I am expecting greater than and equal to 5 bedrooms.


问:
Docker-compose Cron scheduling Python app
Just to say that I am new to docker...
I have a docker-compose application (I like/need the docker-compose way to run multiple containers) that runs a mysql container and a python app, and I would like the python app to run every minute. I tried an infinite loop in the python code, but docker seems to prevent it from launching, so I tried with cron, but without any success (although it might not have any impact, I run docker on Windows, which seems less straightforward than on Linux :(, and use VS Code for development). Therefore, I would like to know if there is a way to use docker-compose and run the python app every minute, and if yes, how to configure cron.

my setup is the following:

docker installed on windows.

I run everything from VS Code' terminal, without any docker extension

A pythonmain.py file (for example, I used emails because I could not see any logs nor print once I run the code from cron. Most likely because cron does not launch the python app):
`

```<code>import mysql.connector as mysql
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
print("Starting Python Docker")

# EMAIL
mail_content = "Hello"
#The mail addresses and password
sender_address = 'email1@mail.com'
sender_pass = 'pwd'
receiver_address = 'email2@mail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'New data email.'   #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.office365.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

#Database
db = mysql.connect(host = 'mydb', user = 'root', password = 'root', port = 3306)
print("db connection passed")
cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS emails")
cursor.execute("SHOW DATABASES")
#connect to the right database
db = mysql.connect(
    host = "mydb",
    user = "root",
    passwd = "root",
    database = "emails"
)
cursor = db.cursor()
## creating a table in database
cursor.execute("CREATE TABLE IF NOT EXISTS emailscount (id VARCHAR(255), count INT)")
## defining the Query for charger data
query = "INSERT INTO emailscount (id, count) VALUES (%s, %s)"
values = ("123",1)
cursor.execute(query, values)
db.commit()
print(cursor.rowcount, "data inserted")

</code>```

`

a dockerfile:
`

```<code>FROM python:3.9
COPY . .
RUN pip install mysql-connector-python requests
# for implementation without cron:
# CMD ["python", "./pythonmain.py"]
# trial with cron, but python app does not launch:
RUN apt-get update
RUN apt-get install -y cron
RUN chmod +x pythonmain.py
RUN crontab crontab
CMD ["cron", "-f"]
</code>```

`

a crontab file:
`

```<code>*/1 * * * * python ./pythonmain.py

</code>```

`

A docker-compose file:
`

```<code>version: "3"
services:
    db:
        container_name: mydb
        image: mysql:5.7
        ports:
            - "33061:3306"
        environment:
            MYSQL_ROOT_PASSWORD: root
    pythonapp:
        container_name: pythonapp
        depends_on:
            - "db"
        links:
            - "db"
        build: ./
        ports:
            - "5001:5000"
</code>```

`

I would like the pythonapp to run every minute after I run the "docker-compose up" command in the terminal. But it does not work (the python app never runs, although all containers seem to be created), and I am not sure it can run as it is with the docker-compose command.
What works perfectly is when the dockerfile has the CMD ["python", "./pythonmain.py"] without everything related to cron, then the python app runs as it should, but of course, just once.

I tried as well to just run the python container from cron using docker build and docker run (not docker-compose up), but without any success neither, the code does not run (i.e. I was not able to replicate most of the examples/tutorials on cron for docker). Furthermore, using docker on windows, I could not find any log of error, even in the AppData\Local\Docker\wsl\data folder (which is empty).

Obviously, I am completely new to docker, so any help would be amazing!
Thanks a lot in advance !!

Body:
Just to say that I am new to docker...
I have a docker-compose application (I like/need the docker-compose way to run multiple containers) that runs a mysql container and a python app, and I would like the python app to run every minute. I tried an infinite loop in the python code, but docker seems to prevent it from launching, so I tried with cron, but without any success (although it might not have any impact, I run docker on Windows, which seems less straightforward than on Linux :(, and use VS Code for development). Therefore, I would like to know if there is a way to use docker-compose and run the python app every minute, and if yes, how to configure cron.

my setup is the following:

docker installed on windows.

I run everything from VS Code' terminal, without any docker extension

A pythonmain.py file (for example, I used emails because I could not see any logs nor print once I run the code from cron. Most likely because cron does not launch the python app):
`

import mysql.connector as mysql
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
print("Starting Python Docker")

# EMAIL
mail_content = "Hello"
#The mail addresses and password
sender_address = 'email1@mail.com'
sender_pass = 'pwd'
receiver_address = 'email2@mail.com'
#Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = 'New data email.'   #The subject line
#The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.office365.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')

#Database
db = mysql.connect(host = 'mydb', user = 'root', password = 'root', port = 3306)
print("db connection passed")
cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS emails")
cursor.execute("SHOW DATABASES")
#connect to the right database
db = mysql.connect(
    host = "mydb",
    user = "root",
    passwd = "root",
    database = "emails"
)
cursor = db.cursor()
## creating a table in database
cursor.execute("CREATE TABLE IF NOT EXISTS emailscount (id VARCHAR(255), count INT)")
## defining the Query for charger data
query = "INSERT INTO emailscount (id, count) VALUES (%s, %s)"
values = ("123",1)
cursor.execute(query, values)
db.commit()
print(cursor.rowcount, "data inserted")

`

a dockerfile:
`

FROM python:3.9
COPY . .
RUN pip install mysql-connector-python requests
# for implementation without cron:
# CMD ["python", "./pythonmain.py"]
# trial with cron, but python app does not launch:
RUN apt-get update
RUN apt-get install -y cron
RUN chmod +x pythonmain.py
RUN crontab crontab
CMD ["cron", "-f"]

`

a crontab file:
`

*/1 * * * * python ./pythonmain.py

`

A docker-compose file:
`

version: "3"
services:
    db:
        container_name: mydb
        image: mysql:5.7
        ports:
            - "33061:3306"
        environment:
            MYSQL_ROOT_PASSWORD: root
    pythonapp:
        container_name: pythonapp
        depends_on:
            - "db"
        links:
            - "db"
        build: ./
        ports:
            - "5001:5000"

`

I would like the pythonapp to run every minute after I run the "docker-compose up" command in the terminal. But it does not work (the python app never runs, although all containers seem to be created), and I am not sure it can run as it is with the docker-compose command.
What works perfectly is when the dockerfile has the CMD ["python", "./pythonmain.py"] without everything related to cron, then the python app runs as it should, but of course, just once.

I tried as well to just run the python container from cron using docker build and docker run (not docker-compose up), but without any success neither, the code does not run (i.e. I was not able to replicate most of the examples/tutorials on cron for docker). Furthermore, using docker on windows, I could not find any log of error, even in the AppData\Local\Docker\wsl\data folder (which is empty).

Obviously, I am completely new to docker, so any help would be amazing!
Thanks a lot in advance !!


问:
Why can't react testing library access elements with Selenium?
I have a selenium / jest project. I have installed react testing library and a few packages, but when I try to make valid assertions, I get an error. Code:

```<code>import { Vocal } from '../../Models/vocalModel';
import {screen} from '@testing-library/dom';

const vocal = new Vocal()

// Test Variables here
let validEmail = 'email@email.com'
let validPassword = 'password'
let invalidEmail = 'ThisEmailIsNotValid'
let invalidPassword = 'ThisPassWordIsNotValid'

describe("Login Test Suite", () => {
    beforeAll(async ()=>{
        await vocal.navigate();
    });
    afterAll( async ()=>{
        await vocal.quit();
    });

    test('A user can login and logout', async () =>{
        await vocal.userLogin(validEmail, validPassword);
        await vocal.userLogout();

        let getSignUpButtonText = await vocal.getText(vocal.signUpButtonLogin)
        console.log(getSignUpButtonText)
        expect(screen.getByText("Sign Up")).toBeVisible();
    })
});
</code>```

When I run this test, the browser runs and the test fails at the final assertion. I get the following error: "TestingLibraryElementError: Unable to find an element with the text: Sign Up. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.".
See photo:
Image of Error here

I've consoled 'getSignUpButtonText' which is defined as the text of that button on the page and it returns "Sign Up" so I know that text is on the page. Why can't screen.getByText('Sign Up') find it?

I have tried a few different packages but I cant seem to get away from this error.

Body:
I have a selenium / jest project. I have installed react testing library and a few packages, but when I try to make valid assertions, I get an error. Code:

import { Vocal } from '../../Models/vocalModel';
import {screen} from '@testing-library/dom';

const vocal = new Vocal()

// Test Variables here
let validEmail = 'email@email.com'
let validPassword = 'password'
let invalidEmail = 'ThisEmailIsNotValid'
let invalidPassword = 'ThisPassWordIsNotValid'

describe("Login Test Suite", () => {
    beforeAll(async ()=>{
        await vocal.navigate();
    });
    afterAll( async ()=>{
        await vocal.quit();
    });

    test('A user can login and logout', async () =>{
        await vocal.userLogin(validEmail, validPassword);
        await vocal.userLogout();

        let getSignUpButtonText = await vocal.getText(vocal.signUpButtonLogin)
        console.log(getSignUpButtonText)
        expect(screen.getByText("Sign Up")).toBeVisible();
    })
});

When I run this test, the browser runs and the test fails at the final assertion. I get the following error: "TestingLibraryElementError: Unable to find an element with the text: Sign Up. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.".
See photo:
Image of Error here

I've consoled 'getSignUpButtonText' which is defined as the text of that button on the page and it returns "Sign Up" so I know that text is on the page. Why can't screen.getByText('Sign Up') find it?

I have tried a few different packages but I cant seem to get away from this error.


问:
Songhe ATMega2560 + Wifi R3 ESP8266 is killing me! [WiFiEsp] >>> Cannot initialize ESP module
I am working with the Songhe Mega2560 + WiFi R3 Mega2560 + ESP8266 4MB Memory integrated circuit for a project involving connecting to a WiFi signal and reading the RSSI value.

Below is a basic sketch that I uploaded to the Mega2560 to communicate to the ESP8266 through Serial3 to test the firmware:

```<code>#include "WiFiEsp.h"

// Emulate Serial3 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL3
#include "SoftwareSerial.h"
SoftwareSerial Serial3(6, 7); // RX, TX
#endif

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial3.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial3);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // Print WiFi MAC address
  printMacAddress();
}

void loop() {
  // do nothing
}
</code>```

I flashed different versions of espressif's AT firmware but the serial monitor keeps showing this:

```<code>22:28:07.009 -> [WiFiEsp] Initializing ESP module
22:28:08.023 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:10.026 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:12.022 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:14.023 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:16.020 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:17.006 -> [WiFiEsp] Cannot initialize ESP module
22:28:23.017 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:23.017 -> [WiFiEsp] No tag found
22:28:23.017 -> WiFi shield not present
</code>```

I am not sure if it is a firmware issue so I have tried multiple versions of AT firmware. The baud rate I have set is 115200. I have been looking at many other sources online, but I cannot seem to initialize WiFiEsp's WiFi module and I would really appreciate some help on this matter.

I have been following these steps for flashing and testing.

Toggle DIP switches 5,6,7 to ON and all else OFF and RXD/TXD to RXD0

Connect USB cable from port COM3 (on my computer) to integrated PCB with Mega2560 + ESP8266 WiFi

Use esptool.py to flash firmware to the ESP8266

The latest, released firmware for ESP8266 is the "ESP8266-IDF-AT_V2.2.1.0.zip" downloadable at espressif.com

I download the factory_xxx.bin to address 0 since I read that it indicates all hardware configurations for the ESP module. Below is the command I ran:

esptool.py --chip auto --port COM3 --baud 115200 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_size 4MB 0x0 factory_WROOM-02.bin

Disconnect USB cable

Toggle DIP switches 1,2,3,4 to ON and all else OFF and RXD/TXD to RXD3

Connect USB cable and upload sketch with Arduino IDE and read serial monitor

This is the procedure I have been trying to debug. If anymore information is required for better help, please let me know and I will try my best to provide.

The screenshot below is the command I run which successfully flashes (I think):

```<code>C:\Users\[MY NAME]\Downloads\ESP8266_NONOS_SDK-3.0.5\ESP8266_NONOS_SDK-3.0.5\bin>esptool.py write_flash --flash_mode dout --flash_size 4MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin
esptool.py v4.4
Found 1 serial ports
Serial port COM3
Connecting....
Detecting chip type... Unsupported detection protocol, switching and trying again...
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: a4:e5:7c:b6:77:c0
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash will be erased from 0x00000000 to 0x00000fff...
Flash will be erased from 0x00001000 to 0x00065fff...
Flash will be erased from 0x001fb000 to 0x001fbfff...
Flash will be erased from 0x001fc000 to 0x001fcfff...
Flash will be erased from 0x000fe000 to 0x000fefff...
Flash will be erased from 0x001fe000 to 0x001fefff...
Flash params set to 0x0360
Compressed 4080 bytes to 2936...
Wrote 4080 bytes (2936 compressed) at 0x00000000 in 0.4 seconds (effective 92.5 kbit/s)...
Hash of data verified.
Compressed 413556 bytes to 296987...
Wrote 413556 bytes (296987 compressed) at 0x00001000 in 26.2 seconds (effective 126.1 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x001fb000 in 0.1 seconds (effective 373.3 kbit/s)...
Hash of data verified.
Compressed 128 bytes to 75...
Wrote 128 bytes (75 compressed) at 0x001fc000 in 0.1 seconds (effective 11.8 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x000fe000 in 0.1 seconds (effective 365.1 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x001fe000 in 0.1 seconds (effective 357.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...
</code>```

After this, I test it with Arduino's SerialPassThrough sketch replacing Serial1 with Serial3 and I get no response from running the command: AT.
I would appreciate any help on how to resolve this and where I could possibly be going wrong. Thanks!

Body:
I am working with the Songhe Mega2560 + WiFi R3 Mega2560 + ESP8266 4MB Memory integrated circuit for a project involving connecting to a WiFi signal and reading the RSSI value.

Below is a basic sketch that I uploaded to the Mega2560 to communicate to the ESP8266 through Serial3 to test the firmware:

#include "WiFiEsp.h"

// Emulate Serial3 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL3
#include "SoftwareSerial.h"
SoftwareSerial Serial3(6, 7); // RX, TX
#endif

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial3.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial3);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // Print WiFi MAC address
  printMacAddress();
}

void loop() {
  // do nothing
}

I flashed different versions of espressif's AT firmware but the serial monitor keeps showing this:

22:28:07.009 -> [WiFiEsp] Initializing ESP module
22:28:08.023 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:10.026 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:12.022 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:14.023 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:16.020 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:17.006 -> [WiFiEsp] Cannot initialize ESP module
22:28:23.017 -> [WiFiEsp] >>> TIMEOUT >>>
22:28:23.017 -> [WiFiEsp] No tag found
22:28:23.017 -> WiFi shield not present

I am not sure if it is a firmware issue so I have tried multiple versions of AT firmware. The baud rate I have set is 115200. I have been looking at many other sources online, but I cannot seem to initialize WiFiEsp's WiFi module and I would really appreciate some help on this matter.

I have been following these steps for flashing and testing.

Toggle DIP switches 5,6,7 to ON and all else OFF and RXD/TXD to RXD0

Connect USB cable from port COM3 (on my computer) to integrated PCB with Mega2560 + ESP8266 WiFi

Use esptool.py to flash firmware to the ESP8266

The latest, released firmware for ESP8266 is the "ESP8266-IDF-AT_V2.2.1.0.zip" downloadable at espressif.com

I download the factory_xxx.bin to address 0 since I read that it indicates all hardware configurations for the ESP module. Below is the command I ran:

esptool.py --chip auto --port COM3 --baud 115200 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_size 4MB 0x0 factory_WROOM-02.bin

Disconnect USB cable

Toggle DIP switches 1,2,3,4 to ON and all else OFF and RXD/TXD to RXD3

Connect USB cable and upload sketch with Arduino IDE and read serial monitor

This is the procedure I have been trying to debug. If anymore information is required for better help, please let me know and I will try my best to provide.

The screenshot below is the command I run which successfully flashes (I think):

C:\Users\[MY NAME]\Downloads\ESP8266_NONOS_SDK-3.0.5\ESP8266_NONOS_SDK-3.0.5\bin>esptool.py write_flash --flash_mode dout --flash_size 4MB-c1 0x0 boot_v1.7.bin 0x01000 at/1024+1024/user1.2048.new.5.bin 0x1fb000 blank.bin 0x1fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x1fe000 blank.bin
esptool.py v4.4
Found 1 serial ports
Serial port COM3
Connecting....
Detecting chip type... Unsupported detection protocol, switching and trying again...
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: a4:e5:7c:b6:77:c0
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash will be erased from 0x00000000 to 0x00000fff...
Flash will be erased from 0x00001000 to 0x00065fff...
Flash will be erased from 0x001fb000 to 0x001fbfff...
Flash will be erased from 0x001fc000 to 0x001fcfff...
Flash will be erased from 0x000fe000 to 0x000fefff...
Flash will be erased from 0x001fe000 to 0x001fefff...
Flash params set to 0x0360
Compressed 4080 bytes to 2936...
Wrote 4080 bytes (2936 compressed) at 0x00000000 in 0.4 seconds (effective 92.5 kbit/s)...
Hash of data verified.
Compressed 413556 bytes to 296987...
Wrote 413556 bytes (296987 compressed) at 0x00001000 in 26.2 seconds (effective 126.1 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x001fb000 in 0.1 seconds (effective 373.3 kbit/s)...
Hash of data verified.
Compressed 128 bytes to 75...
Wrote 128 bytes (75 compressed) at 0x001fc000 in 0.1 seconds (effective 11.8 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x000fe000 in 0.1 seconds (effective 365.1 kbit/s)...
Hash of data verified.
Compressed 4096 bytes to 26...
Wrote 4096 bytes (26 compressed) at 0x001fe000 in 0.1 seconds (effective 357.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

After this, I test it with Arduino's SerialPassThrough sketch replacing Serial1 with Serial3 and I get no response from running the command: AT.
I would appreciate any help on how to resolve this and where I could possibly be going wrong. Thanks!


问:
DisplayEventReceiver.java crash Android
I am facing a crash issue with thousands of users impacted and got the following log for main thread in crashlytics :

I am unable to find any cause of this issue. Any idea about this ?

```<code>main (runnable):tid=1 systid=17039
#00 pc 0x53a6e0 libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool) + 128)
#01 pc 0x6f0e04 libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, bool, BacktraceMap*, bool) const + 236)
#02 pc 0x6fe690 libart.so (art::DumpCheckpoint::Run(art::Thread*) + 208)
#03 pc 0x40295c libart.so (art::Thread::RunCheckpointFunction() + 140)
#04 pc 0x5606d4 libart.so (artQuickGenericJniEndTrampoline + 844)
#05 pc 0x440564 libart.so (art_quick_generic_jni_trampoline + 164)
#06 pc 0x2d24368 memfd:jit-zygote-cache (android.view.Choreographer.scheduleVsyncLocked + 200)
#07 pc 0x2d2412c memfd:jit-zygote-cache (android.view.Choreographer.scheduleFrameLocked + 1516)
#08 pc 0x2d22f1c memfd:jit-zygote-cache (android.view.Choreographer.postCallbackDelayedInternal + 236)
#09 pc 0x2e3c2e4 memfd:jit-zygote-cache (android.view.ViewRootImpl.scheduleTraversals + 980)
#10 pc 0x2e38158 memfd:jit-zygote-cache (android.view.ViewRootImpl.performTraversals + 16600)
#11 pc 0x2e24a54 memfd:jit-zygote-cache (android.view.ViewRootImpl.doTraversal + 724)
#12 pc 0x2e14ec0 memfd:jit-zygote-cache (android.view.ViewRootImpl$TraversalRunnable.run + 64)
#13 pc 0x2d2120c memfd:jit-zygote-cache (android.view.Choreographer.doCallbacks + 812)
#14 pc 0x2d21cd8 memfd:jit-zygote-cache (android.view.Choreographer.doFrame + 1592)
#15 pc 0x2d205ac memfd:jit-zygote-cache (android.view.Choreographer$FrameDisplayEventReceiver.run + 92)
#16 pc 0x2069330 memfd:jit-zygote-cache (android.os.Handler.dispatchMessage + 80)
#17 pc 0x2b3f894 memfd:jit-zygote-cache (android.os.Looper.loopOnce + 1060)
#18 pc 0x2087310 memfd:jit-zygote-cache (android.os.Looper.loop + 576)
#19 pc 0x25cb6c4 memfd:jit-zygote-cache (android.app.ActivityThread.main + 2052)
#20 pc 0x436e00 libart.so (art_quick_invoke_static_stub + 576)
#21 pc 0x469534 libart.so (_jobject* art::InvokeMethod<(art::PointerSize)8>(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jobject*, _jobject*, unsigned long) + 1960)
#22 pc 0x468d64 libart.so (art::Method_invoke(_JNIEnv*, _jobject*, _jobject*, _jobjectArray*) (.__uniq.165753521025965369065708152063621506277) + 48)
#23 pc 0x440554 libart.so (art_quick_generic_jni_trampoline + 148)
#24 pc 0x3035cb8 memfd:jit-zygote-cache (com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 136)
#25 pc 0x20b0d4 libart.so (nterp_helper + 7636)
#26 pc 0x33e974 framework.jar (com.android.internal.os.ZygoteInit.main + 716)
#27 pc 0x436e00 libart.so (art_quick_invoke_static_stub + 576)
#28 pc 0x582718 libart.so (art::JValue art::InvokeWithVarArgs<_jmethodID*>(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, std::__va_list) + 900)
#29 pc 0x5f611c libart.so (art::JNI<true>::CallStaticVoidMethodV(_JNIEnv*, _jclass*, _jmethodID*, std::__va_list) + 160)
#30 pc 0xb0b28 libandroid_runtime.so (_JNIEnv::CallStaticVoidMethod(_jclass*, _jmethodID*, ...) + 120)
#31 pc 0xbc2bc libandroid_runtime.so (android::AndroidRuntime::start(char const*, android::Vector<android::String8> const&, bool) + 980)
#32 pc 0x2580 app_process64 (main + 1320)
#33 pc 0x48a00 libc.so (__libc_init + 96)
       at android.view.DisplayEventReceiver.nativeScheduleVsync(DisplayEventReceiver.java)
       at android.view.DisplayEventReceiver.scheduleVsync(DisplayEventReceiver.java:252)
       at android.view.Choreographer.scheduleVsyncLocked(Choreographer.java:1024)
       at android.view.Choreographer.scheduleFrameLocked(Choreographer.java:767)
       at android.view.Choreographer.postCallbackDelayedInternal(Choreographer.java:552)
       at android.view.Choreographer.postCallbackDelayed(Choreographer.java:535)
       at android.view.Choreographer.postCallback(Choreographer.java:507)
       at android.view.ViewRootImpl.scheduleTraversals(ViewRootImpl.java:2341)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3671)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2383)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:9307)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1186)
       at android.view.Choreographer.doCallbacks(Choreographer.java:986)
       at android.view.Choreographer.doFrame(Choreographer.java:912)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1171)
       at android.os.Handler.handleCallback(Handler.java:938)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:334)
       at android.app.ActivityThread.main(ActivityThread.java:8396)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
</code>```

Tried to check DisplayEventReceiver related issues, didn't get anything.

Title: DisplayEventReceiver.java crash Android

Body:
I am facing a crash issue with thousands of users impacted and got the following log for main thread in crashlytics :

I am unable to find any cause of this issue. Any idea about this ?

main (runnable):tid=1 systid=17039
#00 pc 0x53a6e0 libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool) + 128)
#01 pc 0x6f0e04 libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, bool, BacktraceMap*, bool) const + 236)
#02 pc 0x6fe690 libart.so (art::DumpCheckpoint::Run(art::Thread*) + 208)
#03 pc 0x40295c libart.so (art::Thread::RunCheckpointFunction() + 140)
#04 pc 0x5606d4 libart.so (artQuickGenericJniEndTrampoline + 844)
#05 pc 0x440564 libart.so (art_quick_generic_jni_trampoline + 164)
#06 pc 0x2d24368 memfd:jit-zygote-cache (android.view.Choreographer.scheduleVsyncLocked + 200)
#07 pc 0x2d2412c memfd:jit-zygote-cache (android.view.Choreographer.scheduleFrameLocked + 1516)
#08 pc 0x2d22f1c memfd:jit-zygote-cache (android.view.Choreographer.postCallbackDelayedInternal + 236)
#09 pc 0x2e3c2e4 memfd:jit-zygote-cache (android.view.ViewRootImpl.scheduleTraversals + 980)
#10 pc 0x2e38158 memfd:jit-zygote-cache (android.view.ViewRootImpl.performTraversals + 16600)
#11 pc 0x2e24a54 memfd:jit-zygote-cache (android.view.ViewRootImpl.doTraversal + 724)
#12 pc 0x2e14ec0 memfd:jit-zygote-cache (android.view.ViewRootImpl$TraversalRunnable.run + 64)
#13 pc 0x2d2120c memfd:jit-zygote-cache (android.view.Choreographer.doCallbacks + 812)
#14 pc 0x2d21cd8 memfd:jit-zygote-cache (android.view.Choreographer.doFrame + 1592)
#15 pc 0x2d205ac memfd:jit-zygote-cache (android.view.Choreographer$FrameDisplayEventReceiver.run + 92)
#16 pc 0x2069330 memfd:jit-zygote-cache (android.os.Handler.dispatchMessage + 80)
#17 pc 0x2b3f894 memfd:jit-zygote-cache (android.os.Looper.loopOnce + 1060)
#18 pc 0x2087310 memfd:jit-zygote-cache (android.os.Looper.loop + 576)
#19 pc 0x25cb6c4 memfd:jit-zygote-cache (android.app.ActivityThread.main + 2052)
#20 pc 0x436e00 libart.so (art_quick_invoke_static_stub + 576)
#21 pc 0x469534 libart.so (_jobject* art::InvokeMethod<(art::PointerSize)8>(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jobject*, _jobject*, unsigned long) + 1960)
#22 pc 0x468d64 libart.so (art::Method_invoke(_JNIEnv*, _jobject*, _jobject*, _jobjectArray*) (.__uniq.165753521025965369065708152063621506277) + 48)
#23 pc 0x440554 libart.so (art_quick_generic_jni_trampoline + 148)
#24 pc 0x3035cb8 memfd:jit-zygote-cache (com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 136)
#25 pc 0x20b0d4 libart.so (nterp_helper + 7636)
#26 pc 0x33e974 framework.jar (com.android.internal.os.ZygoteInit.main + 716)
#27 pc 0x436e00 libart.so (art_quick_invoke_static_stub + 576)
#28 pc 0x582718 libart.so (art::JValue art::InvokeWithVarArgs<_jmethodID*>(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, std::__va_list) + 900)
#29 pc 0x5f611c libart.so (art::JNI<true>::CallStaticVoidMethodV(_JNIEnv*, _jclass*, _jmethodID*, std::__va_list) + 160)
#30 pc 0xb0b28 libandroid_runtime.so (_JNIEnv::CallStaticVoidMethod(_jclass*, _jmethodID*, ...) + 120)
#31 pc 0xbc2bc libandroid_runtime.so (android::AndroidRuntime::start(char const*, android::Vector<android::String8> const&, bool) + 980)
#32 pc 0x2580 app_process64 (main + 1320)
#33 pc 0x48a00 libc.so (__libc_init + 96)
       at android.view.DisplayEventReceiver.nativeScheduleVsync(DisplayEventReceiver.java)
       at android.view.DisplayEventReceiver.scheduleVsync(DisplayEventReceiver.java:252)
       at android.view.Choreographer.scheduleVsyncLocked(Choreographer.java:1024)
       at android.view.Choreographer.scheduleFrameLocked(Choreographer.java:767)
       at android.view.Choreographer.postCallbackDelayedInternal(Choreographer.java:552)
       at android.view.Choreographer.postCallbackDelayed(Choreographer.java:535)
       at android.view.Choreographer.postCallback(Choreographer.java:507)
       at android.view.ViewRootImpl.scheduleTraversals(ViewRootImpl.java:2341)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3671)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2383)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:9307)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1186)
       at android.view.Choreographer.doCallbacks(Choreographer.java:986)
       at android.view.Choreographer.doFrame(Choreographer.java:912)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1171)
       at android.os.Handler.handleCallback(Handler.java:938)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loopOnce(Looper.java:233)
       at android.os.Looper.loop(Looper.java:334)
       at android.app.ActivityThread.main(ActivityThread.java:8396)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)

Tried to check DisplayEventReceiver related issues, didn't get anything.


问:
Deploying PWA server with offline support in intranet
I am developing an application that needs to be delivered as following:

PWA application server(Host app/IIS) is installed in the local network

PWA should support offline

Domain SSL not possible on the server as it's not a domain

Un attended installation

No configuration should be forced on the client machine, to change chrome settings etc.

I have tried:

Running from VS, Only works on same machine by design

Published to IIS and tried, works ok on the same machine. Offline does not work on mobile

Self sign SSL is not helping, Offline does not work

One option I found is to host it on our server on the internet, after installation access data from intranet server. Not yet tried this.

Looks like it is impossible to deploy PWA as intranet application with self-sign SSL. Am I missing something ?

Is there a way to automate deployment of PWA with self-sign that supports offline working?


问:
When I check sass version in terminal at vscode it shows an error
I downloaded sass in my terminal. It is running successfully, but when i check the version it shows an error like:</p>
```<code> The term 'saas' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ saas -v
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (saas:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

Body:
I downloaded sass in my terminal. It is running successfully, but when i check the version it shows an error like:

 The term 'saas' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ saas -v
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (saas:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


问:
Difference between 2 apps running a secondary thread for communication and 2 apps using the same communication process
I am new in multi-processing. I am creating an app in modern c++ that communicates with PLCs by modbus TCP. Thus, I have created my library to achieve that and I run the communication process on a different thread and the main thread communicates with it by a shared queue and events. It works well.
Now, I would like to design another app that has a different purpose that would sometime run in parallel to the first one. It still needs to communication with the PLCs. Should I also implement it with multithreading, opening a new canal of communication in a thread? Or should I implement some unique communication process and that every executables would connect to via some pipe? What is the difference between the two and is there a logic to use/exclude one of those solutions?

I see advantages in the multi-threading solution:

If the client fails, it only affects one program until reconnexion,

Shared memory is useful,

It is already implemented in my case

But I also see several advantages for the multi-processing approach. One communication client could be used by many apps. Also among them, it appears to be better for optimization.

I thank you in advance for your help.


问:
Teradata CASE WHEN attribute IN ( Select... from)

I have selected a bunch of IDs and I try to use CASE WHEN to get a column when the IDs which I really want to select are in the IDs I selected earlier.
But it shows Select Failed .3771:Illegal expression in WHEN clause of Case expression.

Any suggestion to get it right?
Please help.

p.s my goal is to select the IDs shown for the first time.


问:
How to include dynamic configmap and secrets in helmfile
I am using helmfile to deploy multiple sub-charts using helmfile sync -e env command.

I am having the configmap and secretes which I need to load based on the environment.

Is there a way to load configmap and secretes based on the environment in the helmfile.

I tried to add in the

dev-configmap.yaml

```<code>  apiVersion: v1
    kind: ConfigMap
    metadata:
        name: backend
        namespace: {{ .Values.namespace }}
    data:
        NODE_ENV: {{ .Values.env }}
</code>```

In helmfile.yaml

```<code>environments:
    envDefaults: &envDefaults
        values:
            - ./values/{{ .Environment.Name }}.yaml
            - kubeContext: ''
              namespace: '{{ .Environment.Name }}'
    dev:
        <<: *envDefaults
        secrets:
            - ./config/secrets/dev.yaml
            - ./config/configmap/dev.yaml
</code>```

Is there a way to import configmap and secrets (Not encrypted) YAML dynamically based on the environment in helmfile?

Body:
I am using helmfile to deploy multiple sub-charts using helmfile sync -e env command.

I am having the configmap and secretes which I need to load based on the environment.

Is there a way to load configmap and secretes based on the environment in the helmfile.

I tried to add in the

dev-configmap.yaml

  apiVersion: v1
    kind: ConfigMap
    metadata:
        name: backend
        namespace: {{ .Values.namespace }}
    data:
        NODE_ENV: {{ .Values.env }}

In helmfile.yaml

environments:
    envDefaults: &envDefaults
        values:
            - ./values/{{ .Environment.Name }}.yaml
            - kubeContext: ''
              namespace: '{{ .Environment.Name }}'
    dev:
        <<: *envDefaults
        secrets:
            - ./config/secrets/dev.yaml
            - ./config/configmap/dev.yaml

Is there a way to import configmap and secrets (Not encrypted) YAML dynamically based on the environment in helmfile?


问:
Due to:Parent module 'mysql.connector.plugins' not loaded, cannot perform relative import
I am doing project of face recognition. this is the code

```<code>def add_data(self):
    if (
        self.var_dep.get() == "select Department"
        or self.var_std_name.get() == ""
        or self.var_std_id.get() == ""
    ):
        messagebox.showerror("Error","All field are required",parent=self.root)
    else:
        try:
            conn = mysql.connector.connect(
                host="localhost",
                username="root",
                password="root",
                database="face_recognizer"
            )
            my_cursor = conn.cursor()
            my_cursor.execute(
                "insert into values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (
                    self.var_dep.get(),
                    self.var_course.get(),
                    self.var_year.get(),
                    self.var_semester.get(),
                    self.var_std_id.get(),
                    self.var_std_name.get(),
                    self.var_div.get(),
                    self.var_roll.get(),
                    self.var_gender.get(),
                    self.var_dob.get(),
                    self.var_email.get(),
                    self.var_phone.get(),
                    self.var_address.get(),
                    self.var_teacher.get(),
                    self.var_radio1.get()
                )
            )
            conn.commit()
            conn.close()
            messagebox.showinfo("Success", "Student details has been added succesfully", parent=self.root)
        except Exception as es:
            messagebox.showerror("Error",f"Due to:{str(es)}",parent=self.root)

</code>```

I tried all the possible ways to try and solve the problem. I watched some YouTube Videos also but I didn't get the proper solution for this one
please help me to reach out the solution for this error:

Due to:Parent module 'mysql.connector.plugins' not loaded, cannot perform relative import

Body:
I am doing project of face recognition. this is the code

def add_data(self):
    if (
        self.var_dep.get() == "select Department"
        or self.var_std_name.get() == ""
        or self.var_std_id.get() == ""
    ):
        messagebox.showerror("Error","All field are required",parent=self.root)
    else:
        try:
            conn = mysql.connector.connect(
                host="localhost",
                username="root",
                password="root",
                database="face_recognizer"
            )
            my_cursor = conn.cursor()
            my_cursor.execute(
                "insert into values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (
                    self.var_dep.get(),
                    self.var_course.get(),
                    self.var_year.get(),
                    self.var_semester.get(),
                    self.var_std_id.get(),
                    self.var_std_name.get(),
                    self.var_div.get(),
                    self.var_roll.get(),
                    self.var_gender.get(),
                    self.var_dob.get(),
                    self.var_email.get(),
                    self.var_phone.get(),
                    self.var_address.get(),
                    self.var_teacher.get(),
                    self.var_radio1.get()
                )
            )
            conn.commit()
            conn.close()
            messagebox.showinfo("Success", "Student details has been added succesfully", parent=self.root)
        except Exception as es:
            messagebox.showerror("Error",f"Due to:{str(es)}",parent=self.root)

I tried all the possible ways to try and solve the problem. I watched some YouTube Videos also but I didn't get the proper solution for this one
please help me to reach out the solution for this error:

Due to:Parent module 'mysql.connector.plugins' not loaded, cannot perform relative import


问:
Can JSONPath Filters be used for InputPath in EvenBridge?
This is my event:

```<code>{
  "version": "0",
  "id": "98453365-2b35-f956-5d00-b906f598ef89",
  "detail-type": "sampleBooks",
  "source": "myBookstore",
  "account": "859378868885",
  "time": "2022-12-22T06:04:27Z",
  "region": "ap-south-1",
  "resources": [],
  "detail": {
    "books": [
      {
        "title": "book6",
        "author": "author1"
      },
      {
        "title": "book7",
        "author": "author1"
      },
      {
        "title": "book8",
        "author": "author3"
      }
    ]
  }
}
</code>```

books is an array of objects with field author. I want to send the books with only author == author1 to an API Destination.

Can we not use filters in InputPath?

I tried to use this InputPath but an error is thrown saying that this Input Path is invalid.

```<code>{
  "books":"$.detail.books[?(@.author=='author1')]"
}
</code>```

Body:
This is my event:

{
  "version": "0",
  "id": "98453365-2b35-f956-5d00-b906f598ef89",
  "detail-type": "sampleBooks",
  "source": "myBookstore",
  "account": "859378868885",
  "time": "2022-12-22T06:04:27Z",
  "region": "ap-south-1",
  "resources": [],
  "detail": {
    "books": [
      {
        "title": "book6",
        "author": "author1"
      },
      {
        "title": "book7",
        "author": "author1"
      },
      {
        "title": "book8",
        "author": "author3"
      }
    ]
  }
}

books is an array of objects with field author. I want to send the books with only author == author1 to an API Destination.

Can we not use filters in InputPath?

I tried to use this InputPath but an error is thrown saying that this Input Path is invalid.

{
  "books":"$.detail.books[?(@.author=='author1')]"
}


问:
How to test Auth::once() in Laravel?
I'm using Auth:once() to authenticate users for a single request.

```<code>if (!Auth::once($this->only('email', 'password'))) {
    RateLimiter::hit($this->throttleKey());

    throw ValidationException::withMessages([
        'email' => __('auth.failed'),
    ]);
}

// we store the user + password for one request in the session
// so we can use it in the next request
$this->session()->put('email', $this->email);
$this->session()->put('password', $this->password);
</code>```

But the test user is permanently authenticated, and assertGuest() is always false, not just for a single request. This is happening only in the test!

```<code>$user = User::factory()->create();

$response = $this->post('/api/login', [
    'email' => $user->email,
    'password' =>' password',
]);

$response = $this->get('/api/home');

$this->assertGuest();
</code>```

I tested manually from Postman, and everything seems to be okay. So I think Laravel considers it a single request for the entire test.

Title: How to test Auth::once() in Laravel?

Body:
I'm using Auth:once() to authenticate users for a single request.

if (!Auth::once($this->only('email', 'password'))) {
    RateLimiter::hit($this->throttleKey());

    throw ValidationException::withMessages([
        'email' => __('auth.failed'),
    ]);
}

// we store the user + password for one request in the session
// so we can use it in the next request
$this->session()->put('email', $this->email);
$this->session()->put('password', $this->password);

But the test user is permanently authenticated, and assertGuest() is always false, not just for a single request. This is happening only in the test!

$user = User::factory()->create();

$response = $this->post('/api/login', [
    'email' => $user->email,
    'password' =>' password',
]);

$response = $this->get('/api/home');

$this->assertGuest();

I tested manually from Postman, and everything seems to be okay. So I think Laravel considers it a single request for the entire test.


问:
Is it possible to see to see all the classes a typeclass is related to? Or at least its subclasses?
I find it very informative and useful to see which instances a class has. It helps me understand what a class is used for and how. Thankfully this information is available both in GHCi (through the :info <class> command) and through the doc on Hackage.

For the same reason, I would love to see the relationship between classes: I'd like to get an overview like the one told by this diagram for any given class:

Is it possible to ask GHCi, Hackage, or any other tool/service for all the classes a given class is related to?

GHCi's :info <class> and Hackage show the superclasses, but not the sub-ones.


问:
how to save all shell context and restore & run in other machine?
I have 2 situations to use this.

I executed a script and run it after 1 year in same machine.
(a lot of thing are changed, some time the result is not same)

I execute a script in both host and docker, then compare the result.
(it is difficult to find shell context diffs whereas finding not-installed packages easy.)

Thereafore, I'd like know way to save all shell context (including variables, function, options and extra), then restore in other machine and run it.

My basic idea is

set > backup.sh ; source backup.sh

option="$(set +o)"; eval "$option"

anything else?

Any suggestion or solution about this?


问:
Png signature reading fail
I am trying to read the signature of png image file using std::ifstream opened it in binary mode but I got only few bytes correct. Surely using png image for input.

Just I want to validate my png image, whats going wrong here.

```<code>#include <fstream>
#include <iostream>
using namespace std;

const auto PNG_SIGN_SIZE = 8;
const uint8_t PNG_SIGN_BUFFER[] = {137, 80, 78, 71, 13, 10, 26, 10};

bool validate(const string& filename) {
    ifstream ifs;
    ifs.open(filename, ios::binary);
    bool is_valid = true;

    if (ifs.is_open()) {
        uint8_t buffer[PNG_SIGN_SIZE]{};

        for (int i = 0; i < PNG_SIGN_SIZE; ++i) {
            ifs >> buffer[i];

            if (ifs.fail()) {
                printf("ERROR: Fail to read bytes.\n");
                is_valid = false;
                break;
            }
        }

        for (int i = 0; i < PNG_SIGN_SIZE; ++i) {
            // printf("%u %u\n", buffer[i], PNG_SIGN_BUFFER[i]);
            if (buffer[i] != PNG_SIGN_BUFFER[i]) {
                is_valid = false;
                break;
            }
        }

    } else {
        printf("ERROR: Could not read <%s>.\n", filename.c_str());
        is_valid = false;
    }

    ifs.close();
    return is_valid;
}

int main() {
    string filename = "baby.png";
    auto res = validate(filename);

    cout << boolalpha << res;

    return 0;
}
</code>```

Title: Png signature reading fail

Body:
I am trying to read the signature of png image file using std::ifstream opened it in binary mode but I got only few bytes correct. Surely using png image for input.

Just I want to validate my png image, whats going wrong here.

#include <fstream>
#include <iostream>
using namespace std;

const auto PNG_SIGN_SIZE = 8;
const uint8_t PNG_SIGN_BUFFER[] = {137, 80, 78, 71, 13, 10, 26, 10};

bool validate(const string& filename) {
    ifstream ifs;
    ifs.open(filename, ios::binary);
    bool is_valid = true;

    if (ifs.is_open()) {
        uint8_t buffer[PNG_SIGN_SIZE]{};

        for (int i = 0; i < PNG_SIGN_SIZE; ++i) {
            ifs >> buffer[i];

            if (ifs.fail()) {
                printf("ERROR: Fail to read bytes.\n");
                is_valid = false;
                break;
            }
        }

        for (int i = 0; i < PNG_SIGN_SIZE; ++i) {
            // printf("%u %u\n", buffer[i], PNG_SIGN_BUFFER[i]);
            if (buffer[i] != PNG_SIGN_BUFFER[i]) {
                is_valid = false;
                break;
            }
        }

    } else {
        printf("ERROR: Could not read <%s>.\n", filename.c_str());
        is_valid = false;
    }

    ifs.close();
    return is_valid;
}

int main() {
    string filename = "baby.png";
    auto res = validate(filename);

    cout << boolalpha << res;

    return 0;
}


问:
How do I see the value of an element of an array using the debugger?
I am trying to debug some code and i think i have the array i'm suppose to memorize messed up. How do I see what elements i have in the array using the debugger (the echivalent of print(long)variable)

I tried using the same command i use to use the array elements: print(long)(%edi, %eax, 4), %eax being the index of the wanted element of the array. But it doesn't work.

gcc -m32 app.s -o app -> gdb app -> b tag -> print(long)(%edi, %eax, 4)


问:
Cannot find latest.yml in the release
What am trying to implement
Am new to electron. Am trying to implement  releases & auto update based on channels. I followed instructions in official documentation here. I also added scripts to generate alpha build.

My Problem

Alpha build is created along with alpha.yml.
[Here is my screenshot]
(https://i.stack.imgur.com/nUin4.png).

Updater instead of looking for alpha.yml it shows an error in terminal Cannot find latest.yml in the release.

What have I tried

[Here is my package.json]
(https://i.stack.imgur.com/xuTS1.png)

The deploy command is for stable release & deploy-alpha is for alpha release. The builder-alpha.json is nothing but a copy of electron builder only difference is the product name.

[This is my main.js]
(https://i.stack.imgur.com/KVlZu.png)

I also tried keeping the appid & name as same too but that didn't work as well. I couldn't find anything more on documentation or in any search results. So any help would be appreciated. Thank you.

Title: Cannot find latest.yml in the release


问:
how to run existing grunt command from scripts in package.json
i want to be able to run a grunt command via the scripts section of a package.json file that resides in a different directory than the Gruntfile.

My folder structure is the following:

design

Gruntfile.js

react-ui

package.json

if i run grunt watch:dev in the design folder everything works as expected. How can i run the same command in the package.json since the Gruntfile is in a different folder?


问:
Whether the connection mode for dataset shared with external user is live or direct query?
Link: https://learn.microsoft.com/en-us/power-bi/collaborate-share/service-dataset-external-org-share-about#considerations-and-limitations

Live connect mode isn't currently supported for in-place dataset
sharing. Power BI will need to change queries in the DirectQuery mode,
which consumes resources on shared capacity or a Premium capacity.

Subsequently it also says:

Users with appropriate permissions in the consumer tenant get live
access to this dataset.

I am finding both the above are contradictory?


问:
How to access terraform input variables using import
I'm trying to use the terraform import flow with input variables, like this:

terraform import -var-file=values.tfvars.json ADDR ID

According to what I read the flow goes throught the import function and the read function.
It seems that I can not access the values that was passed usig the -var-file property in neither one of those functions (import\read).

Is it possible to do so?
if not, I would expect this command to ignore the required values of this solution.


问:
Voice Commands On Flutter Application
I tried to do give a command to the flutter application using voice commands and in the application there was a text to voice function. so when i tried to give read command using voice there was a repeat on that function. how to avoid the repeat.

I have tried to terminate the Listening function after getting one input but it dosen't work.

Tried to terminate the Listening function.
but same error

```<code>import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:newsapp/screens/News_Screen.dart';
import 'package:newsapp/utils/app_colors.dart';
import 'package:newsapp/utils/assets_constants.dart';
import 'package:webfeed/webfeed.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_speech/flutter_speech.dart';

const languages = const [
  // const Language('Francais', 'fr_FR'),
  const Language('English', 'en_US'),
  const Language('Pусский', 'ru_RU'),
  const Language('Italiano', 'it_IT'),
  const Language('Español', 'es_ES'),
];

class Language {
  final String name;
  final String code;

  const Language(this.name, this.code);
}

class BBCNews extends StatefulWidget {
  @override
  _BBCNewsState createState() => _BBCNewsState();
}

class _BBCNewsState extends State<BBCNews> {
  late SpeechRecognition _speech;
  FlutterTts flutterTts = FlutterTts();

  bool _speechRecognitionAvailable = false;
  bool _isListening = false;

  String transcription = '';
  String _currentLocale = 'en_US';
  //Language selectedLang = languages.first;

  @override
  initState() {
    super.initState();
    activateSpeechRecognizer();
  }

  void activateSpeechRecognizer() {
    //print('_MyAppState.activateSpeechRecognizer... ');
    _speech = SpeechRecognition();
    _speech.setAvailabilityHandler(onSpeechAvailability);
    _speech.setRecognitionStartedHandler(onRecognitionStarted);
    _speech.setRecognitionResultHandler(onRecognitionResult);
    _speech.setRecognitionCompleteHandler(onRecognitionComplete);
    _speech.setErrorHandler(errorHandler);
    _speech.activate('en_US').then((res) {
      setState(() => _speechRecognitionAvailable = res);
    });
  }

  var client = http.Client();

  Future myDevBlog() async {
    var response = await client

 .get(Uri.parse('http://feeds.bbci.co.uk/news/world/rss.xml'));

    var channel = RssFeed.parse(response.body);

    final item = channel.items;

    return item;
  }

  Future<void> openFeed(String url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
        forceSafariVC: true,
        forceWebView: false,
      );

      return;
    }
  }

  rightIcon() {
    return const Icon(
      Icons.keyboard_arrow_right,
      color: Colors.grey,
      size: 30,
    );
  }

  @override
  Widget build(BuildContext context) {
    var currentIndex;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.primaryColor,

        //title: const Text('VoiceNews'),

        title: Image.asset(
          AssetConstants.iconPath,
          width: 150,
        ),

        elevation: 10.0,

        actions: [
          IconButton(
              onPressed: _speechRecognitionAvailable && !_isListening
                  ? () => start()
                  : null,
              icon: const Icon(Icons.play_arrow_rounded)),
          IconButton(
              onPressed: _isListening ? () => stop() : null,
              icon: const Icon(Icons.stop_circle))
        ],
      ),
      body: StreamBuilder(
        stream: myDevBlog().asStream(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, int index) {
                if (transcription.toLowerCase() == "play") {
                  // _isListening = false;
                  //stop();
                  print(transcription);
                  speak(snapshot.data[1].title);
                  var currentIndex = 0;
                } else if (transcription.toLowerCase() == "next") {
                  // _isListening = false;
                  speak(snapshot.data[2].title);
                  print(transcription);
                } else if (transcription.toLowerCase() == "all") {
                  // _isListening = false;
                  errorHandler();
                  //speak("Wrong Input");
                  //cancel();
                }
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Card(
                    child: ListTile(
                      title: Text(snapshot.data[index].title),

                      subtitle:

Text(snapshot.data[index].description),

                          //onTap: () =>
speak(snapshot.data[index].title),

                          // onTap: () =>
openFeed(snapshot.data[index].link),

                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) =>

   newsScreen(snapshot.data[index].link),
                                // Pass the arguments as part of the
  RouteSettings. The
                                // DetailScreen reads the arguments
 from these settings.
                                // settings: RouteSettings(
                                //   arguments: todos[index],
                                // ),
                              ),
                            );
                            print(snapshot.data[index].link);
                          },

                          onLongPress: () =>

  speak(snapshot.data[index].description),

                          leading: Text((1 + index).toString()),

                          trailing: rightIcon(),
                        ),
                      ),
                    );
                  },
                );
              } else if (snapshot.hasError ||
                  snapshot.connectionState == ConnectionState.none) {
                return Center(
                  child: Text(snapshot.error.toString()),
                );
              }

              return const Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
        );
      }

      // List<CheckedPopupMenuItem<Language>> get
  _buildLanguagesWidgets => languages

      void start() => _speech.activate(_currentLocale).then((_) {
            return _speech.listen().then((result) {
              print('_MyAppState.start => result $result');

              setState(() {
                _isListening = result;
              });
            });
          });

      void cancel() =>
          _speech.cancel().then((_) => setState(() => _isListening =
   false));

      void stop() => _speech.stop().then((_) {
            setState(() => _isListening = false);
          });
      void onSpeechAvailability(bool result) =>
          setState(() => _speechRecognitionAvailable = result);
      // void onCurrentLocale(String locale) {
      //   // print('_MyAppState.onCurrentLocale... $locale');
      //   setState(
      //       () => _currentLocale = languages.firstWhere((l) =>
    l.code == locale));
      // }

      void onRecognitionStarted() {
        setState(() => _isListening = true);
      }

      void onRecognitionResult(String text) {
        // print('_MyAppState.onRecognitionResult... $text');
        setState(() => transcription = text);
      }

      void onRecognitionComplete(String text) {
        //print('_MyAppState.onRecognitionComplete... $text');
        setState(() => _isListening = false);
      }

      void errorHandler() => activateSpeechRecognizer();

      void speak(String text) async {
        await flutterTts.speak(text);

        await flutterTts.setLanguage("en-US");

        await flutterTts.setPitch(1);

        await flutterTts.setSpeechRate(0.6);
      }
    }
</code>```

Title: Voice Commands On Flutter Application

Body:
I tried to do give a command to the flutter application using voice commands and in the application there was a text to voice function. so when i tried to give read command using voice there was a repeat on that function. how to avoid the repeat.

I have tried to terminate the Listening function after getting one input but it dosen't work.

Tried to terminate the Listening function.
but same error

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:newsapp/screens/News_Screen.dart';
import 'package:newsapp/utils/app_colors.dart';
import 'package:newsapp/utils/assets_constants.dart';
import 'package:webfeed/webfeed.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_speech/flutter_speech.dart';

const languages = const [
  // const Language('Francais', 'fr_FR'),
  const Language('English', 'en_US'),
  const Language('Pусский', 'ru_RU'),
  const Language('Italiano', 'it_IT'),
  const Language('Español', 'es_ES'),
];

class Language {
  final String name;
  final String code;

  const Language(this.name, this.code);
}

class BBCNews extends StatefulWidget {
  @override
  _BBCNewsState createState() => _BBCNewsState();
}

class _BBCNewsState extends State<BBCNews> {
  late SpeechRecognition _speech;
  FlutterTts flutterTts = FlutterTts();

  bool _speechRecognitionAvailable = false;
  bool _isListening = false;

  String transcription = '';
  String _currentLocale = 'en_US';
  //Language selectedLang = languages.first;

  @override
  initState() {
    super.initState();
    activateSpeechRecognizer();
  }

  void activateSpeechRecognizer() {
    //print('_MyAppState.activateSpeechRecognizer... ');
    _speech = SpeechRecognition();
    _speech.setAvailabilityHandler(onSpeechAvailability);
    _speech.setRecognitionStartedHandler(onRecognitionStarted);
    _speech.setRecognitionResultHandler(onRecognitionResult);
    _speech.setRecognitionCompleteHandler(onRecognitionComplete);
    _speech.setErrorHandler(errorHandler);
    _speech.activate('en_US').then((res) {
      setState(() => _speechRecognitionAvailable = res);
    });
  }

  var client = http.Client();

  Future myDevBlog() async {
    var response = await client

 .get(Uri.parse('http://feeds.bbci.co.uk/news/world/rss.xml'));

    var channel = RssFeed.parse(response.body);

    final item = channel.items;

    return item;
  }

  Future<void> openFeed(String url) async {
    if (await canLaunch(url)) {
      await launch(
        url,
        forceSafariVC: true,
        forceWebView: false,
      );

      return;
    }
  }

  rightIcon() {
    return const Icon(
      Icons.keyboard_arrow_right,
      color: Colors.grey,
      size: 30,
    );
  }

  @override
  Widget build(BuildContext context) {
    var currentIndex;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: AppColors.primaryColor,

        //title: const Text('VoiceNews'),

        title: Image.asset(
          AssetConstants.iconPath,
          width: 150,
        ),

        elevation: 10.0,

        actions: [
          IconButton(
              onPressed: _speechRecognitionAvailable && !_isListening
                  ? () => start()
                  : null,
              icon: const Icon(Icons.play_arrow_rounded)),
          IconButton(
              onPressed: _isListening ? () => stop() : null,
              icon: const Icon(Icons.stop_circle))
        ],
      ),
      body: StreamBuilder(
        stream: myDevBlog().asStream(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, int index) {
                if (transcription.toLowerCase() == "play") {
                  // _isListening = false;
                  //stop();
                  print(transcription);
                  speak(snapshot.data[1].title);
                  var currentIndex = 0;
                } else if (transcription.toLowerCase() == "next") {
                  // _isListening = false;
                  speak(snapshot.data[2].title);
                  print(transcription);
                } else if (transcription.toLowerCase() == "all") {
                  // _isListening = false;
                  errorHandler();
                  //speak("Wrong Input");
                  //cancel();
                }
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Card(
                    child: ListTile(
                      title: Text(snapshot.data[index].title),

                      subtitle:

Text(snapshot.data[index].description),

                          //onTap: () =>
speak(snapshot.data[index].title),

                          // onTap: () =>
openFeed(snapshot.data[index].link),

                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) =>

   newsScreen(snapshot.data[index].link),
                                // Pass the arguments as part of the
  RouteSettings. The
                                // DetailScreen reads the arguments
 from these settings.
                                // settings: RouteSettings(
                                //   arguments: todos[index],
                                // ),
                              ),
                            );
                            print(snapshot.data[index].link);
                          },

                          onLongPress: () =>

  speak(snapshot.data[index].description),

                          leading: Text((1 + index).toString()),

                          trailing: rightIcon(),
                        ),
                      ),
                    );
                  },
                );
              } else if (snapshot.hasError ||
                  snapshot.connectionState == ConnectionState.none) {
                return Center(
                  child: Text(snapshot.error.toString()),
                );
              }

              return const Center(
                child: CircularProgressIndicator(),
              );
            },
          ),
        );
      }

      // List<CheckedPopupMenuItem<Language>> get
  _buildLanguagesWidgets => languages

      void start() => _speech.activate(_currentLocale).then((_) {
            return _speech.listen().then((result) {
              print('_MyAppState.start => result $result');

              setState(() {
                _isListening = result;
              });
            });
          });

      void cancel() =>
          _speech.cancel().then((_) => setState(() => _isListening =
   false));

      void stop() => _speech.stop().then((_) {
            setState(() => _isListening = false);
          });
      void onSpeechAvailability(bool result) =>
          setState(() => _speechRecognitionAvailable = result);
      // void onCurrentLocale(String locale) {
      //   // print('_MyAppState.onCurrentLocale... $locale');
      //   setState(
      //       () => _currentLocale = languages.firstWhere((l) =>
    l.code == locale));
      // }

      void onRecognitionStarted() {
        setState(() => _isListening = true);
      }

      void onRecognitionResult(String text) {
        // print('_MyAppState.onRecognitionResult... $text');
        setState(() => transcription = text);
      }

      void onRecognitionComplete(String text) {
        //print('_MyAppState.onRecognitionComplete... $text');
        setState(() => _isListening = false);
      }

      void errorHandler() => activateSpeechRecognizer();

      void speak(String text) async {
        await flutterTts.speak(text);

        await flutterTts.setLanguage("en-US");

        await flutterTts.setPitch(1);

        await flutterTts.setSpeechRate(0.6);
      }
    }


问:
wait for a file to save then run the next line? (Node js)
In an api point I want to save a qrcode as png in local file system then in the same api I want to get that saved image and use it to make a pdf file. But in the function the pdf making function is running before saving the file in the file system. How can I force/ensure the file saved and the move to next line.

console.log("this line 1");

QRCode.toDataURL(`https://www.mindschoolbd.com/verifycertificate/?certificateID=${genId}`, function (err, url) {
    let base64String = url;
    let base64Image = base64String.split(";base64,").pop();

    let writeBuffer = new Buffer.from(base64Image, "base64");
    fs.writeFileSync(
        `./userCertificates/qrCodes/${genId}.png`,
         writeBuffer
    );
    console.log("this line 2");
})
console.log("this line 3");
```
<p>In my case I am getting output like this:</p>
```this line 1
this line 3
this line 2
```
<p>but I want it to be</p>
```this line 1
this line 2
this line 3
```

Body:
In an api point I want to save a qrcode as png in local file system then in the same api I want to get that saved image and use it to make a pdf file. But in the function the pdf making function is running before saving the file in the file system. How can I force/ensure the file saved and the move to next line.

console.log("this line 1");

QRCode.toDataURL(`https://www.mindschoolbd.com/verifycertificate/?certificateID=${genId}`, function (err, url) {
    let base64String = url;
    let base64Image = base64String.split(";base64,").pop();

    let writeBuffer = new Buffer.from(base64Image, "base64");
    fs.writeFileSync(
        `./userCertificates/qrCodes/${genId}.png`,
         writeBuffer
    );
    console.log("this line 2");
})
console.log("this line 3");

In my case I am getting output like this:

this line 1
this line 3
this line 2

but I want it to be

this line 1
this line 2
this line 3


问:
any way to add custom formula in MAP in kibana dashboard
I want to add a custom formula in MAP of kibana dashboard.

As we can add a formula in kibana lenses, is there any way to add the same formula in MAP of kibana dashboard?


问:
Backedn Mapped to error page instead of expected URL
I am trying to send two FormData to spring boot backend, one include files and one include strings. And I use two ajax call to post the data to backend but the ajax post for string data is failed to pass to backend. I looked at the log but I can't get any useful information.

log

```<code>2022-12-22 14:59:26,467 NCOESP [http-nio-8080-exec-1] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:26,522 NCOESP [http-nio-8080-exec-2] DEBUG o.s.c.l.LogFormatUtils:119 - GET "/nco/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js.map", parameters={}
2022-12-22 14:59:26,523 NCOESP [http-nio-8080-exec-2] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to ResourceHttpRequestHandler [ServletContext [/webjars/]]
2022-12-22 14:59:26,526 NCOESP [http-nio-8080-exec-2] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:26,557 NCOESP [http-nio-8080-exec-3] DEBUG o.s.c.l.LogFormatUtils:119 - GET "/nco/webjars/bootstrap/5.1.3/css/bootstrap.min.css.map", parameters={}
2022-12-22 14:59:26,558 NCOESP [http-nio-8080-exec-3] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to ResourceHttpRequestHandler [ServletContext [/webjars/]]
2022-12-22 14:59:26,563 NCOESP [http-nio-8080-exec-3] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:35,054 NCOESP [http-nio-8080-exec-4] DEBUG o.s.c.l.LogFormatUtils:119 - "ERROR" dispatch for POST "/nco/error", parameters={masked}
2022-12-22 14:59:35,055 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-12-22 14:59:35,056 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.m.m.a.AbstractMessageConverterMethodProcessor:268 - Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2022-12-22 14:59:35,057 NCOESP [http-nio-8080-exec-4] DEBUG o.s.c.l.LogFormatUtils:119 - Writing [{timestamp=Thu Dec 22 14:59:35 CST 2022, status=403, error=Forbidden, message=Forbidden, path=/nco/r (truncated)...]
2022-12-22 14:59:35,059 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.FrameworkServlet:1127 - Exiting from "ERROR" dispatch, status 403
2022-12-22 14:59:35,128 NCOESP [http-nio-8080-exec-5] DEBUG o.s.c.l.LogFormatUtils:119 - POST "/nco/reg/upload", parameters={multipart}
2022-12-22 14:59:35,130 NCOESP [http-nio-8080-exec-5] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to nco.user.controller.RegistrationController#upload(MultipartFile[], String[])
2022-12-22 14:59:35,132 NCOESP [http-nio-8080-exec-5] INFO  h.g.h.n.u.c.RegistrationController:28 - *** Reg - upload ****
2022-12-22 14:59:35,218 NCOESP [http-nio-8080-exec-5] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
</code>```

My submit handling

```<code>$('form').submit(function(e) {
      let regGen = JSON.parse(sessionStorage.getItem('reg-general'));
      let paramsString = new URLSearchParams(location.search);
      const searchParams = new URLSearchParams(paramsString);
      const applForm = new FormData();
      const listType = [];
      searchParams.forEach((value, key) => {
        if (key != 'btnNext') {
          if (key==='listTypeApplied')
            listType.push(value);
          else
            applForm.append(key, value)
        }
      });
      applForm.append('listTypeApplied', listType.toString())
      for (const key in regGen) {
        applForm.append(key, regGen[key])
      }

      if ($('form')[0].checkValidity()) {
        $.ajax( {
          url: '/nco/reg/upload',
          type: 'POST',
          data: new FormData(this),
          processData: false,
          contentType: false
        }),
        $.ajax( {
          url: '/nco/reg/submitForm',
          type: 'POST',
          data: applForm,
          processData: false,
        })
      }
      e.preventDefault();
    });
</code>```

Controller

```<code>@Slf4j
@Controller
@RequestMapping("/reg")
public class RegistrationController {

    @Autowired
    protected StorageService storageService;

    @PostMapping({"/upload"})
    public String upload(@RequestParam("file") MultipartFile[] files,  @RequestParam("certFileName") String[] certFileName) {
        log.info("*** Reg - upload ****");
        storageService.store(files[0]);

        return "test/fileUpload";
    }

    @PostMapping({"/submitForm"})
    public String submitForm(@RequestBody RegApplForm form) {
        log.info("*** Reg - submit form ****");
        return "test/submitForm";
    }
}
</code>```

What would be the possible reason causing this bug?

Body:
I am trying to send two FormData to spring boot backend, one include files and one include strings. And I use two ajax call to post the data to backend but the ajax post for string data is failed to pass to backend. I looked at the log but I can't get any useful information.

log

2022-12-22 14:59:26,467 NCOESP [http-nio-8080-exec-1] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:26,522 NCOESP [http-nio-8080-exec-2] DEBUG o.s.c.l.LogFormatUtils:119 - GET "/nco/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js.map", parameters={}
2022-12-22 14:59:26,523 NCOESP [http-nio-8080-exec-2] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to ResourceHttpRequestHandler [ServletContext [/webjars/]]
2022-12-22 14:59:26,526 NCOESP [http-nio-8080-exec-2] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:26,557 NCOESP [http-nio-8080-exec-3] DEBUG o.s.c.l.LogFormatUtils:119 - GET "/nco/webjars/bootstrap/5.1.3/css/bootstrap.min.css.map", parameters={}
2022-12-22 14:59:26,558 NCOESP [http-nio-8080-exec-3] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to ResourceHttpRequestHandler [ServletContext [/webjars/]]
2022-12-22 14:59:26,563 NCOESP [http-nio-8080-exec-3] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK
2022-12-22 14:59:35,054 NCOESP [http-nio-8080-exec-4] DEBUG o.s.c.l.LogFormatUtils:119 - "ERROR" dispatch for POST "/nco/error", parameters={masked}
2022-12-22 14:59:35,055 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-12-22 14:59:35,056 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.m.m.a.AbstractMessageConverterMethodProcessor:268 - Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2022-12-22 14:59:35,057 NCOESP [http-nio-8080-exec-4] DEBUG o.s.c.l.LogFormatUtils:119 - Writing [{timestamp=Thu Dec 22 14:59:35 CST 2022, status=403, error=Forbidden, message=Forbidden, path=/nco/r (truncated)...]
2022-12-22 14:59:35,059 NCOESP [http-nio-8080-exec-4] DEBUG o.s.w.s.FrameworkServlet:1127 - Exiting from "ERROR" dispatch, status 403
2022-12-22 14:59:35,128 NCOESP [http-nio-8080-exec-5] DEBUG o.s.c.l.LogFormatUtils:119 - POST "/nco/reg/upload", parameters={multipart}
2022-12-22 14:59:35,130 NCOESP [http-nio-8080-exec-5] DEBUG o.s.w.s.h.AbstractHandlerMapping:522 - Mapped to nco.user.controller.RegistrationController#upload(MultipartFile[], String[])
2022-12-22 14:59:35,132 NCOESP [http-nio-8080-exec-5] INFO  h.g.h.n.u.c.RegistrationController:28 - *** Reg - upload ****
2022-12-22 14:59:35,218 NCOESP [http-nio-8080-exec-5] DEBUG o.s.w.s.FrameworkServlet:1131 - Completed 200 OK

My submit handling

$('form').submit(function(e) {
      let regGen = JSON.parse(sessionStorage.getItem('reg-general'));
      let paramsString = new URLSearchParams(location.search);
      const searchParams = new URLSearchParams(paramsString);
      const applForm = new FormData();
      const listType = [];
      searchParams.forEach((value, key) => {
        if (key != 'btnNext') {
          if (key==='listTypeApplied')
            listType.push(value);
          else
            applForm.append(key, value)
        }
      });
      applForm.append('listTypeApplied', listType.toString())
      for (const key in regGen) {
        applForm.append(key, regGen[key])
      }

      if ($('form')[0].checkValidity()) {
        $.ajax( {
          url: '/nco/reg/upload',
          type: 'POST',
          data: new FormData(this),
          processData: false,
          contentType: false
        }),
        $.ajax( {
          url: '/nco/reg/submitForm',
          type: 'POST',
          data: applForm,
          processData: false,
        })
      }
      e.preventDefault();
    });

Controller

@Slf4j
@Controller
@RequestMapping("/reg")
public class RegistrationController {

    @Autowired
    protected StorageService storageService;

    @PostMapping({"/upload"})
    public String upload(@RequestParam("file") MultipartFile[] files,  @RequestParam("certFileName") String[] certFileName) {
        log.info("*** Reg - upload ****");
        storageService.store(files[0]);

        return "test/fileUpload";
    }

    @PostMapping({"/submitForm"})
    public String submitForm(@RequestBody RegApplForm form) {
        log.info("*** Reg - submit form ****");
        return "test/submitForm";
    }
}

What would be the possible reason causing this bug?


问:
How to use Iana Cipher name to create Java Cipher Instance
I am working on updating the Cipher suite at my product and all I'm given is the Iana Cipher name - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256.

Java Cipher instance is created by :

```<code>Cipher cipher = Cipher.getInstance(<transformation string>);
</code>```

where the transformation string is in the form - key/mode/padding.

How do I convert the Iana cipher name to the transformation string?

Body:
I am working on updating the Cipher suite at my product and all I'm given is the Iana Cipher name - TLS_DHE_RSA_WITH_AES_128_GCM_SHA256.

Java Cipher instance is created by :

Cipher cipher = Cipher.getInstance(<transformation string>);

where the transformation string is in the form - key/mode/padding.

How do I convert the Iana cipher name to the transformation string?


问:
How does one add <graphics.h> into GCC on a Windows computer for C?
So, I want to add graphics in a program, but <graphics.h> doesn't seem to be supported on the GCC compiler.
I don't have a Linux, so please include Windows Powershell solutions if using command lines for the solution.
I am using the C programming language.
Since I can't find a good solution online by searching for it on Google, GeeksForGeeks, or stackoverflow, I am looking for it by asking this question.

I am not asking how to do in C++, in C!

I was expecting to have no issues, but the GCC compiler couldn't find <graphics.h>.

I hope someone can find a solution!


问:
How to add a new organization in Hyperledger Fabric?
In official documentation of Hyperledger Fabric, if we want to add a new Organization to the network we only have folder named addOrg3 inside the examples (please see the attached screenshot.

If I want to add a 4th Organization. What is the process?

I tried to search on how to add the 4th organization but couldn't find.


问:
How to filter Endpoint with have no agent cortex xdr with python
I want to get endpoint with have no agent but I have no idea about to filter or get output it

this code below to output get all endpoints and out as IP-Address how to filter json about get endpoint have no agent

from code I can get all endpoints but want to get just endpoint with have no agent

import requests

# Please change to your tenants API Key and ID#
api_id = 'x'
api_key = 'x'

headers = {
    "x-xdr-auth-id": str(api_id),
    "Authorization": api_key
}
parameters = {}

# Please change to match your Tenants API Url #
res = requests.post(url="https://api-subdomain.xdr.region.paloaltonetworks.com/public_api/v1/endpoints/get_endpoints/",
                    headers=headers,
                    json=parameters)

# importing the module

import re

# Regex&Filter to get only IPv4 address format
fstring = str(res.json())
fstring = fstring.replace(',', '\n')
ipString = re.findall(r'(?:\d{1,3}\.)+(?:\d{1,3})', fstring)
for i in range(len(ipString)):
    print(ipString[i])
```


问:
Trouble with android emulator (only Google Pixel)
I have a problem with turning on the mobile emulator from Google pixel. I have a total of 4 (different ones) and they all turn on fine, but the one I really need doesn't. It keeps loading that G and nothing happens. Just yesterday everything was working without a problem. It always write:

Time out after 300 seconds waiting for emulator to come online.