问:
Module not found: Error: node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js'
i downgraded my project angular version 14.0.0 to 13.0.0 for fixing this error Mat Dialog boxes close button is not working on IOS devices

by following the answer from
How to downgrade angular version?

but after downgrading when iam trying to run by ng serve iam getting this error

i checked the specified folder there the file asyncToGenerator.js is exists

```<code>./node_modules/idb/build/index.js:1:0-211 - Error: Module not found: Error: Can't resolve '/Volumes/Macintosh HD/Users/ravi/Public/new_mob/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js' in '/Volumes/Macintosh HD/Users/ravi/Public/new_mob/node_modules/idb/build'
</code>```

i tried

```<code>npm install --save-dev @angular-devkit/build-angular
</code>```

still getting same error

my package.json file is

```<code>{
  "name": "new-design",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --poll=2000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-slider/ngx-slider": "^2.0.4",
    "@angular/animations": "^13.0.0",
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.0.0",
    "@angular/core": "^13.0.0",
    "@angular/forms": "^13.0.0",
    "@angular/material": "^13.0.0",
    "@angular/platform-browser": "^13.0.0",
    "@angular/platform-browser-dynamic": "^13.0.0",
    "@angular/router": "^13.0.0",
    "@capacitor/app": "1.1.1",
    "@capacitor/browser": "^4.0.1",
    "@capacitor/camera": "^4.0.1",
    "@capacitor/core": "3.6.0",
    "@capacitor/filesystem": "^4.0.1",
    "@capacitor/geolocation": "^4.0.1",
    "@capacitor/haptics": "1.1.4",
    "@capacitor/status-bar": "1.0.8",
    "@ionic/angular": "^6.1.9",
    "@ionic/pwa-elements": "^3.1.1",
    "@teamhive/lottie-player": "^1.0.0",
    "add": "^2.0.6",
    "angularx-social-login": "^4.1.0",
    "card-validator": "^8.1.1",
    "compressorjs": "^1.1.1",
    "crypto-js": "^4.1.1",
    "firebase": "^9.15.0",
    "html-entities": "^2.3.3",
    "libphonenumber-js": "^1.10.12",
    "ng": "^0.0.0",
    "ngx-cookie-service": "^14.0.1",
    "ngx-device-detector": "^4.0.1",
    "ngx-infinite-scroll": "^10.0.1",
    "ngx-webcam": "^0.4.1",
    "rxjs": "~6.6.0",
    "socket.io-client": "^2.5.0",
    "swiper": "^8.4.2",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.3.10",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/cli": "13.0",
    "@angular/compiler": "^13.0.0",
    "@angular/compiler-cli": "^13.0.0",
    "@angular/language-service": "^13.0.0",
    "@capacitor/cli": "3.6.0",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@types/socket.io-client": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.6.4"
  },
  "description": "An Ionic project"
}

</code>```

my package.json file before downgrading is

```<code>  "name": "new-design",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --port 4200 --poll=2000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-slider/ngx-slider": "^2.0.4",
    "@angular/animations": "^14.2.7",
    "@angular/cdk": "^14.2.7",
    "@angular/common": "^14.0.0",
    "@angular/core": "^14.0.0",
    "@angular/forms": "^14.0.0",
    "@angular/material": "^14.2.7",
    "@angular/platform-browser": "^14.0.0",
    "@angular/platform-browser-dynamic": "^14.0.0",
    "@angular/router": "^14.0.0",
    "@capacitor/app": "1.1.1",
    "@capacitor/browser": "^4.0.1",
    "@capacitor/camera": "^4.0.1",
    "@capacitor/core": "3.6.0",
    "@capacitor/filesystem": "^4.0.1",
    "@capacitor/geolocation": "^4.0.1",
    "@capacitor/haptics": "1.1.4",
    "@capacitor/status-bar": "1.0.8",
    "@ionic/angular": "^6.1.9",
    "@ionic/pwa-elements": "^3.1.1",
    "@teamhive/lottie-player": "^1.0.0",
    "add": "^2.0.6",
    "angularx-social-login": "^4.1.0",
    "apple-signin-auth": "^1.7.5",
    "card-validator": "^8.1.1",
    "compressorjs": "^1.1.1",
    "crypto-js": "^4.1.1",
    "firebase": "^9.15.0",
    "html-entities": "^2.3.3",
    "libphonenumber-js": "^1.10.12",
    "ng": "^0.0.0",
    "ngx-cookie-service": "^14.0.1",
    "ngx-device-detector": "^4.0.1",
    "ngx-infinite-scroll": "^10.0.1",
    "ngx-toggle-switch": "^2.0.5",
    "ngx-ui-switch": "^1.6.0",
    "ngx-webcam": "^0.4.1",
    "rxjs": "~6.6.0",
    "scriptjs": "^2.5.9",
    "socket.io-client": "^2.5.0",
    "swiper": "^8.4.2",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.6",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/cli": "^14.2.6",
    "@angular/compiler": "^14.0.0",
    "@angular/compiler-cli": "^14.0.0",
    "@angular/language-service": "^14.0.0",
    "@capacitor/cli": "3.6.0",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@types/socket.io-client": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.7.3"
  },
  "description": "An Ionic project"
}
</code>```

Can someone help me with this?

Body:
i downgraded my project angular version 14.0.0 to 13.0.0 for fixing this error Mat Dialog boxes close button is not working on IOS devices

by following the answer from
How to downgrade angular version?

but after downgrading when iam trying to run by ng serve iam getting this error

i checked the specified folder there the file asyncToGenerator.js is exists

./node_modules/idb/build/index.js:1:0-211 - Error: Module not found: Error: Can't resolve '/Volumes/Macintosh HD/Users/ravi/Public/new_mob/node_modules/@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js' in '/Volumes/Macintosh HD/Users/ravi/Public/new_mob/node_modules/idb/build'

i tried

npm install --save-dev @angular-devkit/build-angular

still getting same error

my package.json file is

{
  "name": "new-design",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --poll=2000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-slider/ngx-slider": "^2.0.4",
    "@angular/animations": "^13.0.0",
    "@angular/cdk": "^13.0.0",
    "@angular/common": "^13.0.0",
    "@angular/core": "^13.0.0",
    "@angular/forms": "^13.0.0",
    "@angular/material": "^13.0.0",
    "@angular/platform-browser": "^13.0.0",
    "@angular/platform-browser-dynamic": "^13.0.0",
    "@angular/router": "^13.0.0",
    "@capacitor/app": "1.1.1",
    "@capacitor/browser": "^4.0.1",
    "@capacitor/camera": "^4.0.1",
    "@capacitor/core": "3.6.0",
    "@capacitor/filesystem": "^4.0.1",
    "@capacitor/geolocation": "^4.0.1",
    "@capacitor/haptics": "1.1.4",
    "@capacitor/status-bar": "1.0.8",
    "@ionic/angular": "^6.1.9",
    "@ionic/pwa-elements": "^3.1.1",
    "@teamhive/lottie-player": "^1.0.0",
    "add": "^2.0.6",
    "angularx-social-login": "^4.1.0",
    "card-validator": "^8.1.1",
    "compressorjs": "^1.1.1",
    "crypto-js": "^4.1.1",
    "firebase": "^9.15.0",
    "html-entities": "^2.3.3",
    "libphonenumber-js": "^1.10.12",
    "ng": "^0.0.0",
    "ngx-cookie-service": "^14.0.1",
    "ngx-device-detector": "^4.0.1",
    "ngx-infinite-scroll": "^10.0.1",
    "ngx-webcam": "^0.4.1",
    "rxjs": "~6.6.0",
    "socket.io-client": "^2.5.0",
    "swiper": "^8.4.2",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.3.10",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/cli": "13.0",
    "@angular/compiler": "^13.0.0",
    "@angular/compiler-cli": "^13.0.0",
    "@angular/language-service": "^13.0.0",
    "@capacitor/cli": "3.6.0",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@types/socket.io-client": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.6.4"
  },
  "description": "An Ionic project"
}

my package.json file before downgrading is

  "name": "new-design",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --port 4200 --poll=2000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular-slider/ngx-slider": "^2.0.4",
    "@angular/animations": "^14.2.7",
    "@angular/cdk": "^14.2.7",
    "@angular/common": "^14.0.0",
    "@angular/core": "^14.0.0",
    "@angular/forms": "^14.0.0",
    "@angular/material": "^14.2.7",
    "@angular/platform-browser": "^14.0.0",
    "@angular/platform-browser-dynamic": "^14.0.0",
    "@angular/router": "^14.0.0",
    "@capacitor/app": "1.1.1",
    "@capacitor/browser": "^4.0.1",
    "@capacitor/camera": "^4.0.1",
    "@capacitor/core": "3.6.0",
    "@capacitor/filesystem": "^4.0.1",
    "@capacitor/geolocation": "^4.0.1",
    "@capacitor/haptics": "1.1.4",
    "@capacitor/status-bar": "1.0.8",
    "@ionic/angular": "^6.1.9",
    "@ionic/pwa-elements": "^3.1.1",
    "@teamhive/lottie-player": "^1.0.0",
    "add": "^2.0.6",
    "angularx-social-login": "^4.1.0",
    "apple-signin-auth": "^1.7.5",
    "card-validator": "^8.1.1",
    "compressorjs": "^1.1.1",
    "crypto-js": "^4.1.1",
    "firebase": "^9.15.0",
    "html-entities": "^2.3.3",
    "libphonenumber-js": "^1.10.12",
    "ng": "^0.0.0",
    "ngx-cookie-service": "^14.0.1",
    "ngx-device-detector": "^4.0.1",
    "ngx-infinite-scroll": "^10.0.1",
    "ngx-toggle-switch": "^2.0.5",
    "ngx-ui-switch": "^1.6.0",
    "ngx-webcam": "^0.4.1",
    "rxjs": "~6.6.0",
    "scriptjs": "^2.5.9",
    "socket.io-client": "^2.5.0",
    "swiper": "^8.4.2",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.6",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/cli": "^14.2.6",
    "@angular/compiler": "^14.0.0",
    "@angular/compiler-cli": "^14.0.0",
    "@angular/language-service": "^14.0.0",
    "@capacitor/cli": "3.6.0",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@types/socket.io-client": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.7.3"
  },
  "description": "An Ionic project"
}

