问:
What makes $this->makeURL PHP code to point to the class and use its method?
I am a PHP newbie, i looked at these codes (github link) and able to understand 70% - 80% by studying these codes to learn the concept behind it - the MVC concept, view, controller, multiton pattern, etc.

However, this particular code - I can't really understand how it works.

---from init.php ---

```<code>define("APP_URL", APP_PROTOCOL . $_SERVER["HTTP_HOST"] . str_replace("public_html", "", dirname($_SERVER["SCRIPT_NAME"])) . "/");
</code>```

---from view.php ---

```<code> /**
     * Make URL: Creates and returns a clean internal URL.
     * @param mixed $path [optional]
     * @return string
     */
    public function makeURL($path = "") {
        if (is_array($path)) {
            return(APP_URL . implode("/", $path));
        }
        return(APP_URL . $path);
    }
</code>```

---from various html view, index, login, register ---

the usage in the html view portion (Index, Login, Register):

```<code><a class="btn btn-default btn-lg" href="<?= $this->makeURL("profile"); ?>" role="button">Profile</a>

<a class="btn btn-primary btn-lg" href="<?= $this->makeURL("login/logout"); ?>" role="button">Logout</a>

<form action="<?= $this->makeUrl("login/_login"); ?>" method="post">

<a href="<?= $this->makeURL("register"); ?>" class="btn btn-link">Register</a>

<form action="<?= $this->makeUrl("register/_register"); ?>" method="post">

<a href="<?= $this->makeURL("login"); ?>" class="btn btn-link">Cancel</a>
</code>```

-- Need help below this line ---

I can't understand exactly how the makeURL work

These codes: $this->makeURL("profile") or ("register") or ("login")

These codes: $this->makeURL("login/logout") or ("login/_login") or ("register/_register")

My interpretation on item 1 & 2 above as followed:

These codes will makeURL to point to the profile.php or register.php or login.php

These codes: will makeURL to point to the login.php or logout.php, while login/_login will makeURL point to login.php to use _login method, as well as register/_register will makeURL point to register.php and use _register method.

I separated the makeURL as independent file and feed the "profile", "register", "login", "login/logout", "login/_login", "register/_register"

note: there is a redirect method under _login or _register - i understood this part.

A.  I still couldn't understand how exactly $this->makeURL (item # 2 above) can point to the login.php or register.php to use the method _login or _register...?

B.  How the form action post method pass array into makeURL to be used...?

Body:
I am a PHP newbie, i looked at these codes (github link) and able to understand 70% - 80% by studying these codes to learn the concept behind it - the MVC concept, view, controller, multiton pattern, etc.

However, this particular code - I can't really understand how it works.

---from init.php ---

define("APP_URL", APP_PROTOCOL . $_SERVER["HTTP_HOST"] . str_replace("public_html", "", dirname($_SERVER["SCRIPT_NAME"])) . "/");

---from view.php ---

 /**
     * Make URL: Creates and returns a clean internal URL.
     * @param mixed $path [optional]
     * @return string
     */
    public function makeURL($path = "") {
        if (is_array($path)) {
            return(APP_URL . implode("/", $path));
        }
        return(APP_URL . $path);
    }

---from various html view, index, login, register ---

the usage in the html view portion (Index, Login, Register):

<a class="btn btn-default btn-lg" href="<?= $this->makeURL("profile"); ?>" role="button">Profile

<a class="btn btn-primary btn-lg" href="<?= $this->makeURL("login/logout"); ?>" role="button">Logout

<form action="<?= $this->makeUrl("login/_login"); ?>" method="post">

<a href="<?= $this->makeURL("register"); ?>" class="btn btn-link">Register

<form action="<?= $this->makeUrl("register/_register"); ?>" method="post">

<a href="<?= $this->makeURL("login"); ?>" class="btn btn-link">Cancel

-- Need help below this line ---

I can't understand exactly how the makeURL work

These codes: $this->makeURL("profile") or ("register") or ("login")

These codes: $this->makeURL("login/logout") or ("login/_login") or ("register/_register")

My interpretation on item 1 & 2 above as followed:

These codes will makeURL to point to the profile.php or register.php or login.php

These codes: will makeURL to point to the login.php or logout.php, while login/_login will makeURL point to login.php to use _login method, as well as register/_register will makeURL point to register.php and use _register method.

I separated the makeURL as independent file and feed the "profile", "register", "login", "login/logout", "login/_login", "register/_register"

note: there is a redirect method under _login or _register - i understood this part.

A.  I still couldn't understand how exactly $this->makeURL (item # 2 above) can point to the login.php or register.php to use the method _login or _register...?

B.  How the form action post method pass array into makeURL to be used...?


来源: stackexchange

问:
JSON SCHEMA for questionnaires in different languages. The property value depends on the language
I want to define a json schema for a a questionnaire. For example one question is about colour. In english (en) you can select ["red", "green"]. In spanish (es) you can select ["rojo","verde"].

The property colour in english is:

```<code>"colour": {
   "type": "string",
    "enum": ["red", "green"]
}
</code>```

In spanish:

```<code>"colour": {
   "type": "string",
    "enum": ["rojo","verde"]
}
</code>```

How I can define a json schema for checking the data in function of the language?

ContentLicense: CC BY-SA 4.0

Body:
I want to define a json schema for a a questionnaire. For example one question is about colour. In english (en) you can select ["red", "green"]. In spanish (es) you can select ["rojo","verde"].

The property colour in english is:

"colour": {
   "type": "string",
    "enum": ["red", "green"]
}

In spanish:

"colour": {
   "type": "string",
    "enum": ["rojo","verde"]
}

How I can define a json schema for checking the data in function of the language?


问:
I I am running the command npm run build -- --ia32.it throws error
I have write this command and it shows me error

PS C:\Users\hp\OneDrive\Desktop\electron-script> npm run build -- --ia32

electron@1.0.0 build
electron-builder "--ia32"

• electron-builder  version=23.6.0 os=10.0.22000
• description is missed in the package.json  appPackageFile=C:\Users\hp\OneDrive\Desktop\electron-script\package.json
• writing effective config  file=dist\builder-effective-config.yaml
• rebuilding native dependencies  dependencies=@serialport/bindings-cpp@10.8.0 platform=win32 arch=ia32
⨯ cannot execute  cause=exit status 1
errorOut=npm ERR! code 1
npm ERR! path C:\Users\hp\OneDrive\Desktop\electron-script\node_modules@serialport\bindings-cpp
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp-build
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@16.15.0 | win32 | x64
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration
npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON
npm ERR! gyp ERR! find Python checking if "python3" can be used
npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if "python" can be used
npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if the py launcher can be used to find Python 3
npm ERR! gyp ERR! find Python - "py.exe" is not in PATH or produced an error
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python You need to install the latest version of Python.
npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
npm ERR! gyp ERR! find Python you can try one of the following options:
npm ERR! gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python   (accepted by both node-gyp and npm)
npm ERR! gyp ERR! find Python - Set the environment variable PYTHON
npm ERR! gyp ERR! find Python - Set the npm configuration variable python:
npm ERR! gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python For more information consult the documentation at:
npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Python installation to use
npm ERR! gyp ERR! stack     at PythonFinder.fail (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:330:47)

npm ERR! gyp ERR! stack     at PythonFinder.runChecks (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:159:21)
npm ERR! gyp ERR! stack     at PythonFinder. (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:228:18)
npm ERR! gyp ERR! stack     at PythonFinder.execFileCallback (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:294:16)
npm ERR! gyp ERR! stack     at exithandler (node:child_process:406:5)
npm ERR! gyp ERR! stack     at ChildProcess.errorhandler (node:child_process:418:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:527:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)
npm ERR! gyp ERR! stack     at onErrorNT (node:internal/child_process:478:16)
npm ERR! gyp ERR! stack     at processTicksAndRejections (node:internal/process/task_queues:83:21)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\hp\OneDrive\Desktop\electron-script\node_modules@serialport\bindings-cpp
npm ERR! gyp ERR! node -v v16.15.0
npm ERR! gyp ERR! node-gyp -v v9.0.0
npm ERR! gyp ERR! not ok

```<code>npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Local\npm-cache\_logs\2022-12-17T06_19_09_056Z-debug-0.log
</code>```

Body:
I have write this command and it shows me error

PS C:\Users\hp\OneDrive\Desktop\electron-script> npm run build -- --ia32

electron@1.0.0 build
electron-builder "--ia32"

• electron-builder  version=23.6.0 os=10.0.22000
• description is missed in the package.json  appPackageFile=C:\Users\hp\OneDrive\Desktop\electron-script\package.json
• writing effective config  file=dist\builder-effective-config.yaml
• rebuilding native dependencies  dependencies=@serialport/bindings-cpp@10.8.0 platform=win32 arch=ia32
⨯ cannot execute  cause=exit status 1
errorOut=npm ERR! code 1
npm ERR! path C:\Users\hp\OneDrive\Desktop\electron-script\node_modules@serialport\bindings-cpp
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp-build
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.0.0
npm ERR! gyp info using node@16.15.0 | win32 | x64
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration
npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON
npm ERR! gyp ERR! find Python checking if "python3" can be used
npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if "python" can be used
npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\hp\AppData\Local\Programs\Python\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\hp\AppData\Local\Programs\Python\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if the py launcher can be used to find Python 3
npm ERR! gyp ERR! find Python - "py.exe" is not in PATH or produced an error
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python You need to install the latest version of Python.
npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
npm ERR! gyp ERR! find Python you can try one of the following options:
npm ERR! gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python   (accepted by both node-gyp and npm)
npm ERR! gyp ERR! find Python - Set the environment variable PYTHON
npm ERR! gyp ERR! find Python - Set the npm configuration variable python:
npm ERR! gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python For more information consult the documentation at:
npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Python installation to use
npm ERR! gyp ERR! stack     at PythonFinder.fail (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:330:47)

