问:
Node Knexjs Model Without a Callback
Ok, there's a bunch of stuff here... But basically, I'm trying to make a MVC type API in Node with Knexjs querying my database.

My goal was to have my requests enter my router, then pass to a controller, and then finally the controller calls the model methods.

The big problem I'm having is getting my data out of the model WITHOUT using a callback. I'm hoping to avoid callbacks nested in callbacks etc. My hope is that the model just fetches data using Knexjs and returns it.

Ok, so the code.

First: my routes/index.js

```<code>app.use('/users', users);
</code>```

Easy enough, it loads the users sub route and inside routes/users/index.js I handle the various REST requests... in the code below getUsers is a method, defined in my users controller.

```<code>router.get('/', getUsers);
</code>```

Controller users controllers/users.js

```<code>const Users = require('../models/users');

const getUsers = (req, res) => {
  // call the model and get the Users
  Users.getAll((response) => {
    res.status(200).json(response);
  });
};

module.exports = { getUsers };
</code>```

And the model models/users.js

```<code>const knex = require('knex')(require('../../knexfile'));

const getAll = function (callback) {
  knex('users')
    .select('id', 'email')
    .then((users) => {
      callback(users);
    })
    .catch((err) => {
      callback({
        success: false,
        message: 'An error occurred, please try again later.',
        error: err,
      });
    });
};

module.exports = { getAll };
</code>```

OK, here's the big question... How can I modify this model such that it just returns the users so that inside the controller, instead of passing a callback, I can just receive the users such as:

```<code>let users = Users.getAll();
res.status(200).json(users);
</code>```

Last note, I might be way off on my structure logic here, and I'm open to suggestions. But my goal was to have the model be useable from other controllers so that's why I'm not doing the database call directly from the controller. IE. what if another controller or route needed to fetch all users, having the model allows that code to be managed in one location.

Title: Node Knexjs Model Without a Callback

Body:
Ok, there's a bunch of stuff here... But basically, I'm trying to make a MVC type API in Node with Knexjs querying my database.

My goal was to have my requests enter my router, then pass to a controller, and then finally the controller calls the model methods.

The big problem I'm having is getting my data out of the model WITHOUT using a callback. I'm hoping to avoid callbacks nested in callbacks etc. My hope is that the model just fetches data using Knexjs and returns it.

Ok, so the code.

First: my routes/index.js

app.use('/users', users);

Easy enough, it loads the users sub route and inside routes/users/index.js I handle the various REST requests... in the code below getUsers is a method, defined in my users controller.

router.get('/', getUsers);

Controller users controllers/users.js

const Users = require('../models/users');

const getUsers = (req, res) => {
  // call the model and get the Users
  Users.getAll((response) => {
    res.status(200).json(response);
  });
};

module.exports = { getUsers };

And the model models/users.js

const knex = require('knex')(require('../../knexfile'));

const getAll = function (callback) {
  knex('users')
    .select('id', 'email')
    .then((users) => {
      callback(users);
    })
    .catch((err) => {
      callback({
        success: false,
        message: 'An error occurred, please try again later.',
        error: err,
      });
    });
};

module.exports = { getAll };

OK, here's the big question... How can I modify this model such that it just returns the users so that inside the controller, instead of passing a callback, I can just receive the users such as:

let users = Users.getAll();
res.status(200).json(users);

Last note, I might be way off on my structure logic here, and I'm open to suggestions. But my goal was to have the model be useable from other controllers so that's why I'm not doing the database call directly from the controller. IE. what if another controller or route needed to fetch all users, having the model allows that code to be managed in one location.


来源: stackexchange

问:
problem connection nodes with mysql - loading forever
I have a project which contain a simple connection with bd mysql. But I have difficult to run queries because she loading forever and get time out.

connection:

const connection = mysql.createConnection({
    host: dataSource.DB_HOST,
    user: dataSource.DB_USER,
    password: dataSource.DB_PASSWORD,
    database: dataSource.DB_DATABASE
});

function init() : boolean {
    connection.connect(err => {
        if(err) throw new Error(`Open DB: ${err}`);
    });

    return true;
}

function end(): boolean {
    connection.end(err => {
        if(err) throw new Error(`End DB: ${err}`);
    });

    return true;
}

export async function execute<T>(query: string, params: string[]) : Promise<T> {
    if(init()) {
        const queryResult =
            connection.query(query, params, (err, result) => {
                end();
                return err ? Promise.reject(err) : Promise.resolve(result);
            });

        return new Promise<T>((resolve, reject) => queryResult);
    }

    return Promise.reject('Error when connect in database');
}
```
<p>in above code, contain my class with connection db. I tested off environments variables, and she contains DB_HOST, DB_USER, DB_PASSWORD and DB_DATABASE, all corrects.</p>
<p>when I try run query, the execute function load forever and never response to caller.</p>
<p>I try input <code>console.log()</code> like this:</p>
``` export async function execute<T>(query: string, params: string[]) : Promise<T> {
    if(init()) {
        const queryResult =
            connection.query(query, params, (err, result) => {
                end();
                return err ? Promise.reject(err) : Promise.resolve(result);
            });

        console.log(queryResult);
        return new Promise<T>((resolve, reject) => queryResult);
    }

    return Promise.reject('Error when connect in database');
}
```
<p>and In above code the <code>console.log()</code> print <code>queryResult</code> normally.</p>
<p>However the <code>return new Promise<T>((resolve, reject) => queryResult);</code> never return, and all my requests get timeout.</p>
<p>this is my caller of the function <code>execute()</code>:</p>
```    async getClientById(uuid: string) : Promise<Client | null> {
        const query = `
        SELECT
            *
        FROM
            ka_clients
        WHERE
            id = ?
        `;

        const clientDTO = await execute<ClientInterfaceMySQLDTO>(query, [uuid]);
        return ClientRepositoryMySQLAdapter.execute(clientDTO);
    }
```
<p>I try <code>console.log()</code> before call of <code>execute<>()</code> and he print normally, but if I try input <code>console.log()</code> after call <code>execute<>()</code> this is don't show anything in terminal.</p>
<p>The requests never return error, only return timeout.</p>
<pre class="lang-bash prettyprint-override"><code>simoes@Macintosh ka_pay % curl -X PUT https://localhost.com:8080
curl: (28) Failed to connect to localhost.com port 8080 after 75038 ms: Operation timed out
</code>```

the link of project is:
https://github.com/GuilhermeGiacomoSimoes/ka_pay
the path cited files are: src/driversAndFrameworks/ClientRepositoryMySQL.ts and src/driversAndFrameworks/MySQLConfig.ts

ContentLicense: CC BY-SA 4.0

Body:
I have a project which contain a simple connection with bd mysql. But I have difficult to run queries because she loading forever and get time out.

connection:

const connection = mysql.createConnection({
    host: dataSource.DB_HOST,
    user: dataSource.DB_USER,
    password: dataSource.DB_PASSWORD,
    database: dataSource.DB_DATABASE
});

function init() : boolean {
    connection.connect(err => {
        if(err) throw new Error(`Open DB: ${err}`);
    });

    return true;
}

function end(): boolean {
    connection.end(err => {
        if(err) throw new Error(`End DB: ${err}`);
    });

    return true;
}

export async function execute<T>(query: string, params: string[]) : Promise<T> {
    if(init()) {
        const queryResult =
            connection.query(query, params, (err, result) => {
                end();
                return err ? Promise.reject(err) : Promise.resolve(result);
            });

        return new Promise<T>((resolve, reject) => queryResult);
    }

    return Promise.reject('Error when connect in database');
}

in above code, contain my class with connection db. I tested off environments variables, and she contains DB_HOST, DB_USER, DB_PASSWORD and DB_DATABASE, all corrects.

when I try run query, the execute function load forever and never response to caller.

I try input console.log() like this:

 export async function execute<T>(query: string, params: string[]) : Promise<T> {
    if(init()) {
        const queryResult =
            connection.query(query, params, (err, result) => {
                end();
                return err ? Promise.reject(err) : Promise.resolve(result);
            });

        console.log(queryResult);
        return new Promise<T>((resolve, reject) => queryResult);
    }

    return Promise.reject('Error when connect in database');
}

and In above code the console.log() print queryResult normally.

