问:
MongoDB aggregation: how to group/bucket documents in interval with non numeric limits?
I have the following data in MongoDB:

[
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 22,
    "timestamp": T1
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 25,
    "timestamp": T2
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "close",
    "temp": 27,
    "timestamp": T3
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 22,
    "timestamp": T4
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "close",
    "temp": 22,
    "timestamp": T5
  }
]
```
<p>I would like to group the documents from the first "open" until the following "close" and compute the average temperature, opening time and closing time.</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "room": "A",
    "avgTemp": 25,
    "openTimestamp": T1
    "closeTimestamp": T3
  },
  {
    "room": "A",
    "avgTemp": 22,
    "openTimestamp": T4
    "closeTimestamp": T5
  }
]
</code>```

timestamp is an actual timestamp, which I replaced with Tx for ease of reference. Every document has its own autogenerated _id.

I have thought of using $setWindowFields to add a new field closeId, then group by closeId. Ideally, something like this:

```<code>$setWindowFields: {
  partitionBy: {
    room: "$room"
  },
  sortBy: {
    timestamp: 1,
  },
  output: {
    closeId: {
      $first: "$_id",
      window: {
        documents: ["current", "unbounded"],
        filter: {
          $eq: ["$state", "close"]
        }
      },
    },
  },
},
$group: {
  $_id: {
    "closeId": "$closeId",
    "room": "$room"
  },
  avgTemp: { $avg: "$temp" },
  openTimestamp: { $first: "$timestamp" },
  closeTimestamp: { $last: "$timestamp" }
}
</code>```

Unfortunately I couldn't find a way to filter the window like I did in the example query above, and don't know how to get the desired result.

Can anybody help? Thank you!

Body:
I have the following data in MongoDB:

[
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 22,
    "timestamp": T1
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 25,
    "timestamp": T2
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "close",
    "temp": 27,
    "timestamp": T3
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "open",
    "temp": 22,
    "timestamp": T4
  },
  {
    "_id": ObjectId,
    "room": "A",
    "state": "close",
    "temp": 22,
    "timestamp": T5
  }
]

I would like to group the documents from the first "open" until the following "close" and compute the average temperature, opening time and closing time.

[
  {
    "room": "A",
    "avgTemp": 25,
    "openTimestamp": T1
    "closeTimestamp": T3
  },
  {
    "room": "A",
    "avgTemp": 22,
    "openTimestamp": T4
    "closeTimestamp": T5
  }
]

timestamp is an actual timestamp, which I replaced with Tx for ease of reference. Every document has its own autogenerated _id.

I have thought of using $setWindowFields to add a new field closeId, then group by closeId. Ideally, something like this:

$setWindowFields: {
  partitionBy: {
    room: "$room"
  },
  sortBy: {
    timestamp: 1,
  },
  output: {
    closeId: {
      $first: "$_id",
      window: {
        documents: ["current", "unbounded"],
        filter: {
          $eq: ["$state", "close"]
        }
      },
    },
  },
},
$group: {
  $_id: {
    "closeId": "$closeId",
    "room": "$room"
  },
  avgTemp: { $avg: "$temp" },
  openTimestamp: { $first: "$timestamp" },
  closeTimestamp: { $last: "$timestamp" }
}

Unfortunately I couldn't find a way to filter the window like I did in the example query above, and don't know how to get the desired result.

Can anybody help? Thank you!


来源: stackexchange

问:
Dynamodb - Storing GeoJSON object and query near by
I'm developing a service in that users can create some areas in specific GeoLocations. I need to store these GeoJSON objects in the DynamoDB and after that users can get a list of these areas nearby them.
Sample GeoJSON area:

```<code>{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "coordinates": [
          [
            [
              -0.43747807662956006,
              48.39814258251761
            ],
            [
              1.8683247936019427,
              46.53130957770537
            ],
            [
              7.395627732907826,
              44.37308469315661
            ],
            [
              12.21753234390573,
              46.90186461241811
            ],
            [
              11.667244306615714,
              49.672623690020544
            ],
            [
              4.400296800394699,
              51.59354442322967
            ],
            [
              -0.43747807662956006,
              48.39814258251761
            ]
          ]
        ],
        "type": "Polygon"
      }
    }
  ]
}
</code>```

Current location of another user:

```<code>{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "coordinates": [
          4.135524652689355,
          48.16239133362586
        ],
        "type": "Point"
      }
    }
  ]
}
</code>```

This is my gsi5pk and gsi5sk structure:

```<code>// GSI5 - Areas by geohash
gsi5pk: "AREA_GEOHASHES",
gsi5sk: `AREA_GEOHASHES#${geoHashesString}`
</code>```

I think gsi5sk is not a good practice because geoHashesString can be a million characters. So I defined a field in the Dynamodb document called 'geoHashes'. this is my query and it seems everything is OK because I will get the correct items:

```<code>const { lat, lng } = location;
const geoHash = encodeLatLngToGeohash(lat, lng);
params.IndexName = "gsi5";
params.KeyConditionExpression = "gsi5pk = :gsi5pk";
params.FilterExpression = "contains(geoHashes, :geoHash)";
params.ExpressionAttributeValues = {
 ":gsi5pk": "AREA_GEOHASHES",
 ":geoHash": geoHash,
};
</code>```

I think using contains in FilterExpression is not a good way. Also, I think geoHash field can be very heavy. What's your idea? Is there any better way to do this?

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a service in that users can create some areas in specific GeoLocations. I need to store these GeoJSON objects in the DynamoDB and after that users can get a list of these areas nearby them.
Sample GeoJSON area:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "coordinates": [
          [
            [
              -0.43747807662956006,
              48.39814258251761
            ],
            [
              1.8683247936019427,
              46.53130957770537
            ],
            [
              7.395627732907826,
              44.37308469315661
            ],
            [
              12.21753234390573,
              46.90186461241811
            ],
            [
              11.667244306615714,
              49.672623690020544
            ],
            [
              4.400296800394699,
              51.59354442322967
            ],
            [
              -0.43747807662956006,
              48.39814258251761
            ]
          ]
        ],
        "type": "Polygon"
      }
    }
  ]
}

Current location of another user:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "coordinates": [
          4.135524652689355,
          48.16239133362586
        ],
        "type": "Point"
      }
    }
  ]
}

This is my gsi5pk and gsi5sk structure:

// GSI5 - Areas by geohash
gsi5pk: "AREA_GEOHASHES",
gsi5sk: `AREA_GEOHASHES#${geoHashesString}`

I think gsi5sk is not a good practice because geoHashesString can be a million characters. So I defined a field in the Dynamodb document called 'geoHashes'. this is my query and it seems everything is OK because I will get the correct items:

const { lat, lng } = location;
const geoHash = encodeLatLngToGeohash(lat, lng);
params.IndexName = "gsi5";
params.KeyConditionExpression = "gsi5pk = :gsi5pk";
params.FilterExpression = "contains(geoHashes, :geoHash)";
params.ExpressionAttributeValues = {
 ":gsi5pk": "AREA_GEOHASHES",
 ":geoHash": geoHash,
};

I think using contains in FilterExpression is not a good way. Also, I think geoHash field can be very heavy. What's your idea? Is there any better way to do this?


问:
CSS Grid auto-fill with max-content
I have 4 divs, lets call them a,b,c,d. Their heights and widths can change (for example, during translation), but the height of a and b will always be equal (they are 1 row each). I want to arrange them in two columns, with a and c in the left column, b and d in the right column (the widths of the columns are NOT necessarily equal), but when this would cause overflow, I want them to fold into one column, ordered a-b-c-d top-to bottom. The closest I got was this:

.container {
  display: grid;
  grid-template-columns: repeat(2, max-content);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div style="width: 100px; height: 20px; background: red;">A</div>
  <div style="width: 120px; height: 20px; background: yellow;">B</div>
  <div style="width: 80px; height: 40px; background: green;">C</div>
  <div style="width: 130px; height: 60px; background: blue;">D</div>
</div></code>```

Changing the number in the repeat to 1 produces the expected arrangement, but repeat(auto-fill, max-content) doesn't work, as automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes (such as max-content, min-content, auto). Is there any way to achieve this?

Title: CSS Grid auto-fill with max-content

Body:
I have 4 divs, lets call them a,b,c,d. Their heights and widths can change (for example, during translation), but the height of a and b will always be equal (they are 1 row each). I want to arrange them in two columns, with a and c in the left column, b and d in the right column (the widths of the columns are NOT necessarily equal), but when this would cause overflow, I want them to fold into one column, ordered a-b-c-d top-to bottom. The closest I got was this:

.container {
  display: grid;
  grid-template-columns: repeat(2, max-content);
}

A

B

C

D

Changing the number in the repeat to 1 produces the expected arrangement, but repeat(auto-fill, max-content) doesn't work, as automatic repetitions (auto-fill or auto-fit) cannot be combined with intrinsic or flexible sizes (such as max-content, min-content, auto). Is there any way to achieve this?


问:
Failing to pip install parallel-ssh on Macos Monterey
I am trying to install parallel-ssh (pip install parallel-ssh) on MacOs Monterey but failing with the following error. I also tried to install parallel-ssh through Pycharm and failed. Does anyone have any idea on how to resolve this?</p>
```<code>  Building wheel for ssh-python (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [12 lines of output]
      SYSTEM_LIBSSH is unset, starting embedded libssh build
      /bin/sh: cmake: command not found
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/tmp/pip-install-6a7nbbpj/ssh-python_eccf1f272ead42b1bfd160d149a858cb/setup.py", line 38, in <module>
          build_ssh()
        File "/private/tmp/pip-install-6a7nbbpj/ssh-python_eccf1f272ead42b1bfd160d149a858cb/_setup_libssh.py", line 44, in build_ssh
          check_call("""cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../local \
        File "/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 373, in check_call
          raise CalledProcessError(retcode, cmd)
      subprocess.CalledProcessError: Command 'cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../local     -DWITH_GSSAPI=ON     -DWITH_EXAMPLES=OFF     ../libssh' returned non-zero exit status 127.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for ssh-python
  Running setup.py clean for ssh-python
  Building wheel for ssh2-python (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      /bin/sh: cmake: command not found
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/tmp/pip-install-6a7nbbpj/ssh2-python_a7d066eb610d4e788ed21e235ed8d243/setup.py", line 32, in <module>
          build_ssh2()
        File "/private/tmp/pip-install-6a7nbbpj/ssh2-python_a7d066eb610d4e788ed21e235ed8d243/_setup_libssh2.py", line 35, in build_ssh2
          check_call('cmake ../libssh2/libssh2 -DBUILD_SHARED_LIBS=ON \
        File "/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 373, in check_call
          raise CalledProcessError(retcode, cmd)
      subprocess.CalledProcessError: Command 'cmake ../libssh2/libssh2 -DBUILD_SHARED_LIBS=ON     -DENABLE_ZLIB_COMPRESSION=ON -DENABLE_CRYPT_NONE=ON     -DENABLE_MAC_NONE=ON -DCRYPTO_BACKEND=OpenSSL' returned non-zero exit status 127.
      [end of output]

</code>```

Body:
I am trying to install parallel-ssh (pip install parallel-ssh) on MacOs Monterey but failing with the following error. I also tried to install parallel-ssh through Pycharm and failed. Does anyone have any idea on how to resolve this?

  Building wheel for ssh-python (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [12 lines of output]
      SYSTEM_LIBSSH is unset, starting embedded libssh build
      /bin/sh: cmake: command not found
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/tmp/pip-install-6a7nbbpj/ssh-python_eccf1f272ead42b1bfd160d149a858cb/setup.py", line 38, in <module>
          build_ssh()
        File "/private/tmp/pip-install-6a7nbbpj/ssh-python_eccf1f272ead42b1bfd160d149a858cb/_setup_libssh.py", line 44, in build_ssh
          check_call("""cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../local \
        File "/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 373, in check_call
          raise CalledProcessError(retcode, cmd)
      subprocess.CalledProcessError: Command 'cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../local     -DWITH_GSSAPI=ON     -DWITH_EXAMPLES=OFF     ../libssh' returned non-zero exit status 127.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for ssh-python
  Running setup.py clean for ssh-python
  Building wheel for ssh2-python (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [11 lines of output]
      /bin/sh: cmake: command not found
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/tmp/pip-install-6a7nbbpj/ssh2-python_a7d066eb610d4e788ed21e235ed8d243/setup.py", line 32, in <module>
          build_ssh2()
        File "/private/tmp/pip-install-6a7nbbpj/ssh2-python_a7d066eb610d4e788ed21e235ed8d243/_setup_libssh2.py", line 35, in build_ssh2
          check_call('cmake ../libssh2/libssh2 -DBUILD_SHARED_LIBS=ON \
        File "/opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 373, in check_call
          raise CalledProcessError(retcode, cmd)
      subprocess.CalledProcessError: Command 'cmake ../libssh2/libssh2 -DBUILD_SHARED_LIBS=ON     -DENABLE_ZLIB_COMPRESSION=ON -DENABLE_CRYPT_NONE=ON     -DENABLE_MAC_NONE=ON -DCRYPTO_BACKEND=OpenSSL' returned non-zero exit status 127.
      [end of output]


问:
OpenSSL 3.0 Windows compilation with Windows
Earlier with compilation openssl 1.0.2 the output binaries are - ssleay32.dll & libeay32.dll
However with openssl 3.0 compilation the output binaries are - libcrypto-3.dll & libssl-3.dll
Is my understanding correct can someone please confirm.

Not clear with migration steps mentioned in openssl 3.0 migration page https://www.openssl.org/docs/man3.0/man7/migration_guide.html


问:
How to set up custom koa.js server in next.js
I have set up custom koa.js server and every time I make a request to api for example

```<code>/api/login
</code>```

It always ends up in being 404 not found.

I have tried looking for a solution but, could not really find it.

Below is my server.js file

```<code>import '@babel/polyfill';
import dotenv from 'dotenv';
import 'isomorphic-fetch';
import next from 'next';
import Koa from 'koa';
import Router from 'koa-router';
import UserRouter from './routes/user';
import cors from '@koa/cors';

dotenv.config();

const compression = require('compression');

const port = parseInt(process.env.PORT, 10) || 3000;

const dev = process.env.NODE_ENV !== 'production';

const app = next({ dev });

const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();
  server.use(
    cors({
      origin: '*',
    })
  );

  router.get('*', async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(UserRouter.routes()).use(UserRouter.allowedMethods());
  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`Server ready on ${port}`);
  });
});

</code>```

Body:
I have set up custom koa.js server and every time I make a request to api for example

/api/login

It always ends up in being 404 not found.

I have tried looking for a solution but, could not really find it.

Below is my server.js file

import '@babel/polyfill';
import dotenv from 'dotenv';
import 'isomorphic-fetch';
import next from 'next';
import Koa from 'koa';
import Router from 'koa-router';
import UserRouter from './routes/user';
import cors from '@koa/cors';

dotenv.config();

const compression = require('compression');

const port = parseInt(process.env.PORT, 10) || 3000;

const dev = process.env.NODE_ENV !== 'production';

const app = next({ dev });

const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();
  server.use(
    cors({
      origin: '*',
    })
  );

  router.get('*', async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(UserRouter.routes()).use(UserRouter.allowedMethods());
  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`Server ready on ${port}`);
  });
});


问:
How to load hugging face base model from Google Cloud Storage?
I would like to load a hugging face base model (xlm-roberta-base) from Google Cloud Storage without downloading to my local directory if possible. My model is a PyTorch model which builds on the hugging face base model. How can I go about this?

I can download blobs with a particular prefix from my bucket, but I would like to do it without actually persisting the downloaded blobs in my local directory.


问:
Showing Test Ads
My application, which I uploaded to the play store using real advertising IDs, was approved and published. I connected my application with Admob. When I install my app on a real device (not a test device), it shows test ad. What should I do? Has anyone encountered this situation before?

Shows test ad instead of real ad

Title: Showing Test Ads


问:
Node Microservice Jwt
I have my project with microservice architecture . I have an admin server which handles the the authentication and some basic crud  also I have a storage server . In my frontend after the user login I stores his token in a state .

Now I have to send a file to storage server. And to store something in my storage server needs a parameter called userid but my storage server does not have a JWT decoder or something. so I cannot the token in header .

how can I fix this issue .Should I need to store the userid in my state or   should  I need to setup an JWT decoder in my storage server also

Title: Node Microservice Jwt


问:
How to unit test a Singleton class of database connection using PHP PDO?
I was writting a Singleton class of Database connection, but I ran into some problems. Look:

class PDOSingleConnection
{
    private static PDO|null $pdo = null;

    public function __construct(PDO $pdo)
    {
        self::$pdo = $pdo;
    }

    public static function getPDO(
        $hostName = 'localhost',
        $username = 'root',
        $password = '12345'
    ): PDO
    {
        if (is_null(self::$pdo)) {
            try {
                self::$pdo = new PDO("mysql:host=$hostName;", $username, $password);
                self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            } catch (\PDOException $PDOException) {
                throw new \PDOException($PDOException->getMessage());
            }
        }

        return self::$pdo;
    }
}

```

How you can see, I can't test it 'cause I can't mock my dependency(the PDO class).

My first question is: How can I improve this class, so that it is unit testable?

My second question is: I was reading some topics in the community, and I have seen some people saying that "Singletons are bad news". So, Why "Singletons are bad news"? How can I create a single instance of my database connection, without using the Singleton pattern?

Thank you!!

Body:
I was writting a Singleton class of Database connection, but I ran into some problems. Look:

class PDOSingleConnection
{
    private static PDO|null $pdo = null;

    public function __construct(PDO $pdo)
    {
        self::$pdo = $pdo;
    }

    public static function getPDO(
        $hostName = 'localhost',
        $username = 'root',
        $password = '12345'
    ): PDO
    {
        if (is_null(self::$pdo)) {
            try {
                self::$pdo = new PDO("mysql:host=$hostName;", $username, $password);
                self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            } catch (\PDOException $PDOException) {
                throw new \PDOException($PDOException->getMessage());
            }
        }

        return self::$pdo;
    }
}

How you can see, I can't test it 'cause I can't mock my dependency(the PDO class).

My first question is: How can I improve this class, so that it is unit testable?

My second question is: I was reading some topics in the community, and I have seen some people saying that "Singletons are bad news". So, Why "Singletons are bad news"? How can I create a single instance of my database connection, without using the Singleton pattern?

Thank you!!


问:
EF Core 7 - Class / Member Attributes
I have a class attribute which defines a value, then I have a Method attribute, which even defines a value.
Then I want to access the value of the class attribute from the method attribute.

```<code>[MyClassAttribute("SomethingClass")]
public class MyClass
{
    [MyMethodAttribute("SomethingMethod")]
    public void MyMethod() { }
}
</code>```

Something like this should be done:

```<code>public class MyMethodAttribute : Attribute
{
    public MyMethodAttribute(params string value)
    {
        var myClassAttributeValue = PARENTCLASS.MyClassAttributeValue;
        var combined = myClassAttributeValue + value;
    }
}
</code>```

How to achieve that?

Title: EF Core 7 - Class / Member Attributes

Body:
I have a class attribute which defines a value, then I have a Method attribute, which even defines a value.
Then I want to access the value of the class attribute from the method attribute.

[MyClassAttribute("SomethingClass")]
public class MyClass
{
    [MyMethodAttribute("SomethingMethod")]
    public void MyMethod() { }
}

Something like this should be done:

public class MyMethodAttribute : Attribute
{
    public MyMethodAttribute(params string value)
    {
        var myClassAttributeValue = PARENTCLASS.MyClassAttributeValue;
        var combined = myClassAttributeValue + value;
    }
}

How to achieve that?


问:
Why is the query time of my PostgreSQL DB (Postgis) so much slower than in my MySQL DB?
I've been testing the performance of my PGSQL DB and MySQL DB with around a million entries and I've come to the conclusion that MySQL seems to execute my queries much faster, but I feel it should be the other way around and that I'm missing something.

I was also trying the query with and without Postgis functions (for example ST_DistanceSphere), and the queries with Postgis functions were slower, which also suprises me since I'd assume that Postgis would be faster.

The queries I'm trying to optimize are for finding the distance between two points using longitude and latitude.

I've created an index for the geom (geometry) column in PGSQL because i thought that might improve the performance, but it still only performs sequential scans, even if the query returns only around 5-10% of the database entries.

Both DBs have the same data inside of them.
Below I've attached images of the queries and their time to execute and an explain analyze.

Query 1 PGSQL (Fastest, without using Postgis Functions)

```<code>WITH users_filtered AS (
SELECT id, pseudonym, city, (6371 * acos(
                cos( radians(users.latitude) )
              * cos( radians( 49.5099 ) )
              * cos( radians( 6.74549 ) - radians(users.longitude) )
              + sin( radians(users.latitude) )
              * sin( radians( 49.5099 ) )
        ) ) as distance_in_km
FROM users
)
SELECT * FROM users_filtered;

"Seq Scan on users  (cost=0.00..124501.90 rows=1029033 width=29) (actual time=0.032..932.905 rows=1030000 loops=1)"
"  Buffers: shared hit=80768"
"Planning:"
"  Buffers: shared hit=361"
"Planning Time: 1.697 ms"
"Execution Time: 984.460 ms"
</code>```

Query 2 PGSQL (Slowest, with Postgis functions)

```<code>WITH users_filtered AS (
SELECT id, pseudonym, city, ST_DistanceSphere(
    CAST(point(49.5099, 6.74549) AS geometry),
    users.geom
) AS distance_in_m
FROM users
)
SELECT * FROM users_filtered;

"Gather  (cost=1000.00..10909130.85 rows=1029033 width=29) (actual time=3.739..2583.961 rows=1030000 loops=1)"
"  Workers Planned: 2"
"  Workers Launched: 2"
"  Buffers: shared hit=81778"
"  ->  Parallel Seq Scan on users  (cost=0.00..10805227.55 rows=428764 width=29) (actual time=2.096..2147.072 rows=343333 loops=3)"
"        Buffers: shared hit=81778"
"Planning:"
"  Buffers: shared hit=19"
"Planning Time: 0.577 ms"
"Execution Time: 2696.416 ms"
</code>```

Query 3 PGSQL (Middle, with Postgis functions)

```<code>WITH users_filtered AS (
    SELECT id, pseudonym, city, ST_DistanceSphere(
        CAST(point(49.5099, 6.74549) AS geometry),
        users.geom
    ) AS distance_in_m
    FROM users
    WHERE ST_DWithin(users.geom, ST_SetSRID(ST_MakePoint(49.5099, 6.7454),4326), 200000)
)
SELECT * FROM users_filtered;

"Gather  (cost=1000.00..10806234.80 rows=103 width=29) (actual time=1.526..2071.394 rows=1030000 loops=1)"
"  Workers Planned: 2"
"  Workers Launched: 2"
"  Buffers: shared hit=81674"
"  ->  Parallel Seq Scan on users  (cost=0.00..10805224.50 rows=43 width=29) (actual time=1.336..1752.659 rows=343333 loops=3)"
"        Filter: st_dwithin(geom, '0101000020E61000007E1D386744C14840ECC039234AFB1A40'::geometry, '200000'::double precision)"
"        Buffers: shared hit=81674"
"Planning:"
"  Buffers: shared hit=23"
"Planning Time: 1.169 ms"
"Execution Time: 2161.133 ms"
</code>```

Query 1 MySQL (Fastest, this exact same query takes 4-5s in PGSQL)

```<code>SELECT id, pseudonym, city, ROUND(111.045 *
          degrees(acos(cos(radians(49.5099)) *
          cos(radians(users.latitude)) *
          cos(radians(6.74549) -
          radians(users.longitude)) +
          sin(radians(49.5099)) *
          sin(radians(users.latitude)
          )
        )
      )
    ) AS distance_in_km FROM users;

'-> Table scan on users  (cost=272574.70 rows=2515667) (actual time=0.121..1023.582 rows=1030000 loops=1)\n'
</code>```

Query 2 MySQL (Slowest, using ST_Distance_Sphere)

```<code>SELECT id, pseudonym, city, ST_Distance_Sphere(
    point(49.5099, 6.74549),
    point(users.latitude, users.longitude)
) AS distance_in_m FROM users;

'-> Table scan on users (cost=272574.70 rows=2515667) (actual time=0.096..1073.000 rows=1030000 loops=1)\n'
</code>```

Query 3 MySQL (Middle)

```<code>SELECT id, pseudonym, city, (6371 * acos(
                cos( radians(users.latitude) )
              * cos( radians( 49.5099 ) )
              * cos( radians( 6.74549 )
              - radians(users.longitude) )
              + sin( radians(users.latitude) )
              * sin( radians( 49.5099 ) )
        ) ) as distance_in_km
FROM users ORDER BY distance_in_km ASC;

'-> Sort: (6371 * acos((((cos(radians(users.latitude)) * cos(radians(49.5099))) * cos((radians(6.74549) - radians(users.longitude)))) + (sin(radians(users.latitude)) * sin(radians(49.5099))))))  (cost=272574.70 rows=2515667) (actual time=2142.974..2268.429 rows=1030000 loops=1)\n    -> Table scan on users  (cost=272574.70 rows=2515667) (actual time=0.141..1003.752 rows=1030000 loops=1)\n'
</code>```

Does anyone know why PGSQL seems to be so much slower than MySQL, and even more so with the usage of Postgis functions?
I'd appreciate if anyone could point me in the right direction.

Body:
I've been testing the performance of my PGSQL DB and MySQL DB with around a million entries and I've come to the conclusion that MySQL seems to execute my queries much faster, but I feel it should be the other way around and that I'm missing something.

I was also trying the query with and without Postgis functions (for example ST_DistanceSphere), and the queries with Postgis functions were slower, which also suprises me since I'd assume that Postgis would be faster.

The queries I'm trying to optimize are for finding the distance between two points using longitude and latitude.

I've created an index for the geom (geometry) column in PGSQL because i thought that might improve the performance, but it still only performs sequential scans, even if the query returns only around 5-10% of the database entries.

Both DBs have the same data inside of them.
Below I've attached images of the queries and their time to execute and an explain analyze.

Query 1 PGSQL (Fastest, without using Postgis Functions)

WITH users_filtered AS (
SELECT id, pseudonym, city, (6371 * acos(
                cos( radians(users.latitude) )
              * cos( radians( 49.5099 ) )
              * cos( radians( 6.74549 ) - radians(users.longitude) )
              + sin( radians(users.latitude) )
              * sin( radians( 49.5099 ) )
        ) ) as distance_in_km
FROM users
)
SELECT * FROM users_filtered;

"Seq Scan on users  (cost=0.00..124501.90 rows=1029033 width=29) (actual time=0.032..932.905 rows=1030000 loops=1)"
"  Buffers: shared hit=80768"
"Planning:"
"  Buffers: shared hit=361"
"Planning Time: 1.697 ms"
"Execution Time: 984.460 ms"

Query 2 PGSQL (Slowest, with Postgis functions)

WITH users_filtered AS (
SELECT id, pseudonym, city, ST_DistanceSphere(
    CAST(point(49.5099, 6.74549) AS geometry),
    users.geom
) AS distance_in_m
FROM users
)
SELECT * FROM users_filtered;

"Gather  (cost=1000.00..10909130.85 rows=1029033 width=29) (actual time=3.739..2583.961 rows=1030000 loops=1)"
"  Workers Planned: 2"
"  Workers Launched: 2"
"  Buffers: shared hit=81778"
"  ->  Parallel Seq Scan on users  (cost=0.00..10805227.55 rows=428764 width=29) (actual time=2.096..2147.072 rows=343333 loops=3)"
"        Buffers: shared hit=81778"
"Planning:"
"  Buffers: shared hit=19"
"Planning Time: 0.577 ms"
"Execution Time: 2696.416 ms"

Query 3 PGSQL (Middle, with Postgis functions)

WITH users_filtered AS (
    SELECT id, pseudonym, city, ST_DistanceSphere(
        CAST(point(49.5099, 6.74549) AS geometry),
        users.geom
    ) AS distance_in_m
    FROM users
    WHERE ST_DWithin(users.geom, ST_SetSRID(ST_MakePoint(49.5099, 6.7454),4326), 200000)
)
SELECT * FROM users_filtered;

"Gather  (cost=1000.00..10806234.80 rows=103 width=29) (actual time=1.526..2071.394 rows=1030000 loops=1)"
"  Workers Planned: 2"
"  Workers Launched: 2"
"  Buffers: shared hit=81674"
"  ->  Parallel Seq Scan on users  (cost=0.00..10805224.50 rows=43 width=29) (actual time=1.336..1752.659 rows=343333 loops=3)"
"        Filter: st_dwithin(geom, '0101000020E61000007E1D386744C14840ECC039234AFB1A40'::geometry, '200000'::double precision)"
"        Buffers: shared hit=81674"
"Planning:"
"  Buffers: shared hit=23"
"Planning Time: 1.169 ms"
"Execution Time: 2161.133 ms"

Query 1 MySQL (Fastest, this exact same query takes 4-5s in PGSQL)

SELECT id, pseudonym, city, ROUND(111.045 *
          degrees(acos(cos(radians(49.5099)) *
          cos(radians(users.latitude)) *
          cos(radians(6.74549) -
          radians(users.longitude)) +
          sin(radians(49.5099)) *
          sin(radians(users.latitude)
          )
        )
      )
    ) AS distance_in_km FROM users;

'-> Table scan on users  (cost=272574.70 rows=2515667) (actual time=0.121..1023.582 rows=1030000 loops=1)\n'

Query 2 MySQL (Slowest, using ST_Distance_Sphere)

SELECT id, pseudonym, city, ST_Distance_Sphere(
    point(49.5099, 6.74549),
    point(users.latitude, users.longitude)
) AS distance_in_m FROM users;

'-> Table scan on users (cost=272574.70 rows=2515667) (actual time=0.096..1073.000 rows=1030000 loops=1)\n'

Query 3 MySQL (Middle)

SELECT id, pseudonym, city, (6371 * acos(
                cos( radians(users.latitude) )
              * cos( radians( 49.5099 ) )
              * cos( radians( 6.74549 )
              - radians(users.longitude) )
              + sin( radians(users.latitude) )
              * sin( radians( 49.5099 ) )
        ) ) as distance_in_km
FROM users ORDER BY distance_in_km ASC;

'-> Sort: (6371 * acos((((cos(radians(users.latitude)) * cos(radians(49.5099))) * cos((radians(6.74549) - radians(users.longitude)))) + (sin(radians(users.latitude)) * sin(radians(49.5099))))))  (cost=272574.70 rows=2515667) (actual time=2142.974..2268.429 rows=1030000 loops=1)\n    -> Table scan on users  (cost=272574.70 rows=2515667) (actual time=0.141..1003.752 rows=1030000 loops=1)\n'

Does anyone know why PGSQL seems to be so much slower than MySQL, and even more so with the usage of Postgis functions?
I'd appreciate if anyone could point me in the right direction.


问:
Add automatic versioing in package.json file in react js project
Ii want to versioning of my react-js project
i.e  if any branch merge into my main branch then automatically in my package.json file ofthe  main branch version will update
i.e  prev -> 1.2.1
-after merging another branch into main branch-> 1.2.2

is there any way to do this

eg. i have one Main branch and package.json file have version 1.2.1

someone created a new branch form Main branch i.e test
-he raise pr  to merge into main branch  test->Main

after marging test branch I want to automatically change the package.json file version 1.2.2


问:
ERROR: role "test" does not exist - in PL/pgSQL code block
I am unable to think as to why this would fail. The block commands should work if it meets the condition?
On version 14.6</p>
```<code>postgres# DO
postgres# $do$
postgres# DECLARE
postgres#   lc_db_names CONSTANT text[] := array['dev3','dev2','dev1'];
postgres# BEGIN
postgres#   IF current_database() = any(lc_db_names)
postgres#   THEN
postgres#  IF NOT EXISTS (
postgres#    SELECT FROM pg_catalog.pg_roles WHERE  rolname = 'test') THEN
postgres#    create role test login encrypted password 'md5d2cdf586595c9e1ca7c7d7db3951f3fd';
postgres#    create schema authorization test;
postgres#    execute format('grant connect, temporary on database %I to %I', current_database(), 'test');
postgres#  END IF;
postgres#   END IF;
postgres# END
postgres# $do$
postgres# ;

ERROR:  role "test" does not exist
CONTEXT:  SQL statement "grant connect, temporary on database postgres to "test""
PL/pgSQL function inline_code_block line 11 at EXECUTE
</code>```

Body:
I am unable to think as to why this would fail. The block commands should work if it meets the condition?
On version 14.6

postgres# DO
postgres# $do$
postgres# DECLARE
postgres#   lc_db_names CONSTANT text[] := array['dev3','dev2','dev1'];
postgres# BEGIN
postgres#   IF current_database() = any(lc_db_names)
postgres#   THEN
postgres#  IF NOT EXISTS (
postgres#    SELECT FROM pg_catalog.pg_roles WHERE  rolname = 'test') THEN
postgres#    create role test login encrypted password 'md5d2cdf586595c9e1ca7c7d7db3951f3fd';
postgres#    create schema authorization test;
postgres#    execute format('grant connect, temporary on database %I to %I', current_database(), 'test');
postgres#  END IF;
postgres#   END IF;
postgres# END
postgres# $do$
postgres# ;

ERROR:  role "test" does not exist
CONTEXT:  SQL statement "grant connect, temporary on database postgres to "test""
PL/pgSQL function inline_code_block line 11 at EXECUTE


问:
Unable to create Appflow CDK using Python in AWS
, I am trying to deploy an Appflow CDK and get the following error:

Stack Deployments Failed: Error: The stack named cdk-l-appflow-12202022 failed to deploy: UPDATE_ROLLBACK_COMPLETE: Resource handler returned message: "Unable to retrieve secrets for secret Id : arn:aws:secretsmanager:us-east-1:588799296974:secret:vipsfsecret-66dxxqk0BGck-sPRzQs due to access denied. Please ensure that AppFlow has access on secrets manager resource and KMS key used for encryption. (Service: Appflow, Status Code: 403, Request ID: 9aa02dee-db8c-46db-b495-8cb1392f510e)" (RequestToken: 47e0f482-6cd5-c7e6-1121-e107963c82e6, HandlerErrorCode: GeneralServiceException)

The appflow authentication secrets are in Secrets Manager. I have perimissioned it as such:
{
"Version" : "2012-10-17",
"Statement" : [ {
"Effect" : "Allow",
"Principal" : {
"Service" : "secretsmanager.amazonaws.com"
},
"Action" : [ "secretsmanager:GetResourcePolicy", "secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret", "secretsmanager:ListSecretVersionIds", "secretsmanager:ListSecrets" ],
"Resource" : "*"
} ]
}

Does anyone have thoughts/suggestions please?

Tried creating a new KMS and provided Key policy at teamrole level. So permissions including kms:decrypt are given.


问:
node-telegram-bot-api callback_query fires multiply
i`m trying to make telegram bot and dont understand why it works so.
I have three js files index, quiz_creation, question_creation
here is content index.js

```<code>const createQuiz = require('./quiz_creation');
bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  const options = {
    reply_markup: {
        inline_keyboard: [
            [{ text: 'Create Quiz!', callback_data: 'create' }],
            [{ text: 'Start Quiz', callback_data: 'start' }],
        ]
    }
  };
  bot.sendMessage(chatId, 'Welcome to the quizzzo bot!', options);
});

bot.on('callback_query', (query) => {
  const chatId = query.message.chat.id;
  const data = query.data;

  if (data === 'create') {
    createQuiz(bot, chatId);
  } else if (data === 'start') {
    //startQuiz(bot, chatId);
  }
});
</code>```

quiz_creation.js:

```<code>const createQuestion = require('./question_creation');

const createQuiz = (bot, chatId) => {
  bot.sendMessage(chatId, 'What do you want to create?',{
    reply_markup: {
      inline_keyboard: [
        [{ text: 'By Date', callback_data: 'create_date' }],
        [{ text: 'By Number of Users', callback_data: 'create_users' }],
      ]
    }
  });

  bot.on('callback_query', (query) => {
    const chatId = query.message.chat.id;
    const data = query.data;
    bot.answerCallbackQuery(query.id)

    if (data === 'create_date') {

    } else if (data === 'create_users') {
          const message = 'Please send me the number of users for the quiz';
        bot.sendMessage(chatId, message, {reply_markup: {force_reply: true}}).then((msg) => {
          bot.onReplyToMessage(msg.chat.id, msg.message_id, (message) => {
            const number = Number(message.text);
            if (!Number.isNaN(number)) {
              bot.sendMessage(chatId, `Quiz will have ${number} users`);
                      createQuestion(bot, chatId);

            } else {
              bot.sendMessage(chatId, 'Invalid number format, please send a number');
            }
          });
        });
    } else if (data === 'question_one_from_some' || data === 'question_text_answer') {
    }

  });
};

module.exports = createQuiz;
</code>```

and question_creation.js

```<code>const createQuestion = (bot, chatId) => {
    bot.on('callback_query', (query) => {

        const chatId = query.message.chat.id;
        const questionType = query.data;
        bot.answerCallbackQuery(query.id)
        if (questionType === 'question_one_from_some') {
            bot.sendMessage(chatId, 'Please send me the question', {reply_markup: {force_reply: true}}).then((msg) => {

            });
        } else if (questionType === 'question_text_answer') {

        }

      })
};

module.exports = createQuestion;
</code>```

After first run messages from bot send twice and more more more...
I understand that it happens cause bot.on fires for every time i press inline button
but how to fix it?
I tried remove listener for callback query but then inline buttons stop working at all

Body:
i`m trying to make telegram bot and dont understand why it works so.
I have three js files index, quiz_creation, question_creation
here is content index.js

const createQuiz = require('./quiz_creation');
bot.onText(/\/start/, (msg) => {
  const chatId = msg.chat.id;
  const options = {
    reply_markup: {
        inline_keyboard: [
            [{ text: 'Create Quiz!', callback_data: 'create' }],
            [{ text: 'Start Quiz', callback_data: 'start' }],
        ]
    }
  };
  bot.sendMessage(chatId, 'Welcome to the quizzzo bot!', options);
});

bot.on('callback_query', (query) => {
  const chatId = query.message.chat.id;
  const data = query.data;

  if (data === 'create') {
    createQuiz(bot, chatId);
  } else if (data === 'start') {
    //startQuiz(bot, chatId);
  }
});

quiz_creation.js:

const createQuestion = require('./question_creation');

const createQuiz = (bot, chatId) => {
  bot.sendMessage(chatId, 'What do you want to create?',{
    reply_markup: {
      inline_keyboard: [
        [{ text: 'By Date', callback_data: 'create_date' }],
        [{ text: 'By Number of Users', callback_data: 'create_users' }],
      ]
    }
  });

  bot.on('callback_query', (query) => {
    const chatId = query.message.chat.id;
    const data = query.data;
    bot.answerCallbackQuery(query.id)

    if (data === 'create_date') {

    } else if (data === 'create_users') {
          const message = 'Please send me the number of users for the quiz';
        bot.sendMessage(chatId, message, {reply_markup: {force_reply: true}}).then((msg) => {
          bot.onReplyToMessage(msg.chat.id, msg.message_id, (message) => {
            const number = Number(message.text);
            if (!Number.isNaN(number)) {
              bot.sendMessage(chatId, `Quiz will have ${number} users`);
                      createQuestion(bot, chatId);

            } else {
              bot.sendMessage(chatId, 'Invalid number format, please send a number');
            }
          });
        });
    } else if (data === 'question_one_from_some' || data === 'question_text_answer') {
    }

  });
};

module.exports = createQuiz;

and question_creation.js

const createQuestion = (bot, chatId) => {
    bot.on('callback_query', (query) => {

        const chatId = query.message.chat.id;
        const questionType = query.data;
        bot.answerCallbackQuery(query.id)
        if (questionType === 'question_one_from_some') {
            bot.sendMessage(chatId, 'Please send me the question', {reply_markup: {force_reply: true}}).then((msg) => {

            });
        } else if (questionType === 'question_text_answer') {

        }

      })
};

module.exports = createQuestion;

After first run messages from bot send twice and more more more...
I understand that it happens cause bot.on fires for every time i press inline button
but how to fix it?
I tried remove listener for callback query but then inline buttons stop working at all


问:
many re-renders. React limits the number of renders to prevent an infinite loop
Why does one of the following code snippet always triggers this error (many re-renders. React limits the number of renders to prevent an infinite loop) but the other don't.

This code works fine

```<code>const Admin = () => {
  const { adminId } = useParams();
  const navigate = useNavigate();

  let studentEnglishResults: { [key: string]: string } = {};
  let englishResults: string[] = [];

  if (localStorage.length > 0) {

    studentEnglishResults = JSON.parse(
      localStorage.getItem("englishAnswers") as string
    );
    englishResults = Object.keys(studentEnglishResults);
      } else {
  }

  const adminUser = adminUsers.find(
    (adminUser) => adminUser.adminId === adminId
  );

  useEffect(() => {
    if (adminUser?.adminId !== adminId) {
      navigate("/");
    }
  }, []);

  const clearResult = () => {
    localStorage.clear();
  };

  const backToLogin = () => {
    navigate("/");
  };

  return (
    <>
      <div className="bg-gray-400 mx-auto w-3/4 p-3 mt-5">
        <p className="capitalize font-serif">
          <span className="font-bold">Admin</span>
        </p>
      </div>
      <div className="my-10 flex justify-center gap-3 text-white">
        <button
          type="button"
          className="btn bg-green-500"
          onClick={clearResult}
        >
          Generate Results
        </button>

        <button type="button" className="btn bg-red-600" onClick={clearResult}>
          Clear Results
        </button>

        <button type="button" className="btn bg-blue-500" onClick={backToLogin}>
          Login
        </button>
      </div>

      <div className="shadow-md shadow-gray-500 w-2/4 mx-auto p-5">
        <p className="text-2xl text-gray-500">
          Answers Selected by the Student
        </p>
        <table className="table-auto border-collapse border w-full">
          <thead>
            <tr>
              <th className="text-left">Question</th>
              <th className="text-left">Answer</th>
            </tr>
          </thead>
          <tbody>
            {englishResults.map((item, index) => {
              return (
                <tr key={index}>
                  <td className="">{item}</td>
                  <td>{studentEnglishResults[item]}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

export default Admin;
</code>```

But this always triggers error (many re-renders. React limits the number of renders to prevent an infinite loop).

```<code>  const Admin = () => {
  const { adminId } = useParams();
  const navigate = useNavigate();

  const [results, setResults] = useState(false);
  const [studentEnglishResults, setStudentEnglishResults] = useState<{
  [key: string]: string;
  }>({});
  const [englishResults, setEnglishResults] = useState<string[]>([]);

  if (localStorage.length > 0) {
setResult(true)
    setStudentResults(JSON.parse(
      localStorage.getItem("englishAnswers") as string
    );
setEnglishResults(Object.keys(studentEnglishResults));

  } else {
setResult(false)
  }

  const adminUser = adminUsers.find(
    (adminUser) => adminUser.adminId === adminId
  );

  useEffect(() => {
    if (adminUser?.adminId !== adminId) {
      navigate("/");
    }
  }, []);

  const clearResult = () => {
    localStorage.clear();
  };

  const backToLogin = () => {
    navigate("/");
  };

  return (
    <>
      <div className="bg-gray-400 mx-auto w-3/4 p-3 mt-5">
        <p className="capitalize font-serif">
          <span className="font-bold">Admin</span>
        </p>
      </div>
      <div className="my-10 flex justify-center gap-3 text-white">
        <button
          type="button"
          className="btn bg-green-500"
          onClick={clearResult}
        >
          Generate Results
        </button>

        <button type="button" className="btn bg-red-600" onClick={clearResult}>
          Clear Results
        </button>

        <button type="button" className="btn bg-blue-500" onClick={backToLogin}>
          Login
        </button>
      </div>

      <div className="shadow-md shadow-gray-500 w-2/4 mx-auto p-5">
        <p className="text-2xl text-gray-500">
          Answers Selected by the Student
        </p>
        <table className="table-auto border-collapse border w-full">
          <thead>
            <tr>
              <th className="text-left">Question</th>
              <th className="text-left">Answer</th>
            </tr>
          </thead>
          <tbody>
            {englishResults.map((item, index) => {
              return (
                <tr key={index}>
                  <td className="">{item}</td>
                  <td>{studentEnglishResults[item]}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

export default Admin;
</code>```

The difference is the second snippet used useState hook to set the values while the first uses normal variable.

Does this mean using useState to set values is a bad idea. I heard it was encouraged to always use useState to set variables. How do I avoid this error then?

Than you.

Body:
Why does one of the following code snippet always triggers this error (many re-renders. React limits the number of renders to prevent an infinite loop) but the other don't.

This code works fine

const Admin = () => {
  const { adminId } = useParams();
  const navigate = useNavigate();

  let studentEnglishResults: { [key: string]: string } = {};
  let englishResults: string[] = [];

  if (localStorage.length > 0) {

    studentEnglishResults = JSON.parse(
      localStorage.getItem("englishAnswers") as string
    );
    englishResults = Object.keys(studentEnglishResults);
      } else {
  }

  const adminUser = adminUsers.find(
    (adminUser) => adminUser.adminId === adminId
  );

  useEffect(() => {
    if (adminUser?.adminId !== adminId) {
      navigate("/");
    }
  }, []);

  const clearResult = () => {
    localStorage.clear();
  };

  const backToLogin = () => {
    navigate("/");
  };

  return (
    <>

          Admin

        <button
          type="button"
          className="btn bg-green-500"
          onClick={clearResult}
        >
          Generate Results
        </button>

        <button type="button" className="btn bg-red-600" onClick={clearResult}>
          Clear Results
        </button>

        <button type="button" className="btn bg-blue-500" onClick={backToLogin}>
          Login
        </button>

          Answers Selected by the Student

              Question
              Answer

            {englishResults.map((item, index) => {
              return (

                  {item}
                  {studentEnglishResults[item]}

              );
            })}

    </>
  );
};

export default Admin;

But this always triggers error (many re-renders. React limits the number of renders to prevent an infinite loop).

  const Admin = () => {
  const { adminId } = useParams();
  const navigate = useNavigate();

  const [results, setResults] = useState(false);
  const [studentEnglishResults, setStudentEnglishResults] = useState<{
  [key: string]: string;
  }>({});
  const [englishResults, setEnglishResults] = useState<string[]>([]);

  if (localStorage.length > 0) {
setResult(true)
    setStudentResults(JSON.parse(
      localStorage.getItem("englishAnswers") as string
    );
setEnglishResults(Object.keys(studentEnglishResults));

  } else {
setResult(false)
  }

  const adminUser = adminUsers.find(
    (adminUser) => adminUser.adminId === adminId
  );

  useEffect(() => {
    if (adminUser?.adminId !== adminId) {
      navigate("/");
    }
  }, []);

  const clearResult = () => {
    localStorage.clear();
  };

  const backToLogin = () => {
    navigate("/");
  };

  return (
    <>

          Admin

        <button
          type="button"
          className="btn bg-green-500"
          onClick={clearResult}
        >
          Generate Results
        </button>

        <button type="button" className="btn bg-red-600" onClick={clearResult}>
          Clear Results
        </button>

        <button type="button" className="btn bg-blue-500" onClick={backToLogin}>
          Login
        </button>

          Answers Selected by the Student

              Question
              Answer

            {englishResults.map((item, index) => {
              return (

                  {item}
                  {studentEnglishResults[item]}

              );
            })}

    </>
  );
};

export default Admin;

The difference is the second snippet used useState hook to set the values while the first uses normal variable.

Does this mean using useState to set values is a bad idea. I heard it was encouraged to always use useState to set variables. How do I avoid this error then?

Than you.


问:
Apache Solr 5.4 version Log4j upgrade from 1.x to 2.18.0 version
I need to upgrade log4j 1.x to log4j 2.18.0 in my project which is using Apache Solr 5.4.0 which is internally using log4j 1.2.17 and other slf4j dependencies, when I am excluding it from pom it is giving exception of accessing Level class internally, therefore, the exclusion will not work it seems, I tried exploring and found this Upgrade Apache Solr 8.10.1 log4j 2.14.1 version to 2.15 to address critical vulnerability
but it seems this is for solr 8.1 or later which already using log4j2, so please help me in getting log4j upgrade in my project which is using solr 5.4.

Any help would be greatly appreciated.

Thanks


问:
Using springdoc-openapi in combination with openapi-generator-maven-plugin
Our REST API is documented using OpenAPI V3. Documentation annotations are used in the controllers which generate an OpenAPI specification which is displayed using a Swagger UI page. Recently we switched to developing endpoints by writing the specification first. The OpenAPI V3 specification isn't generated but written by hand and used to generate interfaces for the controllers and to generate the data transfer objects. The generated classes are available in the REST API project through a dependency. However, while the generated classes are annotated with the same documentation annotations as the 'old' controllers they don't show up in the Swagger UI documentation page. Not even when the dependency package is scanned explicitly using the springdoc.packages-to-scan option.

Is the springdoc-openapi-ui dependency not able to recognize and display documentation from annotations that are in classes in a dependency?

springdoc-openapi-ui version 1.6.14 and openapi-generator-maven-plugin version 6.2.1 are used as the project runs Java 11. My understanding is that the latest version of Springdoc, springdoc-openapi-ui version 1.6.14, uses/requires Spring Boot 3 which in turn requires Java 17 or higher.


问:
Can I access the SHA hash of an imported JS through the Subresource Integrity or some other source?
I have a library that is imported like this...

```<code> <script src="..."
            integrity="..."
            crossorigin="anonymous"></script>
</code>```

For some reason I still do not fully understand some developers I work with would like access to the hash to make some conditionals. So I have laid my skepticism aside and am looking for a solution to grab it. It would also be nice to be able to generate a hash for a script tag that does not include the integrity already. I assume I can use DOM to access the attribute so the last example is more my real question.

How do I calculate the SHA hash on the browser of the JS file I am using?

Body:
I have a library that is imported like this...

For some reason I still do not fully understand some developers I work with would like access to the hash to make some conditionals. So I have laid my skepticism aside and am looking for a solution to grab it. It would also be nice to be able to generate a hash for a script tag that does not include the integrity already. I assume I can use DOM to access the attribute so the last example is more my real question.

How do I calculate the SHA hash on the browser of the JS file I am using?


问:
SwiftUI Background Processing via BT device
I need to have a functionality that, even after the application goes to the background, processes the application and every equal time (let's assume every one second) sends information to the device connected via BT.

At this point, I would need to create a Timer that prints text every X seconds when the app is in the background.

Is something like this possible in iOS15 and SwiftUI?


问:
r.json() converts the data to native python datatypes and json.dumps() converts to str
I have been coping with an issue since yesterday. In my code I have to extract the data from a system with requests module of python and load that data to snowflake so that someone else from the company can connect the PowerBI to snowflake and use the data for reporting. Previously it was direct connection to the source system but now the data is increased in the source so it takes a lot of time to load that data so that's why loading data to our company's snowflake storage.

I'm having an issue with the requests module in python. I get the data from source. but there is some data which needs to be in proper json format (in double quotes). I have attached a sample data from the response.

resp = requests.get(url, authorization) data = resp.content
this above code returns the data into bytes format.

resp = requests.get(url, authorization) data = resp.json()
this code returns the data into the native format of the python's data types. I make dataframe with this data and this data to snowflake and connect with the powerbi, it gives the json format error because on snowflake data goes with single quotes. which is not a correct JSON format for powerbi.

I have also tried
data = json.dumps(data)
it converts the data to "" quotes but it converts the data to str, and if somehow I convert the data back to dictionary and lists with

eval(data)
it is again in single quotes.

Follwoing is the data set attached.

'data': [{
'name': 'alvin',
'age' : '20',
'addresses':[{ 'house' : '187',
'street' : 'lindsly',
'city' : 'abc',
'country' : 'netherlands'}],
'communications': [{ 'signaling' : True,
'confirm' : False,
'phone' : '0123456'},
{ 'signaling' : True,
'confirm' : True,
'phone' : '0945785'}
}],
'careDegree': 'NO',
'dob': '1911-11-01T09:00:00.000Z',
partnerIds': [{'asvTeamNumbers': [],
'onlineTherapyContract': [],
'_id': '6e31c',
'patientId': 'ZXWB8',
'extra': 'ID'}],
}]

total datasize is almost 13000 rows. Or if there is anyway I can flatten this data into columns without going into to too much time consumptions.

I tried apply() functions for flattening the data but then I don't see anything based on which I should merge the data frames.

```<code>pd.json_normalize(data['data'], record_path=["partnerIds"] , max_level =None).head()

</code>```

Body:
I have been coping with an issue since yesterday. In my code I have to extract the data from a system with requests module of python and load that data to snowflake so that someone else from the company can connect the PowerBI to snowflake and use the data for reporting. Previously it was direct connection to the source system but now the data is increased in the source so it takes a lot of time to load that data so that's why loading data to our company's snowflake storage.

I'm having an issue with the requests module in python. I get the data from source. but there is some data which needs to be in proper json format (in double quotes). I have attached a sample data from the response.

resp = requests.get(url, authorization) data = resp.content
this above code returns the data into bytes format.

resp = requests.get(url, authorization) data = resp.json()
this code returns the data into the native format of the python's data types. I make dataframe with this data and this data to snowflake and connect with the powerbi, it gives the json format error because on snowflake data goes with single quotes. which is not a correct JSON format for powerbi.

I have also tried
data = json.dumps(data)
it converts the data to "" quotes but it converts the data to str, and if somehow I convert the data back to dictionary and lists with

eval(data)
it is again in single quotes.

Follwoing is the data set attached.

'data': [{
'name': 'alvin',
'age' : '20',
'addresses':[{ 'house' : '187',
'street' : 'lindsly',
'city' : 'abc',
'country' : 'netherlands'}],
'communications': [{ 'signaling' : True,
'confirm' : False,
'phone' : '0123456'},
{ 'signaling' : True,
'confirm' : True,
'phone' : '0945785'}
}],
'careDegree': 'NO',
'dob': '1911-11-01T09:00:00.000Z',
partnerIds': [{'asvTeamNumbers': [],
'onlineTherapyContract': [],
'_id': '6e31c',
'patientId': 'ZXWB8',
'extra': 'ID'}],
}]

total datasize is almost 13000 rows. Or if there is anyway I can flatten this data into columns without going into to too much time consumptions.

I tried apply() functions for flattening the data but then I don't see anything based on which I should merge the data frames.

pd.json_normalize(data['data'], record_path=["partnerIds"] , max_level =None).head()


问:
Decode Json Data in Kotlin and pass it in Socket emit event
I want to decode JSON data

from :->

{"receiver_id":"193","signal_data":{},"sender_id":"192","call_to":"null"}

to like this:->

{receiver_id:193,signal_data:{},sender_id:192,call_to:null}

how can I do this in android does anybody know?

I tried JsonParser. but it doesn't work


问:
Ionic capacitor google maps appears over WebView on IOS
Integrated @capacitor/google-maps plugin in an Ionic capacitor application. Plugin is working fine when running the application in browser or in android. But in iOS ionic header is not visible as the plugin renders the map over the WebView.</p>
```<code><ion-content [fullscreen]="true">
  <ion-toolbar class="tool" slot="fixed">
    <ion-icon
      class="back"
      name="arrow-back-circle"
      (click)="handleDismissMap()"
    ></ion-icon>
    <ion-button
      slot="end"
      shape="round"
      class="action-button"
      (click)="handleSaveLocation()"
    >
      <ion-icon slot="start" name="location-outline"></ion-icon>
      Save Location
    </ion-button>
  </ion-toolbar>
  <div id="container">
    <capacitor-google-maps id="map" #map></capacitor-google-maps>
  </div>
</ion-content>
</code>```
```<code>ion-content {
  --background: none;
}

body {
  background: none;
}

#container {
  width: 100%;
  height: 100%;
}

capacitor-google-maps {
  width: 100%;
  height: 100%;
  display: inline-block;
}

ion-toolbar.tool {
  padding: 1rem;
  --background: transparent;

  ion-icon.back {
    color: #fff;
    font-size: 40px;
    margin: 0.4rem 1rem 0 0;
  }

  ion-button.action-button {
    color: #1d4370 !important;
    --color: #1d4370 !important;
    --background: #fff !important;
    font-family: "Gothom Medium" !important;
    ion-icon {
      color: #1d4370 !important;
    }
  }
}
</code>```

Body:
Integrated @capacitor/google-maps plugin in an Ionic capacitor application. Plugin is working fine when running the application in browser or in android. But in iOS ionic header is not visible as the plugin renders the map over the WebView.

<ion-content [fullscreen]="true">
  <ion-toolbar class="tool" slot="fixed">
    <ion-icon
      class="back"
      name="arrow-back-circle"
      (click)="handleDismissMap()"
    ></ion-icon>
    <ion-button
      slot="end"
      shape="round"
      class="action-button"
      (click)="handleSaveLocation()"
    >
      <ion-icon slot="start" name="location-outline"></ion-icon>
      Save Location
    </ion-button>
  </ion-toolbar>

    <capacitor-google-maps id="map" #map></capacitor-google-maps>

</ion-content>

ion-content {
  --background: none;
}

body {
  background: none;
}

#container {
  width: 100%;
  height: 100%;
}

capacitor-google-maps {
  width: 100%;
  height: 100%;
  display: inline-block;
}

ion-toolbar.tool {
  padding: 1rem;
  --background: transparent;

  ion-icon.back {
    color: #fff;
    font-size: 40px;
    margin: 0.4rem 1rem 0 0;
  }

  ion-button.action-button {
    color: #1d4370 !important;
    --color: #1d4370 !important;
    --background: #fff !important;
    font-family: "Gothom Medium" !important;
    ion-icon {
      color: #1d4370 !important;
    }
  }
}


问:
How to simultaneously use SQL-Server and MYSQL databases in Laravel
I use 2 databases in my Laravel project. One is MySQL and the other is SQL Server. My main database is MySQL.

I can use these databases individually, but if I want to join and use one of them in a query, I will face a problem.

This is my code

```<code> $list=DB::connection('mysql')->select('
 SELECT
                pp.mahsool_cod as planed_code,
                SUM(pp.meghdar) as plan_quantity,
                COUNT(*) as planed_count,
                (SELECT SUM(tolid_reports.real_meghdar)
                    FROM tolid_reports WHERE tolid_reports.plan_tolid_date BETWEEN N\''.$head->date2.'\' and N\''.$head->date4.'\'
                    and tolid_reports.plan_cod= planed_code ) as tolid_quantity,
                    (N\''.DB::connection('sqlsrv')->select('select p.Name from farsi.LGS3.Part as p where p.Code =planed_code ').'\') as namee
                FROM pr_planings AS pp
                where pp.tolid_date BETWEEN N\''.$head->date2.'\' and N\''.$head->date4.'\' GROUP by pp.mahsool_cod
  ');
</code>```

I can't to use the second database in the other database subquery

Body:
I use 2 databases in my Laravel project. One is MySQL and the other is SQL Server. My main database is MySQL.

I can use these databases individually, but if I want to join and use one of them in a query, I will face a problem.

This is my code

 $list=DB::connection('mysql')->select('
 SELECT
                pp.mahsool_cod as planed_code,
                SUM(pp.meghdar) as plan_quantity,
                COUNT(*) as planed_count,
                (SELECT SUM(tolid_reports.real_meghdar)
                    FROM tolid_reports WHERE tolid_reports.plan_tolid_date BETWEEN N\''.$head->date2.'\' and N\''.$head->date4.'\'
                    and tolid_reports.plan_cod= planed_code ) as tolid_quantity,
                    (N\''.DB::connection('sqlsrv')->select('select p.Name from farsi.LGS3.Part as p where p.Code =planed_code ').'\') as namee
                FROM pr_planings AS pp
                where pp.tolid_date BETWEEN N\''.$head->date2.'\' and N\''.$head->date4.'\' GROUP by pp.mahsool_cod
  ');

I can't to use the second database in the other database subquery


问:
How to filter an object with ManyToMany field?
I'm building a view where I add a product to a cart. To do this I create an instance of a CartItem model which is related to a cart, a product and has variations (color, size...).

When the instance of CartItem is created I want to check if it already exists to know if I need to increment its stock or create a new one. So I first check for one with the same cart and product (ok so far). But then I don't know how to check if one that has the same variations exists (which is a ManytoMany field).

the view:

```<code>def add_to_cart(request, product_id):

    product = Product.objects.get(id = product_id)
    variation_list = []
    if request.method == "POST":
        print(request.POST)
        for item in request.POST:
            key = item
            value = request.POST[key]
            try:
                variation = Variation.objects.get(product = product, variation_category__iexact = key, variation_value__iexact = value)
                variation_list.append(variation)
            except:
                pass
        print(variation_list)

    try:
        cart = Cart.objects.get(cart_id=_get_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(cart_id=_get_cart_id(request))
        cart.save()

    try:
        cart_item = CartItem.objects.get(product=product,cart=cart)

        # How to filter cart_item so I know if it matches with variation_list

        cart_item.product_quantity +=1
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(product=product,cart=cart)
        cart_item.save()
        for variation in variation_list:
            cart_item.variation_list.add(variation)
    return redirect('cart')
</code>```

the Product model:

```<code>class Product(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=250, blank=True)
    description = models.TextField(blank=True)
    price = models.IntegerField()
    image = models.ImageField(upload_to='media/products')
    stock = models.IntegerField()
    is_available = models.BooleanField(default=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def get_url(self):
        return reverse("product_slug", args=[self.category.slug,self.slug])

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)
</code>```

the Variation model:

```<code>class Variation(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    variation_category = models.CharField(max_length=100, choices=variation_category_choices)
    variation_value = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.product.name} {self.variation_category} {self.variation_value}'
</code>```

and the CartItem model:

```<code>class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart= models.ForeignKey(Cart, on_delete=models.CASCADE)
    product_quantity = models.IntegerField(default=1)
    is_active = models.BooleanField(default=True)
    variation_list = models.ManyToManyField(Variation, blank=True)

    def str(self):
        return self.product.name

    @property
    def total_price(self):
        return self.product_quantity * self.product.price
</code>```

Thanks!

I tried to somehow loop trough CartItem__variation_list and compare it to the variation_list from the request.POST but obviously it didn't work...

Body:
I'm building a view where I add a product to a cart. To do this I create an instance of a CartItem model which is related to a cart, a product and has variations (color, size...).

When the instance of CartItem is created I want to check if it already exists to know if I need to increment its stock or create a new one. So I first check for one with the same cart and product (ok so far). But then I don't know how to check if one that has the same variations exists (which is a ManytoMany field).

the view:

def add_to_cart(request, product_id):

    product = Product.objects.get(id = product_id)
    variation_list = []
    if request.method == "POST":
        print(request.POST)
        for item in request.POST:
            key = item
            value = request.POST[key]
            try:
                variation = Variation.objects.get(product = product, variation_category__iexact = key, variation_value__iexact = value)
                variation_list.append(variation)
            except:
                pass
        print(variation_list)

    try:
        cart = Cart.objects.get(cart_id=_get_cart_id(request))
    except Cart.DoesNotExist:
        cart = Cart.objects.create(cart_id=_get_cart_id(request))
        cart.save()

    try:
        cart_item = CartItem.objects.get(product=product,cart=cart)

        # How to filter cart_item so I know if it matches with variation_list

        cart_item.product_quantity +=1
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(product=product,cart=cart)
        cart_item.save()
        for variation in variation_list:
            cart_item.variation_list.add(variation)
    return redirect('cart')

the Product model:

class Product(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=250, blank=True)
    description = models.TextField(blank=True)
    price = models.IntegerField()
    image = models.ImageField(upload_to='media/products')
    stock = models.IntegerField()
    is_available = models.BooleanField(default=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def get_url(self):
        return reverse("product_slug", args=[self.category.slug,self.slug])

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)

the Variation model:

class Variation(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    variation_category = models.CharField(max_length=100, choices=variation_category_choices)
    variation_value = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.product.name} {self.variation_category} {self.variation_value}'

and the CartItem model:

class CartItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    cart= models.ForeignKey(Cart, on_delete=models.CASCADE)
    product_quantity = models.IntegerField(default=1)
    is_active = models.BooleanField(default=True)
    variation_list = models.ManyToManyField(Variation, blank=True)

    def str(self):
        return self.product.name

    @property
    def total_price(self):
        return self.product_quantity * self.product.price

Thanks!

I tried to somehow loop trough CartItem__variation_list and compare it to the variation_list from the request.POST but obviously it didn't work...


问:
Manually create spring cloud stream bindings based on dynamic configuration
I have a requirement where one or more spring cloud stream kafka-streams bindings need to be created based on dynamic configuration. By dynamic config I mean stream bindings (input-output) will be specified run-time. Either via external property file or from database.

E.g We need to create multiple stream processors where input output topic pairs and relevant configs are provided. Then code should loop through this config create and start those bindings.

In spring cloud stream we write this in a java file

```<code>@StreamListener(StreamBindings.INPUT)
@SendTo(StreamBindings.OUTPUT)
public KStream<String,String> process(KStream<String,String> inputStream) {
    return inputStream
     .map( ... )
     .selectKey( ... )
     .mapValues( ... );
}
</code>```

Where StreamBindings is like

```<code>public interface StreamBindings {
    String INPUT = "input-topic";
    String OUTPUT = "output-topic";

    @Input(INPUT)
    KStream<String,String> inputStream();
    @Input(OUTPUT)
    KStream<String,String> outputStream();
}
</code>```

Now I want a piece of code to create this in run-time based on info I specified above.
Can this be done and how? And can we specify body of process function as an argument, like some kind of message handler?

Body:
I have a requirement where one or more spring cloud stream kafka-streams bindings need to be created based on dynamic configuration. By dynamic config I mean stream bindings (input-output) will be specified run-time. Either via external property file or from database.

E.g We need to create multiple stream processors where input output topic pairs and relevant configs are provided. Then code should loop through this config create and start those bindings.

In spring cloud stream we write this in a java file

@StreamListener(StreamBindings.INPUT)
@SendTo(StreamBindings.OUTPUT)
public KStream<String,String> process(KStream<String,String> inputStream) {
    return inputStream
     .map( ... )
     .selectKey( ... )
     .mapValues( ... );
}

Where StreamBindings is like

public interface StreamBindings {
    String INPUT = "input-topic";
    String OUTPUT = "output-topic";

    @Input(INPUT)
    KStream<String,String> inputStream();
    @Input(OUTPUT)
    KStream<String,String> outputStream();
}

Now I want a piece of code to create this in run-time based on info I specified above.
Can this be done and how? And can we specify body of process function as an argument, like some kind of message handler?


问:
Visual Studio Code - .clang-format *.C files
How do I setup clang-format to grab *.c files on save in VS Code, using "Microsoft C/C++ Extension"?

I want the formatting to automatically happen when I press Ctrl+S. Formatting of *.cpp files works fine.

Workaround I figured out is to add a file association in my settings.json file, making C files pretend to be C++.

"files.associations": {
    "*.c": "cpp",
    ...
}
```

I am not sure, however, what does this break in the background...

Thanks

Body:
How do I setup clang-format to grab *.c files on save in VS Code, using "Microsoft C/C++ Extension"?

I want the formatting to automatically happen when I press Ctrl+S. Formatting of *.cpp files works fine.

Workaround I figured out is to add a file association in my settings.json file, making C files pretend to be C++.

"files.associations": {
    "*.c": "cpp",
    ...
}

I am not sure, however, what does this break in the background...

Thanks


问:
OPENCV LNK 2001 Error: "unresolved external symbol" while adding to/modifying OPENCV source files
I need  to modfiy some OPENCV  source files (VS 2019, C++) but get this error.
I have  OpenCV version 4.6. which is  installed with CMAKE and it  works  well untill I try  to add a  new function in source files.
More precilsely,  I have  performed the  following

I have  modified source feature2d.cpp  by adding the following test function

```<code>void mynewtest()
{
    std::cout<<" this is  opencv";
}
</code>```

Added  in source features2d.hpp  the following

```<code>void  mynewtest();
</code>```

Then I build ALL_BUILD  and build INSTALL using OpenCV.sln in build folder

Next, I have tried to run the following standard code, which gives LNK 2001 Error

```<code>#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <iostream>

using namespace cv;
int main()
{
    mynewtest(); //--- ADDED FUNCTION

    //-----------------------------------------------------------;
    std::string image_path = samples::findFile("starry_night.jpg");
    Mat img = imread(image_path, IMREAD_COLOR);
    if (img.empty())
    {
        std::cout << "Could not read the image: " << image_path << std::endl;
        return 1;
    }
    imshow("Display window", img);
    int k = waitKey(0); // Wait for a keystroke in the window
    if (k == 's')
    {
        imwrite("starry_night.png", img);
    }
    return 0;
}

</code>```

If I comment  mynewtest(); then  the code starts normally.
As I  understand  smth  is with  linking lib libriries but  all the libs are linked well

have tried to re-build opencv using cmake

Body:
I need  to modfiy some OPENCV  source files (VS 2019, C++) but get this error.
I have  OpenCV version 4.6. which is  installed with CMAKE and it  works  well untill I try  to add a  new function in source files.
More precilsely,  I have  performed the  following

I have  modified source feature2d.cpp  by adding the following test function

void mynewtest()
{
    std::cout<<" this is  opencv";
}

Added  in source features2d.hpp  the following

void  mynewtest();

Then I build ALL_BUILD  and build INSTALL using OpenCV.sln in build folder

Next, I have tried to run the following standard code, which gives LNK 2001 Error

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include <iostream>

using namespace cv;
int main()
{
    mynewtest(); //--- ADDED FUNCTION

    //-----------------------------------------------------------;
    std::string image_path = samples::findFile("starry_night.jpg");
    Mat img = imread(image_path, IMREAD_COLOR);
    if (img.empty())
    {
        std::cout << "Could not read the image: " << image_path << std::endl;
        return 1;
    }
    imshow("Display window", img);
    int k = waitKey(0); // Wait for a keystroke in the window
    if (k == 's')
    {
        imwrite("starry_night.png", img);
    }
    return 0;
}

If I comment  mynewtest(); then  the code starts normally.
As I  understand  smth  is with  linking lib libriries but  all the libs are linked well

have tried to re-build opencv using cmake


问:
Prevent Angular 15 iframe update browser history
I have an Angular 15 app with an iframe where I render html content from file.
Since this content may be changed by user I update src value. This affects browser history stack.
I was googling and found here Angular 7 iframe history back button trouble how to solve the issue. There is only one problem. My src variable is base64 content.

This is what I was using before and it renders fine but affects location stack:

.html

```<code><div class="form-data">
    <iframe width="100%" height="100%" [src]="layoutPath"></iframe>
</div>
</code>```

.ts

```<code>private dbLayout: string;
layoutPath: SafeHtml;

ngOnInit() {
    this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}

userChangeSomeContentOfHtml(someUserContent: string) {
    const base64Layout = Base64.encode(dbLayout+ someUserContent);
    this.layoutPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
    }
}
</code>```

According to solution from above link I updated my code to this:

.html

```<code><div class="form-data">
    <iframe #iframe width="100%" height="100%"></iframe>
</div>
</code>```

.ts

```<code>private dbLayout: string;

ngOnInit() {
    this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}

userChangeSomeContentOfHtml(someUserContent: string) {
    const base64Layout = Base64.encode(dbLayout+ someUserContent);
    const layouthPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
    this.iframe.nativeElement.contentWindow.location.replace(layoutPath);
    }
}
</code>```

Unfortunately variable layoutPath is base64 and location.replace leads me to nowhere.

How can I solve this location stack bypass with a base64 content?

Body:
I have an Angular 15 app with an iframe where I render html content from file.
Since this content may be changed by user I update src value. This affects browser history stack.
I was googling and found here Angular 7 iframe history back button trouble how to solve the issue. There is only one problem. My src variable is base64 content.

This is what I was using before and it renders fine but affects location stack:

.html

.ts

private dbLayout: string;
layoutPath: SafeHtml;

ngOnInit() {
    this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}

userChangeSomeContentOfHtml(someUserContent: string) {
    const base64Layout = Base64.encode(dbLayout+ someUserContent);
    this.layoutPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
    }
}

According to solution from above link I updated my code to this:

.html

.ts

private dbLayout: string;

ngOnInit() {
    this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}

userChangeSomeContentOfHtml(someUserContent: string) {
    const base64Layout = Base64.encode(dbLayout+ someUserContent);
    const layouthPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
    this.iframe.nativeElement.contentWindow.location.replace(layoutPath);
    }
}

Unfortunately variable layoutPath is base64 and location.replace leads me to nowhere.

How can I solve this location stack bypass with a base64 content?


问:
PApplet.runSketch trying to access java class in my sketch from a java file inside a folder
I'm trying to create a program that allows you to run multiple sketches off of one master sketch through using the PApplet.runSketch function. This has posed the best option for me but I want to be able to access a collection of java files within multiple folders for better organization of the games. The problem is I have no idea how to do so within the constraints of the function and when I search for pre-existing examples, none properly solve it the way I'd like.

Reason for wanting folders instead of multiple tabs:

The folders would be saved in the same folder alongside my main sketch.pde. The problem with using multiple tabs is that I have games that use up to 5-8+ tabs and that would eventually just clutter everything. So I'm looking for a way to store games in individual folders and then access within my main sketch.pde each individual game's main java file

Here's my code

\sketch.pde

void settings() {
  size(600, 200);
}

void setup() {
  String args[] = {
    "--display=1",
    "--location=0,0",
    "--sketch-path=" + sketchPath("Game1"),
    "Game1"
  };
  Game1 g = new Game1(320, 420);
  PApplet.runSketch(args, g);
}

void draw() {
  background(0);
  ellipse(50, 50, 10, 10);
}
```
<p>\Game1\Game1.java</p>
<pre class="lang-java prettyprint-override"><code>import processing.core.*;

public class Game1 extends PApplet {

    private final int w, h;

    public Game1(int w, int h) {
        this.w = w;
        this.h = h;
    }

    public void settings() {
        size(this.w, this.h);
    }

    public void draw() {
        background(0);
    }

}
</code>```

The problem is that the Game1 class is not recognized because the Game1.java file is within a folder and not present with the sketch.pde, but that is how I want to be able to run the sketches. Any ideas?

Body:
I'm trying to create a program that allows you to run multiple sketches off of one master sketch through using the PApplet.runSketch function. This has posed the best option for me but I want to be able to access a collection of java files within multiple folders for better organization of the games. The problem is I have no idea how to do so within the constraints of the function and when I search for pre-existing examples, none properly solve it the way I'd like.

Reason for wanting folders instead of multiple tabs:

The folders would be saved in the same folder alongside my main sketch.pde. The problem with using multiple tabs is that I have games that use up to 5-8+ tabs and that would eventually just clutter everything. So I'm looking for a way to store games in individual folders and then access within my main sketch.pde each individual game's main java file

Here's my code

\sketch.pde

void settings() {
  size(600, 200);
}

void setup() {
  String args[] = {
    "--display=1",
    "--location=0,0",
    "--sketch-path=" + sketchPath("Game1"),
    "Game1"
  };
  Game1 g = new Game1(320, 420);
  PApplet.runSketch(args, g);
}

void draw() {
  background(0);
  ellipse(50, 50, 10, 10);
}

\Game1\Game1.java

import processing.core.*;

public class Game1 extends PApplet {

    private final int w, h;

    public Game1(int w, int h) {
        this.w = w;
        this.h = h;
    }

    public void settings() {
        size(this.w, this.h);
    }

    public void draw() {
        background(0);
    }

}

The problem is that the Game1 class is not recognized because the Game1.java file is within a folder and not present with the sketch.pde, but that is how I want to be able to run the sketches. Any ideas?


问:
HAL_Delay command not working on STM32 - Nucleo-L
in our Computer Science class, we are learning to use the STEM32 - Nucleo-L controller, to code assembler. I'm a bit further than the rest of the class, so my teacher tasked me to experiment with the "HAL_Delay" command, since he ran into some problems, trying to use the command.

I found out, that the command usually works fine, except if the registers R2 or/and R3 are use for other stuff. I also found out, that the "wait_ms" command works perfectly fine, so should we just use that command or has anyone got a solution. It would also be very usefull, if someone knew the exact location of the subprogram "HAL_Dealy" in the code.

```<code>.syntax unified
.equ L152,1
.include "../Core/src/regs.s"
.global mainasm
mainasm:

main:
    bl      startup
    ldr     R1,=GPIOA
    ldr     R2,=GPIOC

    gruenwechsel:  //Wechsel von Rot auf Grün
        ldr     R0,[R2,ODR] //Ampel auf rot setzen
        mov     R0,#0b1
        strb    R0,[R2,ODR]
        mov     R0,#500
        bl      wait_ms     //500ms Warten
        ldr     R0,[R2,ODR]
        mov     R0,#0b101   //Rote und Grüne LED geichzeitig an
        strb    R0,[R2,ODR]
        mov     R0,#500     //500ms Warten
        bl      wait_ms
        b       Gruen       //Ampel auf Grün setzen

    Gruen:      //Grüner Loop
        ldr     R0,[R2,ODR]
        mov     R0,#0b10000 //Ampel auf Grün
        strb    R0,[R2,ODR]
        ldr     R0,[R1,IDR]
        tst     R0,Bit10    //Schauen ob PA10 gedrueckt ist
        bne     rotwechsel  //Falls ja, in rotwechsel springen
        b       Gruen

    rotwechsel:
        ldr     R0,[R2,ODR]
        mov     R0,#0b00100 //Grüne und Gelbe LED Gleichzeitig an
        strb    R0,[R2,ODR]
        mov     R0,#1000    //Warte 1 Sekunde
        bl      wait_ms
        ldr     R0,[R2,ODR]
        mov     R0,#0b00001 //Rote LED an
        strb    R0,[R2,ODR]
        b       Rot

    Rot:                    //Roter Loop
        ldr     R0,[R2,ODR]
        mov     R0,#0b000001 //LED Rot an
        strb    R0,[R2,ODR]
        ldr     R0,[R1,IDR]
        tst     R0,Bit10 //Schauen ob PA10 gedrückt ist, falls ja, in Grünwechsel springen
        bne     gruenwechsel
        b       Rot

.end

</code>```

Thats my code. If I change the "wait_ms" lines to "HAL_Delay" the code compiles without errors and also loads on to the chip, but it won't do anything, when i press the buttons.

Body:
in our Computer Science class, we are learning to use the STEM32 - Nucleo-L controller, to code assembler. I'm a bit further than the rest of the class, so my teacher tasked me to experiment with the "HAL_Delay" command, since he ran into some problems, trying to use the command.

I found out, that the command usually works fine, except if the registers R2 or/and R3 are use for other stuff. I also found out, that the "wait_ms" command works perfectly fine, so should we just use that command or has anyone got a solution. It would also be very usefull, if someone knew the exact location of the subprogram "HAL_Dealy" in the code.

.syntax unified
.equ L152,1
.include "../Core/src/regs.s"
.global mainasm
mainasm:

main:
    bl      startup
    ldr     R1,=GPIOA
    ldr     R2,=GPIOC

    gruenwechsel:  //Wechsel von Rot auf Grün
        ldr     R0,[R2,ODR] //Ampel auf rot setzen
        mov     R0,#0b1
        strb    R0,[R2,ODR]
        mov     R0,#500
        bl      wait_ms     //500ms Warten
        ldr     R0,[R2,ODR]
        mov     R0,#0b101   //Rote und Grüne LED geichzeitig an
        strb    R0,[R2,ODR]
        mov     R0,#500     //500ms Warten
        bl      wait_ms
        b       Gruen       //Ampel auf Grün setzen

    Gruen:      //Grüner Loop
        ldr     R0,[R2,ODR]
        mov     R0,#0b10000 //Ampel auf Grün
        strb    R0,[R2,ODR]
        ldr     R0,[R1,IDR]
        tst     R0,Bit10    //Schauen ob PA10 gedrueckt ist
        bne     rotwechsel  //Falls ja, in rotwechsel springen
        b       Gruen

    rotwechsel:
        ldr     R0,[R2,ODR]
        mov     R0,#0b00100 //Grüne und Gelbe LED Gleichzeitig an
        strb    R0,[R2,ODR]
        mov     R0,#1000    //Warte 1 Sekunde
        bl      wait_ms
        ldr     R0,[R2,ODR]
        mov     R0,#0b00001 //Rote LED an
        strb    R0,[R2,ODR]
        b       Rot

    Rot:                    //Roter Loop
        ldr     R0,[R2,ODR]
        mov     R0,#0b000001 //LED Rot an
        strb    R0,[R2,ODR]
        ldr     R0,[R1,IDR]
        tst     R0,Bit10 //Schauen ob PA10 gedrückt ist, falls ja, in Grünwechsel springen
        bne     gruenwechsel
        b       Rot

.end

Thats my code. If I change the "wait_ms" lines to "HAL_Delay" the code compiles without errors and also loads on to the chip, but it won't do anything, when i press the buttons.


问:
Is it possible that a linux syscall read(from a regular file) set errno EINTR?
I learned that syscall write to a regular file does not generate EINTR error(Why can't a write to disk be interrupted by signal?)

What about a read syscall in linux? Do "slow" devices include disk device?

(if SA_INTERRUPT is set)


问:
Adjust temperature setpointbased on variance in power price?
I would like to adjust the setpoint of a thermostat based on variances in hourly power prices. When power prices are lower, I want to adjust the temperature higher. When power prices are higher, I want to adjust the temperature lower.

I think is makes sense to base the size of adjustment based on how far the price is from the average value of the prices. At the same time, I may want to have a fixed range for how large the adjustment may be. For days with a big variation in prices, the whole range could be used. For days with little variation in prices, a smaller range should be used. The adjustments could have a range of [-1.5, -1.0, -0.5, 0.0, +0.5, +1.0, +1.5] as an example. In a day with little variation of prices, maybe only the range [-0.5, 0.0, +0.5] would be used.

How could I map an "unknown" size of variation to a fixed range of adjustment values?


问:
set absolute position of element based on entire reveal slide using quarto
How do I set the absolute position of an element in a reveal-js slide based on the entire slide size?

When I try to add an element e.g. in the upper left corner of the slide the element appears upper left relative to the content.

E.g. "topleft" appears further upwards with this code

```<code># testslide1
- 1
- 2
- 3
- 4
- 5

[topleft]{.absolute top="0%" left="0%"}
</code>```

than with this code

```<code># testslide2

[topleft]{.absolute top="0%" left="0%"}
</code>```

while I expected it to have the same position

Body:
How do I set the absolute position of an element in a reveal-js slide based on the entire slide size?

When I try to add an element e.g. in the upper left corner of the slide the element appears upper left relative to the content.

E.g. "topleft" appears further upwards with this code

# testslide1
- 1
- 2
- 3
- 4
- 5

[topleft]{.absolute top="0%" left="0%"}

than with this code

# testslide2

[topleft]{.absolute top="0%" left="0%"}

while I expected it to have the same position


问:
CSS overflow hidden doesn't work with videos
I have 3 divs. The first is called "container" and the other one is called "video1". "Video1" contains the video. Here is the code.

.video1 {
  position: relative;
  bottom: 4rem;
  left: 15rem;
  height: auto;
  overflow: hidden;
}

.video1 video {
  width: 40rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>

    <div class="video1">

        <video src="myvideo.mp4" type="video/mp4"></video>

    </div>
</div></code>```

But when I resize the screen the video doesn't get hidden. displays outside of the div.

What should I do? Thanks.

Body:
I have 3 divs. The first is called "container" and the other one is called "video1". "Video1" contains the video. Here is the code.

.video1 {
  position: relative;
  bottom: 4rem;
  left: 15rem;
  height: auto;
  overflow: hidden;
}

.video1 video {
  width: 40rem;
}

        <video src="myvideo.mp4" type="video/mp4"></video>

But when I resize the screen the video doesn't get hidden. displays outside of the div.

What should I do? Thanks.


问:
Standard process of saving Key-Value Pairs to database
What is the standard process of saving Key-Value Pairs to database?

Will I include key-value pairs with empty values upon saving? If no, when updating a value, will I delete it on the database once I update it to an empty value?

I tried to save Key-Value pairs and I don't know if I'm doing the right thing by saving the ones that don't have empty values. And when I update existing Key-Value pairs from the database, I delete the ones that are empty since I don't save empty values.