npm ERR! gyp ERR! stack     at PythonFinder.runChecks (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:159:21)
npm ERR! gyp ERR! stack     at PythonFinder. (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:228:18)
npm ERR! gyp ERR! stack     at PythonFinder.execFileCallback (C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\lib\find-python.js:294:16)
npm ERR! gyp ERR! stack     at exithandler (node:child_process:406:5)
npm ERR! gyp ERR! stack     at ChildProcess.errorhandler (node:child_process:418:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:527:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)
npm ERR! gyp ERR! stack     at onErrorNT (node:internal/child_process:478:16)
npm ERR! gyp ERR! stack     at processTicksAndRejections (node:internal/process/task_queues:83:21)
npm ERR! gyp ERR! System Windows_NT 10.0.22000
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\hp\AppData\Roaming\nvm\v16.15.0\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd C:\Users\hp\OneDrive\Desktop\electron-script\node_modules@serialport\bindings-cpp
npm ERR! gyp ERR! node -v v16.15.0
npm ERR! gyp ERR! node-gyp -v v9.0.0
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hp\AppData\Local\npm-cache\_logs\2022-12-17T06_19_09_056Z-debug-0.log


问:
Custom Printer Preferences resetting after restarting Printer Spooler/Restarting PC
I have come across a second PC whereby if I Create a New Form with a different paper size, Save the Form and set the new Form as the printer's preference it will save correctly.

but when I restart the printer spooler service/restart the PC the custom Form I created for the printer is reset to another existing form (e.g. Letter)

This started in 2022, could it be a windows 10 update regression? (because I am not experiencing this issue on windows 7/server 2012) or has someone solved this?

Current Solution: When I restart the spooler and custom preferences are reset and set them again and restart the spooler again too, then all will be good for a while(days) before custom preferences are auto-reset


问:
"An error occurred in the deployment tool" Visual Studio issue with deploying to aws keep telling this
"An error occurred in the deployment tool" Visual Studio issue with deploying to aws keep telling this...
Whatever the option we choose the result is same issue.


问:
Reload audio file from DB in JS
I press a button in browser:

```<code>function action() {
  var audio = new Audio("https://mydb.com/output.wav");
  audio.load();
  audio.play();
}
</code>```

Then, I change my sound in DB with other button.

It changes in DB, but it does not reload in JS.

What can I do?

Thank you!

audio.load();

doesn't help

Title: Reload audio file from DB in JS

Body:
I press a button in browser:

function action() {
  var audio = new Audio("https://mydb.com/output.wav");
  audio.load();
  audio.play();
}

Then, I change my sound in DB with other button.

It changes in DB, but it does not reload in JS.

What can I do?

Thank you!

audio.load();

doesn't help


问:
How to add Alert on buy sell arrow
How to add Alert on Buy_Signal & Sell_Signal arrow, I added below code but getting wrong signals. Can anyone help me out with it. Thanks

if (((TriggerCandle > 0) && (time[rates_total - 1] > LastAlertTime)) || (TriggerCandle == 0))
{
        string Text;
        // Up Arrow Alert
        if ((Buy_Signal[rates_total - 1 - TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != 1))))
        {
                Text = AlertText + "Alpha Buy: " + Symbol() + " - " + EnumToString(Period()) + " - Up.";
                if (EnableNativeAlerts) Alert(Text);
                if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Alpha Buy", Text);
                if (EnableSoundAlerts) PlaySound(SoundFileName);
                if (EnablePushAlerts) SendNotification(Text);
                LastAlertTime = time[rates_total - 1];
                LastAlertDirection = 1;
        }
        // Down Arrow Alert
        if ((Sell_Signal[rates_total - 1 - TriggerCandle] > 0) && ((TriggerCandle > 0) || ((TriggerCandle == 0) && (LastAlertDirection != -1))))
        {
                Text = AlertText + "Alpha Sell: " + Symbol() + " - " + EnumToString(Period()) + " - Down.";
                if (EnableNativeAlerts) Alert(Text);
                if (EnableEmailAlerts) SendMail(AlertEmailSubject + "Alpha Sell", Text);
                if (EnableSoundAlerts) PlaySound(SoundFileName);
                if (EnablePushAlerts) SendNotification(Text);
                LastAlertTime = time[rates_total - 1];
                LastAlertDirection = -1;
        }
}
//--- return value of prev_calculated for next call
   return(rates_total);
  }```

Title: How to add Alert on buy sell arrow


问:
tuple becomes empty after one iteration of for loop
I have a problem with this code. Even though the if conditional is for equivalence of the tuple object, after the second iteration of for loop, the whole parent tuple becomes empty, and I receive error:

IndexError: list index out of range
```
<pre class="lang-py prettyprint-override"><code>tup = ((1, 2), (1, 4), (1, 3), (1, 2))

def remove_dup(event, schedule):
    for i in schedule:
        if i == event:
            schedule = tuple((list(schedule[1:])).remove(i))
    return schedule

remove_dup((1, 2), tup)  # should remove (1, 2) of index 3
</code>```

I was hoping that the for loop would remove the last child tuple (1, 2), as it is equivalent to the event.

Body:
I have a problem with this code. Even though the if conditional is for equivalence of the tuple object, after the second iteration of for loop, the whole parent tuple becomes empty, and I receive error:

IndexError: list index out of range

tup = ((1, 2), (1, 4), (1, 3), (1, 2))

def remove_dup(event, schedule):
    for i in schedule:
        if i == event:
            schedule = tuple((list(schedule[1:])).remove(i))
    return schedule

remove_dup((1, 2), tup)  # should remove (1, 2) of index 3

I was hoping that the for loop would remove the last child tuple (1, 2), as it is equivalent to the event.


问:
Keep dummy clocks in SCLK (SPI)
I'm using ESP32 on VSPI in a half-duplex manner with a slave device.

I wish to first send the device a standard SPI transaction, and right after that to keep clocking out dummy pulses in the same VSPI interface (clocking VSPICLK pin with same frequency, with zeros on VSPID).

I managed to send the transaction itself, but I don't find the right way to keep the dummy clocks. Important to mention that the dummy pulses shouldn't block the code so I can handle other tasks.

Any thoughts?

Update:

Getting closer by calling a simple write bytes method

```<code>/**
 * @param data uint8_t *
 * @param size uint32_t
 */
void SPIClass::writeBytes(const uint8_t * data, uint32_t size)
{
    if(_inTransaction){
        return spiWriteNL(_spi, data, size);
    }
    spiSimpleTransaction(_spi);
    spiWriteNL(_spi, data, size);
    spiEndTransaction(_spi);
}
</code>```

But this one blocks...

Previously:

I've tries to send empty bytes in a normal SPI transaction but this is a blocking method and got some lags between bytes (you can see it in the VSCLK blue channel).

dummy clocks with lags, and blocking code

```<code>void write(uint8_t data)
{
    noInterrupts();

    // Working transaction to the device
    // _spi_dev is an SPIClass*
    _spi_dev->beginTransaction();
    _spi_dev->transfer(data);
    _spi_dev->endTransaction();
    delayMicroseconds(10); // Required delay by the slave device to latch the command

    // naively sending dummy bytes - a blocking call
    _spi_dev->beginTransaction();
    for (uint8_t n = 0; n < 100; n++) {
        for (int8_t c = 10; c > 0; c--) _spi_dev->transfer(0x0);
    }
    _spi_dev->endTransaction();

    interrupts();
}

