问:
SqlAlchemy doubly linked tables
I have the following tables declared:

uuidpk = Annotated[UUID, mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)]
user_fk = Annotated[UUID, mapped_column(UUID(as_uuid=True), ForeignKey('userschema.user_account.id'))]
str50 = Annotated[str, mapped_column(String(50))]

class Base(MappedAsDataclass, DeclarativeBase):
    """Subclasses will be converted to dataclasses"""
    pass

class ResidentialAddress(Base):
    __tablename__ = 'residential_address'
    __table_args__ = {'schema': 'userschema'}

    id: Mapped[uuidpk] = mapped_column(init=False)
    address: Mapped[str50]
    user_id: Mapped[user_fk] = mapped_column(init=False)
    user: Mapped['User'] = relationship(back_populates='residential_address', default=None)

class User(Base):
    __tablename__ = 'user_account'
    __table_args__ = {'schema': 'userschema'}

    id: Mapped[uuidpk] = mapped_column(init=False)
    uname: Mapped[str50] = mapped_column(unique=True)
    birthyear: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, default=None)
    current_residential_address_id: Mapped[Optional[UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey('userschema.residential_address.id'), nullable=True, default=None)
    residential_address: Mapped['ResidentialAddress'] = relationship(back_populates='user', viewonly=True, default=None)
```
<p>The idea in this toy-example is that I want the <code>ResidentialAddress</code> entries to retain their <code>user_id</code>, event if the user changes their <code>current_residential_address_id</code>.</p>
<p>I've tried setting the <code>foreign_keys</code> parameters, but I don't think I understand them well enough. Would anyone be kind enough to explain if this is possible/if it isn't?</p>
<p>I've tried setting the relationship in <code>ResidentialAddress</code> to:</p>
<pre class="lang-py prettyprint-override"><code>user: Mapped['User'] = relationship(back_populates='residential_address', remote_side=id, foreign_keys=[user_id], default=None)
</code>```

And the relationship in User to:

residential_address: Mapped['ResidentialAddress'] = relationship(back_populates='user', viewonly=True, foreign_keys=[current_residential_address_id], default=None)
```
<p>However, I get the following suggestion from SqlAlchemy:</p>
```sqlalchemy.exc.ArgumentError: Relationship ResidentialAddress.user could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments.  Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.
```

I'm not sure if using the remote() annotation is the correct way forward, as I'm only finding examples where remote is used in self-referrential tables.

Title: SqlAlchemy doubly linked tables

Body:
I have the following tables declared:

uuidpk = Annotated[UUID, mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)]
user_fk = Annotated[UUID, mapped_column(UUID(as_uuid=True), ForeignKey('userschema.user_account.id'))]
str50 = Annotated[str, mapped_column(String(50))]

class Base(MappedAsDataclass, DeclarativeBase):
    """Subclasses will be converted to dataclasses"""
    pass

class ResidentialAddress(Base):
    __tablename__ = 'residential_address'
    __table_args__ = {'schema': 'userschema'}

    id: Mapped[uuidpk] = mapped_column(init=False)
    address: Mapped[str50]
    user_id: Mapped[user_fk] = mapped_column(init=False)
    user: Mapped['User'] = relationship(back_populates='residential_address', default=None)

class User(Base):
    __tablename__ = 'user_account'
    __table_args__ = {'schema': 'userschema'}

    id: Mapped[uuidpk] = mapped_column(init=False)
    uname: Mapped[str50] = mapped_column(unique=True)
    birthyear: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, default=None)
    current_residential_address_id: Mapped[Optional[UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey('userschema.residential_address.id'), nullable=True, default=None)
    residential_address: Mapped['ResidentialAddress'] = relationship(back_populates='user', viewonly=True, default=None)

The idea in this toy-example is that I want the ResidentialAddress entries to retain their user_id, event if the user changes their current_residential_address_id.

I've tried setting the foreign_keys parameters, but I don't think I understand them well enough. Would anyone be kind enough to explain if this is possible/if it isn't?

I've tried setting the relationship in ResidentialAddress to:

user: Mapped['User'] = relationship(back_populates='residential_address', remote_side=id, foreign_keys=[user_id], default=None)

And the relationship in User to:

residential_address: Mapped['ResidentialAddress'] = relationship(back_populates='user', viewonly=True, foreign_keys=[current_residential_address_id], default=None)

However, I get the following suggestion from SqlAlchemy:

sqlalchemy.exc.ArgumentError: Relationship ResidentialAddress.user could not determine any unambiguous local/remote column pairs based on join condition and remote_side arguments.  Consider using the remote() annotation to accurately mark those elements of the join condition that are on the remote side of the relationship.

I'm not sure if using the remote() annotation is the correct way forward, as I'm only finding examples where remote is used in self-referrential tables.


来源: stackexchange

问:
"error: MSB4040 There is no target in the project" when using MSbuild+Delphi10.2
I'm automating the build of a Delphi 10.2 project
I'm using msbuild with .net 4.0.30319

I'm running rsvars.bat to set the environment variables and then call MSBuild

```<code>start-process "C:\Program Files (x86)\Embarcadero\Studio\19.0\bin\rsvars.bat"

MSBuild Modulos/COM/PCOM.dproj
</code>```

Probably the solution will be something simple and basic that I didn't pay attention to and I'll be mulling over it for days after it's solved

I found some articles related to the topic, but none were able to solve my problem.
https://stackoverflow.com/questions/1342859/error-msb4040-there-is-no-target-in-the-project-when-using-msbuilddelphi2009
https://stackoverflow.com/questions/33564315/how-to-build-a-delphi-project-in-teamcity

I manage to simulate the error through the windows powershell
error in the windows powershell

If i run it through the command prompt I get success, but running through Jenkins does not object success.

ContentLicense: CC BY-SA 4.0

Body:
I'm automating the build of a Delphi 10.2 project
I'm using msbuild with .net 4.0.30319

I'm running rsvars.bat to set the environment variables and then call MSBuild

start-process "C:\Program Files (x86)\Embarcadero\Studio\19.0\bin\rsvars.bat"

MSBuild Modulos/COM/PCOM.dproj

Probably the solution will be something simple and basic that I didn't pay attention to and I'll be mulling over it for days after it's solved

I found some articles related to the topic, but none were able to solve my problem.
https://stackoverflow.com/questions/1342859/error-msb4040-there-is-no-target-in-the-project-when-using-msbuilddelphi2009
https://stackoverflow.com/questions/33564315/how-to-build-a-delphi-project-in-teamcity

I manage to simulate the error through the windows powershell
error in the windows powershell

If i run it through the command prompt I get success, but running through Jenkins does not object success.


问:
How to mock the CloaseableHttpResponse from apache http client 5.x?
I'm using apache http client version 5.x, and I'm struglling to implement mocked unit tests for the CloseableHttpResponse execute(ClassicHttpRequest request) method from CloseableHttpClient class, since the response type is final and there is no public way to instantiate it.

The following question provided some ways to do it, but the discussion seems to be around the older versions of the apache http client, and although I was able to enable mockito to mock final types, it seems to be risky, as documentation itself warns that this is a completely different mocking mechanism that requires more feedback from the community.

Is there an easier/proper way to achieve this?


问:
Parsing HTML page with PHP code in Python
What will be the simpler ways in Python to parse HTML page with PHP code and still get said code during parsing?

From what I've read HTML parsers in Python don't like included PHP code, so for now only option I see is to write parser myself.

On topic, Why I need this? (if someone interested): I need to convert HTML + PHP page into PHP code, which will generate JSON using command line arguments.


问:
JS | Babel | What means and does the mode "spec" and "force all transforms"
What means and does the mode "spec" and "force all transforms"

I suppose "force all transforms" transforms a code to ES5. Is it so?

What about "spec"?

Here I have a react component as an example

Body:
What means and does the mode "spec" and "force all transforms"

I suppose "force all transforms" transforms a code to ES5. Is it so?

What about "spec"?

<a href="https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=false&corejs=false&spec=true&loose=false&code_lz=MYGwhgzhAEDCIEtgGt6RgUwB4BcMDsATGAJQzGBwDpYB7AWwAdb8CdoBvAKGmmBYg4ATgFdKtIQApGQ2owgBKTj17QIIxhiky5i3ioC-Klb1BJkAUQBubaAF5okpXYB8y1av74ItEBiogtADmkgDkZijWbKEKANwm0Aax0Ma8QgSEWk7uquk4IkL4jgkAPABGIjg4LNAs8OZ2HDgAFggQVBGWNvg4Bi71KNAAshglAPQVVSwuCQpcRgZAA&debug=false&forceAllTransforms=true&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=true&timeTravel=false&sourceType=module&lineWrap=false&presets=env%2Creact%2Cstage-2&prettier=true&targets=&version=7.20.11&externalPlugins=&assumptions=%7B%7D" rel="nofollow noreferrer">Here I have a react component as an example


问:
jenkins instance is missing when writing spock test
I am writing a test for which having a Jenkins instance . so I need to mock the Jenkins class and set the instance to Jenkins. What is the method to set the instance?

Import jenkins.model.Jenkins


问:
unable to create a new database from the migrations
im not really sure what is going on to be honest.
I was given a project to take over and I am following the steps in the README

this is the step is giving me an issue is the following:

You can create a new database from the migrations in this project, the command is:

node ace migration:run

my understanding is that i am creating the database records in the mysql instance

Once I run node ace migration:run everything works fine for a while until i hit the following issues:

```<code>....
....
...
❯ migrated database/migrations/1661521523093_phone_numbers
❯ migrated database/migrations/1663691668347_voice_calls
❯ migrated database/migrations/1665766850905_settings
❯ error database/migrations/1667928559943_leads
❯ migrating database/migrations/1672847283595_users
[ error ]  CREATE INDEX payload_idx USING BTREE ON leads (payload_json) - ER_JSON_USED_AS_KEY: JSON column 'payload_json' supports indexing only via generated columns on a specified JSON path.
    at Query.Sequence._packetToError (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14)
    at Query.ErrorPacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/sequences/Query.js:79:18)
    at Protocol._parsePacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:291:23)
    at Parser._parsePacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Parser.js:433:10)
    at Parser.write (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Parser.js:43:10)
    at Protocol.write (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:38:16)
    at Socket.<anonymous> (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:88:28)
    at Socket.<anonymous> (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:526:10)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
    --------------------
    at Protocol._enqueue (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Connection.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:198:25)
    at /Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/dialects/mysql/index.js:132:18
    at new Promise (<anonymous>)
    at Client_MySQL._query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/dialects/mysql/index.js:126:12)
    at executeQuery (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/internal/query-executioner.js:37:17)
    at Client_MySQL.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/client.js:144:12)
    at /Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/transaction.js:363:24
    at new Promise (<anonymous>)
    at Client_MySQL.trxClient.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/transaction.js:358:12)