However the return new Promise<T>((resolve, reject) => queryResult); never return, and all my requests get timeout.

this is my caller of the function execute():

    async getClientById(uuid: string) : Promise<Client | null> {
        const query = `
        SELECT
            *
        FROM
            ka_clients
        WHERE
            id = ?
        `;

        const clientDTO = await execute<ClientInterfaceMySQLDTO>(query, [uuid]);
        return ClientRepositoryMySQLAdapter.execute(clientDTO);
    }

I try console.log() before call of execute<>() and he print normally, but if I try input console.log() after call execute<>() this is don't show anything in terminal.

The requests never return error, only return timeout.

simoes@Macintosh ka_pay % curl -X PUT https://localhost.com:8080
curl: (28) Failed to connect to localhost.com port 8080 after 75038 ms: Operation timed out

the link of project is:
https://github.com/GuilhermeGiacomoSimoes/ka_pay
the path cited files are: src/driversAndFrameworks/ClientRepositoryMySQL.ts and src/driversAndFrameworks/MySQLConfig.ts


问:
How to Revalidate when data in fetcher is change using swr
I want to revalidate the date when on change. This is what I tried:

```<code>const fetchData = async() => {
  const {
    data
  } = await axios.get(`/api/admin/orders${criteria}`, {
    params: {
      name: debouncedValue,
    },
  });
  return data;
};
const {
  data,
  error: err,
  mutate,
} = useSWR(`/api/admin/orders${criteria}/${nameSearch}`, fetchData);
const handleChange = (e: React.ChangeEvent < HTMLInputElement > ) => {
  mutate();
  setNameSearch(e.target.value);
};
</code>```

But the data is no revalidate, I have to use the onTabFocus revalidation.

Body:
I want to revalidate the date when on change. This is what I tried:

const fetchData = async() => {
  const {
    data
  } = await axios.get(`/api/admin/orders${criteria}`, {
    params: {
      name: debouncedValue,
    },
  });
  return data;
};
const {
  data,
  error: err,
  mutate,
} = useSWR(`/api/admin/orders${criteria}/${nameSearch}`, fetchData);
const handleChange = (e: React.ChangeEvent < HTMLInputElement > ) => {
  mutate();
  setNameSearch(e.target.value);
};

But the data is no revalidate, I have to use the onTabFocus revalidation.


问:
Control PostProcessing via unity c# script
I tried to control Unity post-processing in the script, but it didn't work.
I tried to apply the blurred vision effect when my game character's HP was low.
It can't be solved by the way I saw it on YouTube or other sites.

```<code>using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
public class HPBar : MonoBehaviour
{
    private PostProcessVolume volume;
    private Vignette vignette;

    void Start()
    {
        volume = GetComponent<PostProcessVolume>();
        volume.profile.TryGetSettings(out vignette);
        vignette = GetComponent<Vignette>();
    }

    void isLowHP()
    {
        vignette.active = true;
    }
}
</code>```

I want to know how to use post-processing in a script.

Body:
I tried to control Unity post-processing in the script, but it didn't work.
I tried to apply the blurred vision effect when my game character's HP was low.
It can't be solved by the way I saw it on YouTube or other sites.

using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
public class HPBar : MonoBehaviour
{
    private PostProcessVolume volume;
    private Vignette vignette;

    void Start()
    {
        volume = GetComponent<PostProcessVolume>();
        volume.profile.TryGetSettings(out vignette);
        vignette = GetComponent<Vignette>();
    }

    void isLowHP()
    {
        vignette.active = true;
    }
}

I want to know how to use post-processing in a script.


问:
How can i fix MYSQL error in php consumer?
i have this dockerfile for php-consumer:
`

```<code>FROM node:latest as node
FROM php:8.0-fpm

COPY --from=mlocati/php-extension-installer:1.2 /usr/bin/install-php-extensions /usr/local/bin/

COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
COPY --from=node /usr/local/bin/node /usr/local/bin/node
RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm

RUN apt-get update && apt-get install -y \
    libpq-dev \
    wget \
    zlib1g-dev \
    libmcrypt-dev \
    libzip-dev \
    git \
    php7.*-xml \
    pkg-config \
    libcurl4-openssl-dev \
    librabbitmq-dev \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev

RUN apt-get update && apt-get install -y zlib1g-dev libicu-dev g++
RUN docker-php-ext-configure intl
RUN docker-php-ext-install intl

ENV CFLAGS="$CFLAGS -D_GNU_SOURCE"
RUN docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ && \
    docker-php-ext-install mysqli pdo pdo_mysql zip curl sockets pcntl

RUN install-php-extensions \
    decimal \
    pdo_mysql \
    intl \
    amqp \
    bcmath \
    pcntl \
    sockets \
    xsl

RUN pecl install -o -f redis \
    &&  rm -rf /tmp/pear \
    &&  docker-php-ext-enable redis

RUN apt-get update && apt-get install libxslt1-dev -y && docker-php-ext-install xsl

RUN curl -S https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY consume.sh /consumer/consume.sh

WORKDIR /workdir

ENTRYPOINT ["bash", "/consumer/consume.sh"]

</code>```

`

This consume.sh:
`

```<code>#!/bin/bash

sleep 10;
/workdir/bin/console messenger:consume >&1;
</code>```

`

This messenger.yaml:
`

```<code>framework:
  messenger:
    transports:
      movies:
        dsn: "%env(MESSENGER_TRANSPORT_DSN)%"
        options:
          vhost: "/"

    routing:
      App\Message\Tmdb\MovieRequestedMessage: movies

</code>```

`

`

```<code>DATABASE_URL="mysql://user_name:password@mysql/database_name?serverVersion=5.7"
</code>```

`

And when i dispatch the message, i got this error in php_consumer:
`02:46:24 WARNING   [messenger] Error thrown while handling message App\Message\Tmdb\MovieRequestedMessage. Sending for retry #1 using 1000 ms delay. Error: "Handling "App\Message\Tmdb\MovieRequestedMessage" failed: An exception occurred in the driver: SQLSTATE[HY000] [2002] No such file or directory" ["class" => "App\Message\Tmdb\MovieRequestedMessage","retryCount" => 1,"delay" => 1000,"error" => "Handling "App\Message\Tmdb\MovieRequestedMessage" failed: An exception occurred in the driver: SQLSTATE[HY000] [2002] No such file or directory","exception" => Symfony\Component\Messenger\Exception\HandlerFailedException { …}]

docker-compose.yml:

```<code>  php-consumer:
container_name: php_consumer
build:
  context: docker/php-consumer
env_file:
  - .env
volumes:
  - .:/project
depends_on:
  - mysql
  - rabbitmq
  - php-cli
  - php-fpm
environment:
  - "MESSENGER_TRANSPORT_DSN=${MESSENGER_TRANSPORT_DSN}"
  - "DATABASE_URL=${DATABASE_URL}"
networks:
  - network
</code>```

I tried to change mysql to mysql container ip, but it doesn't work.

I would be very grateful for any clarification, and for any help. Thank you so much!

Body:
i have this dockerfile for php-consumer:
`

FROM node:latest as node
FROM php:8.0-fpm

COPY --from=mlocati/php-extension-installer:1.2 /usr/bin/install-php-extensions /usr/local/bin/

COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
COPY --from=node /usr/local/bin/node /usr/local/bin/node
RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm

RUN apt-get update && apt-get install -y \
    libpq-dev \
    wget \
    zlib1g-dev \
    libmcrypt-dev \
    libzip-dev \
    git \
    php7.*-xml \
    pkg-config \
    libcurl4-openssl-dev \
    librabbitmq-dev \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev

RUN apt-get update && apt-get install -y zlib1g-dev libicu-dev g++
RUN docker-php-ext-configure intl
RUN docker-php-ext-install intl

ENV CFLAGS="$CFLAGS -D_GNU_SOURCE"
RUN docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ && \
    docker-php-ext-install mysqli pdo pdo_mysql zip curl sockets pcntl

RUN install-php-extensions \
    decimal \
    pdo_mysql \
    intl \
    amqp \
    bcmath \
    pcntl \
    sockets \
    xsl

RUN pecl install -o -f redis \
    &&  rm -rf /tmp/pear \
    &&  docker-php-ext-enable redis

RUN apt-get update && apt-get install libxslt1-dev -y && docker-php-ext-install xsl