</code>```

This code:

```<code>_spi_dev->transfer(data);
</code>```

ends up with this:

```<code>uint8_t spiTransferByte(spi_t * spi, uint8_t data)
{
    if(!spi) {
        return 0;
    }
    SPI_MUTEX_LOCK();
    spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
    spi->dev->miso_dlen.usr_miso_dbitlen = 7;
    spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
    spi->dev->cmd.update = 1;
    while (spi->dev->cmd.update);
#endif
    spi->dev->cmd.usr = 1;
    while(spi->dev->cmd.usr);
    data = spi->dev->data_buf[0] & 0xFF;
    SPI_MUTEX_UNLOCK();
    return data;
}
</code>```

In Addition this one:

```<code>_spi_dev->beginTransaction();
</code>```

With this:

```<code>void SPIClass::beginTransaction(SPISettings settings)
{
    //check if last freq changed
    uint32_t cdiv = spiGetClockDiv(_spi);
    if(_freq != settings._clock || _div != cdiv) {
        _freq = settings._clock;
        _div = spiFrequencyToClockDiv(_freq);
    }
    spiTransaction(_spi, _div, settings._dataMode, settings._bitOrder);
    _inTransaction = true;
}
</code>```

Title: Keep dummy clocks in SCLK (SPI)

Body:
I'm using ESP32 on VSPI in a half-duplex manner with a slave device.

I wish to first send the device a standard SPI transaction, and right after that to keep clocking out dummy pulses in the same VSPI interface (clocking VSPICLK pin with same frequency, with zeros on VSPID).

I managed to send the transaction itself, but I don't find the right way to keep the dummy clocks. Important to mention that the dummy pulses shouldn't block the code so I can handle other tasks.

Any thoughts?

Update:

Getting closer by calling a simple write bytes method

/**
 * @param data uint8_t *
 * @param size uint32_t
 */
void SPIClass::writeBytes(const uint8_t * data, uint32_t size)
{
    if(_inTransaction){
        return spiWriteNL(_spi, data, size);
    }
    spiSimpleTransaction(_spi);
    spiWriteNL(_spi, data, size);
    spiEndTransaction(_spi);
}

But this one blocks...

Previously:

I've tries to send empty bytes in a normal SPI transaction but this is a blocking method and got some lags between bytes (you can see it in the VSCLK blue channel).

dummy clocks with lags, and blocking code

void write(uint8_t data)
{
    noInterrupts();

    // Working transaction to the device
    // _spi_dev is an SPIClass*
    _spi_dev->beginTransaction();
    _spi_dev->transfer(data);
    _spi_dev->endTransaction();
    delayMicroseconds(10); // Required delay by the slave device to latch the command

    // naively sending dummy bytes - a blocking call
    _spi_dev->beginTransaction();
    for (uint8_t n = 0; n < 100; n++) {
        for (int8_t c = 10; c > 0; c--) _spi_dev->transfer(0x0);
    }
    _spi_dev->endTransaction();

    interrupts();
}

This code:

_spi_dev->transfer(data);

ends up with this:

uint8_t spiTransferByte(spi_t * spi, uint8_t data)
{
    if(!spi) {
        return 0;
    }
    SPI_MUTEX_LOCK();
    spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
    spi->dev->miso_dlen.usr_miso_dbitlen = 7;
    spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
    spi->dev->cmd.update = 1;
    while (spi->dev->cmd.update);
#endif
    spi->dev->cmd.usr = 1;
    while(spi->dev->cmd.usr);
    data = spi->dev->data_buf[0] & 0xFF;
    SPI_MUTEX_UNLOCK();
    return data;
}

In Addition this one:

_spi_dev->beginTransaction();

With this:

void SPIClass::beginTransaction(SPISettings settings)
{
    //check if last freq changed
    uint32_t cdiv = spiGetClockDiv(_spi);
    if(_freq != settings._clock || _div != cdiv) {
        _freq = settings._clock;
        _div = spiFrequencyToClockDiv(_freq);
    }
    spiTransaction(_spi, _div, settings._dataMode, settings._bitOrder);
    _inTransaction = true;
}


问:
How to set a breakpoint in a Clojure program using Calva?
I am working with a Clojure code and need to make changes in some parts of it. For that, I need to stop it in a breakpoint to see what are the values of atoms, variables, .... one step before new changes. The code I am working with is:
https://github.com/lspector/clojush
I need to stop it in breed.clj,defn perform-genetic-operator-list, at the end of line 99 (num-parents).
I am using Calva in VS code and run the code via the terminal with this command:
"lein run clojush.problems.demos.simple-regression".

I tried putting #break inside "num-parents (:parents (get genetic-operators operator))" as:

```<code>num-parents (:parents (get genetic-operators #break operator))
</code>```

but it did not work and program stops showing some errors. Also I tried instrumentation and again did not work.
Any help is highly appreciated. Thanks!

Body:
I am working with a Clojure code and need to make changes in some parts of it. For that, I need to stop it in a breakpoint to see what are the values of atoms, variables, .... one step before new changes. The code I am working with is:
https://github.com/lspector/clojush
I need to stop it in breed.clj,defn perform-genetic-operator-list, at the end of line 99 (num-parents).
I am using Calva in VS code and run the code via the terminal with this command:
"lein run clojush.problems.demos.simple-regression".

I tried putting #break inside "num-parents (:parents (get genetic-operators operator))" as:

num-parents (:parents (get genetic-operators #break operator))

but it did not work and program stops showing some errors. Also I tried instrumentation and again did not work.
Any help is highly appreciated. Thanks!


问:
Weird results for different models of Tensorflow object detection API
I am training 3 different models for covid-19 detection SSD MobileNetV2 FPNLite 320x320, SSD MobileNetV2 FPNLite 640x640, and SSD MobileNetV2 320x320. I have trained each model for 4000 steps, and I have got good but some weird results.

Models
Batch-size
Training Loss
Validation loss
mAP

SSD MobileNetV2 FPNLite 320x320
16
0.22
0.27
0.85

SSD MobileNetV2 FPNLite 640x640
4
0.19
0.25
0.78

SSD MobileNetV2 320x320
16
0.17
0.34
0.83

My second model has gotten less loss value but I am confused why it has gotten fewer mAP values than the other two models. The learning rate for all three models are the same as in the pipeline config

I was expecting high mAP from SSD MobileNetv2 FPNLite 640x640


问:
How to make all the open windows to be displayed in a single one
```<code>import cv2
from datetime import datetime as dt
import numpy as np
import os
from threading import Thread
import imutils
import time
import argparse
import tkinter
from tkinter.ttk import *
import matplotlib.pyplot as plt

class VideoShow:
    """
    Class that continuously shows a frame using a dedicated thread.
    """

    def __init__(self, camname, frame=None):
        self.frame = frame
        self.camname = camname
        self.stopped = False

    def start(self):
        Thread(target=self.show, args=()).start()
        return self

    def show(self):
        while not self.stopped:
            cv2.imshow("Video " + self.camname, self.frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                self.stopped = True
            elif cv2.waitKey(1) & 0xFF == ord('c'):
                cv2.imwrite('Picture_' + self.camname + '.png', self.frame)

    def stop(self):
        self.stopped = True

class VideoGet:
    """
    Class that continuously gets frames from a VideoCapture object
    with a dedicated thread.
    """

    def __init__(self, src=0):
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()
        self.stream.set(cv2.CAP_PROP_BUFFERSIZE, 10)
        self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 1366)
        self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)
        self.stopped = False

    def start(self):
        Thread(target=self.get, args=()).start()
        return self

    def get(self):
        while not self.stopped:
            if not self.grabbed:
                self.stop()
            else:
                (self.grabbed, self.frame) = self.stream.read()

    def stop(self):
        self.stopped = True

cam1 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=1&subtype=1').start()
cam2 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=2&subtype=1').start()
cam3 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=3&subtype=1').start()
cam4 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=4&subtype=1').start()

c1 = VideoShow('Cam_1',cam1.frame).start()
c2 = VideoShow('Cam_2',cam2.frame).start()
c3 = VideoShow('Cam_3',cam3.frame).start()
c4 = VideoShow('Cam_4',cam4.frame).start()

while True:
    if cam1.stopped or c1.stopped or cam2.stopped or c2.stopped or cam3.stopped or c3.stopped or cam4.stopped or c4.stopped:
        cam1.stop()
        c1.stop()
        cam2.stop()
        c2.stop()
        cam3.stop()
        c3.stop()
        cam4.stop()
        c4.stop()

    frame1 = cam1.frame
    c1.frame = cam1.frame
    frame2 = cam2.frame
    c2.frame = cam2.frame
    frame3 = cam3.frame
    c3.frame = cam3.frame
    frame4 = cam4.frame
    c4.frame = cam4.frame

</code>```

I am trying to get the display of all 4 cameras in a single window. Currently they are displaying them as 4 separate window.

The end goal is to capture the image from all four cameras when a certain key is pressed.

I was able to achieve the end goal without using threading, but that resulted in lags in the streams.

Body:
import cv2
from datetime import datetime as dt
import numpy as np
import os
from threading import Thread
import imutils
import time
import argparse
import tkinter
from tkinter.ttk import *
import matplotlib.pyplot as plt

class VideoShow:
    """
    Class that continuously shows a frame using a dedicated thread.
    """

    def __init__(self, camname, frame=None):
        self.frame = frame
        self.camname = camname
        self.stopped = False

    def start(self):
        Thread(target=self.show, args=()).start()
        return self

    def show(self):
        while not self.stopped:
            cv2.imshow("Video " + self.camname, self.frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                self.stopped = True
            elif cv2.waitKey(1) & 0xFF == ord('c'):
                cv2.imwrite('Picture_' + self.camname + '.png', self.frame)

    def stop(self):
        self.stopped = True

class VideoGet:
    """
    Class that continuously gets frames from a VideoCapture object
    with a dedicated thread.
    """

    def __init__(self, src=0):
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()
        self.stream.set(cv2.CAP_PROP_BUFFERSIZE, 10)
        self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 1366)
        self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)
        self.stopped = False

    def start(self):
        Thread(target=self.get, args=()).start()
        return self

    def get(self):
        while not self.stopped:
            if not self.grabbed:
                self.stop()
            else:
                (self.grabbed, self.frame) = self.stream.read()

    def stop(self):
        self.stopped = True

cam1 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=1&subtype=1').start()
cam2 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=2&subtype=1').start()
cam3 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=3&subtype=1').start()
cam4 = VideoGet('rtsp://username:password@192.168.1.70:554/cam/realmonitor?channel=4&subtype=1').start()

c1 = VideoShow('Cam_1',cam1.frame).start()
c2 = VideoShow('Cam_2',cam2.frame).start()
c3 = VideoShow('Cam_3',cam3.frame).start()
c4 = VideoShow('Cam_4',cam4.frame).start()

while True:
    if cam1.stopped or c1.stopped or cam2.stopped or c2.stopped or cam3.stopped or c3.stopped or cam4.stopped or c4.stopped:
        cam1.stop()
        c1.stop()
        cam2.stop()
        c2.stop()
        cam3.stop()
        c3.stop()
        cam4.stop()
        c4.stop()

    frame1 = cam1.frame
    c1.frame = cam1.frame
    frame2 = cam2.frame
    c2.frame = cam2.frame
    frame3 = cam3.frame
    c3.frame = cam3.frame
    frame4 = cam4.frame
    c4.frame = cam4.frame

I am trying to get the display of all 4 cameras in a single window. Currently they are displaying them as 4 separate window.

The end goal is to capture the image from all four cameras when a certain key is pressed.

I was able to achieve the end goal without using threading, but that resulted in lags in the streams.


问:
How to convert list of objects into string and then into byte array
The list contains two objects or more I want to create string with the name of its properties and values.

```<code>async Task<string> ICsvHandler.CsvHandler()
{
    var employees =  new List<objectModel>();

    employees.Add(new objectModel("1234", "543", "", "7865", "filhal null"));
    employees.Add(new objectModel("1234", "543", "0000", "7865", "filhal null"));
    Console.WriteLine(employees);

    ExportCsv(employees);
    return null;
}

void ExportCsv<T>(List<T> genericList)
{
    try
    {
        string fileName = $"{ DateTime.Now.ToUniversalTime().ToString("yyyyMMDDHHmmss") }{ ".csv" }";

        var sb = new StringBuilder();

        foreach (var prop in typeof(T).GetProperties())
            header += prop.Name + ",";
        header = header.Substring(0, header.Length - 2);
        sb.AppendLine(header);

        foreach (var obj in genericList)
        {
            var line = "";
            foreach (var prop in info)
                line += prop.GetValue(obj, null)+"," ;

            line = line.Substring(0, line.Length - 2);
            sb.AppendLine(line);
            char [] ch= sb.ToString().ToCharArray();
            _cloudStorageService.UploadFileFromMemoryAsync(fileName,ch);
        }
    }
    catch (System.Exception)
    {
        throw;
    }
}
</code>```

I am getting name of the property when I run but not the values of object.
I want to understand why my values are not coming into the StringBuilder with line += prop.GetValue(obj, null) + ",";. this only shows ,,,,,,,,,

Expecting name of property along with its values but getting name in header and not values.

Body:
The list contains two objects or more I want to create string with the name of its properties and values.

async Task<string> ICsvHandler.CsvHandler()
{
    var employees =  new List<objectModel>();

    employees.Add(new objectModel("1234", "543", "", "7865", "filhal null"));
    employees.Add(new objectModel("1234", "543", "0000", "7865", "filhal null"));
    Console.WriteLine(employees);

    ExportCsv(employees);
    return null;
}

void ExportCsv<T>(List<T> genericList)
{
    try
    {
        string fileName = $"{ DateTime.Now.ToUniversalTime().ToString("yyyyMMDDHHmmss") }{ ".csv" }";

        var sb = new StringBuilder();

        foreach (var prop in typeof(T).GetProperties())
            header += prop.Name + ",";
        header = header.Substring(0, header.Length - 2);
        sb.AppendLine(header);

        foreach (var obj in genericList)
        {
            var line = "";
            foreach (var prop in info)
                line += prop.GetValue(obj, null)+"," ;

            line = line.Substring(0, line.Length - 2);
            sb.AppendLine(line);
            char [] ch= sb.ToString().ToCharArray();
            _cloudStorageService.UploadFileFromMemoryAsync(fileName,ch);
        }
    }
    catch (System.Exception)
    {
        throw;
    }
}

I am getting name of the property when I run but not the values of object.
I want to understand why my values are not coming into the StringBuilder with line += prop.GetValue(obj, null) + ",";. this only shows ,,,,,,,,,

Expecting name of property along with its values but getting name in header and not values.


问:
Django-rearart sequence of postgres id field with 0 instead of 1
I want to reset the sequence of a "postgresql" table to start from "0" in a django application.

My code is:

views.py

```<code>sequence_sql = connection.ops.sequence_reset_sql(no_style(), [ModelName])
with connection.cursor() as cursor:
      for sql in sequence_sql:
            cursor.execute(sql)
print("sequence reset")
</code>```

The sequence is restarted successfully; but with "1".
I want the sequence to start from 0.

How can I achieve that?

Body:
I want to reset the sequence of a "postgresql" table to start from "0" in a django application.

My code is:

views.py

sequence_sql = connection.ops.sequence_reset_sql(no_style(), [ModelName])
with connection.cursor() as cursor:
      for sql in sequence_sql:
            cursor.execute(sql)
print("sequence reset")

The sequence is restarted successfully; but with "1".
I want the sequence to start from 0.

How can I achieve that?


问:
SetWindowCompositionAttribute in Lua
I am able to write script in VB to get Aero Blur on windows form using SetWindowCompositionAttribute. But how write this to lua script?. Is it possible?. Any Example?</p>

Title: SetWindowCompositionAttribute in Lua


问:
How to collaborate mapbox markers and firebase realtime data?
I've been trying to figure out how to connect firebase and mapbox together since I am new and trying to learn more about it. Is there any way I can do so the markers in the mapbox will follow the firebase realtime data?

Below is the code written in kotlin.

I tried searching around but it seems like there are rare guides for mapbox.

package com.example.s_tore

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.mapbox.geojson.Point.fromLngLat
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.plugin.annotation.AnnotationConfig
import com.mapbox.maps.plugin.annotation.AnnotationPlugin
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationManager
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager

class smap : AppCompatActivity() {

    var mapView: MapView? = null
    private lateinit var database: DatabaseReference
    var annotationApi : AnnotationPlugin? = null
    lateinit var annotationConfig: AnnotationConfig
    var layer1DD = "map_annotation"

    var pointAnnotationManager : PointAnnotationManager? = null

    var markerlist : ArrayList<PointAnnotationOptions> = ArrayList()

    var latitudeList : ArrayList<Double> = ArrayList()
    var longitudeList : ArrayList<Double> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_smap)

        mapView = findViewById(R.id.maps)
        createDummyAList()
        mapView?.getMapboxMap()!!.loadStyleUri(
            Style.MAPBOX_STREETS,
            object : Style.OnStyleLoaded{
                override fun onStyleLoaded(style: Style) {

                    ZoomCamera()

                    annotationApi = mapView?.annotations
                    annotationConfig = AnnotationConfig(
                        layerId = layer1DD
                    )

                    pointAnnotationManager = annotationApi?.createPointAnnotationManager(annotationConfig)

                    createMarkerOnMap()
                }
            }
        )
    }
    private fun ZoomCamera(){
        mapView!!.getMapboxMap().setCamera(
            CameraOptions.Builder().center(fromLngLat(122.061213, 6.913414))
                .zoom(17.0)
                .build())
    }

    private fun createDummyAList(){

        latitudeList.add(6.914586)
        longitudeList.add(122.061069)

    }

    private fun createMarkerOnMap(){

        val bitmap = convertDrawabletoBitMap(AppCompatResources.getDrawable(this, R.drawable.locationmark))
        for (i in 0 until 1000){
            val pointAnnotationOptions : PointAnnotationOptions = PointAnnotationOptions()
                .withPoint(fromLngLat(longitudeList.get(i),latitudeList.get(i)))
                .withIconImage(bitmap!!)

            markerlist.add(pointAnnotationOptions)
        }

        pointAnnotationManager?.create(markerlist)

    }

    private fun convertDrawabletoBitMap(sourceDrawable: Drawable?):Bitmap{

        return if(sourceDrawable is BitmapDrawable){
            sourceDrawable.bitmap
        }else{
            val constatState = sourceDrawable?.constantState

            val drawable = constatState?.newDrawable()?.mutate()
            val bitmap : Bitmap = Bitmap.createBitmap(
                drawable!!.intrinsicWidth,drawable!!.intrinsicHeight,
                Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            drawable.setBounds(0, 0, canvas.width, canvas.height)
            drawable.draw(canvas)
            bitmap
        }
    }
}
```


问:
How to efficiently access private fields of object instead of Reflection
I have a use case where in I want to filter out results based on the input I receive from the user.

My data object looks like this:

```<code>class Data {
  Data(String x, String y, String z) {
    // setting the private fields
  }

  private String x;
  private String y;
  private String z;
}
</code>```

In the request I'll receive 2 values which field to filter on and what should be it's desired value

```<code>record Request(String attribute, String value);

Request request = new Request("x", "123");
</code>```

So I used Reflection to find which field I need to be filtering on and applied lambda operation to get the desired result

```<code>Data data = new Data("123", "abc", "pqr");

Field requestedField = Data.getClass().getDeclaredField(request.attribute());

requestedField.setAccessible(true);

String fieldValue = requestedField.get(data)

// filtering can happen here
</code>```

But since Reflection is not an efficient way of doing this and it should be avoided, is there any other way to do this?

Open to 3P libraries also.

I tried using ReflectASM but I couldn't access the private fields.

Any efficient approach for solving this would be appreciated

Body:
I have a use case where in I want to filter out results based on the input I receive from the user.

My data object looks like this:

class Data {
  Data(String x, String y, String z) {
    // setting the private fields
  }

  private String x;
  private String y;
  private String z;
}

In the request I'll receive 2 values which field to filter on and what should be it's desired value

record Request(String attribute, String value);

Request request = new Request("x", "123");

So I used Reflection to find which field I need to be filtering on and applied lambda operation to get the desired result

Data data = new Data("123", "abc", "pqr");

Field requestedField = Data.getClass().getDeclaredField(request.attribute());

requestedField.setAccessible(true);

String fieldValue = requestedField.get(data)

// filtering can happen here

But since Reflection is not an efficient way of doing this and it should be avoided, is there any other way to do this?

Open to 3P libraries also.

I tried using ReflectASM but I couldn't access the private fields.

Any efficient approach for solving this would be appreciated


问:
Show 32 issues in app issue report of real device - android
In app issue report of my mobile show me 32 issues like bellow:

I used from inspect code of android studio and I have not any error (just i have some warning). How can I resolve these issues?


问:
local.ERROR: foreach() argument must be of type array|object, null given
```<code> public function sku_combination(Request $request)
    {
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        } else {
            $colors_active = 0;
        }

        $unit_price = $request->unit_price;
        $product_name = $request->name;

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                // foreach (json_decode($request[$name][0]) as $key => $item) {
                foreach ($request[$name] as $key =>$item) {
                    // array_push($data, $item->value);
                    array_push($data, $item);
                }
                array_push($options, $data);
            }
        }

        $combinations = Combinations::makeCombinations($options);
        return view('backend.product.products.sku_combinations', compact('combinations', 'unit_price', 'colors_active', 'product_name'));
    }
</code>```

The array showing ,given null how to fix this.in this the foreach argument must be of type array|object but null given

The blade file for it is

```<code><tbody>
@foreach($attributes as $key => $attribute)
 <tr>
   <td>{{$key+1}}</td>
   <td>{{$attribute->getTranslation('name')}}</td>
   <td>
    @foreach($attribute->attribute_values as $key => $value)
    <span class="badge badge-inline badge-md bg-soft-dark">{{ $value->value }}</span>
   @endforeach
   </td>
   <td class="text-right">
   @can('view_product_attribute_values')
  <a class="btn btn-soft-info btn-icon btn-circle btn-sm" href="{{route('attributes.show', $attribute->id)}}" title="{{ translate('Attribute values') }}">
 <i class="las la-cog"></i>
 </a>
@endcan
@can('edit_product_attribute')
<a class="btn btn-soft-primary btn-icon btn-circle btn-sm" href="{{route('attributes.edit', ['id'=>$attribute->id, 'lang'=>env('DEFAULT_LANGUAGE')] )}}" title="{{ translate('Edit') }}">
<i class="las la-edit"></i>
</a>
@endcan
 @can('delete_product_attribute')
<a href="#" class="btn btn-soft-danger btn-icon btn-circle btn-sm confirm-delete" data-href="{{route('attributes.destroy', $attribute->id)}}" title="{{ translate('Delete') }}">
<i class="las la-trash"></i>
 </a>
@endcan
</td>
</tr>
@endforeach
</tbody>
</code>```

is this  the details what you wanted.in this the name values given the error showing foreach argument must be of type array|object but given null

Body:
 public function sku_combination(Request $request)
    {
        $options = array();
        if ($request->has('colors_active') && $request->has('colors') && count($request->colors) > 0) {
            $colors_active = 1;
            array_push($options, $request->colors);
        } else {
            $colors_active = 0;
        }

        $unit_price = $request->unit_price;
        $product_name = $request->name;

        if ($request->has('choice_no')) {
            foreach ($request->choice_no as $key => $no) {
                $name = 'choice_options_' . $no;
                $data = array();
                // foreach (json_decode($request[$name][0]) as $key => $item) {
                foreach ($request[$name] as $key =>$item) {
                    // array_push($data, $item->value);
                    array_push($data, $item);
                }
                array_push($options, $data);
            }
        }

        $combinations = Combinations::makeCombinations($options);
        return view('backend.product.products.sku_combinations', compact('combinations', 'unit_price', 'colors_active', 'product_name'));
    }

The array showing ,given null how to fix this.in this the foreach argument must be of type array|object but null given

The blade file for it is

@foreach($attributes as $key => $attribute)

   {{$key+1}}
   {{$attribute->getTranslation('name')}}

    @foreach($attribute->attribute_values as $key => $value)
    {{ $value->value }}
   @endforeach

   @can('view_product_attribute_values')
  id)}}" title="{{ translate('Attribute values') }}">