</code>```

I found the following stackoverflow post that contains the same error BUT they dont explain what code they ran to solve the error:
ER_JSON_USED_AS_KEY: JSON column 'parent_ids' supports indexing only via generated columns on a specified JSON path

i tried to run the following code in mysql workbench but I didnt get it to work

```<code>ALTER TABLE leads
DROP CONSTRAINT payload_json;
</code>```

this is the response in mysql::

Error Code: 3940. Constraint 'payload_json' does not exist.

this is the ace file:

```<code>require('reflect-metadata')
require('source-map-support').install({ handleUncaughtExceptions: false })

const { Ignitor } = require('@adonisjs/core/build/standalone')
new Ignitor(__dirname)
  .ace()
  .handle(process.argv.slice(2))
</code>```

any advice is welcomed

Body:
im not really sure what is going on to be honest.
I was given a project to take over and I am following the steps in the README

this is the step is giving me an issue is the following:

You can create a new database from the migrations in this project, the command is:

node ace migration:run

my understanding is that i am creating the database records in the mysql instance

Once I run node ace migration:run everything works fine for a while until i hit the following issues:

....
....
...
❯ migrated database/migrations/1661521523093_phone_numbers
❯ migrated database/migrations/1663691668347_voice_calls
❯ migrated database/migrations/1665766850905_settings
❯ error database/migrations/1667928559943_leads
❯ migrating database/migrations/1672847283595_users
[ error ]  CREATE INDEX payload_idx USING BTREE ON leads (payload_json) - ER_JSON_USED_AS_KEY: JSON column 'payload_json' supports indexing only via generated columns on a specified JSON path.
    at Query.Sequence._packetToError (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14)
    at Query.ErrorPacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/sequences/Query.js:79:18)
    at Protocol._parsePacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:291:23)
    at Parser._parsePacket (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Parser.js:433:10)
    at Parser.write (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Parser.js:43:10)
    at Protocol.write (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:38:16)
    at Socket.<anonymous> (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:88:28)
    at Socket.<anonymous> (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:526:10)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
    --------------------
    at Protocol._enqueue (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Connection.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/mysql/lib/Connection.js:198:25)
    at /Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/dialects/mysql/index.js:132:18
    at new Promise (<anonymous>)
    at Client_MySQL._query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/dialects/mysql/index.js:126:12)
    at executeQuery (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/internal/query-executioner.js:37:17)
    at Client_MySQL.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/client.js:144:12)
    at /Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/transaction.js:363:24
    at new Promise (<anonymous>)
    at Client_MySQL.trxClient.query (/Users/juancasas/Desktop/studio code/lead-axis/lead-axis-back/node_modules/knex/lib/execution/transaction.js:358:12)

I found the following stackoverflow post that contains the same error BUT they dont explain what code they ran to solve the error:
ER_JSON_USED_AS_KEY: JSON column 'parent_ids' supports indexing only via generated columns on a specified JSON path

i tried to run the following code in mysql workbench but I didnt get it to work

ALTER TABLE leads
DROP CONSTRAINT payload_json;

this is the response in mysql::

Error Code: 3940. Constraint 'payload_json' does not exist.

this is the ace file:

require('reflect-metadata')
require('source-map-support').install({ handleUncaughtExceptions: false })

const { Ignitor } = require('@adonisjs/core/build/standalone')
new Ignitor(__dirname)
  .ace()
  .handle(process.argv.slice(2))

any advice is welcomed


问:
403 Forbidden (error code: 50007): Cannot send messages to this user
I have a bot on discord and when i start the host, i get this message repeatable "403 Forbidden (error code: 50007): Cannot send messages to this user". What should I do. I will let the main.py code here. I have a folder with commands also that runs on a bot, if that code from above is looking alright, I can give you the others.

import discord
from discord import app_commands
from readsettings import ReadSettings
from command_handler import CommandHander
import time
import functions as Functions

settings = ReadSettings('settings.json')
commandHandler = None

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.all())
        self.synced = False
        self.started = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id=settings['Discord_Guild_ID']))
            self.synced = True
        print(f"Logged into bot account: {self.user}.")
        commandHandler.initialize()
        await Functions.sendLogToChannel(client, f'{settings["Bot_Name"]} Started!', f'{settings["Bot_Name"]} has successfully started!', 0x00ff00, tag=True)

client = aclient()
tree = app_commands.CommandTree(client)
commandHandler = CommandHander(client, tree, settings)`
client.run(settings['Bot_Token'])
```


问:
Pyhon Parallel-Ssh Sending Commands In Loop In a Single Shell Does Not Work
I have been trying to send a single command in a loop for a single client in a single shell because different commands need to go before the loop to get into a terminal using Parallel-ssh.

Code:

```<code>pclient = ParallelSSHClient(['ipaddress'], user="username", password='password')
shell = pclient.open_shell()
commands = ["echo 'Hello, world!' > example.txt"]
pclient.run_shell_commands(shell, commands)

for _ in range(20):
    pclient.run_shell_commands(shell, ["cat example.txt"])
    for sell in shell:
        for line in sell.stdout:
            print(line)
</code>```

After every iteration, I expect it to print both of the commands' outputs.

However, the moment it prints out the last line in the first iteration it's not moving forward in the loop. there is not error message and the code does not continue

I tried using ParallelSSHclient as well as SSHClient, closing the shell, getting the exit code and running each command individually.

I don't understand why it won't continue the loop and print the next output ...

Body:
I have been trying to send a single command in a loop for a single client in a single shell because different commands need to go before the loop to get into a terminal using Parallel-ssh.

Code:

pclient = ParallelSSHClient(['ipaddress'], user="username", password='password')
shell = pclient.open_shell()
commands = ["echo 'Hello, world!' > example.txt"]
pclient.run_shell_commands(shell, commands)

for _ in range(20):
    pclient.run_shell_commands(shell, ["cat example.txt"])
    for sell in shell:
        for line in sell.stdout:
            print(line)

After every iteration, I expect it to print both of the commands' outputs.

However, the moment it prints out the last line in the first iteration it's not moving forward in the loop. there is not error message and the code does not continue

I tried using ParallelSSHclient as well as SSHClient, closing the shell, getting the exit code and running each command individually.

I don't understand why it won't continue the loop and print the next output ...


问:
How to undo adding a certain patch to Git's staging area?
After doing git add --patch and painstakingly selecting which patches I want to add and which I don't want to add, and editing some of those I chose to add too, I realized that I have added one patch that I shouldn't have added. Is there any way to undo adding that patch only, something like git add --patch --reverse?


问:
Send query parameters from API Gateway to a Step Functions Choice
I have an AWS Step Function called trough API Gateway with the following Choice:

```<code>"Router": {
        "Type": "Choice",
        "Choices": [
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl501mg",
            "Next": "Queclink GL501MG Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl502mg",
            "Next": "Queclink GL502MG Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl505",
            "Next": "Queclink GL505 Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "tive",
            "Next": "Tive"
          },
          {
            "Variable": "$.deviceType", // Something like $.queryparams.deviceType ?
            "StringEquals": "kkmKG01",
            "Next": "KkmKG01"
          }
        ],
        "Default": "Error"
      },