Can someone help me with this?


来源: stackexchange

问:
unirest encoding space to '20' but the server expect as '+'
I am trying to pass quesry as queryString function of UniRest. I was getting signature mismatch.

Afte check ing through all the function, I got to know unirest uses 'com.mashape.unirest.http.utils.Base64Coder;' to encode query params. This is encoding space in query param to '%20'.

My server expects '+' for space.

```<code>actual query String = "2023-01-05 00:00:00"
Unirest encoding = "2023-01-06%2000%3A00%3A00"
expected query String = "2023-01-06+00%3A00%3A00"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to pass quesry as queryString function of UniRest. I was getting signature mismatch.

Afte check ing through all the function, I got to know unirest uses 'com.mashape.unirest.http.utils.Base64Coder;' to encode query params. This is encoding space in query param to '%20'.

My server expects '+' for space.

actual query String = "2023-01-05 00:00:00"
Unirest encoding = "2023-01-06%2000%3A00%3A00"
expected query String = "2023-01-06+00%3A00%3A00"


问:
ubuntu,arm-rockchip830-linux-uclibcgnueabihf cross-compile OpenSSL
enviroment:ubuntu arm64;
cross compile tool:arm-rockchip830-linux-uclibcgnueabihf-  32bit;
openssl version:OpenSSL 1.1.1b  26 Feb 2019

after configured,when I make，it report error like this:
enter image description here

I don't know how to fix this problem,asking for help


问:
creating logging for django rest framework
I'm creating a logger for my application.
It should create a file day wise and if the file size is cross 100MB it will create a new file for that
this is my logger_config.py

```<code>import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Use a TimedRotatingFileHandler to log to a file that rotates every day
handler = TimedRotatingFileHandler('loggerFiles', when='D', interval=1, backupCount=30)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Logging levels
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")

import os
filepath = None
def check_log_file_size(filepath):
    """
    Check if the log file has exceeded the maximum size
    """
    size = os.path.getsize(filepath)
    if size > 100000000: # 100000000 bytes = 100MB
        new_filepath = f'{filepath}_1'
        os.rename(filepath, new_filepath)
</code>```

that is how I'm using it.

```<code>class MyView(APIView):
    def get(self, request):
        try:
            # some code that may raise an exception
            1/0
        except Exception as e:
            logger.exception("An exception occurred: %s", e)
            return Response({"error": "An exception occurred"}, status=status.HTTP_400_BAD_REQUEST)
</code>```

but the problem is it is not creating fils as I want.

Body:
I'm creating a logger for my application.
It should create a file day wise and if the file size is cross 100MB it will create a new file for that
this is my logger_config.py

import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Use a TimedRotatingFileHandler to log to a file that rotates every day
handler = TimedRotatingFileHandler('loggerFiles', when='D', interval=1, backupCount=30)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Logging levels
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")

import os
filepath = None
def check_log_file_size(filepath):
    """
    Check if the log file has exceeded the maximum size
    """
    size = os.path.getsize(filepath)
    if size > 100000000: # 100000000 bytes = 100MB
        new_filepath = f'{filepath}_1'
        os.rename(filepath, new_filepath)

that is how I'm using it.

class MyView(APIView):
    def get(self, request):
        try:
            # some code that may raise an exception
            1/0
        except Exception as e:
            logger.exception("An exception occurred: %s", e)
            return Response({"error": "An exception occurred"}, status=status.HTTP_400_BAD_REQUEST)

but the problem is it is not creating fils as I want.


问:
GoogleTagManager integration issue - Internal error - Function call: __fm_validateEventData
I have integrated GoogleTagManager in project, I am sending a dummy event with basic Params.

Event details -

```<code>firebaseAnalytics = FirebaseAnalytics.getInstance(this)
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "my_item_id")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle)
</code>```

But getting this issue -

```<code>Event does not have parameter "item_id" and no default value was defined. Returning "undefined".
Event does not have parameter "test1" and no default value was defined. Returning "undefined".
Internal error - Function call: __fm_validateEventData
Apply TypeError: object has no charAt property
</code>```

Same event is working in demo project.

Body:
I have integrated GoogleTagManager in project, I am sending a dummy event with basic Params.

Event details -

firebaseAnalytics = FirebaseAnalytics.getInstance(this)
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "my_item_id")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle)

But getting this issue -

Event does not have parameter "item_id" and no default value was defined. Returning "undefined".
Event does not have parameter "test1" and no default value was defined. Returning "undefined".
Internal error - Function call: __fm_validateEventData
Apply TypeError: object has no charAt property

Same event is working in demo project.


问:
problems in energy saving algorithns and simulation of wireless sensor network based on clustering routing protocol
What is the problems  energy saving algorithns and simulation of wireless sensor network based on clustering routing protocol

The problems  energy saving algorithns


问:
Logs 100K request per second in real-time with python logging package
I have to get the data from one of my localhost ports and saved it to a log file. To do this, I use the logging package. Here is my code:

In the first step I designed my custom TimedRotatingFileHandler:

```<code>from logging.handlers import BaseRotatingHandler,
TimedRotatingFileHandler
from itertools import islice
import logging
import time
import os

_intervals = {
 "S": 1,
 "M": 60,
 "H": 60 * 60,
 "D": 60 * 60 * 24,
 "MIDNIGHT": 60 * 60 * 24,
 "W": 60 * 60 * 24 * 7}

class CustomTimedRotatingFileHandler(BaseRotatingHandler):
    """File handler that uses the current time in the log filename.

    The time is quantisized to a configured interval. See
    TimedRotatingFileHandler for the meaning of the when, interval, utc and
    atTime arguments.

    If backupCount is non-zero, then older filenames that match the base
    filename are deleted to only leave the backupCount most recent copies,
    whenever opening a new log file with a different name.

    """

    def __init__(self, filenamePattern, when="h", interval=1, backupCount=0,
                 encoding=None, delay=False, utc=False, atTime=None):
        self.when = when.upper()
        self.backupCount = backupCount
        self.utc = utc
         self.atTime = atTime
        try:
             key = "W" if self.when.startswith("W") else self.when
             self.interval = _intervals[key]
        except KeyError:
             raise ValueError(
                 f"Invalid rollover interval specified: {self.when}"
             ) from None
        if self.when.startswith("W"):
             if len(self.when) != 2:
                 raise ValueError(
                     "You must specify a day for weekly rollover from 0 to 6 "
                     f"(0 is Monday): {self.when}"
                 )
             if not "0" <= self.when[1] <= "6":
                 raise ValueError(
                     f"Invalid day specified for weekly rollover: {self.when}"
                 )
             self.dayOfWeek = int(self.when[1])

         self.interval = self.interval * interval
         self.pattern = os.path.abspath(os.fspath(filenamePattern))

         # determine best time to base our rollover times on
         # prefer the creation time of the most recently created log file.
         t = now = time.time()
         entry = next(self._matching_files(), None)
         if entry is not None:
             t = entry.stat().st_ctime
             while t + self.interval < now:
                 t += self.interval

         self.rolloverAt = self.computeRollover(t)

         # delete older files on startup and not delaying
         if not delay and backupCount > 0:
             keep = backupCount
             if os.path.exists(self.baseFilename):
                 keep += 1
                 delete = islice(self._matching_files(), keep, None)
                 for entry in delete:
                     os.remove(entry.path)

         # Will set self.baseFilename indirectly, and then may use
         # self.baseFilename to open. So by this point self.rolloverAt and
         # self.interval must be known.
         super().__init__(filenamePattern, "a", encoding, delay)

     @property
     def baseFilename(self):
         """Generate the 'current' filename to open"""
         # use the start of *this* interval, not the next
         t = self.rolloverAt - self.interval
         if self.utc:
             time_tuple = time.gmtime(t)
         else:
             time_tuple = time.localtime(t)
             dst = time.localtime(self.rolloverAt)[-1]
             if dst != time_tuple[-1] and self.interval > 3600:
                 # DST switches between t and self.rolloverAt, adjust
                 addend = 3600 if dst else -3600
                 time_tuple = time.localtime(t + added)
         return time.strftime(self.pattern, time_tuple)

     @baseFilename.setter
     def baseFilename(self, _):
         # assigned to by FileHandler, just ignore this as we use self.pattern
         # instead
         pass

     def _matching_files(self):
         """Generate DirEntry entries that match the filename pattern.

         The files are ordered by their last modification time, most recent
         files first.
         """
         matches = []
         pattern = self.pattern
         for entry in os.scandir(os.path.dirname(pattern)):
             if not entry.is_file():
                 continue
             try:
                 time.strptime(entry.path, pattern)
                 matches.append(entry)
             except ValueError:
                 continue
         matches.sort(key=lambda e: e.stat().st_mtime, reverse=True)
         return iter(matches)

     def doRollover(self):
         """Do a roll-over. This basically needs to open a new generated filename.
         """
         if self.stream:
             self.stream.close()
             self.stream = None

         if self.backupCount > 0:
             delete = islice(self._matching_files(), self.backupCount, None)
             for entry in delete:
                 os.remove(entry.path)

         now = int(time.time())
         rollover = self.computeRollover(now)
         while rollover <= now:
             rollover += self.interval
         if not self.utc:
             # If DST changes and midnight or weekly rollover, adjust for this.
             if self.when == "MIDNIGHT" or self.when.startswith("W"):
                 dst = time.localtime(now)[-1]
                 if dst != time.localtime(rollover)[-1]:
                     rollover += 3600 if dst else -3600
         self.rolloverAt = rollover

         if not self.delay:
             self.stream = self._open()

     # borrow *some* TimedRotatingFileHandler methods
     computeRollover = TimedRotatingFileHandler.computeRollover
     shouldRollover = TimedRotatingFileHandler.shouldRollover

 def setup_handlers():
     formatter = logging.Formatter('%(message)s')
     loggers = {'log_t': logging.getLogger('t'),
                'log_b': logging.getLogger('b'),
                'log': logging.getLogger('log')}

     for logger in loggers:
         loggers[logger].setLevel(logging.INFO)
         if logger == 'log':
             when = 'M'
             interval = 5
             backup_count = 24
             filename_pattern = 'logs/%Y_%m_%d_%H_%M.txt'

         else:
             when = 'H'
             interval = 1
             backup_count = 2
             filename_pattern = f'logs/%Y_%m_%d_%H_{logger}.txt'

         handler = CustomTimedRotatingFileHandler(filenamePattern=filename_pattern,
                                                  when=when, interval=interval, backupCount=backup_count)
         handler.setFormatter(formatter)
         loggers[logger].addHandler(handler)

     return loggers