@endcan
@can('edit_product_attribute')
$attribute->id, 'lang'=>env('DEFAULT_LANGUAGE')] )}}" title="{{ translate('Edit') }}">

@endcan
 @can('delete_product_attribute')
id)}}" title="{{ translate('Delete') }}">

@endcan

@endforeach

is this  the details what you wanted.in this the name values given the error showing foreach argument must be of type array|object but given null


问:
Flutter Web asking for camera permission on first screen
My Flutter Web app asks for camera permission on the first screen. The problem is that I do not request for camera permissions anywhere, except when users tap a button.

I'm afraid that the camera permission is going to scare some users away.

Can you please tell me why users are asked to allow the camera on the first screen when I'm not asking for it on it?

Thanks


问:
permutation and combination of n numbers in array output of permutation and combination should be in two digits
I tried this code for combination of my input but I'm getting the output results of same length as I entered in my input field but I want only two digit output

```<code>let str = $('#num').val();
            let first = $('#first').val();
            let second = $('#second').val();
            let permutation = (str, result) => {
                if (str.length == 0) {
                    x = result;
                    y = Object.values(x);
                     console.log(result);

                }
                for (let i = 0; i < str.length; i++) {
                    let rest = str.substring(0, i) + str.substring(i + 1)

                    permutation(rest, result + str[i])
                }
            }
            permutation(str, '')
            var x = result;
</code>```