RUN curl -S https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY consume.sh /consumer/consume.sh

WORKDIR /workdir

ENTRYPOINT ["bash", "/consumer/consume.sh"]

`

This consume.sh:
`

#!/bin/bash

sleep 10;
/workdir/bin/console messenger:consume >&1;

`

This messenger.yaml:
`

framework:
  messenger:
    transports:
      movies:
        dsn: "%env(MESSENGER_TRANSPORT_DSN)%"
        options:
          vhost: "/"

    routing:
      App\Message\Tmdb\MovieRequestedMessage: movies

`

`

DATABASE_URL="mysql://user_name:password@mysql/database_name?serverVersion=5.7"

`

And when i dispatch the message, i got this error in php_consumer:
`02:46:24 WARNING   [messenger] Error thrown while handling message App\Message\Tmdb\MovieRequestedMessage. Sending for retry #1 using 1000 ms delay. Error: "Handling "App\Message\Tmdb\MovieRequestedMessage" failed: An exception occurred in the driver: SQLSTATE[HY000] [2002] No such file or directory" ["class" => "App\Message\Tmdb\MovieRequestedMessage","retryCount" => 1,"delay" => 1000,"error" => "Handling "App\Message\Tmdb\MovieRequestedMessage" failed: An exception occurred in the driver: SQLSTATE[HY000] [2002] No such file or directory","exception" => Symfony\Component\Messenger\Exception\HandlerFailedException { …}]

docker-compose.yml:

  php-consumer:
container_name: php_consumer
build:
  context: docker/php-consumer
env_file:
  - .env
volumes:
  - .:/project
depends_on:
  - mysql
  - rabbitmq
  - php-cli
  - php-fpm
environment:
  - "MESSENGER_TRANSPORT_DSN=${MESSENGER_TRANSPORT_DSN}"
  - "DATABASE_URL=${DATABASE_URL}"
networks:
  - network

I tried to change mysql to mysql container ip, but it doesn't work.

I would be very grateful for any clarification, and for any help. Thank you so much!


问:
FXC and DXC Shader Compiler Macro Expansion differences
Using the FXC Shader compiler a macro could be defined like this:

```<code>#define OUT_MACRO(index) SV_Target##index

float4 PSMain(VSOutput In) : OUT_MACRO(0)
{...}
</code>```

This fails using the DXC compiler though with various errors messages which basically are always a result of it just straight up ignoring the macro.

Giving DXC the "-flegacy-macro-expansion" flag did not seem to resolve the issue either. I am unsure how I can make the above macro work using DXC for Shader Model 6 and above.

Body:
Using the FXC Shader compiler a macro could be defined like this:

#define OUT_MACRO(index) SV_Target##index

float4 PSMain(VSOutput In) : OUT_MACRO(0)
{...}

This fails using the DXC compiler though with various errors messages which basically are always a result of it just straight up ignoring the macro.

Giving DXC the "-flegacy-macro-expansion" flag did not seem to resolve the issue either. I am unsure how I can make the above macro work using DXC for Shader Model 6 and above.


问:
AttributeError: module 'cv2' has no attribute 'mcc'
```<code>detector = cv2.mcc.CCheckerDetector_create()
</code>```

This is line returns the error.
I have already installed opencv-contrib, why does it still give the error?

```<code>opencv-contrib-python==4.6.0.66
opencv-python==4.6.0.66
</code>```

Body:
detector = cv2.mcc.CCheckerDetector_create()

This is line returns the error.
I have already installed opencv-contrib, why does it still give the error?

opencv-contrib-python==4.6.0.66
opencv-python==4.6.0.66


问:
How to show context menu at desired position in pyqt5?
My aim is to display context menu at desired position, base on mainwindow.  Based on user mood, Mainwindow may be dragged from one position to another  or shrink or grow. At this situation, context menu display position will change.  If Mainwindow dragged to right most of screen, then the context menu will display left to qcombo box. if Mainwindow dragged to left most of the screen, then the context menu will display right to Qcombox position. If mainwindow is centre, then context menu will apper on right to qcombobox. simply context menu to display in available screen. (Not under the cursor or at a fixed postition)

```<code>
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QPushButton, QVBoxLayout,QMenu
from PyQt5.QtCore import Qt,QPoint

class CheckableComboBox(QComboBox):
    def __init__(self, xposi,yposi):
        super().__init__()
        self.xpo = xposi
        self.ypo = yposi

        self.setEditable(True)
        self.lineEdit().setReadOnly(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)

        self.setStyleSheet("QComboBox QAbstractItemView::item {border: none;padding-left: 5px;}")
        self.lineEdit().installEventFilter(self)
        self.closeOnLineEditClick = True
        self.double_click = None

    def showMenu(self,pos):
        menu = QMenu()
        clear_action = menu.addAction("Clear Selection")
        copy_action = menu.addAction(("Copy"))
        action = menu.exec_(self.mapToGlobal(QPoint(self.xpo,self.ypo)))

        if action == clear_action:
            self.combo.setCurrentIndex(1)

class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        mainLayout = QVBoxLayout()
        self.setLayout(mainLayout)

        self.data = ['America', 'Russia', 'China', 'Germany', 'France', 'India']

        self.combo = CheckableComboBox(100,100) #self.pos_x,self.pos_y)
        self.combo.setFixedSize(600,60)

        btn = QPushButton('Print Values')
        btn.clicked.connect(self.getValue)

        mainLayout.addWidget(self.combo)
        mainLayout.addWidget(btn)

        self.combo.addItems(self.data)
        self.siz = None

    def moveEvent(self,e):
        self.siz = self.pos()
        self.pos_x = self.siz.x()
        self.pos_y = self.siz_y()
        # super().moveEvent(e)

    def getValue(self):
        print(self.combo.currentData())

if __name__ == '__main__':
    app = QApplication(sys.argv)

    app.setStyleSheet('''QWidget {font-size: 20px;}''')

    myApp = MyApp()
    myApp.show()
    app.exit(app.exec_())
</code>```

.

Body:
My aim is to display context menu at desired position, base on mainwindow.  Based on user mood, Mainwindow may be dragged from one position to another  or shrink or grow. At this situation, context menu display position will change.  If Mainwindow dragged to right most of screen, then the context menu will display left to qcombo box. if Mainwindow dragged to left most of the screen, then the context menu will display right to Qcombox position. If mainwindow is centre, then context menu will apper on right to qcombobox. simply context menu to display in available screen. (Not under the cursor or at a fixed postition)

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QPushButton, QVBoxLayout,QMenu
from PyQt5.QtCore import Qt,QPoint

class CheckableComboBox(QComboBox):
    def __init__(self, xposi,yposi):
        super().__init__()
        self.xpo = xposi
        self.ypo = yposi

        self.setEditable(True)
        self.lineEdit().setReadOnly(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)

        self.setStyleSheet("QComboBox QAbstractItemView::item {border: none;padding-left: 5px;}")
        self.lineEdit().installEventFilter(self)
        self.closeOnLineEditClick = True
        self.double_click = None

    def showMenu(self,pos):
        menu = QMenu()
        clear_action = menu.addAction("Clear Selection")
        copy_action = menu.addAction(("Copy"))
        action = menu.exec_(self.mapToGlobal(QPoint(self.xpo,self.ypo)))

        if action == clear_action:
            self.combo.setCurrentIndex(1)

class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        mainLayout = QVBoxLayout()
        self.setLayout(mainLayout)

        self.data = ['America', 'Russia', 'China', 'Germany', 'France', 'India']

        self.combo = CheckableComboBox(100,100) #self.pos_x,self.pos_y)
        self.combo.setFixedSize(600,60)

        btn = QPushButton('Print Values')
        btn.clicked.connect(self.getValue)

        mainLayout.addWidget(self.combo)
        mainLayout.addWidget(btn)

        self.combo.addItems(self.data)
        self.siz = None

    def moveEvent(self,e):
        self.siz = self.pos()
        self.pos_x = self.siz.x()
        self.pos_y = self.siz_y()
        # super().moveEvent(e)

    def getValue(self):
        print(self.combo.currentData())

if __name__ == '__main__':
    app = QApplication(sys.argv)

    app.setStyleSheet('''QWidget {font-size: 20px;}''')

    myApp = MyApp()
    myApp.show()
    app.exit(app.exec_())