</code>```

In the second step, I created a Syslog class to get the data from the port:

```<code>from handler import setup_handlers
import socketserver
import os
import re

HOST, PORT = "0.0.0.0", 8080

PATTERNS = [r'pattern1', r'pattern2', r'pattern3', r'pattern4',
            r'pattern5', r'pattern6', r'pattern7', r'pattern8']

class SysLogUDPHandler(socketserver.BaseRequestHandler):

    @staticmethod
    def __check_log_type(text):

        if 'LOG_T' in text:
            log_type = 'teardown'
        elif 'LOG_B' in text:
            log_type = 'built'
        else:
            log_type = None

        return log_type

    @staticmethod
    def __get_pattern(pattern, text):

        result = re.split(pattern, text)
        if len(result) > 1:
            result = result[1].split(',')[0]

        else:
            result = ' '

        return result

    def __get_data(self, data) -> str:

        logs = ''
        for pattern in PATTERNS:
            log = self.__get_pattern(pattern=pattern, text=data)
            if log:
                logs += log
                logs += ','

        return logs

    def handle(self) -> None:
        request = self.request[0].decode()
        log_type = self.__check_log_type(request)
        if log_type in ['log_t', 'log_b']:
            logs = self.__get_data(data=request)
            loggers[log_type].info(logs)

        else:
            print('Invalid log type!')

        data = bytes.decode(self.request[0])
        loggers['log'].info(data)

if __name__ == "__main__":
    try:
        os.makedirs('logs', exist_ok=True)
        loggers = setup_handlers()
        server = socketserver.UDPServer((HOST, PORT), SysLogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print("Ctrl+C Pressed. Shutting down.")
</code>```

The challenge is the rate of requests per second is around 100,000 which is really high. Therefore, I miss a huge part of the requests. I guess it is around 80%! What is the best practice to log this amount of data?

Body:
I have to get the data from one of my localhost ports and saved it to a log file. To do this, I use the logging package. Here is my code:

In the first step I designed my custom TimedRotatingFileHandler:

from logging.handlers import BaseRotatingHandler,
TimedRotatingFileHandler
from itertools import islice
import logging
import time
import os

_intervals = {
 "S": 1,
 "M": 60,
 "H": 60 * 60,
 "D": 60 * 60 * 24,
 "MIDNIGHT": 60 * 60 * 24,
 "W": 60 * 60 * 24 * 7}

class CustomTimedRotatingFileHandler(BaseRotatingHandler):
    """File handler that uses the current time in the log filename.

    The time is quantisized to a configured interval. See
    TimedRotatingFileHandler for the meaning of the when, interval, utc and
    atTime arguments.

    If backupCount is non-zero, then older filenames that match the base
    filename are deleted to only leave the backupCount most recent copies,
    whenever opening a new log file with a different name.

    """

    def __init__(self, filenamePattern, when="h", interval=1, backupCount=0,
                 encoding=None, delay=False, utc=False, atTime=None):
        self.when = when.upper()
        self.backupCount = backupCount
        self.utc = utc
         self.atTime = atTime
        try:
             key = "W" if self.when.startswith("W") else self.when
             self.interval = _intervals[key]
        except KeyError:
             raise ValueError(
                 f"Invalid rollover interval specified: {self.when}"
             ) from None
        if self.when.startswith("W"):
             if len(self.when) != 2:
                 raise ValueError(
                     "You must specify a day for weekly rollover from 0 to 6 "
                     f"(0 is Monday): {self.when}"
                 )
             if not "0" <= self.when[1] <= "6":
                 raise ValueError(
                     f"Invalid day specified for weekly rollover: {self.when}"
                 )
             self.dayOfWeek = int(self.when[1])

         self.interval = self.interval * interval
         self.pattern = os.path.abspath(os.fspath(filenamePattern))

         # determine best time to base our rollover times on
         # prefer the creation time of the most recently created log file.
         t = now = time.time()
         entry = next(self._matching_files(), None)
         if entry is not None:
             t = entry.stat().st_ctime
             while t + self.interval < now:
                 t += self.interval

         self.rolloverAt = self.computeRollover(t)

         # delete older files on startup and not delaying
         if not delay and backupCount > 0:
             keep = backupCount
             if os.path.exists(self.baseFilename):
                 keep += 1
                 delete = islice(self._matching_files(), keep, None)
                 for entry in delete:
                     os.remove(entry.path)

         # Will set self.baseFilename indirectly, and then may use
         # self.baseFilename to open. So by this point self.rolloverAt and
         # self.interval must be known.
         super().__init__(filenamePattern, "a", encoding, delay)

     @property
     def baseFilename(self):
         """Generate the 'current' filename to open"""
         # use the start of *this* interval, not the next
         t = self.rolloverAt - self.interval
         if self.utc:
             time_tuple = time.gmtime(t)
         else:
             time_tuple = time.localtime(t)
             dst = time.localtime(self.rolloverAt)[-1]
             if dst != time_tuple[-1] and self.interval > 3600:
                 # DST switches between t and self.rolloverAt, adjust
                 addend = 3600 if dst else -3600
                 time_tuple = time.localtime(t + added)
         return time.strftime(self.pattern, time_tuple)

     @baseFilename.setter
     def baseFilename(self, _):
         # assigned to by FileHandler, just ignore this as we use self.pattern
         # instead
         pass

     def _matching_files(self):
         """Generate DirEntry entries that match the filename pattern.

         The files are ordered by their last modification time, most recent
         files first.
         """
         matches = []
         pattern = self.pattern
         for entry in os.scandir(os.path.dirname(pattern)):
             if not entry.is_file():
                 continue
             try:
                 time.strptime(entry.path, pattern)
                 matches.append(entry)
             except ValueError:
                 continue
         matches.sort(key=lambda e: e.stat().st_mtime, reverse=True)
         return iter(matches)

     def doRollover(self):
         """Do a roll-over. This basically needs to open a new generated filename.
         """
         if self.stream:
             self.stream.close()
             self.stream = None

         if self.backupCount > 0:
             delete = islice(self._matching_files(), self.backupCount, None)
             for entry in delete:
                 os.remove(entry.path)

         now = int(time.time())
         rollover = self.computeRollover(now)
         while rollover <= now:
             rollover += self.interval
         if not self.utc:
             # If DST changes and midnight or weekly rollover, adjust for this.
             if self.when == "MIDNIGHT" or self.when.startswith("W"):
                 dst = time.localtime(now)[-1]
                 if dst != time.localtime(rollover)[-1]:
                     rollover += 3600 if dst else -3600
         self.rolloverAt = rollover

         if not self.delay:
             self.stream = self._open()

     # borrow *some* TimedRotatingFileHandler methods
     computeRollover = TimedRotatingFileHandler.computeRollover
     shouldRollover = TimedRotatingFileHandler.shouldRollover

 def setup_handlers():
     formatter = logging.Formatter('%(message)s')
     loggers = {'log_t': logging.getLogger('t'),
                'log_b': logging.getLogger('b'),
                'log': logging.getLogger('log')}

     for logger in loggers:
         loggers[logger].setLevel(logging.INFO)
         if logger == 'log':
             when = 'M'
             interval = 5
             backup_count = 24
             filename_pattern = 'logs/%Y_%m_%d_%H_%M.txt'

         else:
             when = 'H'
             interval = 1
             backup_count = 2
             filename_pattern = f'logs/%Y_%m_%d_%H_{logger}.txt'

         handler = CustomTimedRotatingFileHandler(filenamePattern=filename_pattern,
                                                  when=when, interval=interval, backupCount=backup_count)
         handler.setFormatter(formatter)
         loggers[logger].addHandler(handler)

     return loggers

In the second step, I created a Syslog class to get the data from the port:

from handler import setup_handlers
import socketserver
import os
import re

HOST, PORT = "0.0.0.0", 8080

PATTERNS = [r'pattern1', r'pattern2', r'pattern3', r'pattern4',
            r'pattern5', r'pattern6', r'pattern7', r'pattern8']

class SysLogUDPHandler(socketserver.BaseRequestHandler):

    @staticmethod
    def __check_log_type(text):

        if 'LOG_T' in text:
            log_type = 'teardown'
        elif 'LOG_B' in text:
            log_type = 'built'
        else:
            log_type = None

        return log_type

    @staticmethod
    def __get_pattern(pattern, text):

        result = re.split(pattern, text)
        if len(result) > 1:
            result = result[1].split(',')[0]

        else:
            result = ' '

        return result

    def __get_data(self, data) -> str:

        logs = ''
        for pattern in PATTERNS:
            log = self.__get_pattern(pattern=pattern, text=data)
            if log:
                logs += log
                logs += ','

        return logs

    def handle(self) -> None:
        request = self.request[0].decode()
        log_type = self.__check_log_type(request)
        if log_type in ['log_t', 'log_b']:
            logs = self.__get_data(data=request)
            loggers[log_type].info(logs)

        else:
            print('Invalid log type!')

        data = bytes.decode(self.request[0])
        loggers['log'].info(data)

if __name__ == "__main__":
    try:
        os.makedirs('logs', exist_ok=True)
        loggers = setup_handlers()
        server = socketserver.UDPServer((HOST, PORT), SysLogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print("Ctrl+C Pressed. Shutting down.")

The challenge is the rate of requests per second is around 100,000 which is really high. Therefore, I miss a huge part of the requests. I guess it is around 80%! What is the best practice to log this amount of data?


问:
Old login token is not getting removed on re-login after successfull log-out
On Log-out i am clearing cookies like this:

```<code>    const logoutUser = () => {
        setUserData(undefined);
        Cookies.remove('admin_details');
    };

</code>```

and also updating headers through auth link in Apollo Client like this:

```<code> const authLink = new ApolloLink((operation, forward) => {
     // add the authorization to the headers
     const token = getToken();
     if (token) {
         operation.setContext(({headers = {}}) => ({
             headers: {
                 ...headers,
                 authorization: token ? `Bearer ${token}` : '',
             },
         }));
     } else {
         operation.setContext(({headers = {}}) => ({
             headers: {
                 ...headers,
            },
         }));
     }

     return forward(operation);
 });
</code>```

So I am not sure why the previous header token is set even after successfully log-out

Here is my APOLLO graphql setup file

```<code>  const getToken = (): string | undefined => {
    const adminDetails = Cookies.get('admin_details');
    if (adminDetails) {
        const userDataCookies = JSON.parse(
            adminDetails,
        ) as AdminLoginMutation['login'];
        return userDataCookies.access_token;
    }

    return undefined;
};

const logoutAndRedirectToLogin = () => {
    Cookies.remove('admin_details');
    window.location.reload();
    window.location.replace('/auth/login');
};

const getRequestHeaders = () => {
    let header;
    const token = getToken();

    if (token) {
        header = {
            authorization: token ? `Bearer ${token}` : undefined,
        };
    } else {
        header = {
            isadmin: true,
        };
    }

    return header;
};

const getUrl = (): {
    ws: string;
    http: string;
} => {
    if (
        process.env.END_POINT &&
        typeof process.env.END_POINT === 'string'
    ) {
        if (process.env.END_POINT.includes('localhost')) {
            return {
                ws: 'ws://' + process.env.END_POINT,
                http: 'http://' + process.env.END_POINT,
            };
        } else {
            return {
                ws: 'wss://' + process.env.END_POINT,
                http: 'https://' + process.env.END_POINT,
            };
        }
    } else {
        return {ws: '', http: ''};
    }
};

const httpLink = createHttpLink({
    uri: getUrl().http,
    headers: getRequestHeaders(),
});

const wsLink = new GraphQLWsLink(
    createWsClient({
        url: getUrl().ws,
        connectionParams: {
            headers: getRequestHeaders(),
        },
    }),
);

const authLink = new ApolloLink((operation, forward) => {
    // add the authorization to the headers
    const token = getToken();
    if (token) {
        operation.setContext(({headers = {}}) => ({
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : '',
            },
        }));
    } else {
        operation.setContext(({headers = {}}) => ({
            headers: {
                ...headers,
            },
        }));
    }

    return forward(operation);
});