for example
input:123
output that i want

12
13
21
23
31
32

Body:
I tried this code for combination of my input but I'm getting the output results of same length as I entered in my input field but I want only two digit output

let str = $('#num').val();
            let first = $('#first').val();
            let second = $('#second').val();
            let permutation = (str, result) => {
                if (str.length == 0) {
                    x = result;
                    y = Object.values(x);
                     console.log(result);

                }
                for (let i = 0; i < str.length; i++) {
                    let rest = str.substring(0, i) + str.substring(i + 1)

                    permutation(rest, result + str[i])
                }
            }
            permutation(str, '')
            var x = result;

for example
input:123
output that i want

12
13
21
23
31
32


问:
Bulk Excel Upload from Angular shows Page Unresponsive
I am trying to upload the excel from UI (angular8 and node 14) and try to process it, but while retrieving data from excel for bulk data(1800 rows almost 12mb file ) it shows a Page Unresponsive pop-up many times and I can understand, chrome browser trying to use a lot of memory and result is Page Unresponsive pop-up. is there any way to disable or not show this pop-up or any solution for this issue?

Thanks in advance.

I am attaching below working Ts file code.

code:

```<code>onFileChange(evt: any) {
  const target: DataTransfer = (evt.target) as DataTransfer;
  const selectedFile = evt.target.files[0];
  const reader: FileReader = new FileReader();
  reader.readAsBinaryString(selectedFile);
  reader.onload = (e: any) => {
  const bstr: string = e.target.result;
  const wbk: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});

    wbk.SheetNames.forEach(sheet =>{
      setTimeout(()=>{}, 250);  //I am trying to use timeout to refresh the flow but not working
     const  data1 = XLSX.utils.sheet_to_json(wbk.Sheets[sheet]);
     console.log(data1);
    })

  }
};
</code>```

Body:
I am trying to upload the excel from UI (angular8 and node 14) and try to process it, but while retrieving data from excel for bulk data(1800 rows almost 12mb file ) it shows a Page Unresponsive pop-up many times and I can understand, chrome browser trying to use a lot of memory and result is Page Unresponsive pop-up. is there any way to disable or not show this pop-up or any solution for this issue?

Thanks in advance.

I am attaching below working Ts file code.

code:

onFileChange(evt: any) {
  const target: DataTransfer = (evt.target) as DataTransfer;
  const selectedFile = evt.target.files[0];
  const reader: FileReader = new FileReader();
  reader.readAsBinaryString(selectedFile);
  reader.onload = (e: any) => {
  const bstr: string = e.target.result;
  const wbk: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});

    wbk.SheetNames.forEach(sheet =>{
      setTimeout(()=>{}, 250);  //I am trying to use timeout to refresh the flow but not working
     const  data1 = XLSX.utils.sheet_to_json(wbk.Sheets[sheet]);
     console.log(data1);
    })

  }
};