.


问:
This app could not be installed at this time Apple Watch
I have just develop an apple watch with companion mode.
When I try to distribute this app for testers using app distribution and getting error like this:

Anyone know how to solve this problem?

Expected: Watch App can be installed


问:
SQLITE3 on STM32 FreeRTOS and FATFS
I am trying to port SQLITE3 on top of FatFs supported by the STM32Cube using the FreeRTOS and MicroSD Card on STM32F429-EVAL1 board.
Could you please share the source if anyone is successful with this implementation?

I see that I can use test_demovfs.c file from sqlite3, but need to figure out how to integrate it with the FatFs-based project. Any support in this regard is highly appreciable.

Title: SQLITE3 on STM32 FreeRTOS and FATFS


问:
RuntimeError: Sizes of tensors must match except in dimension 2. Expected size 421 but got size 71 for tensor number 1 in the list
I am trying to follow this tutorial

when I try to predict I get the runtime error on the below line

```<code># compute N predictions
pred = model_RNN.predict(n=FC_N, future_covariates=covariates)
</code>```

RuntimeError: Sizes of tensors must match except in dimension 2. Expected size 421 but got size 71 for tensor number 1 in the list.

which list it is referring to?

My train data size is 421 and valdiation is 105
not sure what 71 it is referring to.

Below is the full code

```<code>## load data
from darts import TimeSeries
df = df[['close']]
ts = TimeSeries.from_dataframe(df, freq='b')
#ts = pd.Series(df['close'], index=df.index)

series = df

plt.figure(100, figsize=(12,5))
series.plot()

# analyze its seasonality

is_seasonal, periodicity = check_seasonality(ts, max_lag=240)
dict_seas ={
    "is seasonal?":is_seasonal,
    "periodicity (months)":f'{periodicity:.1f}',
    "periodicity (~years)": f'{periodicity/12:.1f}'}
_ = [print(k,":",v) for k,v in dict_seas.items()]

# split training vs test dataset
train, val = ts.split_after(0.8)

# normalize the time series

trf = Scaler()
# fit the transformer to the training dataset
train_trf = trf.fit_transform(train)
# apply the transformer to the validation set and the complete series
val_trf = trf.transform(val)
ts_trf = trf.transform(ts)

# create month and year covariate series

year_series = datetime_attribute_timeseries(
    pd.date_range(start=ts.start_time(),
        freq=ts.freq_str,
        periods=len(ts)),
    attribute='year',
    one_hot=False)
year_series = Scaler().fit_transform(year_series)

month_series = datetime_attribute_timeseries(
    year_series,
    attribute='month',
    one_hot=True)

covariates = year_series.stack(month_series)
cov_train, cov_val = covariates.split_after(0.8)

# helper function: fit the RNN model

def fit_it(model, train, val, flavor):
    t_start =  time.perf_counter()
    print("\nbeginning the training of the {0} RNN:".format(flavor))

    res = model.fit(train,
             future_covariates=covariates,
             val_series=val,
             val_future_covariates=covariates,
             verbose=True)

    res_time = time.perf_counter() - t_start
    print("training of the {0} RNN has completed:".format(flavor), f'{res_time:.2f} sec')

    return res

# set up, fit, run, plot, and evaluate the RNN model

def run_RNN(flavor, ts, train, val):

    # set the model up
    model_RNN = RNNModel(
        model=flavor,
        model_name=flavor + str(" RNN"),
        input_chunk_length=periodicity,
        training_length=20,
        hidden_dim=20,
        batch_size=16,
        n_epochs=EPOCH,
        dropout=0,
        optimizer_kwargs={'lr': 1e-3},
        log_tensorboard=True,
        random_state=42,
        force_reset=True)

    if flavor == "RNN": flavor = "Vanilla"

    # fit the model
    fit_it(model_RNN, train, val, flavor)

    # compute N predictions
    pred = model_RNN.predict(n=FC_N, future_covariates=covariates)

    # plot predictions vs actual
    plot_fitted(pred, ts, flavor)

    # print accuracy metrics
    res_acc = accuracy_metrics(pred, ts)
    print(flavor + " : ")
    _ = [print(k,":",f'{v:.4f}') for k,v in res_acc.items()]

    return [pred, res_acc]

# run 3 different flavors of RNN on the time series:
flavors = ["LSTM", "GRU", "RNN"]

# call the RNN model setup for each of the 3 RNN flavors
res_flavors = [run_RNN(flv, ts_trf, train_trf, val_trf) for flv in flavors]
</code>```

Body:
I am trying to follow this tutorial

when I try to predict I get the runtime error on the below line

# compute N predictions
pred = model_RNN.predict(n=FC_N, future_covariates=covariates)

RuntimeError: Sizes of tensors must match except in dimension 2. Expected size 421 but got size 71 for tensor number 1 in the list.

which list it is referring to?

My train data size is 421 and valdiation is 105
not sure what 71 it is referring to.

Below is the full code

## load data
from darts import TimeSeries
df = df[['close']]
ts = TimeSeries.from_dataframe(df, freq='b')
#ts = pd.Series(df['close'], index=df.index)

series = df

plt.figure(100, figsize=(12,5))
series.plot()

# analyze its seasonality

is_seasonal, periodicity = check_seasonality(ts, max_lag=240)
dict_seas ={
    "is seasonal?":is_seasonal,
    "periodicity (months)":f'{periodicity:.1f}',
    "periodicity (~years)": f'{periodicity/12:.1f}'}
_ = [print(k,":",v) for k,v in dict_seas.items()]

# split training vs test dataset
train, val = ts.split_after(0.8)

# normalize the time series

trf = Scaler()
# fit the transformer to the training dataset
train_trf = trf.fit_transform(train)
# apply the transformer to the validation set and the complete series
val_trf = trf.transform(val)
ts_trf = trf.transform(ts)

# create month and year covariate series

year_series = datetime_attribute_timeseries(
    pd.date_range(start=ts.start_time(),
        freq=ts.freq_str,
        periods=len(ts)),
    attribute='year',
    one_hot=False)
year_series = Scaler().fit_transform(year_series)

month_series = datetime_attribute_timeseries(
    year_series,
    attribute='month',
    one_hot=True)

covariates = year_series.stack(month_series)
cov_train, cov_val = covariates.split_after(0.8)

# helper function: fit the RNN model

def fit_it(model, train, val, flavor):
    t_start =  time.perf_counter()
    print("\nbeginning the training of the {0} RNN:".format(flavor))

    res = model.fit(train,
             future_covariates=covariates,
             val_series=val,
             val_future_covariates=covariates,
             verbose=True)

    res_time = time.perf_counter() - t_start
    print("training of the {0} RNN has completed:".format(flavor), f'{res_time:.2f} sec')

    return res

# set up, fit, run, plot, and evaluate the RNN model

def run_RNN(flavor, ts, train, val):

    # set the model up
    model_RNN = RNNModel(
        model=flavor,
        model_name=flavor + str(" RNN"),
        input_chunk_length=periodicity,
        training_length=20,
        hidden_dim=20,
        batch_size=16,
        n_epochs=EPOCH,
        dropout=0,
        optimizer_kwargs={'lr': 1e-3},
        log_tensorboard=True,
        random_state=42,
        force_reset=True)

    if flavor == "RNN": flavor = "Vanilla"

    # fit the model
    fit_it(model_RNN, train, val, flavor)

    # compute N predictions
    pred = model_RNN.predict(n=FC_N, future_covariates=covariates)

    # plot predictions vs actual
    plot_fitted(pred, ts, flavor)

    # print accuracy metrics
    res_acc = accuracy_metrics(pred, ts)
    print(flavor + " : ")
    _ = [print(k,":",f'{v:.4f}') for k,v in res_acc.items()]

    return [pred, res_acc]

# run 3 different flavors of RNN on the time series:
flavors = ["LSTM", "GRU", "RNN"]

# call the RNN model setup for each of the 3 RNN flavors
res_flavors = [run_RNN(flv, ts_trf, train_trf, val_trf) for flv in flavors]


问:
Webpack encore compatibility with MAMP?
Please, can I use Webpack encore with MAMP for build my assets in apps? Because it's activate in my IDE but nothing is display in my site...