const returnConnectionLink = (): ApolloLink => {
    return split(
        ({query}) => {
            const definition = getMainDefinition(query);
            return (
                definition.kind === 'OperationDefinition' &&
                definition.operation === 'subscription'
            );
        },
        wsLink,
        httpLink,
    );
};

const splitLink = returnConnectionLink();

const errorLink = onError(({networkError, graphQLErrors}) => {
    // To retry on network errors, we recommend the RetryLink
    // instead of the onError link. This just logs the error.
    if (networkError) {
        if (
            networkError.message.includes('authorization') ||
            networkError.message.includes('unauthorized')
        ) {
            logoutAndRedirectToLogin();
        }
    }

    if (graphQLErrors) {
        graphQLErrors.forEach(({extensions: {code}}) => {
            if (code === 'UNAUTHENTICATED') {
                logoutAndRedirectToLogin();
            }
        });
    }
});

const cache = new InMemoryCache();

const links: Array<ApolloLink | RequestHandler> = [splitLink, errorLink];

export const graphqlClient = new ApolloClient({
    cache: cache,
    link: authLink.concat(ApolloLink.from(links)),
    ssrMode: typeof window === 'undefined',
    name: process.env.REACT_PUBLIC_APP_NAME
        ? process.env.REACT_PUBLIC_APP_NAME + '_web'
        : 'web',
    version: process.env.REACT_PUBLIC_APP_VERSION,
    defaultOptions: {
        watchQuery: {
            fetchPolicy: 'cache-and-network',
        },
    },
});

</code>```

-Basically i want that,

Old login token should removed on re-login after successfull log-out

-NOTE

This issue comes sometimes but not everytime so not sure where am i going wrong

Any help would be appreciated. THANK YOU :)

Body:
On Log-out i am clearing cookies like this:

    const logoutUser = () => {
        setUserData(undefined);
        Cookies.remove('admin_details');
    };

and also updating headers through auth link in Apollo Client like this:

 const authLink = new ApolloLink((operation, forward) => {
     // add the authorization to the headers
     const token = getToken();
     if (token) {
         operation.setContext(({headers = {}}) => ({
             headers: {
                 ...headers,
                 authorization: token ? `Bearer ${token}` : '',
             },
         }));
     } else {
         operation.setContext(({headers = {}}) => ({
             headers: {
                 ...headers,
            },
         }));
     }

     return forward(operation);
 });

So I am not sure why the previous header token is set even after successfully log-out

Here is my APOLLO graphql setup file

  const getToken = (): string | undefined => {
    const adminDetails = Cookies.get('admin_details');
    if (adminDetails) {
        const userDataCookies = JSON.parse(
            adminDetails,
        ) as AdminLoginMutation['login'];
        return userDataCookies.access_token;
    }

    return undefined;
};

const logoutAndRedirectToLogin = () => {
    Cookies.remove('admin_details');
    window.location.reload();
    window.location.replace('/auth/login');
};

const getRequestHeaders = () => {
    let header;
    const token = getToken();

    if (token) {
        header = {
            authorization: token ? `Bearer ${token}` : undefined,
        };
    } else {
        header = {
            isadmin: true,
        };
    }

    return header;
};

const getUrl = (): {
    ws: string;
    http: string;
} => {
    if (
        process.env.END_POINT &&
        typeof process.env.END_POINT === 'string'
    ) {
        if (process.env.END_POINT.includes('localhost')) {
            return {
                ws: 'ws://' + process.env.END_POINT,
                http: 'http://' + process.env.END_POINT,
            };
        } else {
            return {
                ws: 'wss://' + process.env.END_POINT,
                http: 'https://' + process.env.END_POINT,
            };
        }
    } else {
        return {ws: '', http: ''};
    }
};

const httpLink = createHttpLink({
    uri: getUrl().http,
    headers: getRequestHeaders(),
});

const wsLink = new GraphQLWsLink(
    createWsClient({
        url: getUrl().ws,
        connectionParams: {
            headers: getRequestHeaders(),
        },
    }),
);

const authLink = new ApolloLink((operation, forward) => {
    // add the authorization to the headers
    const token = getToken();
    if (token) {
        operation.setContext(({headers = {}}) => ({
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : '',
            },
        }));
    } else {
        operation.setContext(({headers = {}}) => ({
            headers: {
                ...headers,
            },
        }));
    }

    return forward(operation);
});

const returnConnectionLink = (): ApolloLink => {
    return split(
        ({query}) => {
            const definition = getMainDefinition(query);
            return (
                definition.kind === 'OperationDefinition' &&
                definition.operation === 'subscription'
            );
        },
        wsLink,
        httpLink,
    );
};

const splitLink = returnConnectionLink();

const errorLink = onError(({networkError, graphQLErrors}) => {
    // To retry on network errors, we recommend the RetryLink
    // instead of the onError link. This just logs the error.
    if (networkError) {
        if (
            networkError.message.includes('authorization') ||
            networkError.message.includes('unauthorized')
        ) {
            logoutAndRedirectToLogin();
        }
    }

    if (graphQLErrors) {
        graphQLErrors.forEach(({extensions: {code}}) => {
            if (code === 'UNAUTHENTICATED') {
                logoutAndRedirectToLogin();
            }
        });
    }
});

const cache = new InMemoryCache();

const links: Array<ApolloLink | RequestHandler> = [splitLink, errorLink];

export const graphqlClient = new ApolloClient({
    cache: cache,
    link: authLink.concat(ApolloLink.from(links)),
    ssrMode: typeof window === 'undefined',
    name: process.env.REACT_PUBLIC_APP_NAME
        ? process.env.REACT_PUBLIC_APP_NAME + '_web'
        : 'web',
    version: process.env.REACT_PUBLIC_APP_VERSION,
    defaultOptions: {
        watchQuery: {
            fetchPolicy: 'cache-and-network',
        },
    },
});

-Basically i want that,

Old login token should removed on re-login after successfull log-out

-NOTE

This issue comes sometimes but not everytime so not sure where am i going wrong

Any help would be appreciated. THANK YOU :)


问:
Error Running terminal command in Mac App
I'm trying to run terminal command pluginkit -m in my mac app but it returns message match: unauthorized discovery flag (PKDiscoverAll).But if I run ls command it works fine.

Can someone please explain how can I run pluginkit -m command or point me to documentation where apple explains why these command can't be run from an app. These commands run fine on my terminal.

Here is my code

```<code>    let task = Process()
    let pipe = Pipe()

    task.standardOutput = pipe
    task.standardError = pipe
    task.arguments = ["-c", "pluginkit -m"]
    task.executableURL = URL(fileURLWithPath: "/bin/zsh") //<--updated
    task.standardInput = nil

    try task.run()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!