问:
Maps cannot load when the screen is moving too fast
I have a list of points that are the coordinates of the journey.
It runs normally when I use a vehicle marker run on the map with a duration of 500 ms.

But when I used animateToRegion to make the map follow the vehicle, problems started to happen:

Normally, map needs about 1second to load. So when use animateToRegion with duration is 500 ms. Map hasn't downloaded yet. ( as the right of image )

  const intervalRef = useInterval(
    () => {
      if (timerRef.current < data.length - 1) {
        setTimer(timer => timer + 1);
        timerRef.current += 1;
      } else {
        window.clearInterval(intervalRef.current);
        if (timerRef.current === data.length - 1) {
          setPlayed(false);
        }
      }
    },
    isPlayed ? timeDuration : null,
  );
  // timer update per timeDuration = 500ms

  useEffect(() => {
    animateMarker();
    mapRef?.current?.animateToRegion({
      latitude: data[timer].Lt,
      longitude: data[timer].Ln,
      latitudeDelta: SUP_LATITUDE_DELTA,
      longitudeDelta: SUP_LONGITUDE_DELTA,
    });
  }, [timer]);

  const animateMarker = () => {
    const newCoordinate = {
      latitude: data[timer].Lt,
      longitude: data[timer].Ln,
      latitudeDelta: SUP_LATITUDE_DELTA,
      longitudeDelta: SUP_LONGITUDE_DELTA,
    };

    if (Platform.OS === 'android') {
      if (marker) {
        marker.animateMarkerToCoordinate(
          newCoordinate,
          timer == 0 ? 0 : timeDuration,
        );
      }
    } else {
      coordinate.timing(newCoordinate).start();
    }
  };

```

Video demo

So does someone have any solutions for it?

Body:
I have a list of points that are the coordinates of the journey.
It runs normally when I use a vehicle marker run on the map with a duration of 500 ms.

But when I used animateToRegion to make the map follow the vehicle, problems started to happen:

Normally, map needs about 1second to load. So when use animateToRegion with duration is 500 ms. Map hasn't downloaded yet. ( as the right of image )

  const intervalRef = useInterval(
    () => {
      if (timerRef.current < data.length - 1) {
        setTimer(timer => timer + 1);
        timerRef.current += 1;
      } else {
        window.clearInterval(intervalRef.current);
        if (timerRef.current === data.length - 1) {
          setPlayed(false);
        }
      }
    },
    isPlayed ? timeDuration : null,
  );
  // timer update per timeDuration = 500ms

  useEffect(() => {
    animateMarker();
    mapRef?.current?.animateToRegion({
      latitude: data[timer].Lt,
      longitude: data[timer].Ln,
      latitudeDelta: SUP_LATITUDE_DELTA,
      longitudeDelta: SUP_LONGITUDE_DELTA,
    });
  }, [timer]);

  const animateMarker = () => {
    const newCoordinate = {
      latitude: data[timer].Lt,
      longitude: data[timer].Ln,
      latitudeDelta: SUP_LATITUDE_DELTA,
      longitudeDelta: SUP_LONGITUDE_DELTA,
    };

    if (Platform.OS === 'android') {
      if (marker) {
        marker.animateMarkerToCoordinate(
          newCoordinate,
          timer == 0 ? 0 : timeDuration,
        );
      }
    } else {
      coordinate.timing(newCoordinate).start();
    }
  };

Video demo

So does someone have any solutions for it?


问:
How to train GPT2 with Tensorflow
I'm trying to train gpt2 model with custom dataset, but it fails with the error below.

```<code>ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.
</code>```

I thought model and dataset are correctly defined and processed by referring this article.

But the error shows up when model.fit is executed.

Can someone tell me how to resolve the error, or proper way to train the model?

```<code>from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
import tensorflow as tf

# Define the model
model = TFGPT2LMHeadModel.from_pretrained('gpt2', from_pt=True)
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=[loss, *[None] * model.config.n_layer], metrics=[metric], run_eagerly=True)
model.summary()
</code>```
```<code># Obtain the tokeinizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
tokenizer.add_special_tokens({
  "eos_token": "</s>",
  "bos_token": "<s>",
  "unk_token": "<unk>",
  "pad_token": "<pad>",
  "mask_token": "<mask>"
})
</code>```
```<code># Get single string
paths = ['data.txt']  # each file only contains some sentences.

single_string = ''
for filename in paths:
    with open(filename, "r", encoding='utf-8') as f:
        x = f.read()
    single_string += x + tokenizer.eos_token

string_tokenized = tokenizer.encode(single_string)

print(string_tokenized)
</code>```
```<code># creating the TensorFlow dataset
examples = []
block_size = 100
BATCH_SIZE = 12
BUFFER_SIZE = 1000
for i in range(0, len(string_tokenized) - block_size + 1, block_size):
    examples.append(string_tokenized[i:i + block_size])
inputs, labels = [], []
for ex in examples:
    inputs.append(ex[:-1])
    labels.append(ex[1:])
dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)

print(dataset)
</code>```
```<code># train the model
num_epoch = 10
history = model.fit(dataset, epochs=num_epoch) # <- shows the error
</code>```

Title: How to train GPT2 with Tensorflow

Body:
I'm trying to train gpt2 model with custom dataset, but it fails with the error below.

ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

I thought model and dataset are correctly defined and processed by referring this article.

But the error shows up when model.fit is executed.

Can someone tell me how to resolve the error, or proper way to train the model?

from transformers import TFGPT2LMHeadModel, GPT2Tokenizer
import tensorflow as tf

# Define the model
model = TFGPT2LMHeadModel.from_pretrained('gpt2', from_pt=True)
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=[loss, *[None] * model.config.n_layer], metrics=[metric], run_eagerly=True)
model.summary()

# Obtain the tokeinizer
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
tokenizer.add_special_tokens({
  "eos_token": "</s>",
  "bos_token": "<s>",
  "unk_token": "<unk>",
  "pad_token": "<pad>",
  "mask_token": "<mask>"
})

# Get single string
paths = ['data.txt']  # each file only contains some sentences.

single_string = ''
for filename in paths:
    with open(filename, "r", encoding='utf-8') as f:
        x = f.read()
    single_string += x + tokenizer.eos_token

string_tokenized = tokenizer.encode(single_string)

print(string_tokenized)

# creating the TensorFlow dataset
examples = []
block_size = 100
BATCH_SIZE = 12
BUFFER_SIZE = 1000
for i in range(0, len(string_tokenized) - block_size + 1, block_size):
    examples.append(string_tokenized[i:i + block_size])
inputs, labels = [], []
for ex in examples:
    inputs.append(ex[:-1])
    labels.append(ex[1:])
dataset = tf.data.Dataset.from_tensor_slices((inputs, labels))
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)

print(dataset)

# train the model
num_epoch = 10
history = model.fit(dataset, epochs=num_epoch) # <- shows the error


问:
Problem with retrieving data from table using qraphQL
I have a problem with reading data from the database.

This is my code:

```<code>getCountrytByID:async(args,req)=>{
        try {
            return await countries.findAll({

                where: {
                  root:args.root
                }
            })
        } catch(err) {
           throw err;
        }
    },
</code>```

My database

Example: I want to read all data that have root = 1 or root = 2

Body:
I have a problem with reading data from the database.

This is my code:

getCountrytByID:async(args,req)=>{
        try {
            return await countries.findAll({

                where: {
                  root:args.root
                }
            })
        } catch(err) {
           throw err;
        }
    },

My database

Example: I want to read all data that have root = 1 or root = 2


问:
operation not permitted: /dev/nulleval MacOS Ventura 13.0.1
(eval):3: operation not permitted: /dev/nulleval

This is the output I am seeing on my macbook with ventura latest update, this caused when I tried installing git-lfs.

But not able to get rid of this.

Tried the following:

Going to settings, privacy and giving the full disk access to terminal.

Hard-Resetting the terminal.

This it the output after I do ls -ld /dev /dev/null (if it helps)

OUTPUT:

dr-xr-xr-x  4 root  wheel       4769 Dec 17 12:30 /dev

crw-rw-rw-  1 root  wheel  0x3000002 Dec 17 12:48 /dev/null


问:
Toggling LEDs in a respond to a counter at different scenarios
I am trying to toggle leds on and off based on two scenarios.

a counter.(input from two buttons - one for counting up and the other for counting down)

a specific time for led to be ON

if counter is equal to 1: turn ON led 1 for x amount of time (specify at index 0 of the Time array) - all other leds are off;

if counter is equal to 2:  turn off the previous led that was ON (even if the specify time of ON for that led was not elapsed) then turn ON led 2 for x amount of time.

the above should be same for all 5 indexes.

here is the code I have got so far for counting the button presses:

```<code>//Buttons//

const uint8_t MINBTNCOUNT = 0;
const uint8_t MAXBTNCOUNT = 4;