</code>```

The last option (kkmKG01) doesn't match because the device can't send a deviceType in it's payload.
What I want to do is to specify the deviceType in a query param since I can configure the url my device calls.

I added a query param in both the Method Request and Integration Request in API Gateway:

But I don't know how to check the deviceType from the query param instead on the deviceType from the payload in my Step Function.

Body:
I have an AWS Step Function called trough API Gateway with the following Choice:

"Router": {
        "Type": "Choice",
        "Choices": [
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl501mg",
            "Next": "Queclink GL501MG Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl502mg",
            "Next": "Queclink GL502MG Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "queclink-gl505",
            "Next": "Queclink GL505 Uplink"
          },
          {
            "Variable": "$.deviceType",
            "StringEquals": "tive",
            "Next": "Tive"
          },
          {
            "Variable": "$.deviceType", // Something like $.queryparams.deviceType ?
            "StringEquals": "kkmKG01",
            "Next": "KkmKG01"
          }
        ],
        "Default": "Error"
      },

The last option (kkmKG01) doesn't match because the device can't send a deviceType in it's payload.
What I want to do is to specify the deviceType in a query param since I can configure the url my device calls.

I added a query param in both the Method Request and Integration Request in API Gateway:

But I don't know how to check the deviceType from the query param instead on the deviceType from the payload in my Step Function.


问:
brew install node: problems with npm
On my Mac (OS 11.6) I installed node.js using the highly recommended

% brew install node

installing version 19.3.0.
and I had to explicitly delete and chown some old stuff because the previous version of node (16) was installed with something that made all its pieces owned by root, and brew doesn't like to work with sudo.

The node command works. But it doesn't seem to have installed the npm command along with it, despite declaring loudly that it does.

```<code>% ll `which npm`
lrwxr-xr-x  1 root  admin    38B Mar  8  2022 /usr/local/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js
</code>```

Which is almost certainly wrong, because

```<code>% ll `which node`
lrwxr-xr-x  1 ken  admin    30B Jan  4 10:31 /usr/local/bin/node -> ../Cellar/node/19.3.0/bin/node
</code>```

looks completely different.

Trying a brew reinstall revealed problems with postinstall:

```<code>% brew -v postinstall node
==> Postinstalling node
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall node
</code>```

What?  Verbose, and no clue?

And when I try to run npm (with any subcommand) I get the error traceback listed below. How to fix? How to correctly install the npm command to go with my current brew install?

```<code>% npm init
node:internal/modules/cjs/loader:1039
  const err = new Error(message);
              ^
Error: Cannot find module '../../package.json'
Require stack:
- /usr/local/lib/node_modules/npm/lib/utils/unsupported.js
- /usr/local/lib/node_modules/npm/lib/cli.js
- /usr/local/lib/node_modules/npm/bin/npm-cli.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/unsupported.js:3:19)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/local/lib/node_modules/npm/lib/utils/unsupported.js',
    '/usr/local/lib/node_modules/npm/lib/cli.js',
    '/usr/local/lib/node_modules/npm/bin/npm-cli.js'
  ]
}