</code>```

Body:
I'm trying to run terminal command pluginkit -m in my mac app but it returns message match: unauthorized discovery flag (PKDiscoverAll).But if I run ls command it works fine.

Can someone please explain how can I run pluginkit -m command or point me to documentation where apple explains why these command can't be run from an app. These commands run fine on my terminal.

Here is my code

    let task = Process()
    let pipe = Pipe()

    task.standardOutput = pipe
    task.standardError = pipe
    task.arguments = ["-c", "pluginkit -m"]
    task.executableURL = URL(fileURLWithPath: "/bin/zsh") //<--updated
    task.standardInput = nil

    try task.run()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: .utf8)!


问:
node_modules\gifsicle: Command failed

node_modules\gifsicle: Command failed.
Exit code: 1
Command: node lib/install.js
Arguments:
Directory: D:\Project\PFS\pfs-portal\node_modules\gifsicle
Output:
‼ connect ETIMEDOUT 49.44.79.236:443
  ‼ gifsicle pre-build test failed
  i compiling from source
  × Error: Command failed: C:\WINDOWS\system32\cmd.exe /s /c "autoreconf -ivf"
'autoreconf' is not recognized as an internal or external command,
operable program or batch file.
```

I have tried this all solution not working for me
Yarn install
clear chache
yarn force install
verbose
deleted node modules nothing is working for me

i want to install packages through yarn

Title: node_modules\gifsicle: Command failed

Body:
node_modules\gifsicle: Command failed.
Exit code: 1
Command: node lib/install.js
Arguments:
Directory: D:\Project\PFS\pfs-portal\node_modules\gifsicle
Output:
‼ connect ETIMEDOUT 49.44.79.236:443
  ‼ gifsicle pre-build test failed
  i compiling from source
  × Error: Command failed: C:\WINDOWS\system32\cmd.exe /s /c "autoreconf -ivf"
'autoreconf' is not recognized as an internal or external command,
operable program or batch file.

I have tried this all solution not working for me
Yarn install
clear chache
yarn force install
verbose
deleted node modules nothing is working for me

i want to install packages through yarn


问:
How to stop a thread in python and continue it after a specific time?
I am creating an MP3 music player with lyrics synchronization feature. I want to stop the synchronization of lyrics when the user presses on the pause button (tkinter). The code looks like this:

```<code>    def highlightlyrics():
            a=threading.Thread(target=SyncLyrics)
            a.start()
        # code of lyrics synchronization
    def SyncLyrics():
        global playing
        pygame.mixer.music.pause()
        try:
            # this if statement is for when the user uploads an lrc
            if playing and TimePlaying_value>=1:
                NoToRoundOff=TimePlaying_value
                    # list contains the nearest lyrics timestamps to the time of the song
                dictionary=[]
                    # this list contains the position of timestamps
                pos=[]
                    # this for loop is for finding the nearest lyrics of timestamps of the song
                for x in range(len(LYRICS)):
                    if times[x]-NoToRoundOff>0:
                        dictionary.append(times[x]-NoToRoundOff)
                        pos.append(x)
                        ls.select_set(min(pos)-2)
                        pygame.mixer.music.unpause()
                        break
                # this for loop is for continuation of synchronization
                for x in range(min(pos),len(LYRICS)):
                    ls.select_clear(x-1)
                    ls.select_set(x)
                    time.sleep(float((format(times[x+1]-times[x],'.2f'))))
        except Exception as e:
                raise e
                thread._stop()

#I tried to create a variable where a Boolean value is stored when the user #clicks on the pause button the variable data goes to true
        #The code i tried to fix this:

        def change():
            global is_paused
            if PlayButton['image']==str(PLay):
                pygame.mixer.music.unpause()
                PlayButton['image']=PAuse
                PlayButton.pack()
                is_paused=False
            else:
                pygame.mixer.music.pause()
                PlayButton['image']=PLay
                PlayButton.pack()
                is_paused=True
        def SyncLyrics():
            global playing
            pygame.mixer.music.pause()
            try:
                # this if statement is for when the user uploads [lyrics ](https://en.wikipedia.org/wiki/LRC_(file_format)) file after the song is started
                if playing and TimePlaying_value>=1:
                    NoToRoundOff=TimePlaying_value
                    # list contains the nearest lyrics timestamps to the time of the song
                    dictionary=[]
                    # this list contains the position of timestamps
                    pos=[]
                    # this for loop is for finding the nearest lyrics of timestamps of the song
                    if not is_paused:
                        for x in range(len(LYRICS)):
                            if times[x]-NoToRoundOff>0:
                                dictionary.append(times[x]-NoToRoundOff)
                                pos.append(x)
                                ls.select_set(min(pos)-2)
                                pygame.mixer.music.unpause()
                                break
                                for x in range(min(pos),len(LYRICS)):
                                     ls.select_clear(x-1)
                                     ls.select_set(x)
                                     time.sleep(float((format(times[x+1]-times[x],'.2f'))))
                    else:
                        pass
                print(is_paused)# When I clicked on the pause button it shows me the output as false. But it had to give true.
                # this for loop is for continuation of synchronization
                for x in range(min(pos),len(LYRICS)):
                    ls.select_clear(x-1)
                    ls.select_set(x)
                    time.sleep(float((format(times[x+1]-times[x],'.2f'))))
            except Exception as e:
                raise e
                thread._stop()
</code>```

The main problem of the code is that the is_paused variable doesn't gets update to true when i click on paused button
If you have understood the question please answer. IF you have any type of query comment it.

Body:
I am creating an MP3 music player with lyrics synchronization feature. I want to stop the synchronization of lyrics when the user presses on the pause button (tkinter). The code looks like this:

    def highlightlyrics():
            a=threading.Thread(target=SyncLyrics)
            a.start()
        # code of lyrics synchronization
    def SyncLyrics():
        global playing
        pygame.mixer.music.pause()
        try:
            # this if statement is for when the user uploads an lrc
            if playing and TimePlaying_value>=1:
                NoToRoundOff=TimePlaying_value
                    # list contains the nearest lyrics timestamps to the time of the song
                dictionary=[]
                    # this list contains the position of timestamps
                pos=[]
                    # this for loop is for finding the nearest lyrics of timestamps of the song
                for x in range(len(LYRICS)):
                    if times[x]-NoToRoundOff>0:
                        dictionary.append(times[x]-NoToRoundOff)
                        pos.append(x)
                        ls.select_set(min(pos)-2)
                        pygame.mixer.music.unpause()
                        break
                # this for loop is for continuation of synchronization
                for x in range(min(pos),len(LYRICS)):
                    ls.select_clear(x-1)
                    ls.select_set(x)
                    time.sleep(float((format(times[x+1]-times[x],'.2f'))))
        except Exception as e:
                raise e
                thread._stop()

#I tried to create a variable where a Boolean value is stored when the user #clicks on the pause button the variable data goes to true
        #The code i tried to fix this:

        def change():
            global is_paused
            if PlayButton['image']==str(PLay):
                pygame.mixer.music.unpause()
                PlayButton['image']=PAuse
                PlayButton.pack()
                is_paused=False
            else:
                pygame.mixer.music.pause()
                PlayButton['image']=PLay
                PlayButton.pack()
                is_paused=True
        def SyncLyrics():
            global playing
            pygame.mixer.music.pause()
            try:
                # this if statement is for when the user uploads [lyrics ](https://en.wikipedia.org/wiki/LRC_(file_format)) file after the song is started
                if playing and TimePlaying_value>=1:
                    NoToRoundOff=TimePlaying_value
                    # list contains the nearest lyrics timestamps to the time of the song
                    dictionary=[]
                    # this list contains the position of timestamps
                    pos=[]
                    # this for loop is for finding the nearest lyrics of timestamps of the song
                    if not is_paused:
                        for x in range(len(LYRICS)):
                            if times[x]-NoToRoundOff>0:
                                dictionary.append(times[x]-NoToRoundOff)
                                pos.append(x)
                                ls.select_set(min(pos)-2)
                                pygame.mixer.music.unpause()
                                break
                                for x in range(min(pos),len(LYRICS)):
                                     ls.select_clear(x-1)
                                     ls.select_set(x)
                                     time.sleep(float((format(times[x+1]-times[x],'.2f'))))
                    else:
                        pass
                print(is_paused)# When I clicked on the pause button it shows me the output as false. But it had to give true.
                # this for loop is for continuation of synchronization
                for x in range(min(pos),len(LYRICS)):
                    ls.select_clear(x-1)
                    ls.select_set(x)
                    time.sleep(float((format(times[x+1]-times[x],'.2f'))))
            except Exception as e:
                raise e
                thread._stop()

The main problem of the code is that the is_paused variable doesn't gets update to true when i click on paused button
If you have understood the question please answer. IF you have any type of query comment it.


问:
how to slove modbus_read_registers read error: Operation not permitted?
I used ubuntu16 socat to generate a pair of virtual serial ports and wrote code to try Modbus RTU communication, but the host got an error reading slave map holdover register address: read error: Operation not permitted

master.c

```<code>        ret = modbus_read_registers(mb, 2000, 3, table);
        if(ret == 3)
            printf("read success : 0x%02x 0x%02x 0x%02x \n", table[0], table[1], table[2]);
        else
        {
            printf("read error: %s\n", modbus_strerror(errno));
            break;
        }
</code>```

slave.c

```<code>    mb_mapping = modbus_mapping_new_start_address(0, 0, 0, 0, 2000, 3, 0, 0);
    if(mb_mapping == NULL)
    {
        modbus_free(mb);
        printf("new mapping failed: %s\n", modbus_strerror(errno));
        return 0;
    }

    //保持寄存器数据
    mb_mapping->tab_registers[0] = 0x1001;
    mb_mapping->tab_registers[1] = 0x1002;
    mb_mapping->tab_registers[2] = 0x1003;
</code>```

socat:

error:

I consulted a lot of materials and tried to solve the problem, but in the end there was no result

Body:
I used ubuntu16 socat to generate a pair of virtual serial ports and wrote code to try Modbus RTU communication, but the host got an error reading slave map holdover register address: read error: Operation not permitted