I configured webpack encore, it launches correctly without errors in my terminal.
My assets/Images are loading on my site but not my SCSS with "yarn encore dev --watch".
And with "yarn dev-server", my assets/Images don't loading on my site but my SCSS is OK

I don't understand, please why this difference??

webpack.config.js

```<code>const Encore = require('@symfony/webpack-encore');
require("dotenv").config();
// line to add
const BrowserSyncPlugin = require("browser-sync-webpack-plugin"); // line to add
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or subdirectory deploy
// .setManifestKeyPrefix('http://localhost:8888/portfolio/public/build/')

.copyFiles({
    from: './assets/images',

    //to: 'images/[path][name].[ext]',

// optional target path, relative to the output dir
    // if versioning is enabled, add the file hash too
    to: 'images/[path][name].[hash:8].[ext]',

// only copy files matching this pattern
    //pattern: /\.(png|jpg|jpeg)$/
})

/*
 * ENTRY CONFIG
 *
 * Each entry will result in one JavaScript file (e.g. app.js)
 * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
 */
.addEntry('app', './assets/app.js')
// .addStyleEntry('app', './assets/styles/app.css')
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')

// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()

// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()

/*
 * FEATURE CONFIG
 *
 * Enable & configure other features below. For a full
 * list of features, see:
 * https://symfony.com/doc/current/frontend.html#adding-more-features
 */
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())

// configure Babel
// .configureBabel((config) => {
//     config.plugins.push('@babel/a-babel-plugin');
// })

// enables and configure @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
    config.useBuiltIns = 'usage';
    config.corejs = '3.23';
})

// enables Sass/SCSS support
.enableSassLoader()

// uncomment if you use TypeScript
//.enableTypeScriptLoader()

// uncomment if you use React
//.enableReactPreset()

// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())

// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
// entry to add
.addPlugin(new BrowserSyncPlugin(
    {
        host: "localhost",
        port: 8888,
        proxy: process.env.PROXY,
        files: [
            {
                match: ["src/*.php"],
            },
            {
                match: ["templates/*.twig"],
            },
            {
                match: ["assets/*.js"],
            },
            {
                match: ["assets/*.css"],
            },
            {
                match: ["assets/*.jpg"],
            },
        ],
        notify: false,
    },

    {

        reload: true,
    }
))
;

// fetch the config, then modify it!
const config = Encore.getWebpackConfig();

// add an extension
config.resolve.extensions.push('json');

// export the final config
module.exports = config;
</code>```

Title: Webpack encore compatibility with MAMP?

Body:
Please, can I use Webpack encore with MAMP for build my assets in apps? Because it's activate in my IDE but nothing is display in my site...

I configured webpack encore, it launches correctly without errors in my terminal.
My assets/Images are loading on my site but not my SCSS with "yarn encore dev --watch".
And with "yarn dev-server", my assets/Images don't loading on my site but my SCSS is OK

I don't understand, please why this difference??

webpack.config.js

const Encore = require('@symfony/webpack-encore');
require("dotenv").config();
// line to add
const BrowserSyncPlugin = require("browser-sync-webpack-plugin"); // line to add
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or subdirectory deploy
// .setManifestKeyPrefix('http://localhost:8888/portfolio/public/build/')

.copyFiles({
    from: './assets/images',

    //to: 'images/[path][name].[ext]',

// optional target path, relative to the output dir
    // if versioning is enabled, add the file hash too
    to: 'images/[path][name].[hash:8].[ext]',

// only copy files matching this pattern
    //pattern: /\.(png|jpg|jpeg)$/
})

/*
 * ENTRY CONFIG
 *
 * Each entry will result in one JavaScript file (e.g. app.js)
 * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
 */
.addEntry('app', './assets/app.js')
// .addStyleEntry('app', './assets/styles/app.css')
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')

// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()

// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()

/*
 * FEATURE CONFIG
 *
 * Enable & configure other features below. For a full
 * list of features, see:
 * https://symfony.com/doc/current/frontend.html#adding-more-features
 */
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())

// configure Babel
// .configureBabel((config) => {
//     config.plugins.push('@babel/a-babel-plugin');
// })

// enables and configure @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
    config.useBuiltIns = 'usage';
    config.corejs = '3.23';
})

// enables Sass/SCSS support
.enableSassLoader()

// uncomment if you use TypeScript
//.enableTypeScriptLoader()

// uncomment if you use React
//.enableReactPreset()

// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())

// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
// entry to add
.addPlugin(new BrowserSyncPlugin(
    {
        host: "localhost",
        port: 8888,
        proxy: process.env.PROXY,
        files: [
            {
                match: ["src/*.php"],
            },
            {
                match: ["templates/*.twig"],
            },
            {
                match: ["assets/*.js"],
            },
            {
                match: ["assets/*.css"],
            },
            {
                match: ["assets/*.jpg"],
            },
        ],
        notify: false,
    },

    {

        reload: true,
    }
))
;

// fetch the config, then modify it!
const config = Encore.getWebpackConfig();

// add an extension
config.resolve.extensions.push('json');

// export the final config
module.exports = config;


问:
Python PIL - How to put text on a video
I am writing a program that puts captions on the screen and I am using PIL because it has high-quality text that is way better than the default moviepy text. I currently can put the text on a black screen, I tried using a fully transparent image as a sort of hack but that didn't work. So if anyone knows how to put PIL text on an image, or up the quality of the default moviepy text, let me know, please. Here is my basic code to put white text on a black background:

```<code>import numpy as np
from moviepy.editor import *
from PIL import Image, ImageFont, ImageDraw

SIZE = (1280, 720)
DURATION = 2
FPS = 1

TEXT = "I am having a hard time"
FONT_SIZE = 100
TEXT_COLOR_HEX = "#ffffff"
FONT = "Amiri-Bold"

def create_PIL():
    img = Image.new("RGB", size=SIZE)
    #draw = ImageDraw.Draw(img)
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(f"../Fonts/UniNeue-Trial-Bold.ttf", size=FONT_SIZE)
    draw.text((100, 100), TEXT, font=font, fill=TEXT_COLOR_HEX)
    img = np.array(img)
    return VideoClip(lambda t: img, duration=DURATION).set_fps(FPS)

final = concatenate_videoclips(
    [create_PIL()]
)

final.write_videofile('./test.mp4')
</code>```

I am trying to put this text onto a video, and I need to have custom start and duration times but all this does it put it on a black screen, which is what I expected but not what I want.

Title: Python PIL - How to put text on a video

Body:
I am writing a program that puts captions on the screen and I am using PIL because it has high-quality text that is way better than the default moviepy text. I currently can put the text on a black screen, I tried using a fully transparent image as a sort of hack but that didn't work. So if anyone knows how to put PIL text on an image, or up the quality of the default moviepy text, let me know, please. Here is my basic code to put white text on a black background:

import numpy as np
from moviepy.editor import *
from PIL import Image, ImageFont, ImageDraw

SIZE = (1280, 720)
DURATION = 2
FPS = 1

TEXT = "I am having a hard time"
FONT_SIZE = 100
TEXT_COLOR_HEX = "#ffffff"
FONT = "Amiri-Bold"

def create_PIL():
    img = Image.new("RGB", size=SIZE)
    #draw = ImageDraw.Draw(img)
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(f"../Fonts/UniNeue-Trial-Bold.ttf", size=FONT_SIZE)
    draw.text((100, 100), TEXT, font=font, fill=TEXT_COLOR_HEX)
    img = np.array(img)
    return VideoClip(lambda t: img, duration=DURATION).set_fps(FPS)

final = concatenate_videoclips(
    [create_PIL()]
)

final.write_videofile('./test.mp4')

I am trying to put this text onto a video, and I need to have custom start and duration times but all this does it put it on a black screen, which is what I expected but not what I want.


问:
Mock DBSet<T> and call AsQueryable method return an empty list
I use entity framework core 6, XUnit for testing, Moq 4.16.1

I have a List, Mock it as DBSet<T>, I call AsQueryable method on DBSet<T> then return a empty list. If i mock AsQueryable method on DBSet<T>, i will have a expected list. Can you tell me Why?

This is my code