Node.js v19.3.0
</code>```

Title: brew install node: problems with npm

Body:
On my Mac (OS 11.6) I installed node.js using the highly recommended

% brew install node

installing version 19.3.0.
and I had to explicitly delete and chown some old stuff because the previous version of node (16) was installed with something that made all its pieces owned by root, and brew doesn't like to work with sudo.

The node command works. But it doesn't seem to have installed the npm command along with it, despite declaring loudly that it does.

% ll `which npm`
lrwxr-xr-x  1 root  admin    38B Mar  8  2022 /usr/local/bin/npm -> ../lib/node_modules/npm/bin/npm-cli.js

Which is almost certainly wrong, because

% ll `which node`
lrwxr-xr-x  1 ken  admin    30B Jan  4 10:31 /usr/local/bin/node -> ../Cellar/node/19.3.0/bin/node

looks completely different.

Trying a brew reinstall revealed problems with postinstall:

% brew -v postinstall node
==> Postinstalling node
Warning: The post-install step did not complete successfully
You can try again using:
  brew postinstall node

What?  Verbose, and no clue?

And when I try to run npm (with any subcommand) I get the error traceback listed below. How to fix? How to correctly install the npm command to go with my current brew install?

% npm init
node:internal/modules/cjs/loader:1039
  const err = new Error(message);
              ^
Error: Cannot find module '../../package.json'
Require stack:
- /usr/local/lib/node_modules/npm/lib/utils/unsupported.js
- /usr/local/lib/node_modules/npm/lib/cli.js
- /usr/local/lib/node_modules/npm/bin/npm-cli.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/unsupported.js:3:19)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/local/lib/node_modules/npm/lib/utils/unsupported.js',
    '/usr/local/lib/node_modules/npm/lib/cli.js',
    '/usr/local/lib/node_modules/npm/bin/npm-cli.js'
  ]
}

Node.js v19.3.0


问:
Checksum error for plugin github.com/hashicorp/azure version 1.3.1

Overview of the Issue

Hello there, I'm facing a checksum error while performing a packer init with azure plugin.

```<code>Failed getting the "github.com/hashicorp/azure" plugin: 1 error occurred: * could not get sha256 checksum file for github.com/hashicorp/azure version 1.3.1. Is the file present on the release and correctly named ? Get "https://objects.githubusercontent.com/github-production-release-asset-2e65be/361409316/cbfe3de3-680b-4c47-b744-bbde6a784bac?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230103%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230103T103126Z&X-Amz-Expires=300&X-Amz-Signature=52275607836fbd0304f7ce9d44575c6f128b4978fe43bd0c7f12e0b81e628552&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=361409316&response-content-disposition=attachment%3B%20filename%3Dpacker-plugin-azure_v1.3.1_SHA256SUMS&response-content-type=application%2Foctet-stream": x509: certificate signed by unknown authority
</code>```

Reproduction Steps

Use hashicorp azure plugin, I guess

Plugin and Packer version

Azure plugin version 1.3.1
Packer version 1.8.2

Operating system and Environment details

Packer is running on an Ubuntu WSL

What did I tried exactly and what did I expected ?

I tried a Packer Init. Packer is supposed to initiate the plugins.

I tried to update packer, update the host, install ca-certificate. None of this resolve the issue.

Do you know how I can get away with this errors ?

Thank you :)

I tried a Packer Init. Packer is supposed to initiate the plugins.

Body:
Overview of the Issue

Hello there, I'm facing a checksum error while performing a packer init with azure plugin.

Failed getting the "github.com/hashicorp/azure" plugin: 1 error occurred: * could not get sha256 checksum file for github.com/hashicorp/azure version 1.3.1. Is the file present on the release and correctly named ? Get "https://objects.githubusercontent.com/github-production-release-asset-2e65be/361409316/cbfe3de3-680b-4c47-b744-bbde6a784bac?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230103%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230103T103126Z&X-Amz-Expires=300&X-Amz-Signature=52275607836fbd0304f7ce9d44575c6f128b4978fe43bd0c7f12e0b81e628552&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=361409316&response-content-disposition=attachment%3B%20filename%3Dpacker-plugin-azure_v1.3.1_SHA256SUMS&response-content-type=application%2Foctet-stream": x509: certificate signed by unknown authority

Reproduction Steps

Use hashicorp azure plugin, I guess

Plugin and Packer version

Azure plugin version 1.3.1
Packer version 1.8.2

Operating system and Environment details

Packer is running on an Ubuntu WSL

What did I tried exactly and what did I expected ?

I tried a Packer Init. Packer is supposed to initiate the plugins.

I tried to update packer, update the host, install ca-certificate. None of this resolve the issue.

Do you know how I can get away with this errors ?

Thank you :)

I tried a Packer Init. Packer is supposed to initiate the plugins.


问:
How to convert a smooth shape into a convex polygon using python?

Given a smooth contour, I want to approximate a regular convex polygon from it. The number of vertices in the polygon could be a parameter which we can pass.

I am absolutely lost on this. I would appreciate any literature, resource, approach you have.

https://docs.opencv.org/4.x/d4/d73/tutorial_py_contours_begin.html#gsc.tab=0

```<code>import numpy as np
import cv2 as cv
im = cv.imread('test.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
</code>```

All i have found is this resource

Body:
Given a smooth contour, I want to approximate a regular convex polygon from it. The number of vertices in the polygon could be a parameter which we can pass.

I am absolutely lost on this. I would appreciate any literature, resource, approach you have.

https://docs.opencv.org/4.x/d4/d73/tutorial_py_contours_begin.html#gsc.tab=0

import numpy as np
import cv2 as cv
im = cv.imread('test.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

All i have found is this resource


问:
How can I set the node-gyp's paths for config.gypi and common.gypi when running npm install?
I'm trying to run npm install after starting to make a PCF Component and ran into the following error:

npm ERR! gyp ERR! stack FetchError: request to https://nodejs.org/download/release/v18.12.1/node-v18.12.1-headers.tar.gz failed, reason: write EPROTO 1C4D0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:c:\ws\deps\openssl\openssl\ssl\statem\extensions.c:922:

To get around it, I followed through the solution here and set, after a lot of unzipping and copy/pasting files to make absolutely certain things get looked at properly, added the following line to my .npmrc file: nodedir=C:\Users\fwilbur001\.node-gyp\18.12.1. Afterwards, I wound up with a different error:

npm ERR! gyp WARN read config.gypi ENOENT: no such file or directory, open 'C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil\C:\Users\fwilbur001\.node-gyp\18.12.1\include\node\config.gypi'

As you can see, node-gyp is attempting to add the config.gypi file's path to, ostensibly, the full path. I ran npm install --verbose to get a better look, and what I found is that node-gyp tries to create the config.gypi in the module's directory, tries to use Python 3.10, and then fails to locate common.gypi because it looks at a bad path (see below):

```<code>npm ERR! gyp info spawn C:\Users\fwilbur001\AppData\Local\Programs\Python\Python310\python.exe
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp\\gyp\\gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'msvs',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\build\\config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp\\addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\C:\\Users\\fwilbur001\\.node-gyp\\18.12.1\\common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=C:\\Users\\fwilbur001\\.node-gyp\\18.12.1',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=C:\\\\Users\\\\fwilbur001\\\\.node-gyp\\\\18.12.1\\\\$(Configuration)\\\\node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp: C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil\\u202aC:\Users\fwilbur001\.node-gyp\18.12.1\common.gypi not found (cwd: C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil) while reading includes of binding.gyp while trying to load binding.gyp
</code>```

I'm at a loss. Any advice? Please help.

Body:
I'm trying to run npm install after starting to make a PCF Component and ran into the following error:

npm ERR! gyp ERR! stack FetchError: request to https://nodejs.org/download/release/v18.12.1/node-v18.12.1-headers.tar.gz failed, reason: write EPROTO 1C4D0000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled:c:\ws\deps\openssl\openssl\ssl\statem\extensions.c:922:

To get around it, I followed through the solution here and set, after a lot of unzipping and copy/pasting files to make absolutely certain things get looked at properly, added the following line to my .npmrc file: nodedir=C:\Users\fwilbur001\.node-gyp\18.12.1. Afterwards, I wound up with a different error:

npm ERR! gyp WARN read config.gypi ENOENT: no such file or directory, open 'C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil\C:\Users\fwilbur001\.node-gyp\18.12.1\include\node\config.gypi'

As you can see, node-gyp is attempting to add the config.gypi file's path to, ostensibly, the full path. I ran npm install --verbose to get a better look, and what I found is that node-gyp tries to create the config.gypi in the module's directory, tries to use Python 3.10, and then fails to locate common.gypi because it looks at a bad path (see below):

npm ERR! gyp info spawn C:\Users\fwilbur001\AppData\Local\Programs\Python\Python310\python.exe
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp\\gyp\\gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'msvs',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\build\\config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp\\addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\C:\\Users\\fwilbur001\\.node-gyp\\18.12.1\\common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=C:\\Users\\fwilbur001\\.node-gyp\\18.12.1',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=C:\\\\Users\\\\fwilbur001\\\\.node-gyp\\\\18.12.1\\\\$(Configuration)\\\\node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'C:\\Users\\fwilbur001\\Desktop\\dev\\project_thing\\node_modules\\bufferutil\\build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp: C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil\\u202aC:\Users\fwilbur001\.node-gyp\18.12.1\common.gypi not found (cwd: C:\Users\fwilbur001\Desktop\dev\project_thing\node_modules\bufferutil) while reading includes of binding.gyp while trying to load binding.gyp

I'm at a loss. Any advice? Please help.


问:
Pause a function on hover of an element in Javascript
I've been working with some javascript code which is from codepen, I forked it for my own usage and added some code to auto rotate the outer circle.

What I am unable to do is modify the code to pause on the shown element when I hover over the centre element .circle--rotate

The code I am working with for myself is on https://codepen.io/CelticWebs/pen/oNMxdrK. To attempt to do what I wanted, auto animate as well as pass eon hover, I added the following code at line 111 in the javascript:

```<code>function movetheone() {
  i.is(":animated") || (p.direction = "right", p.step = d, o())
}
let abc = setInterval(movetheone, 3000);
$('.circle--rotate').hover(() => {
  clearInterval(abc);
}, () => {
  movetheone
})
</code>```

This spins the circle automatically, then does stop spinning when you hover over it but unfortunately it often moves forward one place before pausing, which make the hover pointless as it moves away from what you wanted to stop on.  It also doesn't start back up when you move away.

Does anybody have any suggestions on making this work better please?

I've made the link to the code more obvious above for those asking for more of the code.  Thanks.

Body:
I've been working with some javascript code which is from codepen, I forked it for my own usage and added some code to auto rotate the outer circle.

What I am unable to do is modify the code to pause on the shown element when I hover over the centre element .circle--rotate

The code I am working with for myself is on https://codepen.io/CelticWebs/pen/oNMxdrK. To attempt to do what I wanted, auto animate as well as pass eon hover, I added the following code at line 111 in the javascript:

function movetheone() {
  i.is(":animated") || (p.direction = "right", p.step = d, o())
}
let abc = setInterval(movetheone, 3000);
$('.circle--rotate').hover(() => {
  clearInterval(abc);
}, () => {
  movetheone
})

This spins the circle automatically, then does stop spinning when you hover over it but unfortunately it often moves forward one place before pausing, which make the hover pointless as it moves away from what you wanted to stop on.  It also doesn't start back up when you move away.

Does anybody have any suggestions on making this work better please?

I've made the link to the code more obvious above for those asking for more of the code.  Thanks.


问:
Pass spool file data to a function
I am fetching a SQL query into a spool file. That spool file has 10 account numbers i need to pass each account number to a function as an input parameter My script looks like this

Spool test.log

Select account_num from account where customer = 1234556;

Spool off
Exit;

Now i will get 10 account in the spool file...i need to pass each account to a function as input parameter as

Function(account_num)

Help me how to achieve this

I haven't tried anything

Title: Pass spool file data to a function


问:
Is it possible for cerberus to check nested recursive structure?
So there is a response, which has recursive list children :

```<code>resp = [{'name': "child-1",
      'cap': 3,
      'children': [
          {
              'name': "child-11",
              'cap': 3,
              'children': [
                  {
                      'name': "child-111",
                      'cap': 3,
                      'children': []
                  },
                  {
                      'name': "child-112",
                      'cap': "Str err",
                      'children': []
                  }
              ]
          }
      ]
      },
     {
         'name': "child-2",
         'cap': 3,
         'children': []
     }
     ]
</code>```

and I would like to check if all children have correct structure ('name': "child-112" should raise error)

Is it possible to make recursive schema?

I know that I can add my own type e.g:

```<code>group_schema = {
    'name': {'type': 'string', 'required': True},
    'cap': {'type': 'integer', 'required': True},
    'children': {
        'type': 'list',
        'required': True,
        'schema': {
            \*\*'type': 'group'\*\*
        }
    }
}
</code>```

but I don't know how to validate it. Hope You guys are more experienced. Thanks for help

Body:
So there is a response, which has recursive list children :

resp = [{'name': "child-1",
      'cap': 3,
      'children': [
          {
              'name': "child-11",
              'cap': 3,
              'children': [
                  {
                      'name': "child-111",
                      'cap': 3,
                      'children': []
                  },
                  {
                      'name': "child-112",
                      'cap': "Str err",
                      'children': []
                  }
              ]
          }
      ]
      },
     {
         'name': "child-2",
         'cap': 3,
         'children': []
     }
     ]

and I would like to check if all children have correct structure ('name': "child-112" should raise error)

Is it possible to make recursive schema?

I know that I can add my own type e.g:

group_schema = {
    'name': {'type': 'string', 'required': True},
    'cap': {'type': 'integer', 'required': True},
    'children': {
        'type': 'list',
        'required': True,
        'schema': {
            \*\*'type': 'group'\*\*
        }
    }
}

but I don't know how to validate it. Hope You guys are more experienced. Thanks for help


问:
How to create live link in Github?
I am trying to create a Github live link but it's not generating.

I had uploaded a code and expecting that a live link will be generated but its not comming .

Title: How to create live link in Github?


问:
Reactive mongodb performance vs non-reactive
We run the same query using reactive and non-reactive mongodb clients on the same mongodb servers and same collection (mongoTemplate is of type MongoTemplate and ReactiveMongoTemplate) respectively)

Pageable pageable = PageRequest.of(0, 5000);
Query query = new Query().with(pageable);
query.fields().include(fieldsToProject.toArray(String[]::new));
return mongoTemplate.find(query, MyEntity.class);

On reactive it takes about twice more time

I found some info that reactive is a bit heavier but not THAT much.
I was expecting to see similar of slightly different performance but not that much difference
Is there indeed some known issue about it? Any idea how to troubleshoot?

thank you


问:
Mui Tab Drag/Drop focus tab is not focused (i.e. colored)
I managed to make the React MUI Basic Tab component work with dnd-kit. However, to switch tabs I had to 'brute force' it programmatically and use setFocus for the <Tab... /> component. I also had to do the same thing for the styling.

I was wondering if there is a more friendly way to doing this?. I would appreciate any ideas/help for this.

Here is the example I made on Stackblitz.


问:
Cannot get location with Geolocation API on PWA
I am reaching you because I am facing an issue regarding the gathering of GPS coordinates using only the GPS module of an android tablet device through a Progressive Web Application made with React in Javascript.

I need to collect the GPS coordinates of the tablet even when there is no internet connection. Permissions are granted. The code is working perfectly until Google Chrome V104. Starting at Chrome V105, coordinates are not gathered offline anymore. I am using the Javascript Geolocation API to get the coordinates.
Regarding the logs of the app, it looks like the callbacks of the Geolocation API are completely ignored and are not even called.

Do you know why the geolocation callbacks are completely ignored ?

Here is the functions where I do the Geolocation API calls:

location.js:

```<code>module.exports = class Location {

  constructor() {
    this.ready = 'geolocation' in navigator
    this.id = null
  }

  get() {
    return new Promise((resolve, reject) => {
      if (!this.ready) return reject(new Error('no geolocation in navigator'))

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const coord = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            alt: position.coords.altitude
          }
          return resolve(coord)
        },
        (error) => {
          return reject(error)
        }
      )
    })
  }

  watch(resolve, reject) {
    const options = {
      maximumAge: 5 * 60 * 1000 // 5 minutes is the maximum age of a possible cached position that is acceptable to return
    }

    this.id = navigator.geolocation.watchPosition(
      (position) => {
        const coord = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          alt: position.coords.altitude
        }
        return resolve(coord)
      },
      (error) => {
        return reject(error)
      },
      options
    )
  }

  clean() {
    if (this.id === null) return
    navigator.geolocation.clearWatch(this.id)
  }

}
</code>```

Call to the location functions from Shell.js (componentDidMount):

```<code>async componentDidMount () {
    try {
      const position = await location.get()
      log.info(`location.get() returns ${JSON.stringify(position)}`)
    } catch (error) {
      log.error('location.get() errors', error)
    }

    location.watch(
      (position) => {
        // Decrease alt precision
        if (position.alt) position.alt = parseInt(position.alt)

        // A GPS fix has already been made
        if (this.state.position !== null) {
          function equalTo5(a, b) {
            return a.toFixed(5) === b.toFixed(5)
          }

          const sameLat = equalTo5(this.state.position.lat, position.lat)
          const sameLng = equalTo5(this.state.position.lng, position.lng)
          if (sameLat && sameLng) return

          server.setPosition(position)
          this.setState({position})
        } else {
          log.info(`GPS reading ${JSON.stringify(position)}`)
          server.setPosition(position)
          this.setState({position})
        }
      },
      (error) => {
        if (error.message.startsWith('Only secure origins are allowed')) {
          const position = {lat: 13, lng: 37, alt: 1337}
          log.info(`GPS fake reading ${JSON.stringify(position)}`)
          this.setState({position})
          return
        }

        log.error('GPS cannot get location', error)
        if (this.state.position === null) this.setState({positionError: error})
      })

    this.getServiceWorkerRegistration()
  }