master.c

        ret = modbus_read_registers(mb, 2000, 3, table);
        if(ret == 3)
            printf("read success : 0x%02x 0x%02x 0x%02x \n", table[0], table[1], table[2]);
        else
        {
            printf("read error: %s\n", modbus_strerror(errno));
            break;
        }

slave.c

    mb_mapping = modbus_mapping_new_start_address(0, 0, 0, 0, 2000, 3, 0, 0);
    if(mb_mapping == NULL)
    {
        modbus_free(mb);
        printf("new mapping failed: %s\n", modbus_strerror(errno));
        return 0;
    }

    //保持寄存器数据
    mb_mapping->tab_registers[0] = 0x1001;
    mb_mapping->tab_registers[1] = 0x1002;
    mb_mapping->tab_registers[2] = 0x1003;

socat:

error:

I consulted a lot of materials and tried to solve the problem, but in the end there was no result


问:
Django share common permission across django app
I would like to know if there is a better way to implement common permission that is very similar across django app. For example, app1 need permission_x, app2 need permission_x, and app3 need permission_x too. In order to satisfy this i made permissions.py and create permission_x class which inherits from BasePermission on each app.

app1/permissions.py

```<code>from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS
</code>```

app2/permissions.py

```<code>from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS
</code>```

app3/permissions.py

```<code>from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS
</code>```

As you can see, neither app1, app2, nor app3 need these basic permissions. They are exactly the same as each other. I implemented it as above, but is there a better way to do it? I tried looking and couldn't find anything that suits my needs, maybe create sub-app?

Body:
I would like to know if there is a better way to implement common permission that is very similar across django app. For example, app1 need permission_x, app2 need permission_x, and app3 need permission_x too. In order to satisfy this i made permissions.py and create permission_x class which inherits from BasePermission on each app.

app1/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

app2/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

app3/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS

class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

As you can see, neither app1, app2, nor app3 need these basic permissions. They are exactly the same as each other. I implemented it as above, but is there a better way to do it? I tried looking and couldn't find anything that suits my needs, maybe create sub-app?


问:
Cannot find axios-jsonp
I installed axios-jsonp, but the error saids there is no jsonpAdapter.
Could someone help me?

I use Vue.js and I want to get data from API.

error: Require statement not part of import statement.

```<code>export default defineComponent({
  setup() {
    const jsonpAdapter = require("axios-jsonp");
    const getProductList = async (inputValue: string) => {
      const appId = <myappId>;

      axios({
        url:
          "https://shopping.yahooapis.jp/ShoppingWebService/V3/itemSearch?appid=" +
          appId +
          "&query=" +
          inputValue,
        adapter: jsonpAdapter,
      });
    };
</code>```

package.json

```<code>  "packages": {
    "": {
      "name": "vue3-sales-app",
      "version": "0.1.0",
      "dependencies": {
        "axios": "^1.2.2",
        "core-js": "^3.8.3",
        "jsonp": "^0.1.0",
        "vue": "^3.2.13",
        "vue-router": "^4.0.3",
        "vuex": "^4.0.0"
      },
      "devDependencies": {
        "@typescript-eslint/eslint-plugin": "^5.4.0",
        "@typescript-eslint/parser": "^5.4.0",
        "@vue/cli-plugin-babel": "^5.0.8",
        "@vue/cli-plugin-eslint": "^5.0.8",
        "@vue/cli-plugin-router": "~5.0.0",
        "@vue/cli-plugin-typescript": "^5.0.8",
        "@vue/cli-plugin-vuex": "~5.0.0",
        "@vue/cli-service": "~5.0.0",
        "@vue/eslint-config-typescript": "^9.1.0",
        "axios-jsonp": "^1.0.4",
        "eslint": "^7.32.0",
        "eslint-config-prettier": "^8.3.0",
        "eslint-plugin-prettier": "^4.0.0",
        "eslint-plugin-vue": "^8.0.3",
        "prettier": "^2.4.1",
        "typescript": "~4.5.5"
      }
    },
</code>```

I tried npm install axios-jsonp

Log:

$npm install axios-jsonp

added 392 packages, changed 1 package, and audited 1024 packages in 5s

112 packages are looking for funding   run npm fund for details

15 low severity vulnerabilities

To address all issues possible (including breaking changes), run:

npm audit fix --force

Some issues need review, and may require choosing a different
dependency.

Run npm audit for details.

Title: Cannot find axios-jsonp

Body:
I installed axios-jsonp, but the error saids there is no jsonpAdapter.
Could someone help me?

I use Vue.js and I want to get data from API.

error: Require statement not part of import statement.