```<code>
public static class MockDbExtensions
{
    public static Mock<DbSet<T>> MockDbSet<T>(this IQueryable<T> testData) where T : class
    {
        Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(new TestAsyncQueryProvider<T>(testData.Provider));
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(testData.Expression);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(testData.ElementType);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => testData.GetEnumerator());
        dbSetMock.As<IAsyncEnumerable<T>>().Setup(m => m.GetAsyncEnumerator(default)).Returns(() => new TestAsyncEnumerator<T>(testData.GetEnumerator()));
        return dbSetMock;
    }

    public static Mock<DbSet<T>> MockDbSet<T>(this IEnumerable<T> elements) where T : class
    {
        var testData = elements.AsQueryable();
        return testData.MockDbSet();
    }

    public static Mock<DbSet<T>> MockDbSet<T>(this T[] elements) where T : class
    {
        var testData = elements.AsQueryable();
        return testData.MockDbSet();
    }
}

internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider
{
    private readonly IQueryProvider _inner;

    internal TestAsyncQueryProvider(IQueryProvider inner)
    {
        _inner = inner;
    }

    public IQueryable CreateQuery(Expression expression)
    {
        return new TestAsyncEnumerable<TEntity>(expression);
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
    {
        return new TestAsyncEnumerable<TElement>(expression);
    }

    public object Execute(Expression expression)
    {
        return _inner.Execute(expression);
    }

    public TResult Execute<TResult>(Expression expression)
    {
        return _inner.Execute<TResult>(expression);
    }

    public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
    {
        return new TestAsyncEnumerable<TResult>(expression);
    }

    public TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = new CancellationToken())
    {
        var expectedResultType = typeof(TResult).GetGenericArguments()[0];
        var executionResult = ((IQueryProvider)this).Execute(expression);

        return (TResult)typeof(Task).GetMethod(nameof(Task.FromResult))
            .MakeGenericMethod(expectedResultType)
            .Invoke(null, new[] { executionResult });
    }
}

internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T>
{
    public TestAsyncEnumerable(IEnumerable<T> enumerable)
        : base(enumerable)
    { }

    public TestAsyncEnumerable(Expression expression)
        : base(expression)
    { }

    public IAsyncEnumerator<T> GetEnumerator()
    {
        return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
    }

    public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
    {
        return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
    }

    IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this);
}

internal class TestAsyncEnumerator<T> : IAsyncEnumerator<T>
{
    private readonly IEnumerator<T> _inner;

    public TestAsyncEnumerator(IEnumerator<T> inner)
    {
        _inner = inner;
    }

    public void Dispose()
    {
        _inner.Dispose();
    }

    public T Current => _inner.Current;

    public Task<bool> MoveNext(CancellationToken cancellationToken)
    {
        return Task.FromResult(_inner.MoveNext());
    }

    public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(_inner.MoveNext());

    public ValueTask DisposeAsync()
    {
        _inner.Dispose();
        return new ValueTask();
    }
}

public class ReportTemplateServiceTests
{

    private List<ReportTemplateType> CreateReportTemplateTypes()
    {
        return new List<ReportTemplateType>
            {
                new ReportTemplateType { Id = new Guid("144013ED-2D77-4572-8AB4-483C66E4EF1D"), Name = "Financial statements", DisplayOrder = 3, CmsId = 101475, IsActive = true },
                new ReportTemplateType { Id = new Guid("058F8F85-A735-48F3-B526-79855FFF1EB0"), Name = "Reports", DisplayOrder = 1, CmsId = 100473, IsActive = true },
                new ReportTemplateType { Id = new Guid("69D55B31-69BB-4BBC-82F1-A707B484E99B"), Name = "Letters", DisplayOrder = 2, CmsId = 100474, IsActive = true },
                new ReportTemplateType { Id = new Guid("19D2650B-CE8E-4B54-95D9-ACAFA5C1CE40"), Name = "Custom working papers", DisplayOrder = 4, CmsId = 101476, IsActive = true },
            };
    }

    public async void CreateReportTemplateAsync_Success()
    {
        // Arrange
        var reportTemplates = CreateReportTemplates().MockDbSet().Object;

        var a = reportTemplates.AsQueryable().ToList(); // return empty list after call AsQueryable()
    }
}

</code>```

I mock AsQueryable method on DBSet<T>, i will have a expected list.

Body:
I use entity framework core 6, XUnit for testing, Moq 4.16.1

I have a List, Mock it as DBSet<T>, I call AsQueryable method on DBSet<T> then return a empty list. If i mock AsQueryable method on DBSet<T>, i will have a expected list. Can you tell me Why?

This is my code

public static class MockDbExtensions
{
    public static Mock<DbSet<T>> MockDbSet<T>(this IQueryable<T> testData) where T : class
    {
        Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(new TestAsyncQueryProvider<T>(testData.Provider));
        dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(testData.Expression);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(testData.ElementType);
        dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => testData.GetEnumerator());
        dbSetMock.As<IAsyncEnumerable<T>>().Setup(m => m.GetAsyncEnumerator(default)).Returns(() => new TestAsyncEnumerator<T>(testData.GetEnumerator()));
        return dbSetMock;
    }

    public static Mock<DbSet<T>> MockDbSet<T>(this IEnumerable<T> elements) where T : class
    {
        var testData = elements.AsQueryable();
        return testData.MockDbSet();
    }

    public static Mock<DbSet<T>> MockDbSet<T>(this T[] elements) where T : class
    {
        var testData = elements.AsQueryable();
        return testData.MockDbSet();
    }
}

internal class TestAsyncQueryProvider<TEntity> : IAsyncQueryProvider
{
    private readonly IQueryProvider _inner;

    internal TestAsyncQueryProvider(IQueryProvider inner)
    {
        _inner = inner;
    }

    public IQueryable CreateQuery(Expression expression)
    {
        return new TestAsyncEnumerable<TEntity>(expression);
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
    {
        return new TestAsyncEnumerable<TElement>(expression);
    }

    public object Execute(Expression expression)
    {
        return _inner.Execute(expression);
    }

    public TResult Execute<TResult>(Expression expression)
    {
        return _inner.Execute<TResult>(expression);
    }

    public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression)
    {
        return new TestAsyncEnumerable<TResult>(expression);
    }

    public TResult ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = new CancellationToken())
    {
        var expectedResultType = typeof(TResult).GetGenericArguments()[0];
        var executionResult = ((IQueryProvider)this).Execute(expression);

        return (TResult)typeof(Task).GetMethod(nameof(Task.FromResult))
            .MakeGenericMethod(expectedResultType)
            .Invoke(null, new[] { executionResult });
    }
}

internal class TestAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T>
{
    public TestAsyncEnumerable(IEnumerable<T> enumerable)
        : base(enumerable)
    { }

    public TestAsyncEnumerable(Expression expression)
        : base(expression)
    { }

    public IAsyncEnumerator<T> GetEnumerator()
    {
        return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
    }

    public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default)
    {
        return new TestAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
    }

    IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider<T>(this);
}

internal class TestAsyncEnumerator<T> : IAsyncEnumerator<T>
{
    private readonly IEnumerator<T> _inner;

    public TestAsyncEnumerator(IEnumerator<T> inner)
    {
        _inner = inner;
    }

    public void Dispose()
    {
        _inner.Dispose();
    }

    public T Current => _inner.Current;

    public Task<bool> MoveNext(CancellationToken cancellationToken)
    {
        return Task.FromResult(_inner.MoveNext());
    }

    public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(_inner.MoveNext());

    public ValueTask DisposeAsync()
    {
        _inner.Dispose();
        return new ValueTask();
    }
}

public class ReportTemplateServiceTests
{

    private List<ReportTemplateType> CreateReportTemplateTypes()
    {
        return new List<ReportTemplateType>
            {
                new ReportTemplateType { Id = new Guid("144013ED-2D77-4572-8AB4-483C66E4EF1D"), Name = "Financial statements", DisplayOrder = 3, CmsId = 101475, IsActive = true },
                new ReportTemplateType { Id = new Guid("058F8F85-A735-48F3-B526-79855FFF1EB0"), Name = "Reports", DisplayOrder = 1, CmsId = 100473, IsActive = true },
                new ReportTemplateType { Id = new Guid("69D55B31-69BB-4BBC-82F1-A707B484E99B"), Name = "Letters", DisplayOrder = 2, CmsId = 100474, IsActive = true },
                new ReportTemplateType { Id = new Guid("19D2650B-CE8E-4B54-95D9-ACAFA5C1CE40"), Name = "Custom working papers", DisplayOrder = 4, CmsId = 101476, IsActive = true },
            };
    }