</code>```

I checked the documentation, the code didn't got deprecated, and the functions' signature are always the same.

I looked at the Google Chrome release notes but nothing is specified about a potential change about the way the position is acquiered, or the requirements for this feature to work.

I am doing a call to getCurrentPosition and then I am watching the changes of the position once I have one.

Regarding the Android settings, I disable everything that lead to use something else than the GPS feature to get the coordinates.

To give you a bit more of context, the tablet is connected to a wifi network emitted from a wifi chip embedded into a machine. The machine's wifi doesn't provide access to internet.

I tested the code over Android 8 and 11, and over Google Chrome V70 (Android 8 only), V90, V104, V105, V106, V107, V108

Thanks for your help

Body:
I am reaching you because I am facing an issue regarding the gathering of GPS coordinates using only the GPS module of an android tablet device through a Progressive Web Application made with React in Javascript.

I need to collect the GPS coordinates of the tablet even when there is no internet connection. Permissions are granted. The code is working perfectly until Google Chrome V104. Starting at Chrome V105, coordinates are not gathered offline anymore. I am using the Javascript Geolocation API to get the coordinates.
Regarding the logs of the app, it looks like the callbacks of the Geolocation API are completely ignored and are not even called.

Do you know why the geolocation callbacks are completely ignored ?

Here is the functions where I do the Geolocation API calls:

location.js:

module.exports = class Location {

  constructor() {
    this.ready = 'geolocation' in navigator
    this.id = null
  }

  get() {
    return new Promise((resolve, reject) => {
      if (!this.ready) return reject(new Error('no geolocation in navigator'))

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const coord = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            alt: position.coords.altitude
          }
          return resolve(coord)
        },
        (error) => {
          return reject(error)
        }
      )
    })
  }

  watch(resolve, reject) {
    const options = {
      maximumAge: 5 * 60 * 1000 // 5 minutes is the maximum age of a possible cached position that is acceptable to return
    }

    this.id = navigator.geolocation.watchPosition(
      (position) => {
        const coord = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          alt: position.coords.altitude
        }
        return resolve(coord)
      },
      (error) => {
        return reject(error)
      },
      options
    )
  }

  clean() {
    if (this.id === null) return
    navigator.geolocation.clearWatch(this.id)
  }

}

Call to the location functions from Shell.js (componentDidMount):

async componentDidMount () {
    try {
      const position = await location.get()
      log.info(`location.get() returns ${JSON.stringify(position)}`)
    } catch (error) {
      log.error('location.get() errors', error)
    }

    location.watch(
      (position) => {
        // Decrease alt precision
        if (position.alt) position.alt = parseInt(position.alt)

        // A GPS fix has already been made
        if (this.state.position !== null) {
          function equalTo5(a, b) {
            return a.toFixed(5) === b.toFixed(5)
          }

          const sameLat = equalTo5(this.state.position.lat, position.lat)
          const sameLng = equalTo5(this.state.position.lng, position.lng)
          if (sameLat && sameLng) return

          server.setPosition(position)
          this.setState({position})
        } else {
          log.info(`GPS reading ${JSON.stringify(position)}`)
          server.setPosition(position)
          this.setState({position})
        }
      },
      (error) => {
        if (error.message.startsWith('Only secure origins are allowed')) {
          const position = {lat: 13, lng: 37, alt: 1337}
          log.info(`GPS fake reading ${JSON.stringify(position)}`)
          this.setState({position})
          return
        }

        log.error('GPS cannot get location', error)
        if (this.state.position === null) this.setState({positionError: error})
      })

    this.getServiceWorkerRegistration()
  }

I checked the documentation, the code didn't got deprecated, and the functions' signature are always the same.

I looked at the Google Chrome release notes but nothing is specified about a potential change about the way the position is acquiered, or the requirements for this feature to work.

I am doing a call to getCurrentPosition and then I am watching the changes of the position once I have one.

Regarding the Android settings, I disable everything that lead to use something else than the GPS feature to get the coordinates.

To give you a bit more of context, the tablet is connected to a wifi network emitted from a wifi chip embedded into a machine. The machine's wifi doesn't provide access to internet.

I tested the code over Android 8 and 11, and over Google Chrome V70 (Android 8 only), V90, V104, V105, V106, V107, V108

Thanks for your help


问:
How to comment a comment in XML?
I know it is possible to comment somethin in XML like this:

```<code><?xml version = "1.0" encoding = "UTF-8" ?>
<!--Students grades are uploaded by months-->
<class_list>
   <student>
      <name>Tanmay</name>
      <grade>A</grade>
   </student>
   <!--
   <student>
      <name>Tanmay 2</name>
      <grade>C</grade>
   </student>
   -->
</class_list>
</code>```

But if I wanted to comment all students and preserve the current comments? Like this it isnt possible:

```<code><?xml version = "1.0" encoding = "UTF-8" ?>
<!--Students grades are uploaded by months-->
<class_list>
<!-- this would comment the whole <student> stuff
   <student>
      <name>Tanmay</name>
      <grade>A</grade>
   </student>
   <!-- a comment now:
   <student>
      <name>Tanmay 2</name>
      <grade>C</grade>
   </student>
   -->
-->
</class_list>
</code>```

In C++ and Java e.g. we can comment like this:

// for inside blockers

and /* */ this will comment over the // blocks

```<code>int exampleSum(int a, int b)
{
    // do something
    return a + b;
}
</code>```

So I could comment the whole method

```<code>/*
int exampleSum(int a, int b)
{
    // do something
    return a + b;
}
*/
</code>```

Is there a way to do that in XML?

Title: How to comment a comment in XML?

Body:
I know it is possible to comment somethin in XML like this:

<?xml version = "1.0" encoding = "UTF-8" ?>

<class_list>
   <student>
      <name>Tanmay</name>
      <grade>A</grade>
   </student>

</class_list>

But if I wanted to comment all students and preserve the current comments? Like this it isnt possible:

<?xml version = "1.0" encoding = "UTF-8" ?>

<class_list>

-->
</class_list>

In C++ and Java e.g. we can comment like this:

// for inside blockers

and /* */ this will comment over the // blocks

int exampleSum(int a, int b)
{
    // do something
    return a + b;
}

So I could comment the whole method

/*
int exampleSum(int a, int b)
{
    // do something
    return a + b;
}
*/

Is there a way to do that in XML?


问:
How can Improve inconsistency performance of retrieving data from Cosmos DB? [C# Library - LowCode Environment]
My scenario is slightly different than normal

The tech stack is using something called OutSystems a 'low-code' platform. We have a C# library for connecting to Cosmos DB, but this is only initiated when it's in use. It isn't a constant running API, therefor each time we call the DB, the Cosmos connection is initiated for the first time.

I am running a query which returns about 8k records which has 10 columns of small data. When running my query I am getting really inconsistent timings ranging from 800ms - 3000ms. I am pretty sure I am on the only person using and querying it at the moment.

My code:

```<code>    private async Task<string> QueryItemsAsync(string filter, string partitionKey, int offset, int limit, string columns = null)
    {
        var sqlQuery = QueryBuilder(filter, partitionKey, offset, limit, columns);
        var results = new List<Dictionary<string, string>>();

        using (var feedIterator = this.container.GetItemQueryIterator<Dictionary<string, string>>(sqlQuery, null, new QueryRequestOptions() { }))
        {
            while (feedIterator.HasMoreResults)
            {
                foreach (var item in await feedIterator.ReadNextAsync().ConfigureAwait(false))
                {
                    results.Add(item);
                }
            }
        }
        return JsonConvert.SerializeObject(results);
    }