export default defineComponent({
  setup() {
    const jsonpAdapter = require("axios-jsonp");
    const getProductList = async (inputValue: string) => {
      const appId = <myappId>;

      axios({
        url:
          "https://shopping.yahooapis.jp/ShoppingWebService/V3/itemSearch?appid=" +
          appId +
          "&query=" +
          inputValue,
        adapter: jsonpAdapter,
      });
    };

package.json

  "packages": {
    "": {
      "name": "vue3-sales-app",
      "version": "0.1.0",
      "dependencies": {
        "axios": "^1.2.2",
        "core-js": "^3.8.3",
        "jsonp": "^0.1.0",
        "vue": "^3.2.13",
        "vue-router": "^4.0.3",
        "vuex": "^4.0.0"
      },
      "devDependencies": {
        "@typescript-eslint/eslint-plugin": "^5.4.0",
        "@typescript-eslint/parser": "^5.4.0",
        "@vue/cli-plugin-babel": "^5.0.8",
        "@vue/cli-plugin-eslint": "^5.0.8",
        "@vue/cli-plugin-router": "~5.0.0",
        "@vue/cli-plugin-typescript": "^5.0.8",
        "@vue/cli-plugin-vuex": "~5.0.0",
        "@vue/cli-service": "~5.0.0",
        "@vue/eslint-config-typescript": "^9.1.0",
        "axios-jsonp": "^1.0.4",
        "eslint": "^7.32.0",
        "eslint-config-prettier": "^8.3.0",
        "eslint-plugin-prettier": "^4.0.0",
        "eslint-plugin-vue": "^8.0.3",
        "prettier": "^2.4.1",
        "typescript": "~4.5.5"
      }
    },

I tried npm install axios-jsonp

Log:

$npm install axios-jsonp

added 392 packages, changed 1 package, and audited 1024 packages in 5s

112 packages are looking for funding   run npm fund for details

15 low severity vulnerabilities

To address all issues possible (including breaking changes), run:

npm audit fix --force

Some issues need review, and may require choosing a different
dependency.

Run npm audit for details.


问:
Module build failed (from ./node_modules/postcss-loader/dist/cjs.js): SyntaxError
I am using fuse theme in angular I get the error while ng serve</p>
```<code>(479:20) C:\Brijesh\ABC\EmployeePWA\dev-employee-frontend\src\@fuse\components\alert\alert.component.scss The `text-primary-800` class does not exist. If `text-primary-800` is a custom class, make sure it is defined within a `@layer` directive.

  477 |   @apply text-white;
  478 | }
> 479 | .dark fuse-alert.fuse-alert-appearance-outline.fuse-alert-type-primary .fuse-alert-container .fuse-alert-title,
      |                    ^
  480 | .dark fuse-alert.fuse-alert-appearance-outline.fuse-alert-type-primary .fuse-alert-container .fuse-alert-dismiss-button {
  481 |   @apply text-white;
</code>```

Body:
I am using fuse theme in angular I get the error while ng serve

(479:20) C:\Brijesh\ABC\EmployeePWA\dev-employee-frontend\src\@fuse\components\alert\alert.component.scss The `text-primary-800` class does not exist. If `text-primary-800` is a custom class, make sure it is defined within a `@layer` directive.

  477 |   @apply text-white;
  478 | }
> 479 | .dark fuse-alert.fuse-alert-appearance-outline.fuse-alert-type-primary .fuse-alert-container .fuse-alert-title,
      |                    ^
  480 | .dark fuse-alert.fuse-alert-appearance-outline.fuse-alert-type-primary .fuse-alert-container .fuse-alert-dismiss-button {
  481 |   @apply text-white;


问:
How Do I Manipulate UIkit confirm dialog while using it in angular
So I wanted to manipulate/customize UIkit confirm modal's styles on my own but I am not able to do it in angular

```<code>UIkit.modal.confirm('My message!', {
      labels: {
        cancel: 'No',
        ok: 'Yes'
      }
    });
</code>```

this i did but I wanna change the modal's background color, buttons color,font style,font color and I wanna make the confirm modal appear in the middle

I did things like adding 'cls' below the label object like

```<code>UIkit.modal.confirm('My message!', {
      labels: {
        cancel: 'Abort mission',
        ok: 'Everthing is fine'
      },
        cls:'my-class'
    });
</code>```

and wrote a css for it in the corresponding css it didn't made a change

and i tried

```<code>var confirmBtn = document.querySelector('.uk-modal-footer .uk-button-primary'); confirmBtn.style.backgroundColor = '#ff0000'; var cancelBtn = document.querySelector('.uk-modal-footer .uk-button-default'); cancelBtn.style.backgroundColor = '#00ff00';
</code>```

It's not working and also the 'promise' i.e. using of 'then' function is not working for the two buttons yes and no if I do any of these things

Body:
So I wanted to manipulate/customize UIkit confirm modal's styles on my own but I am not able to do it in angular

UIkit.modal.confirm('My message!', {
      labels: {
        cancel: 'No',
        ok: 'Yes'
      }
    });

this i did but I wanna change the modal's background color, buttons color,font style,font color and I wanna make the confirm modal appear in the middle

I did things like adding 'cls' below the label object like

UIkit.modal.confirm('My message!', {
      labels: {
        cancel: 'Abort mission',
        ok: 'Everthing is fine'
      },
        cls:'my-class'
    });

and wrote a css for it in the corresponding css it didn't made a change

and i tried

var confirmBtn = document.querySelector('.uk-modal-footer .uk-button-primary'); confirmBtn.style.backgroundColor = '#ff0000'; var cancelBtn = document.querySelector('.uk-modal-footer .uk-button-default'); cancelBtn.style.backgroundColor = '#00ff00';

It's not working and also the 'promise' i.e. using of 'then' function is not working for the two buttons yes and no if I do any of these things


问:
React Native İnstallation Error: Command failed: gradlew.bat app:installDebug
error Failed to install the app. Make sure you have an Android emulator running or a device connected.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Note: C:\Users\w10\Desktop\AwesomeProject\android\app\src\debug\java\com\awesomeproject\ReactNativeFlipper.java uses or overrides a deprecated API.</p>


Title: How to check JS Webauthn Assertion in PHP 8.1?

Body:
I'm trying to implement WebAuthn in a JavaScript/PHP project and I'm "stuck" at the final assertion verification process.

In detail, I pass the "assertion" parameters from JavaScript (Jquery) to PHP script like this:

navigator.credentials.get( { publicKey: {
    allowCredentials:   [...],
    challenge:      Uint8Array.from( ..., c => c.charCodeAt( 0 ) ),
    rpId:           window.location.hostname,
    timeout:        60000,
    userVerification:   'preferred'
} } )
.then( ( assertion ) => {
    $.ajax( { data: 'login=' + encodeURIComponent( JSON.stringify( {
        ...,
        'rawid':        new Uint8Array( assertion.rawId ),
        'authenticatordata':    new Uint8Array( assertion.response.authenticatorData ),
        'clientdatajson':   new Uint8Array( assertion.response.clientDataJSON ),
        'signature':        new Uint8Array( assertion.response.signature )
    } ) ) } )

And once the "public key" corresponding to the authenticator employed by the user has been identified within a database, I try to validate in PHP 8.1 the "assertion" in this way:

    $jsonInput = json_decode( '{"authenticatordata":{"0":201,"1":157,"2":215,"3":147,"4":42,"5":142,"6":165,"7":93,"8":198,"9":108,"10":247,"11":140,"12":253,"13":224,"14":178,"15":122,"16":185,"17":204,"18":239,"19":151,"20":3,"21":24,"22":2,"23":25,"24":212,"25":39,"26":42,"27":95,"28":255,"29":195,"30":201,"31":113,"32":5,"33":0,"34":0,"35":0,"36":16},"clientdatajson":{"0":123,"1":34,"2":116,"3":121,"4":112,"5":101,"6":34,"7":58,"8":34,"9":119,"10":101,"11":98,"12":97,"13":117,"14":116,"15":104,"16":110,"17":46,"18":103,"19":101,"20":116,"21":34,"22":44,"23":34,"24":99,"25":104,"26":97,"27":108,"28":108,"29":101,"30":110,"31":103,"32":101,"33":34,"34":58,"35":34,"36":77,"37":68,"38":65,"39":119,"40":77,"41":68,"42":65,"43":119,"44":77,"45":68,"46":65,"47":119,"48":77,"49":103,"50":34,"51":44,"52":34,"53":111,"54":114,"55":105,"56":103,"57":105,"58":110,"59":34,"60":58,"61":34,"62":104,"63":116,"64":116,"65":112,"66":115,"67":58,"68":47,"69":47,"70":109,"71":111,"72":114,"73":109,"74":105,"75":110,"76":111,"77":46,"78":114,"79":101,"80":115,"81":105,"82":101,"83":108,"84":46,"85":99,"86":111,"87":109,"88":34,"89":44,"90":34,"91":99,"92":114,"93":111,"94":115,"95":115,"96":79,"97":114,"98":105,"99":103,"100":105,"101":110,"102":34,"103":58,"104":102,"105":97,"106":108,"107":115,"108":101,"109":125},"signature":{"0":48,"1":69,"2":2,"3":33,"4":0,"5":251,"6":22,"7":162,"8":18,"9":206,"10":81,"11":110,"12":4,"13":3,"14":217,"15":148,"16":51,"17":132,"18":130,"19":31,"20":122,"21":186,"22":65,"23":73,"24":195,"25":170,"26":106,"27":35,"28":90,"29":149,"30":56,"31":1,"32":58,"33":222,"34":51,"35":69,"36":212,"37":2,"38":32,"39":77,"40":161,"41":139,"42":133,"43":49,"44":79,"45":218,"46":34,"47":45,"48":115,"49":178,"50":156,"51":139,"52":185,"53":13,"54":197,"55":248,"56":116,"57":217,"58":81,"59":111,"60":117,"61":68,"62":44,"63":141,"64":197,"65":87,"66":68,"67":1,"68":89,"69":222,"70":154}}' );
    $publickey = json_decode( '{"0":48,"1":89,"2":48,"3":19,"4":6,"5":7,"6":42,"7":134,"8":72,"9":206,"10":61,"11":2,"12":1,"13":6,"14":8,"15":42,"16":134,"17":72,"18":206,"19":61,"20":3,"21":1,"22":7,"23":3,"24":66,"25":0,"26":4,"27":229,"28":126,"29":127,"30":191,"31":207,"32":67,"33":42,"34":66,"35":212,"36":251,"37":1,"38":126,"39":36,"40":232,"41":163,"42":188,"43":151,"44":84,"45":50,"46":83,"47":251,"48":29,"49":196,"50":24,"51":208,"52":131,"53":96,"54":190,"55":14,"56":239,"57":104,"58":123,"59":78,"60":90,"61":70,"62":76,"63":54,"64":211,"65":91,"66":74,"67":243,"68":252,"69":69,"70":192,"71":132,"72":245,"73":206,"74":214,"75":67,"76":210,"77":165,"78":46,"79":230,"80":191,"81":6,"82":19,"83":241,"84":201,"85":188,"86":235,"87":232,"88":84,"89":130,"90":185}', TRUE );
    $jsonInput->authenticatordata = ( array ) $jsonInput->authenticatordata;    // [201,157,215,147,42,142,165,93,198,108,247,140,253,224,178,122,185,204,239,151,3,24,2,25,212,39,42,95,255,195,201,113,5,0,0,0,16]
    $jsonInput->clientdatajson = ( array ) $jsonInput->clientdatajson;      // [123,34,116,121,112,101,34,58,34,119,101,98,97,117,116,104,110,46,103,101,116,34,44,34,99,104,97,108,108,101,110,103,101,34,58,34,77,68,65,119,77,68,65,119,77,68,65,119,77,103,34,44,34,111,114,105,103,105,110,34,58,34,104,116,116,112,115,58,47,47,109,111,114,109,105,110,111,46,114,101,115,105,101,108,46,99,111,109,34,44,34,99,114,111,115,115,79,114,105,103,105,110,34,58,102,97,108,115,101,125]
    $jsonInput->signature = ( array ) $jsonInput->signature;            // [48,69,2,33,0,251,22,162,18,206,81,110,4,3,217,148,51,132,130,31,122,186,65,73,195,170,106,35,90,149,56,1,58,222,51,69,212,2,32,77,161,139,133,49,79,218,34,45,115,178,156,139,185,13,197,248,116,217,81,111,117,68,44,141,197,87,68,1,89,222,154]

    echo openssl_verify(
        implode( array_map( 'chr', $jsonInput->authenticatordata ) ) . hash( 'sha256', json_encode( implode( array_map( 'chr', $jsonInput->clientdatajson ) ) ) ),
        implode( array_map( 'chr', $jsonInput->signature ) ),
        "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split( base64_encode( implode( array_map( 'chr', $publickey ) ) ), 64 ) . "-----END PUBLIC KEY-----",
        OPENSSL_ALGO_SHA256
    );
    echo '
';
    echo openssl_error_string(); // error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error

/*The processed Windows Hello (From Windows 11) authenticator-generated public key results at the end:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5X5/v89DKkLU+wF+JOijvJdUMlP7
HcQY0INgvg7vaHtOWkZMNtNbSvP8RcCE9c7WQ9KlLua/BhPxybzr6FSCuQ==
-----END PUBLIC KEY-----

*/

Another example with a different authenticator (Widows Hello from Windows 10):

    $jsonInput                      = json_decode( '{"authenticatordata":[201,157,215,147,42,142,165,93,198,108,247,140,253,224,178,122,185,204,239,151,3,24,2,25,212,39,42,95,255,195,201,113,5,0,0,0,2],"clientdatajson":[123,34,116,121,112,101,34,58,34,119,101,98,97,117,116,104,110,46,103,101,116,34,44,34,99,104,97,108,108,101,110,103,101,34,58,34,77,68,65,119,77,68,65,119,77,68,65,119,77,103,34,44,34,111,114,105,103,105,110,34,58,34,104,116,116,112,115,58,47,47,109,111,114,109,105,110,111,46,114,101,115,105,101,108,46,99,111,109,34,44,34,99,114,111,115,115,79,114,105,103,105,110,34,58,102,97,108,115,101,44,34,111,116,104,101,114,95,107,101,121,115,95,99,97,110,95,98,101,95,97,100,100,101,100,95,104,101,114,101,34,58,34,100,111,32,110,111,116,32,99,111,109,112,97,114,101,32,99,108,105,101,110,116,68,97,116,97,74,83,79,78,32,97,103,97,105,110,115,116,32,97,32,116,101,109,112,108,97,116,101,46,32,83,101,101,32,104,116,116,112,115,58,47,47,103,111,111,46,103,108,47,121,97,98,80,101,120,34,125],"signature":[94,96,8,15,78,8,75,244,177,242,61,244,7,240,100,98,176,74,243,176,215,209,229,61,5,137,178,77,240,88,160,220,9,110,33,171,52,255,65,140,191,209,29,49,26,111,164,65,47,1,90,77,95,196,60,132,185,189,145,0,138,65,212,242,210,222,55,91,211,208,15,216,252,81,6,132,159,42,234,186,78,81,121,187,45,71,22,178,83,210,196,161,31,247,188,218,211,159,5,102,249,213,142,158,230,99,182,166,78,62,153,107,53,133,150,96,95,99,213,172,19,44,243,114,127,167,155,195,88,172,236,229,233,212,65,100,127,98,4,4,71,124,29,174,104,65,190,218,221,16,228,85,137,216,250,89,49,77,245,120,146,72,7,23,67,144,108,160,195,204,216,51,100,159,32,208,151,249,87,146,54,31,230,48,241,67,235,8,171,198,53,8,83,178,8,203,6,173,76,213,212,128,241,72,129,162,159,13,234,49,6,140,253,159,107,115,91,151,195,25,203,27,98,81,41,96,254,88,92,126,78,207,59,114,214,238,153,34,100,49,59,246,249,99,255,49,71,178,42,226,62,246,149,193,91,140]}' );
    $publickey                      = json_decode( '{"0":48,"1":130,"2":1,"3":34,"4":48,"5":13,"6":6,"7":9,"8":42,"9":134,"10":72,"11":134,"12":247,"13":13,"14":1,"15":1,"16":1,"17":5,"18":0,"19":3,"20":130,"21":1,"22":15,"23":0,"24":48,"25":130,"26":1,"27":10,"28":2,"29":130,"30":1,"31":1,"32":0,"33":226,"34":31,"35":139,"36":141,"37":197,"38":58,"39":76,"40":61,"41":52,"42":104,"43":160,"44":127,"45":66,"46":27,"47":61,"48":3,"49":107,"50":228,"51":250,"52":6,"53":98,"54":104,"55":214,"56":5,"57":33,"58":182,"59":247,"60":175,"61":107,"62":236,"63":71,"64":232,"65":98,"66":163,"67":112,"68":213,"69":174,"70":56,"71":131,"72":160,"73":93,"74":200,"75":85,"76":35,"77":234,"78":116,"79":212,"80":172,"81":0,"82":232,"83":78,"84":48,"85":90,"86":122,"87":93,"88":100,"89":212,"90":88,"91":250,"92":91,"93":228,"94":248,"95":14,"96":42,"97":228,"98":123,"99":149,"100":36,"101":205,"102":21,"103":172,"104":116,"105":44,"106":113,"107":229,"108":246,"109":50,"110":110,"111":219,"112":122,"113":219,"114":26,"115":72,"116":17,"117":120,"118":63,"119":148,"120":176,"121":94,"122":110,"123":133,"124":131,"125":199,"126":213,"127":219,"128":22,"129":29,"130":88,"131":178,"132":141,"133":62,"134":170,"135":76,"136":121,"137":62,"138":237,"139":192,"140":214,"141":82,"142":122,"143":113,"144":244,"145":124,"146":2,"147":5,"148":39,"149":83,"150":68,"151":252,"152":219,"153":233,"154":27,"155":128,"156":77,"157":160,"158":241,"159":92,"160":1,"161":0,"162":171,"163":214,"164":233,"165":178,"166":240,"167":207,"168":227,"169":74,"170":134,"171":206,"172":217,"173":193,"174":89,"175":79,"176":56,"177":217,"178":152,"179":229,"180":175,"181":47,"182":146,"183":145,"184":101,"185":173,"186":39,"187":106,"188":252,"189":194,"190":107,"191":221,"192":150,"193":30,"194":122,"195":73,"196":204,"197":49,"198":242,"199":60,"200":227,"201":208,"202":10,"203":223,"204":182,"205":195,"206":105,"207":113,"208":99,"209":119,"210":41,"211":215,"212":234,"213":227,"214":166,"215":69,"216":66,"217":160,"218":83,"219":131,"220":109,"221":111,"222":216,"223":9,"224":55,"225":176,"226":107,"227":4,"228":108,"229":37,"230":235,"231":100,"232":88,"233":14,"234":154,"235":247,"236":143,"237":102,"238":106,"239":48,"240":200,"241":8,"242":152,"243":187,"244":73,"245":126,"246":95,"247":139,"248":83,"249":140,"250":199,"251":151,"252":46,"253":174,"254":25,"255":82,"256":240,"257":199,"258":41,"259":126,"260":106,"261":126,"262":93,"263":201,"264":70,"265":217,"266":151,"267":46,"268":117,"269":139,"270":144,"271":29,"272":43,"273":76,"274":59,"275":180,"276":255,"277":208,"278":43,"279":124,"280":111,"281":168,"282":50,"283":221,"284":105,"285":134,"286":153,"287":113,"288":141,"289":2,"290":3,"291":1,"292":0,"293":1}', TRUE );
    $jsonInput->authenticatordata   = ( array ) $jsonInput->authenticatordata;
    $jsonInput->clientdatajson      = ( array ) $jsonInput->clientdatajson;
    $jsonInput->signature           = ( array ) $jsonInput->signature;

    echo openssl_verify(
        implode( array_map( 'chr', $jsonInput->authenticatordata ) ) . hash( 'sha256', implode( array_map( 'chr', $jsonInput->clientdatajson ) ) ),
        implode( array_map( 'chr', $jsonInput->signature ) ),
        "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split( base64_encode( implode( array_map( 'chr', $publickey ) ) ), 64 ) . "-----END PUBLIC KEY-----",
        OPENSSL_ALGO_SHA256
    );
    echo '
';
    echo openssl_error_string(); // error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag

    /*
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4h+LjcU6TD00aKB/Qhs9
    A2vk+gZiaNYFIbb3r2vsR+hio3DVrjiDoF3IVSPqdNSsAOhOMFp6XWTUWPpb5PgO
    KuR7lSTNFax0LHHl9jJu23rbGkgReD+UsF5uhYPH1dsWHViyjT6qTHk+7cDWUnpx
    9HwCBSdTRPzb6RuATaDxXAEAq9bpsvDP40qGztnBWU842Zjlry+SkWWtJ2r8wmvd
    lh56Scwx8jzj0ArftsNpcWN3Kdfq46ZFQqBTg21v2Ak3sGsEbCXrZFgOmvePZmow
    yAiYu0l+X4tTjMeXLq4ZUvDHKX5qfl3JRtmXLnWLkB0rTDu0/9ArfG+oMt1phplx
    jQIDAQAB
    -----END PUBLIC KEY-----
    */

1. However the "openssl_verify" function returns failure (0) instead
of success (1). Where am I wrong?

2. Why does Windows Hello return a short public key in the first case?
Is it equally valid?

3. Is this the correct way to convert to PEM and use the public key
generated by credential.response.getPublicKey()?

Note: in a different context, I transfer the public key from javascript (jquery) to PHP 8.1 like this:

    navigator.credentials.create( { publicKey: {
        attestation:            'none',
        authenticatorSelection: { userVerification: 'preferred' },
        challenge:              Uint8Array.from( ..., c => c.charCodeAt( 0 ) ),
        excludeCredentials:     [],
        pubKeyCredParams:       [],
        rp:                     { id: window.location.hostname, name: window.document.title },
        timeout:                60000,
        user:                   { id: Uint8Array.from( ..., c => c.charCodeAt( 0 ) ), displayName: ..., name: ... }
    } } )
    .then( ( credential ) => {
        $.ajax( { data: 'data=' + encodeURIComponent( JSON.stringify( {
            ...,
            'publickey':            new Uint8Array( credential.response.getPublicKey() ),
            'authenticatordata':    new Uint8Array( credential.response.getAuthenticatorData() ),
            'transports':           credential.response.getTransports()
        } ) ) } )


问:
How can I use setInterval in a lambda function
I'm a beginner and I have configured a lambda function with a timeout of 10 minutes and I want to run a certain function inside my lambda function with 30 second time interval. For this I used a 'setInterval()' function and my code look like this, and when I test it Function 1 executes but the function 2 which has to execute every 30 seconds doesn't work. How to fix this?</p>
```<code>import { default as fetch, Request } from 'node-fetch';

const GRAPHQL_ENDPOINT = process.env....;
const GRAPHQL_API_KEY = process.env....;

/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */
export const handler = async (event) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);

  let statusCode = 200;
  let body;
  let response;

  async function Func2(){

    try {
     // function 2 this is called in every 30 seconds, and this is a async function calling a graphql endpoint
  };
    }catch(error){
      statusCode = 400;
    body = {
      errors: [
        {
          status: response.status,
          message: error.message,
          stack: error.stack
        }
      ]
    };
   }
  }

  try {

    // Function 1, this is an async function calling a graphql endpoint

    setInterval(() => Func2(), 30000);

  } catch (error) {
    statusCode = 400;
    body = {
      errors: [
        {
          status: response.status,
          message: error.message,
          stack: error.stack
        }
      ]
    };
    return {
    statusCode,
    body: JSON.stringify(body)
  };
 }

   return {
     statusCode,
     body: JSON.stringify(body)
   };
 };
</code>```

Body:
I'm a beginner and I have configured a lambda function with a timeout of 10 minutes and I want to run a certain function inside my lambda function with 30 second time interval. For this I used a 'setInterval()' function and my code look like this, and when I test it Function 1 executes but the function 2 which has to execute every 30 seconds doesn't work. How to fix this?

import { default as fetch, Request } from 'node-fetch';

const GRAPHQL_ENDPOINT = process.env....;
const GRAPHQL_API_KEY = process.env....;

/**
 * @type {import('@types/aws-lambda').APIGatewayProxyHandler}
 */
export const handler = async (event) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);

  let statusCode = 200;
  let body;
  let response;

  async function Func2(){

    try {
     // function 2 this is called in every 30 seconds, and this is a async function calling a graphql endpoint
  };
    }catch(error){
      statusCode = 400;
    body = {
      errors: [
        {
          status: response.status,
          message: error.message,
          stack: error.stack
        }
      ]
    };
   }
  }

  try {

    // Function 1, this is an async function calling a graphql endpoint

    setInterval(() => Func2(), 30000);

  } catch (error) {
    statusCode = 400;
    body = {
      errors: [
        {
          status: response.status,
          message: error.message,
          stack: error.stack
        }
      ]
    };
    return {
    statusCode,
    body: JSON.stringify(body)
  };
 }

   return {
     statusCode,
     body: JSON.stringify(body)
   };
 };