    public async void CreateReportTemplateAsync_Success()
    {
        // Arrange
        var reportTemplates = CreateReportTemplates().MockDbSet().Object;

        var a = reportTemplates.AsQueryable().ToList(); // return empty list after call AsQueryable()
    }
}

I mock AsQueryable method on DBSet<T>, i will have a expected list.


问:
Why bind-bound ComboboxSelected is executed once before the event, and only this once.python.tkinter.bind
I'm a newbie.
I'm having a problem making a small toy,When I use tkinter .
After I execute the script, it prints "?" directly in the terminal, and this time I don't trigger "ComboboxSelected".
enter image description here
Then, when I select the drop-down box other item, I think the event is fired, but there is no new "?" is printed

enter image description here
My English is weak,so these texts are translated by translation software.
There may be some errors.

```<code>import tkinter
from tkinter import ttk

top = top = tkinter.Tk()
cbox = ttk.Combobox(top)
cbox.grid(column=0)
cbox["value"] = ["a","b","c"]

def func(cbox):
    print("?")

cbox.bind("<<ComboboxSelected>>>", func(cbox))

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

When I repeat bind twice, "?" Was printed twice, which I think proves that the loop is not clogged

```<code>

import tkinter
from tkinter import ttk

top = top = tkinter.Tk()
cbox = ttk.Combobox(top)
cbox.grid(column=0)
cbox\["value"\] = \["a","b","c"\]

def func(cbox):
print("?")

cbox.bind("\<\<ComboboxSelected\>\>", func(cbox))
cbox.bind("\<\<ComboboxSelected\>\>", func(cbox))

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

enter image description here

I found another problem and he does work.
text
But why,I don't understand.

Body:
I'm a newbie.
I'm having a problem making a small toy,When I use tkinter .
After I execute the script, it prints "?" directly in the terminal, and this time I don't trigger "ComboboxSelected".
enter image description here
Then, when I select the drop-down box other item, I think the event is fired, but there is no new "?" is printed

enter image description here
My English is weak,so these texts are translated by translation software.
There may be some errors.

import tkinter
from tkinter import ttk

top = top = tkinter.Tk()
cbox = ttk.Combobox(top)
cbox.grid(column=0)
cbox["value"] = ["a","b","c"]

def func(cbox):
    print("?")

cbox.bind("<<ComboboxSelected>>>", func(cbox))

top.mainloop()

When I repeat bind twice, "?" Was printed twice, which I think proves that the loop is not clogged

import tkinter
from tkinter import ttk

top = top = tkinter.Tk()
cbox = ttk.Combobox(top)
cbox.grid(column=0)
cbox\["value"\] = \["a","b","c"\]

def func(cbox):
print("?")

cbox.bind("\<\<ComboboxSelected\>\>", func(cbox))
cbox.bind("\<\<ComboboxSelected\>\>", func(cbox))

top.mainloop()

enter image description here

I found another problem and he does work.
text
But why,I don't understand.


问:
custom color in MUI dialog not working (MUI v-5)

```<code>.App {
  text-align: center;
 ** --amenalBlue: #15426C;
  --amenalOrange: #D9A460;**
}
h2,h3{
  color: gray;
}

/* common table head style */
.tableHead {
 *** background-color: var(--amenalOrange);***

}
.tableHead th {
  color: var(--amenalBlue);
  font-weight: bold;
}

</code>```

Table head is not taking custom color which i have added but normal hex code is taking. This is happning in MUI table used inside MUI dialog

Body:
.App {
  text-align: center;
 ** --amenalBlue: #15426C;
  --amenalOrange: #D9A460;**
}
h2,h3{
  color: gray;
}

/* common table head style */
.tableHead {
 *** background-color: var(--amenalOrange);***

}
.tableHead th {
  color: var(--amenalBlue);
  font-weight: bold;
}

Table head is not taking custom color which i have added but normal hex code is taking. This is happning in MUI table used inside MUI dialog


问:
cause of RuntimeException: Unable to start activity ComponentInfo in specific activity only in specific devices ( oppo devics )
Crashlytics StackTrace :

```<code>Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{MerchantProfileDetailsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3763)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3931)
   at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
   at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
   at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2350)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:264)
   at android.app.ActivityThread.main(ActivityThread.java:8312)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
</code>```

I am unable to reproduce this. and it is reported only in Oppo devices.

Where should i look for clues?

Body:
Crashlytics StackTrace :

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{MerchantProfileDetailsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3763)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3931)
   at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
   at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
   at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2350)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:264)
   at android.app.ActivityThread.main(ActivityThread.java:8312)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)

I am unable to reproduce this. and it is reported only in Oppo devices.

Where should i look for clues?


问:
tkinter frame is shown without button clicked
I have a very lengthy python script that contains all of the features of my tool and I'm trying to split it by its functions into multiple files which later can be imported and to make further development easier. For now, I have 2 files. One will be the main execution file and the other one is the file to contains general functions.

main.py

```<code>from tkinter import *
from tkinter import filedialog, ttk
from PIL import ImageTk, Image

import pandas as pd
import vaex
from pyexcelerate import Workbook
from pyxlsb import open_workbook as open_xlsb
from math import ceil
from datetime import datetime
import win32com.client
import os
import re
import general

if __name__ == '__main__':
    w=Tk()
    w.geometry('900x500')
    w.resizable(0,0)
    w.title('Excel Processor')

    general.Home(w)

    img1 = ImageTk.PhotoImage(Image.open("C:\\class_testing\\assets\\open.png"))
    Button(w,command=general.ToggleWin(w),image=img1, border=0).place(x=5,y=10) <-- the problem is  when I pass the class to command it displays the toggle menu frame even when it's not clicked

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

general.py

```<code>from tkinter import *
from tkinter import filedialog, ttk
from PIL import ImageTk, Image

import pandas as pd
import vaex
from pyexcelerate import Workbook
from pyxlsb import open_workbook as open_xlsb
from math import ceil
from datetime import datetime
import win32com.client
import os
import re
import tkinter as tk

class BulletLabel(Label):
    def __init__(self, master, *args, **kwargs):
        text = kwargs.pop('text', '')
        kwargs['text'] = self.bulletise(text)
        Label.__init__(self, master, *args, **kwargs)

    def bulletise(self, text):
        if len(text) == 0:
            return ''
        lines = text.split('\n')
        parts = []
        for line in lines:
            parts.extend(['\u2022', line, '\n'])
        return ''.join(parts)

    def configure(self, *args, **kwargs):
        text = kwargs.pop('text', '')
        if text != '':
            kwargs['text'] = self.bulletise(text)
        Label.configure(*args, **kwargs)

class Home(tk.Frame):

    def __init__(self,master):
        tk.Frame.__init__(self, master)
        self.f2=Frame(master, width=900,height=455, background='white')
        self.f2.pack()

        self.f2.place(x=0, y=50)

        self.label_title = Label(master,text='EXCEL PROCESSOR', font=('Calibri', 14, 'bold'), fg='#EE4D2D')
        self.label_title.place(x=80,y=11)

        self.label_menu = Label(master,text='Welcome!', font=(None, 10, 'bold'), fg='#EE4D2D', background='white')
        self.label_menu.place(x=80,y=70)

        self.instruct_text="Excel Processor is an offline data processing tool that allows you to do excel functions to your data in a faster way. "+\
            "It is built as a desktop application on windows operating system. The current version includes eight features:"
        self.label_instruct = Label(master, text=self.instruct_text, wraplength=740, justify='left', font=(None, 10), background='white')
        self.label_instruct.place(x=80,y=100)

        self.blabel = BulletLabel(master, text="    Lookup  -  do excel lookup function between two large files.\n    "+\
            "Merge  -  merge similar files with the same column names into one file.\n    "+\
            "Filter  -  filter data based on condition.\n    "+\
            "Convert  -  convert xlsx files to csv or the other way around.\n    "+\
            "Column operations  -  perform operations to create another column.\n    "+\
            "Count appearances  -  count value appearances in a column.\n    "+\
            "Split >1m rows data  -  split a table that contains more than one million rows of data.\n    "+\
            "Split between sheets  -  split an excel file that contains more than one sheet.\n    "+\
            "Split table by column  -  split a table by unique values of a column.\n    "+\
            "Split tables in 1 sheet  -  split an excel file that contains more than one table in one sheet.",
            wraplength=740, justify='left', font=(None, 10), background='white')
        self.blabel.place(x=80, y=140)