</code>```

I've noticed that once I query over 1000 rows the performance seems to be the same as if it was 8000.

If I query 'Top 1' the return time is < 40ms.
If I query 'Top 1000' the return time is > 1200ms

Is this the most efficient loop?

If anyone can refactor it, I will love you forever

With the tech stack, it makes debugging super difficult as I cannot live debug. I have to write logs and to console... It takes about 5 minutes to make a change and debug so it's not a quick task hence why I am asking SO.

Thanks in advance,
Sam

edit: The query returns a flat JSON structure

Body:
My scenario is slightly different than normal

The tech stack is using something called OutSystems a 'low-code' platform. We have a C# library for connecting to Cosmos DB, but this is only initiated when it's in use. It isn't a constant running API, therefor each time we call the DB, the Cosmos connection is initiated for the first time.

I am running a query which returns about 8k records which has 10 columns of small data. When running my query I am getting really inconsistent timings ranging from 800ms - 3000ms. I am pretty sure I am on the only person using and querying it at the moment.

My code:

    private async Task<string> QueryItemsAsync(string filter, string partitionKey, int offset, int limit, string columns = null)
    {
        var sqlQuery = QueryBuilder(filter, partitionKey, offset, limit, columns);
        var results = new List<Dictionary<string, string>>();

        using (var feedIterator = this.container.GetItemQueryIterator<Dictionary<string, string>>(sqlQuery, null, new QueryRequestOptions() { }))
        {
            while (feedIterator.HasMoreResults)
            {
                foreach (var item in await feedIterator.ReadNextAsync().ConfigureAwait(false))
                {
                    results.Add(item);
                }
            }
        }
        return JsonConvert.SerializeObject(results);
    }

I've noticed that once I query over 1000 rows the performance seems to be the same as if it was 8000.

If I query 'Top 1' the return time is < 40ms.
If I query 'Top 1000' the return time is > 1200ms

Is this the most efficient loop?

If anyone can refactor it, I will love you forever

With the tech stack, it makes debugging super difficult as I cannot live debug. I have to write logs and to console... It takes about 5 minutes to make a change and debug so it's not a quick task hence why I am asking SO.

Thanks in advance,
Sam

edit: The query returns a flat JSON structure


问:
i push an image to docker registry, but i cannot see it later?
I push an image to docker registry via pipeline and i see the following in the logs:

```<code>/usr/bin/docker images
/usr/bin/docker push <some_repo_name>.azurecr.io/databasedump:7655
REPOSITORY                                  TAG         IMAGE ID       CREATED        SIZE
<some_repo_name>.azurecr.io/databasedump               7655        d57770eee265   1 second ago   404MB
<18_other_lines>
The push refers to repository [<some_repo_name>.azurecr.io/databasedump]
</code>```

But when i later execute

```<code>docker image ls -a
</code>```

only the
<18_other_lines>
appear,

and when i execute in another pipeline the following:

```<code>docker images <some_repo_name>.azurecr.io/databasedump:7578
</code>```

the result is empty:

```<code>========================== Starting Command Output ===========================
/usr/bin/bash /home/vsts/work/_temp/9c8c1b17-1f60-4710-997a-8f1a66f67e24.sh
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
</code>```

Any idea why this happens?
And by the way in the same pipeline, but in another job i execute:

```<code>      docker pull <some_repo_name>.azurecr.io/databasedump:7578
      docker run --publish 3306:3306 <some_repo_name>.azurecr.io/databasedump:7578
</code>```

and i do not see errors in the log.

And all i need here is to see at which ip is the maria db image started, in order to connect to it via python code.

Body:
I push an image to docker registry via pipeline and i see the following in the logs:

/usr/bin/docker images
/usr/bin/docker push <some_repo_name>.azurecr.io/databasedump:7655
REPOSITORY                                  TAG         IMAGE ID       CREATED        SIZE
<some_repo_name>.azurecr.io/databasedump               7655        d57770eee265   1 second ago   404MB
<18_other_lines>
The push refers to repository [<some_repo_name>.azurecr.io/databasedump]

But when i later execute

docker image ls -a

only the
<18_other_lines>
appear,

and when i execute in another pipeline the following:

docker images <some_repo_name>.azurecr.io/databasedump:7578

the result is empty:

========================== Starting Command Output ===========================
/usr/bin/bash /home/vsts/work/_temp/9c8c1b17-1f60-4710-997a-8f1a66f67e24.sh
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE

Any idea why this happens?
And by the way in the same pipeline, but in another job i execute:

      docker pull <some_repo_name>.azurecr.io/databasedump:7578
      docker run --publish 3306:3306 <some_repo_name>.azurecr.io/databasedump:7578

and i do not see errors in the log.

And all i need here is to see at which ip is the maria db image started, in order to connect to it via python code.


问:
Email Verification Fail in Django webapp hosted on Elastic Beanstalk with nginx
I was making a web app on Django. I tried to send an email verification link to any new user who registers on my website. The thing works fine when I am hosting it on localhost but not upon hosting on AWS Elastic Beanstalk. The verification link generated fine. And I found a very similar issue.

Email Verification Fail in Django webapp hosted on Elastic Beanstalk

That answers to the case of appach. But I use nginx instead of appach.

settings.py

```<code>ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_EMAIL_REQUIRED = True
LOGIN_REDIRECT_URL = 'timeline:index'
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login'
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_EMAIL_SUBJECT_PREFIX = ''
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
ACCOUNT_UNIQUE_EMAIL = True
DEFAULT_FROM_EMAIL = 'tnajun@gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

</code>```

urls.py

```<code>from django.contrib import admin
from django.urls import path, re_path, include
from django.contrib.staticfiles.urls import static
from . import settings
from django.views.generic import RedirectView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('timeline.urls')),
    path('contact/', include('contact_form.urls')),
    path('accounts/email/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/inactive/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/password/change/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/confirm-email/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/', include('allauth.urls')),
    path('accounts/', include('accounts.urls')),
    re_path(r'^accounts/confirm-email/[^/]+/', RedirectView.as_view(pattern_name='timeline:index'), kwargs=None),
]
</code>```

Procfile

```<code>web: gunicorn --bind :8000 --workers 3 --threads 2 config.wsgi:application
</code>```

python3.7

Django==3.2.4

django-allauth==0.44.0

I tied ACCOUNT_EMAIL_VERIFICATION = "none" on EB and it works fine but that is not what I want.

Body:
I was making a web app on Django. I tried to send an email verification link to any new user who registers on my website. The thing works fine when I am hosting it on localhost but not upon hosting on AWS Elastic Beanstalk. The verification link generated fine. And I found a very similar issue.

Email Verification Fail in Django webapp hosted on Elastic Beanstalk

That answers to the case of appach. But I use nginx instead of appach.

settings.py

ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_EMAIL_REQUIRED = True
LOGIN_REDIRECT_URL = 'timeline:index'
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login'
ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_EMAIL_SUBJECT_PREFIX = ''
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
ACCOUNT_UNIQUE_EMAIL = True
DEFAULT_FROM_EMAIL = 'tnajun@gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

urls.py

from django.contrib import admin
from django.urls import path, re_path, include
from django.contrib.staticfiles.urls import static
from . import settings
from django.views.generic import RedirectView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('timeline.urls')),
    path('contact/', include('contact_form.urls')),
    path('accounts/email/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/inactive/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/password/change/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/confirm-email/', RedirectView.as_view(pattern_name='timeline:index')),
    path('accounts/', include('allauth.urls')),
    path('accounts/', include('accounts.urls')),
    re_path(r'^accounts/confirm-email/[^/]+/', RedirectView.as_view(pattern_name='timeline:index'), kwargs=None),
]

Procfile

web: gunicorn --bind :8000 --workers 3 --threads 2 config.wsgi:application

python3.7

Django==3.2.4

django-allauth==0.44.0

I tied ACCOUNT_EMAIL_VERIFICATION = "none" on EB and it works fine but that is not what I want.


问:
why does python allows me to access elements not specified in __all__ within a module?
I have the following directory structure:

```<code>.
├── main.py
└── myproj
    ├── __init__.py
    └── mymodule.py
</code>```

This is mymodule.py:

```<code>hello = "hello"
byebye = "byebye"
class sayHello():
    def __init__(self):
        print("Hello World!")

class sayBye():
    def __init__(self):
        print("ByeBye World!")
</code>```

I want only to expose the sayHello class when someone imports like: from myproj import *. My understanding is that this can be achieved by adding an __all__ in the __init__.py file.

init.py

```<code>__all__ = ["sayHello"]
</code>```

but I can still access everything from the mymodule.py module

main.py

```<code>from myproj.mymodule import *

sayBye()
print(locals())
</code>```

Output:

```<code>$ python main.py
ByeBye World!
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10daf5210>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/simon/junk/main.py', '__cached__': None, 'hello': 'hello', 'byebye': 'byebye', 'sayHello': <class 'myproj.mymodule.sayHello'>, 'sayBye': <class 'myproj.mymodule.sayBye'>}
</code>```

I can also access variables like hello, and byebye, which I was not expecting to. I was expecting some sort of error, since everywhere in the docs seems to imply that only the symbols specified in __all__ will be exported.

Body:
I have the following directory structure:

.
├── main.py
└── myproj
    ├── __init__.py
    └── mymodule.py

This is mymodule.py:

hello = "hello"
byebye = "byebye"
class sayHello():
    def __init__(self):
        print("Hello World!")

class sayBye():
    def __init__(self):
        print("ByeBye World!")

I want only to expose the sayHello class when someone imports like: from myproj import *. My understanding is that this can be achieved by adding an __all__ in the __init__.py file.

init.py

__all__ = ["sayHello"]

but I can still access everything from the mymodule.py module

main.py

from myproj.mymodule import *

sayBye()
print(locals())

Output:

$ python main.py
ByeBye World!
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10daf5210>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/simon/junk/main.py', '__cached__': None, 'hello': 'hello', 'byebye': 'byebye', 'sayHello': <class 'myproj.mymodule.sayHello'>, 'sayBye': <class 'myproj.mymodule.sayBye'>}

I can also access variables like hello, and byebye, which I was not expecting to. I was expecting some sort of error, since everywhere in the docs seems to imply that only the symbols specified in __all__ will be exported.


问:
Add the Edit form link to google sheets when form is submitted
I had set up a code previously but it was deleted by someone on our team but now I can't seem to get it working. I need the google forms to automatically add the link to edit the form to the google sheet when a form is submitted.</p>
```<code>function createFormTrigger() {
  var triggerName = 'addFormResponseUrl';
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  ScriptApp.newTrigger(triggerName).forSpreadsheet(spreadsheet).onFormSubmit().create();
}