//Button1// count up
uint8_t buttonPin = 2;
uint8_t buttonPressCount = 0;
uint8_t lstbuttonPressCount = 0;
uint8_t PUSHED = 0;
unsigned long timePushed = 0;
uint8_t currentButtonState = HIGH;
uint8_t lastButtonState = HIGH;
uint32_t millisTimePress = 0;
//Button2// count down
uint8_t buttonPin2 = 3;
uint8_t buttonPressCount2 = 0;
uint8_t lstbuttonPressCount2 = 0;
uint8_t PUSHED2 = 0;
unsigned long timePushed2 = 0;
uint8_t currentButtonState2 = HIGH;
uint8_t lastButtonState2 = HIGH;
uint32_t millisTimePress2 = 0;

////Leds/////
const int ledPins[] ={4,5,6,7,8}; // array of leds pins
const int numOfLeds =  (sizeof(ledPins) / sizeof(ledPins[0])); // size of Leds

//time translating//
#define sec * 1000
#define min * 60000
#define ms * 1

// LEDS ON Time Lengths //
const unsigned long ledOnTime[] = {19 sec, 44 sec, 9 sec, 7 sec, 33 sec};

void setup() {
  Serial.begin(115200);

    pinMode(buttonPin, INPUT_PULLUP);
    pinMode(buttonPin2, INPUT_PULLUP);

   // setting up the digital pins for the leds to be an output //
  for (int j = 0; j < numOfLeds; j++)
  {
    pinMode(ledPins[j], OUTPUT);
  }
}

void loop() {
  buttonPress1 ();
  buttonPress2 ();
}

void buttonPress1 ()
{
    byte currentButtonState = digitalRead (buttonPin);

    if (lastButtonState != currentButtonState)  {
        lastButtonState = currentButtonState;
         delay (35);             // debounce

        //******************
        //has the switch been pushed ?
        if (currentButtonState == PUSHED)
        {
           //record the time the switch closed
           timePushed = millis();

        }
        //******************
    //switch has been released
    else
    {
      //calculate the time the switch was closed
      timePushed = millis() - timePushed;

      if(timePushed < 500)
      {
        buttonPressCount++;
        if( buttonPressCount == 0)
  {
    buttonPressCount = 4;
  }
  if( buttonPressCount == 5)
  {
    buttonPressCount = 1;
  }
        Serial.print("button count: ");
        Serial.println(buttonPressCount);
      }
    }
  }
}

void buttonPress2 ()
{
    byte currentButtonState2 = digitalRead (buttonPin2);

    if (lastButtonState2 != currentButtonState2)
    {
        lastButtonState2 = currentButtonState2;
         delay (35);             // debounce

        //******************
        //has the switch been pushed ?
        if (currentButtonState2 == PUSHED2)
        {
           //record the time the switch closed
           timePushed2 = millis();

        }
        //******************
    //switch has been released
    else
    {
      //calculate the time the switch was closed
      timePushed2 = millis() - timePushed2;

      if(timePushed2 < 500)
      {
        buttonPressCount--;
        if( buttonPressCount == 0)
  {
    buttonPressCount = 4;
  }
  if( buttonPressCount == 5)
  {
    buttonPressCount = 1;
  }
        Serial.print("button count: ");
        Serial.println(buttonPressCount);
      }

    }
  }
}
</code>```

I try to add another main function for toggling the LEDS based on a counter
and based on the ledOnTimearray

Here is my failed attempting:

```<code>void ledToggle()
{
  for(int i = 0; i < MAXBTNCOUNT; i++)
  {
  if(counter != lstcounter)
  {
    Serial.print("counter:");
    Serial.println(counter);
    lstcounter = counter;

    if(millis() - timeButtonPressed <= ledOnTime[i])
    {
      Serial.print(ledOnTime[i]);
      digitalWrite(ledPins[i], HIGH);
    }

  }
   if(millis() > timeButtonPressed +  ledOnTime[i] || counter != lstcounter)
    {
     digitalWrite(ledPins[i], LOW);
    }
}
}

</code>```

Thanks for helping!

I have tried to write a for loop I named

```<code>void ledToggle()
</code>```

but without success.

Body:
I am trying to toggle leds on and off based on two scenarios.

a counter.(input from two buttons - one for counting up and the other for counting down)

a specific time for led to be ON

if counter is equal to 1: turn ON led 1 for x amount of time (specify at index 0 of the Time array) - all other leds are off;

if counter is equal to 2:  turn off the previous led that was ON (even if the specify time of ON for that led was not elapsed) then turn ON led 2 for x amount of time.

the above should be same for all 5 indexes.

here is the code I have got so far for counting the button presses:

//Buttons//

const uint8_t MINBTNCOUNT = 0;
const uint8_t MAXBTNCOUNT = 4;

//Button1// count up
uint8_t buttonPin = 2;
uint8_t buttonPressCount = 0;
uint8_t lstbuttonPressCount = 0;
uint8_t PUSHED = 0;
unsigned long timePushed = 0;
uint8_t currentButtonState = HIGH;
uint8_t lastButtonState = HIGH;
uint32_t millisTimePress = 0;
//Button2// count down
uint8_t buttonPin2 = 3;
uint8_t buttonPressCount2 = 0;
uint8_t lstbuttonPressCount2 = 0;
uint8_t PUSHED2 = 0;
unsigned long timePushed2 = 0;
uint8_t currentButtonState2 = HIGH;
uint8_t lastButtonState2 = HIGH;
uint32_t millisTimePress2 = 0;

////Leds/////
const int ledPins[] ={4,5,6,7,8}; // array of leds pins
const int numOfLeds =  (sizeof(ledPins) / sizeof(ledPins[0])); // size of Leds

//time translating//
#define sec * 1000
#define min * 60000
#define ms * 1

// LEDS ON Time Lengths //
const unsigned long ledOnTime[] = {19 sec, 44 sec, 9 sec, 7 sec, 33 sec};

void setup() {
  Serial.begin(115200);

    pinMode(buttonPin, INPUT_PULLUP);
    pinMode(buttonPin2, INPUT_PULLUP);

   // setting up the digital pins for the leds to be an output //
  for (int j = 0; j < numOfLeds; j++)
  {
    pinMode(ledPins[j], OUTPUT);
  }
}

void loop() {
  buttonPress1 ();
  buttonPress2 ();
}

void buttonPress1 ()
{
    byte currentButtonState = digitalRead (buttonPin);

    if (lastButtonState != currentButtonState)  {
        lastButtonState = currentButtonState;
         delay (35);             // debounce

        //******************
        //has the switch been pushed ?
        if (currentButtonState == PUSHED)
        {
           //record the time the switch closed
           timePushed = millis();

        }
        //******************
    //switch has been released
    else
    {
      //calculate the time the switch was closed
      timePushed = millis() - timePushed;

      if(timePushed < 500)
      {
        buttonPressCount++;
        if( buttonPressCount == 0)
  {
    buttonPressCount = 4;
  }
  if( buttonPressCount == 5)
  {
    buttonPressCount = 1;
  }
        Serial.print("button count: ");
        Serial.println(buttonPressCount);
      }
    }
  }
}

void buttonPress2 ()
{
    byte currentButtonState2 = digitalRead (buttonPin2);

    if (lastButtonState2 != currentButtonState2)
    {
        lastButtonState2 = currentButtonState2;
         delay (35);             // debounce

        //******************
        //has the switch been pushed ?
        if (currentButtonState2 == PUSHED2)
        {
           //record the time the switch closed
           timePushed2 = millis();

        }
        //******************
    //switch has been released
    else
    {
      //calculate the time the switch was closed
      timePushed2 = millis() - timePushed2;

      if(timePushed2 < 500)
      {
        buttonPressCount--;
        if( buttonPressCount == 0)
  {
    buttonPressCount = 4;
  }
  if( buttonPressCount == 5)
  {
    buttonPressCount = 1;
  }
        Serial.print("button count: ");
        Serial.println(buttonPressCount);
      }

    }
  }
}

I try to add another main function for toggling the LEDS based on a counter
and based on the ledOnTimearray

Here is my failed attempting:

void ledToggle()
{
  for(int i = 0; i < MAXBTNCOUNT; i++)
  {
  if(counter != lstcounter)
  {
    Serial.print("counter:");
    Serial.println(counter);
    lstcounter = counter;

    if(millis() - timeButtonPressed <= ledOnTime[i])
    {
      Serial.print(ledOnTime[i]);
      digitalWrite(ledPins[i], HIGH);
    }

  }
   if(millis() > timeButtonPressed +  ledOnTime[i] || counter != lstcounter)
    {
     digitalWrite(ledPins[i], LOW);
    }
}
}

Thanks for helping!

I have tried to write a for loop I named

void ledToggle()

but without success.


问:
How to fix `Parameter format not correct - Compilation with Kotlin compile daemon was not successful` in flutter, vs code?
I recently installed flutter in vs code and created a new flutter project. It worked in web.
But failed after using  flutter build apk.

Could someone help me, please?

Compilation with Kotlin compile daemon was not successful
java.rmi.ServerError: Error occurred in server thread; nested exception is:

```<code>        java.lang.NoClassDefFoundError: kotlin/reflect/full/KClasses
        at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:388)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)
        at java.rmi/sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
        at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
        at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:164)
        at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:217)
        at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
        at com.sun.proxy.$Proxy121.compile(Unknown Source)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.incrementalCompilationWithDaemon(GradleKotlinCompilerWork.kt:313)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:231)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:168)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:135)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:207)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:198)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:97)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:735)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:491)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.executeImpl(Tasks.kt:404)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:357)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