def page_home(f1p):
    f1p.destroy()
    Home()
    ToggleWin()

class ToggleWin(tk.Frame):

    def __init__(self,master):
        tk.Frame.__init__(self,master)
        self.f1=Frame(master,width=216,height=570,bg='#EE4D2D')
        self.f1.place(x=0,y=0)
</code>```

Body:
I have a very lengthy python script that contains all of the features of my tool and I'm trying to split it by its functions into multiple files which later can be imported and to make further development easier. For now, I have 2 files. One will be the main execution file and the other one is the file to contains general functions.

main.py

from tkinter import *
from tkinter import filedialog, ttk
from PIL import ImageTk, Image

import pandas as pd
import vaex
from pyexcelerate import Workbook
from pyxlsb import open_workbook as open_xlsb
from math import ceil
from datetime import datetime
import win32com.client
import os
import re
import general

if __name__ == '__main__':
    w=Tk()
    w.geometry('900x500')
    w.resizable(0,0)
    w.title('Excel Processor')

    general.Home(w)

    img1 = ImageTk.PhotoImage(Image.open("C:\\class_testing\\assets\\open.png"))
    Button(w,command=general.ToggleWin(w),image=img1, border=0).place(x=5,y=10) <-- the problem is  when I pass the class to command it displays the toggle menu frame even when it's not clicked

    w.mainloop()

general.py

from tkinter import *
from tkinter import filedialog, ttk
from PIL import ImageTk, Image

import pandas as pd
import vaex
from pyexcelerate import Workbook
from pyxlsb import open_workbook as open_xlsb
from math import ceil
from datetime import datetime
import win32com.client
import os
import re
import tkinter as tk

class BulletLabel(Label):
    def __init__(self, master, *args, **kwargs):
        text = kwargs.pop('text', '')
        kwargs['text'] = self.bulletise(text)
        Label.__init__(self, master, *args, **kwargs)

    def bulletise(self, text):
        if len(text) == 0:
            return ''
        lines = text.split('\n')
        parts = []
        for line in lines:
            parts.extend(['\u2022', line, '\n'])
        return ''.join(parts)

    def configure(self, *args, **kwargs):
        text = kwargs.pop('text', '')
        if text != '':
            kwargs['text'] = self.bulletise(text)
        Label.configure(*args, **kwargs)

class Home(tk.Frame):

    def __init__(self,master):
        tk.Frame.__init__(self, master)
        self.f2=Frame(master, width=900,height=455, background='white')
        self.f2.pack()

        self.f2.place(x=0, y=50)

        self.label_title = Label(master,text='EXCEL PROCESSOR', font=('Calibri', 14, 'bold'), fg='#EE4D2D')
        self.label_title.place(x=80,y=11)

        self.label_menu = Label(master,text='Welcome!', font=(None, 10, 'bold'), fg='#EE4D2D', background='white')
        self.label_menu.place(x=80,y=70)

        self.instruct_text="Excel Processor is an offline data processing tool that allows you to do excel functions to your data in a faster way. "+\
            "It is built as a desktop application on windows operating system. The current version includes eight features:"
        self.label_instruct = Label(master, text=self.instruct_text, wraplength=740, justify='left', font=(None, 10), background='white')
        self.label_instruct.place(x=80,y=100)

        self.blabel = BulletLabel(master, text="    Lookup  -  do excel lookup function between two large files.\n    "+\
            "Merge  -  merge similar files with the same column names into one file.\n    "+\
            "Filter  -  filter data based on condition.\n    "+\
            "Convert  -  convert xlsx files to csv or the other way around.\n    "+\
            "Column operations  -  perform operations to create another column.\n    "+\
            "Count appearances  -  count value appearances in a column.\n    "+\
            "Split >1m rows data  -  split a table that contains more than one million rows of data.\n    "+\
            "Split between sheets  -  split an excel file that contains more than one sheet.\n    "+\
            "Split table by column  -  split a table by unique values of a column.\n    "+\
            "Split tables in 1 sheet  -  split an excel file that contains more than one table in one sheet.",
            wraplength=740, justify='left', font=(None, 10), background='white')
        self.blabel.place(x=80, y=140)

def page_home(f1p):
    f1p.destroy()
    Home()
    ToggleWin()

class ToggleWin(tk.Frame):

    def __init__(self,master):
        tk.Frame.__init__(self,master)
        self.f1=Frame(master,width=216,height=570,bg='#EE4D2D')
        self.f1.place(x=0,y=0)


问:
How do I get the length of a structure? (NASM)
If I define a structure like so:

```<code>section .bss
    struc mystruc
        .x: resb 1
        .y: resb 1
    endstruc
</code>```

How would I get the length of the structure?

Body:
If I define a structure like so:

section .bss
    struc mystruc
        .x: resb 1
        .y: resb 1
    endstruc

How would I get the length of the structure?


问:
How to get the label text from a html string in Kotlin
In my Kotlin project, I got this json response from an API request. The field html I think it includes a html string, my question is that how could I parse and get this form-label text value in this html string? Because I want to assert it in my UI test case.

```<code>"question": {
    "id": "1c3000d8091-fadc-4a01-9525-8072581abe25",
    "created": 1629896001695,
    "updated": 1653953634651,
    "html": "\n      <style>\n        @supports (font: -apple-system-body) {\n          * {\n            font: -apple-system-body !important;\n          }\n        }\n        .wizard_1629896007101_rating .item {\n          margin: 1rem 0;\n          font-size: large;\n          letter-spacing: 0.5rem;\n          cursor: pointer;\n        }\n ... \n  <label class=\"form-label\">\n  Please answer the 1st question.\n  </label>\n\n        \n      <label class=\"form-radio item\">\n ..."
}

</code>```

Body:
In my Kotlin project, I got this json response from an API request. The field html I think it includes a html string, my question is that how could I parse and get this form-label text value in this html string? Because I want to assert it in my UI test case.

"question": {
    "id": "1c3000d8091-fadc-4a01-9525-8072581abe25",
    "created": 1629896001695,
    "updated": 1653953634651,
    "html": "\n


问:
Open VSCode and attach to container from terminal
I would like to open VSCode from the terminal, but instead of opening a directory or file, I would like to attach the VSCode session to a running container using the Dev Containers extension.

I have tried using the --folder-uri flag with the vscode-remote option as suggested here (i.e., code --folder-uri=vscode-remote://<container name> --verbose) which does not seem to open anything.


问:
React Native | Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver
Issue found in Google Play Store Pre-launch report

the detailed exception stack trace is

```<code>java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}
</code>```
```<code>Exception java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:4035)
  at android.app.ActivityThread.access$1400 (ActivityThread.java:237)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1924)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:223)
  at android.app.ActivityThread.main (ActivityThread.java:7664)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:592)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1715)
  at android.app.ContextImpl.startService (ContextImpl.java:1670)
  at android.content.ContextWrapper.startService (ContextWrapper.java:720)
  at alj.a (PG:2)
  at alm.a (PG:3)
  at wnv.a (PG:2)
  at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive (PG:6)
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:4026)
</code>```

"react-native": "0.70.1"

Body:
Issue found in Google Play Store Pre-launch report

the detailed exception stack trace is

java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}

Exception java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:4035)
  at android.app.ActivityThread.access$1400 (ActivityThread.java:237)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1924)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:223)
  at android.app.ActivityThread.main (ActivityThread.java:7664)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:592)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{7f7aa4f u0a192 TRNB bg:+1m35s375ms idle change:uncached procs:4 seq(0,0,0)}
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1715)
  at android.app.ContextImpl.startService (ContextImpl.java:1670)
  at android.content.ContextWrapper.startService (ContextWrapper.java:720)
  at alj.a (PG:2)
  at alm.a (PG:3)
  at wnv.a (PG:2)
  at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive (PG:6)
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:4026)

"react-native": "0.70.1"