function addFormResponseUrl(e) {
  // Get the Google Form linked to the response
  var responseSheet = e.range.getSheet();
  var googleFormUrl = responseSheet.getFormUrl();
  var googleForm = FormApp.openByUrl(googleFormUrl);

  // Get the form response based on the timestamp
  var timestamp = new Date(e.namedValues.Timestamp[0]);
  var formResponse = googleForm.getResponses(timestamp).pop();

  // Get the Form response URL and add it to the Google Spreadsheet
  var responseUrl = formResponse.getEditResponseUrl();
  var row = e.range.getRow();
  var responseColumn = 241; // Column where the response URL is recorded.
  responseSheet.getRange(row, responseColumn).setValue(responseUrl);
}
</code>```

Body:
I had set up a code previously but it was deleted by someone on our team but now I can't seem to get it working. I need the google forms to automatically add the link to edit the form to the google sheet when a form is submitted.

function createFormTrigger() {
  var triggerName = 'addFormResponseUrl';
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  ScriptApp.newTrigger(triggerName).forSpreadsheet(spreadsheet).onFormSubmit().create();
}

function addFormResponseUrl(e) {
  // Get the Google Form linked to the response
  var responseSheet = e.range.getSheet();
  var googleFormUrl = responseSheet.getFormUrl();
  var googleForm = FormApp.openByUrl(googleFormUrl);

  // Get the form response based on the timestamp
  var timestamp = new Date(e.namedValues.Timestamp[0]);
  var formResponse = googleForm.getResponses(timestamp).pop();

  // Get the Form response URL and add it to the Google Spreadsheet
  var responseUrl = formResponse.getEditResponseUrl();
  var row = e.range.getRow();
  var responseColumn = 241; // Column where the response URL is recorded.
  responseSheet.getRange(row, responseColumn).setValue(responseUrl);
}


问:
Universal app starts under Rosetta rather than natively on Apple silicon
I have a primary application that is built for x86_64 and runs perfectly fine on Apple silicon under Rosetta translation.

I also have a secondary Electron application that is built as a Universal binary.  When I start the secondary application 'standalone' on Apple silicon it runs natively as expected.

So far, so good.

However, when I get the primary application to start the secondary application, it seems to run under Rosetta.  I'm guessing this is because the primary application is running under the context of Rosetta, so when it starts the secondary Universal application it also starts under Rosetta.

Is there any way to force the secondary application to run natively rather than under Rosetta?


问:
Pygmo2: What is the point of evolving an archipelago in a loop if number of generations already set in algo
I want to solve a multi-objective problem with nsga2 or moead taking advantage of the parallelism available in pygmo library. I have seen a very nice example on github  posted below. However I am not sure I understand it correctly. Setting the number of generations to 10 in the nsga2 algorithm,  it then loops 10 iterations (the so-called number of evolutions) calling the function evolve on the archipelago. Why should we do this evolution specifically ? Could we not set the number of generations to 100 instead of 10 ? or use archi.evolve(10).

The goal here is to speed up the pareto frontier approximation, e.g. instead of using 200 gen and 200 pop size on one core , I would expect that parallelize 50 gen and 50 pop size on 8 cores would do the job. But I am not sure how to do it.

```<code>""Example that illustrates multi-objective optimization using pygmo."""

import pygmo as pg
import numpy as np
from multiprocessing import Process, freeze_support

def optimize(popsize=100, generations=10, islands=3, evolutions=10,
             prob=pg.problem(FonsecaFleming(5))):
    """Start optimization process."""
    # set up algorithm and optimize
    algo = pg.algorithm(pg.nsga2(gen=generations))
    archi = pg.archipelago(islands, algo=algo, prob=prob, pop_size=popsize)

    # evolution
    fits_log, vectors_log = [], []
    for e in range(0, evolutions):
        # evolve islands
        archi.evolve(e)
        archi.wait()
        # extract data
        vectors = [isl.get_population().get_x() for isl in archi]
        vectors_log.append(vectors)
        fits = [isl.get_population().get_f() for isl in archi]
        fits_log.append(fits)

    return [fits_log, vectors_log]

if __name__ == '__main__':
    freeze_support()
    Process(target=optimize).start()
</code>```

Because nsga2 does not seem compatible with a topology in pygmo, I have decided to use moead instead (tell me if i am wrong).

Using a priori-knowledge, i have created a population of 200 individuals , each a vector of 30 variables. I have set fully connected topology to allow communications between the islands of the archipelago. See below my code.

```<code>   algo.set_verbosity(10)
   archi = pg.archipelago(n=8, algo=algo, pop=pop)
   archi.set_topology(pg.fully_connected(len(archi)))
   archi.evolve()
  archi.wait_check()
</code>```

and output:

The code runs but I would have expected different values in the log (ADF, ideal1, ideal2) displayed for each process. Indeed for each generation , all islands have the same output parameters. Is that normal ? Also it is not that much faster (464 seconds instead of 729s)...

Body:
I want to solve a multi-objective problem with nsga2 or moead taking advantage of the parallelism available in pygmo library. I have seen a very nice example on github  posted below. However I am not sure I understand it correctly. Setting the number of generations to 10 in the nsga2 algorithm,  it then loops 10 iterations (the so-called number of evolutions) calling the function evolve on the archipelago. Why should we do this evolution specifically ? Could we not set the number of generations to 100 instead of 10 ? or use archi.evolve(10).

The goal here is to speed up the pareto frontier approximation, e.g. instead of using 200 gen and 200 pop size on one core , I would expect that parallelize 50 gen and 50 pop size on 8 cores would do the job. But I am not sure how to do it.

""Example that illustrates multi-objective optimization using pygmo."""

import pygmo as pg
import numpy as np
from multiprocessing import Process, freeze_support

def optimize(popsize=100, generations=10, islands=3, evolutions=10,
             prob=pg.problem(FonsecaFleming(5))):
    """Start optimization process."""
    # set up algorithm and optimize
    algo = pg.algorithm(pg.nsga2(gen=generations))
    archi = pg.archipelago(islands, algo=algo, prob=prob, pop_size=popsize)

    # evolution
    fits_log, vectors_log = [], []
    for e in range(0, evolutions):
        # evolve islands
        archi.evolve(e)
        archi.wait()
        # extract data
        vectors = [isl.get_population().get_x() for isl in archi]
        vectors_log.append(vectors)
        fits = [isl.get_population().get_f() for isl in archi]
        fits_log.append(fits)

    return [fits_log, vectors_log]

if __name__ == '__main__':
    freeze_support()
    Process(target=optimize).start()

Because nsga2 does not seem compatible with a topology in pygmo, I have decided to use moead instead (tell me if i am wrong).

Using a priori-knowledge, i have created a population of 200 individuals , each a vector of 30 variables. I have set fully connected topology to allow communications between the islands of the archipelago. See below my code.

   algo.set_verbosity(10)
   archi = pg.archipelago(n=8, algo=algo, pop=pop)
   archi.set_topology(pg.fully_connected(len(archi)))
   archi.evolve()
  archi.wait_check()

and output:

The code runs but I would have expected different values in the log (ADF, ideal1, ideal2) displayed for each process. Indeed for each generation , all islands have the same output parameters. Is that normal ? Also it is not that much faster (464 seconds instead of 729s)...


问:
Refer last filled cell adjacent to a column of dates
I would like to create a comparison table in a dashboard sheet that refers to data inputted in different sheets.

All the other sheets are the same format: Column A (Header Column) has a list of dates, Columns B-E have data which I would like to refer to in the dashboard sheet. Data in columns B-E is entered manually when the date arrives, so I would like the table in the dashboard sheet to automatically show the cells adjacent to the latest date/latest filled row.

I have tried basic VLOOKUP but can't seem to figure out any way to automatically refer to the row with the latest date or last filled row.


问:
Cypress can't bypass login page with Cognito authorization
I'm getting Cognito credentials with custom command:

```<code>import { Auth } from "aws-amplify";
import "cypress-localstorage-commands";
Cypress.Commands.add("loginByCognitoApi", () => {
      //configures auth
    const awsconfig = {
      aws_user_pools_id: Cypress.env("userPoolId"),
      aws_user_pools_web_client_id: Cypress.env("clientId"),
    };
    Auth.configure(awsconfig);
    //sign in
    const signIn = Auth.signIn(Cypress.env("username"), Cypress.env("password"));
    //get the tokens and store into the local storage
    cy.wrap(signIn, { log: false }).then((cognitoResponse) => {
      const keyPrefixWithUsername = `${cognitoResponse.keyPrefix}.${cognitoResponse.username}`;
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.idToken`,
        cognitoResponse.signInUserSession.idToken.jwtToken,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.accessToken`,
        cognitoResponse.signInUserSession.accessToken.jwtToken,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.refreshToken`,
        cognitoResponse.signInUserSession.refreshToken.token,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.clockDrift`,
        cognitoResponse.signInUserSession.clockDrift,
      );
      window.localStorage.setItem(
        `${cognitoResponse.keyPrefix}.LastAuthUser`,
        cognitoResponse.username,
      );
      window.localStorage.setItem("amplify-authenticator-authState", "signedIn");
      console.log(localStorage)
    })

});
</code>```

authorization data
After cy.visit() all storage is cleared and redirects back to login screen
Please, advise what could be wrong. Thank you!

Expected: bypass login page
Actual: redirects back to login page

Body:
I'm getting Cognito credentials with custom command:

import { Auth } from "aws-amplify";
import "cypress-localstorage-commands";
Cypress.Commands.add("loginByCognitoApi", () => {
      //configures auth
    const awsconfig = {
      aws_user_pools_id: Cypress.env("userPoolId"),
      aws_user_pools_web_client_id: Cypress.env("clientId"),
    };
    Auth.configure(awsconfig);
    //sign in
    const signIn = Auth.signIn(Cypress.env("username"), Cypress.env("password"));
    //get the tokens and store into the local storage
    cy.wrap(signIn, { log: false }).then((cognitoResponse) => {
      const keyPrefixWithUsername = `${cognitoResponse.keyPrefix}.${cognitoResponse.username}`;
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.idToken`,
        cognitoResponse.signInUserSession.idToken.jwtToken,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.accessToken`,
        cognitoResponse.signInUserSession.accessToken.jwtToken,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.refreshToken`,
        cognitoResponse.signInUserSession.refreshToken.token,
      );
      window.localStorage.setItem(
        `${keyPrefixWithUsername}.clockDrift`,
        cognitoResponse.signInUserSession.clockDrift,
      );
      window.localStorage.setItem(
        `${cognitoResponse.keyPrefix}.LastAuthUser`,
        cognitoResponse.username,
      );
      window.localStorage.setItem("amplify-authenticator-authState", "signedIn");
      console.log(localStorage)
    })

});

authorization data
After cy.visit() all storage is cleared and redirects back to login screen
Please, advise what could be wrong. Thank you!

Expected: bypass login page
Actual: redirects back to login page


问:
SLIM PHP PHINX cannot do a migration to a MySQL container
I am trying to do a migration with PHINX in a database with a MySQL container, but getting the following issue.

PDOException: SQLSTATE[HY000] [2002] Connection refused in /var/www/html/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php:86

This is my phinx.php:

```<code><?php

require './vendor/autoload.php';

return
[
    'paths' => [
        'migrations' => 'database/migrations',
        'seeds' => '/database/seeds'
    ],
    'migration_base_class' => '\Migrations\Migration',
    'environments' => [
        'default_environment' => 'dev',
        'default_database' => 'dev',
        'dev' => [
            'adapter' => 'mysql',
            'host' => '127.0.0.1',
            'name' => 'db_slim',
            'user' => 'db_slim',
            'pass' => 'root',
        ]
    ]
];
</code>```

Migration class:

```<code><?php

namespace Migrations;

use Illuminate\Database\Capsule\Manager as Capsule;
use Phinx\Migration\AbstractMigration;

class Migration extends AbstractMigration
{
    /** @var \Illuminate\Database\Capsule\Manager $capsule */
    public $capsule;
    /** @var \Illuminate\Database\Schema\Builder $capsule */
    public $schema;

    public function init()
    {
        $this->capsule = new Capsule;
        $this->capsule->addConnection([
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'database' => 'db_slim',
            'username' => 'db_slim',
            'password' => 'root',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
        ]);

        $this->capsule->bootEloquent();
        $this->capsule->setAsGlobal();
        $this->schema = $this->capsule->schema();
    }
}
</code>```

Create table instruction:

```<code><?php
declare(strict_types=1);

use Migrations\Migration;

final class CreateUsersTable extends Migration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $this->schema->create('users', function (Illuminate\Database\Schema\Blueprint $table)
        {
            $table->increments("id");
            $table->string("name");
            $table->string("email");
            $table->string("password");
            $table->timestamps();
        });
    }
}
</code>```

Docker container:

```<code>mysql:
    image: mysql:5.7.29
    container_name: mysql_slim
    restart: unless-stopped
    tty: true
    ports:
      - "3307:3306"
    environment:
      MYSQL_DATABASE: db_slim
      MYSQL_USER: db_slim
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    networks:
      - php-challenge
    volumes:
      - ./mysql:/var/lib/mysql
</code>```

I can access the container DB with tools like a workbench, php-storm database tab, I don't know why I try do execute phinx.php migrate is getting the issue, for some reason, I think that my conn values (host, etc) do not work.

I've tried to do the same command migration outside the container (with a local MySQL env) and works, is there another way to solve or connect to the MySQL container?

Body:
I am trying to do a migration with PHINX in a database with a MySQL container, but getting the following issue.

PDOException: SQLSTATE[HY000] [2002] Connection refused in /var/www/html/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php:86

This is my phinx.php:

<?php

require './vendor/autoload.php';

return
[
    'paths' => [
        'migrations' => 'database/migrations',
        'seeds' => '/database/seeds'
    ],
    'migration_base_class' => '\Migrations\Migration',
    'environments' => [
        'default_environment' => 'dev',
        'default_database' => 'dev',
        'dev' => [
            'adapter' => 'mysql',
            'host' => '127.0.0.1',
            'name' => 'db_slim',
            'user' => 'db_slim',
            'pass' => 'root',
        ]
    ]
];

Migration class:

<?php

namespace Migrations;

use Illuminate\Database\Capsule\Manager as Capsule;
use Phinx\Migration\AbstractMigration;

class Migration extends AbstractMigration
{
    /** @var \Illuminate\Database\Capsule\Manager $capsule */
    public $capsule;
    /** @var \Illuminate\Database\Schema\Builder $capsule */
    public $schema;

    public function init()
    {
        $this->capsule = new Capsule;
        $this->capsule->addConnection([
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'database' => 'db_slim',
            'username' => 'db_slim',
            'password' => 'root',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
        ]);

        $this->capsule->bootEloquent();
        $this->capsule->setAsGlobal();
        $this->schema = $this->capsule->schema();
    }
}

Create table instruction:

<?php
declare(strict_types=1);

use Migrations\Migration;

final class CreateUsersTable extends Migration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $this->schema->create('users', function (Illuminate\Database\Schema\Blueprint $table)
        {
            $table->increments("id");
            $table->string("name");
            $table->string("email");
            $table->string("password");
            $table->timestamps();
        });
    }
}

Docker container:

mysql:
    image: mysql:5.7.29
    container_name: mysql_slim
    restart: unless-stopped
    tty: true
    ports:
      - "3307:3306"
    environment:
      MYSQL_DATABASE: db_slim
      MYSQL_USER: db_slim
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    networks:
      - php-challenge
    volumes:
      - ./mysql:/var/lib/mysql

I can access the container DB with tools like a workbench, php-storm database tab, I don't know why I try do execute phinx.php migrate is getting the issue, for some reason, I think that my conn values (host, etc) do not work.

I've tried to do the same command migration outside the container (with a local MySQL env) and works, is there another way to solve or connect to the MySQL container?


问:
Flutter wearOS Round Watch Widget alignment
Hello I would like to have three bottons at the end of my screen. What works for a rectangular clock as follows.

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            child: Text('test'),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Row(
              children: [
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.delete),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.edit),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.play_arrow),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
              ],
            ),
          )
        ],
      )
    );
</code>```

But when I have a round clock the buttons are no longer completely in the picture. How can I guarantee that the buttons are completely visible?

Body:
Hello I would like to have three bottons at the end of my screen. What works for a rectangular clock as follows.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            child: Text('test'),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Row(
              children: [
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.delete),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.edit),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
                ElevatedButton(
                  onPressed: () => {},
                  child: Icon(Icons.play_arrow),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(0),
                    backgroundColor: Colors.green, // <-- Button color
                    foregroundColor: Colors.white, // <-- Splash color
                  ),
                ),
              ],
            ),
          )
        ],
      )
    );

But when I have a round clock the buttons are no longer completely in the picture. How can I guarantee that the buttons are completely visible?


问:
Call the method every 20 seconds for multiple times then for every minute
I have five tabs on my page.

If I am on Tab5 then I want that the callAutoRefresh function gets called multiple times for 20 seconds followed by auto-refresh every min till the user is on the tab.

If a user leaves the tab then the callAutoRefresh function should stop execution. And then we should start over if we come back to tab5.

```<code>const initialInterval = setInterval(function() {
  intervalCount++;
  if (intervalCount < 3) {
    callAutoRefresh(id);
  } else {
    const minuteLongInterval = setInterval(function() {
      if (localStorage.getItem("container") == "MyContainer") {
        callAutoRefresh(id);
      } else {
        clearInterval(minuteLongInterval);
      }
    }, 60000);
    clearInterval(initialInterval);
  }
}, 20000);
</code>```

I have tried to use the setInterval() function. The problem is It stops executing when the container gets changed but it already has the getAutoRefresh method stacked up in the memory -
So if I get back to tab5 it starts executing the getAutoRefresh method for the current id. And stacked up methods for the previous IDs as well.

Appreciate any small help.

Body:
I have five tabs on my page.

If I am on Tab5 then I want that the callAutoRefresh function gets called multiple times for 20 seconds followed by auto-refresh every min till the user is on the tab.

If a user leaves the tab then the callAutoRefresh function should stop execution. And then we should start over if we come back to tab5.

const initialInterval = setInterval(function() {
  intervalCount++;
  if (intervalCount < 3) {
    callAutoRefresh(id);
  } else {
    const minuteLongInterval = setInterval(function() {
      if (localStorage.getItem("container") == "MyContainer") {
        callAutoRefresh(id);
      } else {
        clearInterval(minuteLongInterval);
      }
    }, 60000);
    clearInterval(initialInterval);
  }
}, 20000);

I have tried to use the setInterval() function. The problem is It stops executing when the container gets changed but it already has the getAutoRefresh method stacked up in the memory -
So if I get back to tab5 it starts executing the getAutoRefresh method for the current id. And stacked up methods for the previous IDs as well.

Appreciate any small help.