.
.
.
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseKotlin'.
> Compilation error. See log for more details

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 17s
Running Gradle task 'assembleRelease'...                           18.5s
Gradle task assembleRelease failed with exit code 1
</code>```

Body:
I recently installed flutter in vs code and created a new flutter project. It worked in web.
But failed after using  flutter build apk.

Could someone help me, please?

Compilation with Kotlin compile daemon was not successful
java.rmi.ServerError: Error occurred in server thread; nested exception is:

        java.lang.NoClassDefFoundError: kotlin/reflect/full/KClasses
        at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:388)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
        at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at java.base/java.lang.Thread.run(Thread.java:829)
        at java.rmi/sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
        at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
        at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:164)
        at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:217)
        at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
        at com.sun.proxy.$Proxy121.compile(Unknown Source)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.incrementalCompilationWithDaemon(GradleKotlinCompilerWork.kt:313)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemon(GradleKotlinCompilerWork.kt:231)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.compileWithDaemonOrFallbackImpl(GradleKotlinCompilerWork.kt:168)
        at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:135)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:207)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:198)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:97)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:735)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompilerAsync$kotlin_gradle_plugin(Tasks.kt:491)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.executeImpl(Tasks.kt:404)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:357)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

.
.
.
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileReleaseKotlin'.
> Compilation error. See log for more details

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 17s
Running Gradle task 'assembleRelease'...                           18.5s
Gradle task assembleRelease failed with exit code 1


问:
Run Bat file Using C#
I have a bat file having below line

```<code>cd C:\Program Files\test\design
call open.bat   Proj pswd/XXXXXX /ALL Design
</code>```

I want to run this bat file using C# code.
Please help me out with the code .I have tried couple of code but its not invoking application

```<code>var t=System.Diagnostics.Process.Start(@"A:\LogInBat\E3D4.0-Model_40.bat");

</code>```

Title: Run Bat file Using C#

Body:
I have a bat file having below line

cd C:\Program Files\test\design
call open.bat   Proj pswd/XXXXXX /ALL Design

I want to run this bat file using C# code.
Please help me out with the code .I have tried couple of code but its not invoking application

var t=System.Diagnostics.Process.Start(@"A:\LogInBat\E3D4.0-Model_40.bat");


问:
Button event handling overflowing to other scenes
I'm making a menu in Pygame for a game I'm making. I made a scene system that controls what things are displayed on the screen. Clicking buttons changes the scene, and also key variables in the game such as options, game settings, etc. My problem is that when I click a button, the click seems to overflow into the other screen, accidentally clicking other buttons and skipping the said scene.

Game Loop (some code left out):

```<code>while run:
    clock.tick(60)
    #basic program stuff
    event_list = pygame.event.get()
    for event in event_list :
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                if scene != "Menu":
                    scene = "Map"
                    infoToggle = False

    screen.fill("red")
    if scene == "Menu":
        titleText = utils.text("Tile Wars", 750, 50 , reallylargefont, (0,0,0), screen)
        if start_button.draw():
            scene = "ChooseNation"
    if scene == "ChooseNation":
        if lutosia_button.draw():
            nationplayed = "Lutosia"
            scene = "Map"
        if muonetta_button.draw():
            nationplayed = "Muonetta"
            scene = "Map"
    if scene != "Map":
        infoToggle = False
    #important functions
    if scene == "Map":
        world.draw()
        draw_grid()
    #buttons
        if gov_button.draw():
            print("government")
            scene = "Gov"
        if tech_button.draw():
            print("technology")
            scene = "Tech"
        if dip_button.draw() and phase == "Diplomacy":
            print('DIPLOMACY!!!')
            scene = "Dip"
    #click handling
    action = world.isClicked(event_list)
    mapClicked = action[0]
    if mapClicked == True and scene == "Map":

        infoToggle = True
        terrainType = action[1]
        tileNumber = action[5]
        ownerName = owner_data[action[3]][action[4]]

        expansion = gamfuncs.expand(action[2], action[3], action[4], map_data, action[1], nationplayed)
        if expansion[0] == True and phase == "Expansion":
            expansionRow = expansion[1]
            expansionCol = expansion[2]
            map_data[expansionRow][expansionCol] = expansion[3]
            owner_data[expansionRow][expansionCol] = expansion[4]
            ownerName = owner_data[action[3]][action[4]]
            world.update(map_data)
            phase = "Diplomacy"

    #final stuff in the loop
    mapClicked = False

    pygame.display.update()

pygame.quit()
</code>```

Button Code:

```<code>pygame.init()

class Button():
    def __init__(self,x,y,image,screen,scale) -> None:
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width*scale), int(height*scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.screen = screen
        self.clicked = False

    def draw(self):

        action = False
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
                if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                    self.clicked = True
                    action = True
                if pygame.mouse.get_pressed()[0] == 0:
                    self.clicked = False
        self.screen.blit(self.image, (self.rect.x, self.rect.y))
        return action
</code>```

I tried to remedy this by adding artificial time between the button click detection and the scene change, like this:

```<code> if scene == "Menu":
        titleText = utils.text("Tile Wars", 750, 50 , reallylargefont, (0,0,0), screen)
        if start_button.draw():
            scene = "ChooseNation"
            pygame.time.wait(100)
    if scene == "ChooseNation":
        if lutosia_button.draw():
            nationplayed = "Lutosia"
            pygame.time.wait(100)
            scene = "Map"
        if muonetta_button.draw():
            nationplayed = "Muonetta"
            pygame.time.wait(100)
            scene = "Map"
</code>```

I expected it to cause a delay in the click handling so it wouldn't skip the scene, but it did the same thing, albeit with a small delay. Why is this happening and how can I fix it?

Body:
I'm making a menu in Pygame for a game I'm making. I made a scene system that controls what things are displayed on the screen. Clicking buttons changes the scene, and also key variables in the game such as options, game settings, etc. My problem is that when I click a button, the click seems to overflow into the other screen, accidentally clicking other buttons and skipping the said scene.

Game Loop (some code left out):

while run:
    clock.tick(60)
    #basic program stuff
    event_list = pygame.event.get()
    for event in event_list :
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                if scene != "Menu":
                    scene = "Map"
                    infoToggle = False

    screen.fill("red")
    if scene == "Menu":
        titleText = utils.text("Tile Wars", 750, 50 , reallylargefont, (0,0,0), screen)
        if start_button.draw():
            scene = "ChooseNation"
    if scene == "ChooseNation":
        if lutosia_button.draw():
            nationplayed = "Lutosia"
            scene = "Map"
        if muonetta_button.draw():
            nationplayed = "Muonetta"
            scene = "Map"
    if scene != "Map":
        infoToggle = False
    #important functions
    if scene == "Map":
        world.draw()
        draw_grid()
    #buttons
        if gov_button.draw():
            print("government")
            scene = "Gov"
        if tech_button.draw():
            print("technology")
            scene = "Tech"
        if dip_button.draw() and phase == "Diplomacy":
            print('DIPLOMACY!!!')
            scene = "Dip"
    #click handling
    action = world.isClicked(event_list)
    mapClicked = action[0]
    if mapClicked == True and scene == "Map":

        infoToggle = True
        terrainType = action[1]
        tileNumber = action[5]
        ownerName = owner_data[action[3]][action[4]]

        expansion = gamfuncs.expand(action[2], action[3], action[4], map_data, action[1], nationplayed)
        if expansion[0] == True and phase == "Expansion":
            expansionRow = expansion[1]
            expansionCol = expansion[2]
            map_data[expansionRow][expansionCol] = expansion[3]
            owner_data[expansionRow][expansionCol] = expansion[4]
            ownerName = owner_data[action[3]][action[4]]
            world.update(map_data)
            phase = "Diplomacy"

    #final stuff in the loop
    mapClicked = False

    pygame.display.update()

pygame.quit()

Button Code:

pygame.init()

class Button():
    def __init__(self,x,y,image,screen,scale) -> None:
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width*scale), int(height*scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.screen = screen
        self.clicked = False

    def draw(self):

        action = False
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
                if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                    self.clicked = True
                    action = True
                if pygame.mouse.get_pressed()[0] == 0:
                    self.clicked = False
        self.screen.blit(self.image, (self.rect.x, self.rect.y))
        return action

I tried to remedy this by adding artificial time between the button click detection and the scene change, like this:

 if scene == "Menu":
        titleText = utils.text("Tile Wars", 750, 50 , reallylargefont, (0,0,0), screen)
        if start_button.draw():
            scene = "ChooseNation"
            pygame.time.wait(100)
    if scene == "ChooseNation":
        if lutosia_button.draw():
            nationplayed = "Lutosia"
            pygame.time.wait(100)
            scene = "Map"
        if muonetta_button.draw():
            nationplayed = "Muonetta"
            pygame.time.wait(100)
            scene = "Map"

I expected it to cause a delay in the click handling so it wouldn't skip the scene, but it did the same thing, albeit with a small delay. Why is this happening and how can I fix it?