问:
POST API request body rejected by Trade-Me API
I'm trying to use the Trade Me API (https://developer.trademe.co.nz/api-reference/selling-methods/list-an-item) to list an item for sale, but I'm getting an error message that says "Please enter a description" and "Please select the payment methods you will accept" and "Please select a shipping option."

I've double-checked that I'm including a description and that I've selected payment and shipping options, but I'm still getting this error. Here is my code:

```<code># Install and load required packages
library(httr)
library(jsonlite)
library(tidyverse)

# Set API keys and secrets
consumer_key <- "my_key"
consumer_secret <- "my_secret"
access_token <- "my_token"
access_secret <- "my_token_secret"

# Set API endpoint URL
api_url <- "https://api.tmsandbox.co.nz/v1/Selling.json"

auth <- paste0(
  "OAuth oauth_consumer_key=", consumer_key,
  ",oauth_token=", access_token,
  ",oauth_signature_method=PLAINTEXT",
  ",oauth_signature=", consumer_secret, "%26", access_secret)

headers <- c('Authorization' = auth,
             'Content-Type' = 'application/json' # set the content type to JSON
             )

# Set request body
body <- list(
  Category = "3849",
  Title = "Arty surprise",
  Description = list(
    Paragraph = "All true art lovers will buy this"
  ),
  StartPrice = 7.0,
  BuyNowPrice = 9.0,
  Duration = 7.0,
  Pickup = 3,
  IsBrandNew = 'false',
  ShippingOptions = list(
    ShippingOption = list(
      Type = "Undecided"
    )
  ),
  PaymentMethods = list(
    PaymentMethod = c("Cash", "CreditCard")
  )
)

# Make POST request to API
response <- POST(
  url = api_url,
  body = body,
  add_headers(headers),
  encode = "json"
)

# Retrieve the response content as a list object
response_data <- httr::content(response)

print(response_data)
</code>```

Here is the error message I'm getting:

```<code>$Success
[1] FALSE

$Description
[1] "Please enter a description\r\nPlease select the payment methods you will accept.\r\nPlease select a shipping option."
</code>```

Any help with this issue would be greatly appreciated!

Body:
I'm trying to use the Trade Me API (https://developer.trademe.co.nz/api-reference/selling-methods/list-an-item) to list an item for sale, but I'm getting an error message that says "Please enter a description" and "Please select the payment methods you will accept" and "Please select a shipping option."

I've double-checked that I'm including a description and that I've selected payment and shipping options, but I'm still getting this error. Here is my code:

# Install and load required packages
library(httr)
library(jsonlite)
library(tidyverse)

# Set API keys and secrets
consumer_key <- "my_key"
consumer_secret <- "my_secret"
access_token <- "my_token"
access_secret <- "my_token_secret"

# Set API endpoint URL
api_url <- "https://api.tmsandbox.co.nz/v1/Selling.json"

auth <- paste0(
  "OAuth oauth_consumer_key=", consumer_key,
  ",oauth_token=", access_token,
  ",oauth_signature_method=PLAINTEXT",
  ",oauth_signature=", consumer_secret, "%26", access_secret)

headers <- c('Authorization' = auth,
             'Content-Type' = 'application/json' # set the content type to JSON
             )

# Set request body
body <- list(
  Category = "3849",
  Title = "Arty surprise",
  Description = list(
    Paragraph = "All true art lovers will buy this"
  ),
  StartPrice = 7.0,
  BuyNowPrice = 9.0,
  Duration = 7.0,
  Pickup = 3,
  IsBrandNew = 'false',
  ShippingOptions = list(
    ShippingOption = list(
      Type = "Undecided"
    )
  ),
  PaymentMethods = list(
    PaymentMethod = c("Cash", "CreditCard")
  )
)

# Make POST request to API
response <- POST(
  url = api_url,
  body = body,
  add_headers(headers),
  encode = "json"
)

# Retrieve the response content as a list object
response_data <- httr::content(response)

print(response_data)

Here is the error message I'm getting:

$Success
[1] FALSE

$Description
[1] "Please enter a description\r\nPlease select the payment methods you will accept.\r\nPlease select a shipping option."

Any help with this issue would be greatly appreciated!


来源: stackexchange

问:
How to fix time-outing job which aggregates data in an SQL server database?
There is a microservice written in .NET 6 which periodically updates/aggregates data in an SQL server database. For some months/years there were basically no changes and everything worked fine.

One day some jobs started to time out after the default 30 seconds in a production environment. We don't know about any version/configuration changes.

Line 130: [00:00:16.765 --className-- 2291711 WRN] Aggregator job UpdatePerHourValuesJob failed: System.Threading.Tasks.TaskCanceledException: A task was canceled.

Line 2306: [00:07:10.624 --className-- 2563388 WRN] Aggregator job UpdatePerHourValuesJob failed: Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

For a hot fix, we increased the timeout to 3 minutes, but some jobs are still time-outing. Some of these time-outing jobs practically should just read about 30 rows from a database, make a sum of their values and write it back to this database.

Any ideas what could have happened there and how to fix it?

ContentLicense: CC BY-SA 4.0


问:
Styled-components Prop `className` did not match. React Component-library, Vite, NextJS
I have made a component-library with components that are built with Vite and use styled-components for the CSS-in-JS styling. I have also added a function that makes it possible to render custom CSS-variables. However when I use the custom CSS-variables within a NextJS project i get the following error:

Warning: Prop className did not match. Server: "sc-dkrFOg sc-hLBbgP eJoCTZ jOEnLc button" Client: "sc-dkrFOg sc-hLBbgP eJoCTZ eWjpmy button"

This error only occurs when I add the custom CSS-variables to the globals.css within styles in the Next-project. The CSS-variables work like this:

```<code>const withStyles = (WrappedComponent) => (props) => {
  verifyGlobals(WrappedComponent.globals);

  const { className } = WrappedComponent;
  const prefix = 'icl';

  let rootElement;
  if (typeof document !== 'undefined') {
    rootElement = getComputedStyle(document.documentElement);
  }

  const newProps: typeof props = {};

  for (const property in WrappedComponent.defaultProps) {
    if (props[property] !== WrappedComponent.defaultProps[property])
      newProps[property] = props[property];
    else if (rootElement && rootElement.getPropertyValue(`--${prefix}-${className}-${property}`)) {
      newProps[property] = rootElement.getPropertyValue(`--${prefix}-${className}-${property}`);
    } else if (rootElement && checkGlobals(rootElement, WrappedComponent.globals, property)) {
      newProps[property] = rootElement.getPropertyValue(getGlobalName(WrappedComponent.globals, property));
    } else
      newProps[property] = WrappedComponent.defaultProps[property];
  }

  return newProps;
};

</code>```

And the button looks like this with the "withStyles":

```<code>const Button = (
    props: ButtonType,
) => {
  props = withStyles(Button)(props);
...
...
 return (props.unstyled ? <button className={`${className}${classes}`}>
                <div>{props.text}</div>
              </button> :
              <Solid
                  className={`${className}${classes}`}
                  {...props}
                  onClick={props.onClick}
              >
                {leftIcon()}
                <div> {props.text} </div>
                {rightIcon()}
              </Solid>
      );
...
...
Button.defaultProps = defaultProps;
Button.className = className;
Button.globals = globals;

export default Button;
</code>```

The withStyles makes it possible to give a property for the button, for example the backgroundColor through CSS-variables like this:

```<code>:root {
    --icl-button-backgroundColor:red;
}
</code>```

However that is the issue within Next, this will cause the button to render with no CSS at all and give the error. This all works in React or PHP projects, but not in NextJS due to some issue with SSR.

I have tried a bunch of bugfixes, but nobody experiences this issue in this specific manner. Any help is welcome. Thanks!

Edit:
I have tried the following fix that is often commented under similair posts:

```<code>{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}
</code>```

However this does not work. Besides that I would prefer to have a fix within the component-library and not in the Next-JS project. Best case scenario would be to import the library and have it working without having to add additional configs within your Next-JS project.

Body:
I have made a component-library with components that are built with Vite and use styled-components for the CSS-in-JS styling. I have also added a function that makes it possible to render custom CSS-variables. However when I use the custom CSS-variables within a NextJS project i get the following error:

Warning: Prop className did not match. Server: "sc-dkrFOg sc-hLBbgP eJoCTZ jOEnLc button" Client: "sc-dkrFOg sc-hLBbgP eJoCTZ eWjpmy button"

This error only occurs when I add the custom CSS-variables to the globals.css within styles in the Next-project. The CSS-variables work like this:

const withStyles = (WrappedComponent) => (props) => {
  verifyGlobals(WrappedComponent.globals);

  const { className } = WrappedComponent;
  const prefix = 'icl';

  let rootElement;
  if (typeof document !== 'undefined') {
    rootElement = getComputedStyle(document.documentElement);
  }

  const newProps: typeof props = {};

  for (const property in WrappedComponent.defaultProps) {
    if (props[property] !== WrappedComponent.defaultProps[property])
      newProps[property] = props[property];
    else if (rootElement && rootElement.getPropertyValue(`--${prefix}-${className}-${property}`)) {
      newProps[property] = rootElement.getPropertyValue(`--${prefix}-${className}-${property}`);
    } else if (rootElement && checkGlobals(rootElement, WrappedComponent.globals, property)) {
      newProps[property] = rootElement.getPropertyValue(getGlobalName(WrappedComponent.globals, property));
    } else
      newProps[property] = WrappedComponent.defaultProps[property];
  }

  return newProps;
};

And the button looks like this with the "withStyles":

const Button = (
    props: ButtonType,
) => {
  props = withStyles(Button)(props);
...
...
 return (props.unstyled ? <button className={`${className}${classes}`}>

{props.text}

              </button> :
              <Solid
                  className={`${className}${classes}`}
                  {...props}
                  onClick={props.onClick}
              >
                {leftIcon()}

 {props.text}

                {rightIcon()}
              </Solid>
      );
...
...
Button.defaultProps = defaultProps;
Button.className = className;
Button.globals = globals;

export default Button;

The withStyles makes it possible to give a property for the button, for example the backgroundColor through CSS-variables like this:

:root {
    --icl-button-backgroundColor:red;
}

However that is the issue within Next, this will cause the button to render with no CSS at all and give the error. This all works in React or PHP projects, but not in NextJS due to some issue with SSR.

I have tried a bunch of bugfixes, but nobody experiences this issue in this specific manner. Any help is welcome. Thanks!

Edit:
I have tried the following fix that is often commented under similair posts:

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

However this does not work. Besides that I would prefer to have a fix within the component-library and not in the Next-JS project. Best case scenario would be to import the library and have it working without having to add additional configs within your Next-JS project.


问:
I want a way to download snaps by username or profile link or snap link from snapchat app using python
I searched a lot for a way to download the snaps from snapchat app using python
the snaps that apear when you click of user photo and disapears after 24 hours

All what I found is downloading stories and managed to do that with this code

```<code>import requests
import re
import shutil

def download_file(download_url):

    with requests.get(download_url, stream=True) as r:
        with open(fr'video.png', 'wb') as f:
            shutil.copyfileobj(r.raw, f)

url = 'https://story.snapchat.com/p/4cf3899b-690c-4872-a8a0-1c2f91db6563/2619293115389952'

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
}
response = requests.get(url, headers=headers)
download_url = re.search(
    r'"snapUrls":{"mediaUrl":"([^"]+)', response.text).group(1)

download_file(download_url)
</code>```

so If anyone have a way to download snaps, that it will be great

Body:
I searched a lot for a way to download the snaps from snapchat app using python
the snaps that apear when you click of user photo and disapears after 24 hours

All what I found is downloading stories and managed to do that with this code

import requests
import re
import shutil

def download_file(download_url):

    with requests.get(download_url, stream=True) as r:
        with open(fr'video.png', 'wb') as f:
            shutil.copyfileobj(r.raw, f)

url = 'https://story.snapchat.com/p/4cf3899b-690c-4872-a8a0-1c2f91db6563/2619293115389952'

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
}
response = requests.get(url, headers=headers)
download_url = re.search(
    r'"snapUrls":{"mediaUrl":"([^"]+)', response.text).group(1)

download_file(download_url)

so If anyone have a way to download snaps, that it will be great


问:
Error in creating procedure to loop through a mysql table to insert values into another table
The code I am using is:

```<code>CREATE PROCEDURE ksname_gen() BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*)
FROM ks_framework
WHERE fn_id = 1 INTO n;
SET i = 0;
WHILE i < n DO
INSERT INTO taskksname_map (taskset_id, ksname01, ksname02, role_no)
SELECT (
    taskset_id,
    (
      SELECT ks_name
      FROM ks_framework
        RIGHT JOIN ks_definitions ON ks_definitions.ord = ks_framework.ord
        RIGHT JOIN taskskill_map ON taskskill_map.role_no = ks_definitions.role_no
      WHERE fn_id = 1
        AND ks_definitions.role_no = 3
        AND taskskill_map.taskset_id = i
        AND ks_definitions.ord = ks_id01
    ),
    (
      SELECT ks_name
      FROM ks_framework
        RIGHT JOIN ks_definitions ON ks_definitions.ord = ks_framework.ord
        RIGHT JOIN taskskill_map ON taskskill_map.role_no = ks_definitions.role_no
      WHERE fn_id = 1
        AND ks_definitions.role_no = 3
        AND taskskill_map.taskset_id = i
        AND ks_definitions.ord = ks_id02
    ),
    role_no
  )
FROM taskskill_map
WHERE taskskill_map.taskset_id = i
  AND taskskill_map.role_no = 3;
SET i = i + 1;
END WHILE;
END;
</code>```

The error message: 'ERROR 1241 (21000): Operand should contain 1 column(s)'.
My suspicion is that the counter (i) is not being read inside the two subqueries, leading to multiple values. When I run the subqueries with a specific integer value for i, I get a single result. If so, how to make the counter run inside the subqueries? If not, then please suggest how I can copy the data following any other approach.
I am new to coding.

Body:
The code I am using is:

CREATE PROCEDURE ksname_gen() BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*)
FROM ks_framework
WHERE fn_id = 1 INTO n;
SET i = 0;
WHILE i < n DO
INSERT INTO taskksname_map (taskset_id, ksname01, ksname02, role_no)
SELECT (
    taskset_id,
    (
      SELECT ks_name
      FROM ks_framework
        RIGHT JOIN ks_definitions ON ks_definitions.ord = ks_framework.ord
        RIGHT JOIN taskskill_map ON taskskill_map.role_no = ks_definitions.role_no
      WHERE fn_id = 1
        AND ks_definitions.role_no = 3
        AND taskskill_map.taskset_id = i
        AND ks_definitions.ord = ks_id01
    ),
    (
      SELECT ks_name
      FROM ks_framework
        RIGHT JOIN ks_definitions ON ks_definitions.ord = ks_framework.ord
        RIGHT JOIN taskskill_map ON taskskill_map.role_no = ks_definitions.role_no
      WHERE fn_id = 1
        AND ks_definitions.role_no = 3
        AND taskskill_map.taskset_id = i
        AND ks_definitions.ord = ks_id02
    ),
    role_no
  )
FROM taskskill_map
WHERE taskskill_map.taskset_id = i
  AND taskskill_map.role_no = 3;
SET i = i + 1;
END WHILE;
END;

The error message: 'ERROR 1241 (21000): Operand should contain 1 column(s)'.
My suspicion is that the counter (i) is not being read inside the two subqueries, leading to multiple values. When I run the subqueries with a specific integer value for i, I get a single result. If so, how to make the counter run inside the subqueries? If not, then please suggest how I can copy the data following any other approach.
I am new to coding.


问:
Azure Forms Recognizer Prebuilt-Invoice crashes during processing a file with "Name or service not known"
I am trying to run the Microsoft Cognitive Services Form Recognizer on premise.
While the general layout analyzer works fine for me, the FR for the invoice model is constantly crashing:

The error message is:

```<code>fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
</code>```

or in detail:

```<code>status: SERVING
fail: formrecognizerinvoice[0]
      Unhandled exception in OcrHandlerService. System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
         at  .․. (HttpContent , Dictionary`2 , RequestCorrelation , Details , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , RequestCorrelation , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , CancellationToken ) Time='12/22/2022 9:35:57 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Process' sourceLineNumber='170' sourceFilePath='/source/src/OcrHandler/Handler/OcrHandler.cs' errorCode='1204' errorCode Description='Unhandled exception happened during running OCR handler.'
fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at  .․. (OcrVerticalQueueMessage , CancellationToken )
         at  .⁎. . .MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.QueueManager.<>c__DisplayClass9_0.<<RegisterConcurrentWorkScheduler>b__0>d.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.ConcurrentWorkScheduler`1.Work(T item, TaskCompletionSource`1 source) Time='12/22/2022 9:35:57 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Work' sourceLineNumber='138' sourceFilePath='/source/src/Common/Storage/Queue/Worker/ConcurrentWorkScheduler.cs' errorCode='1217' errorCode Description='Unhandled exception happened in queue worker.'
fail: formrecognizerinvoice[0]
      Unhandled exception in OcrHandlerService. System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
         at  .․. (HttpContent , Dictionary`2 , RequestCorrelation , Details , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , RequestCorrelation , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , CancellationToken ) Time='12/22/2022 9:35:58 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Process' sourceLineNumber='170' sourceFilePath='/source/src/OcrHandler/Handler/OcrHandler.cs' errorCode='1204' errorCode Description='Unhandled exception happened during running OCR handler.'
fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at  .․. (OcrVerticalQueueMessage , CancellationToken )
         at  .⁎. . .MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.QueueManager.<>c__DisplayClass9_0.<<RegisterConcurrentWorkScheduler>b__0>d.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.ConcurrentWorkScheduler`1.Work(T item, TaskCompletionSource`1 source) Time='12/22/2022 9:35:58 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Work' sourceLineNumber='138' sourceFilePath='/source/src/Common/Storage/Queue/Worker/ConcurrentWorkScheduler.cs' errorCode='1217' errorCode Description='Unhandled exception happened in queue worker.'
</code>```

I was using a yaml file to run the container with

```<code>sudo podman play kube ./rech_container_only.yaml
</code>```
```<code># Created with podman-3.4.7
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2022-12-22T08:56:40Z"
  labels:
    app: xxxx
  name: xxxx
spec:
  containers:
  - args:
    - ./run.sh
    - eula=accept
    - Billing=https://frxxxx.cognitiveservices.azure.com/
    - ApiKey=XXXXX
    env:
    - name: EULA
      value: accept
    - name: Billing
      value: https://frxxxx.cognitiveservices.azure.com/
    - name: ApiKey
      value: xxxx
    image: mcr.microsoft.com/azure-cognitive-services/form-recognizer/invoice:latest
    name: xxxx
    ports:
    - containerPort: 5050
      hostPort: 5005
    securityContext:
      capabilities: {}
    stdin: true
    tty: true
</code>```

The general service status is okay:

```<code>curl -X GET "http://localhost:5005/status" -H  "accept: application/json"
{"service":"formrecognizerinvoice","apiStatus":"Valid","apiStatusMessage":"Api Key is valid, no action needed."}
</code>```

The call on the api was done via curl command:

```<code>curl -X POST "http://localhost:5005/formrecognizer/v2.1/prebuilt/invoice/analyze"
-H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"source\":\"https://rechnungen-muster.de/images/musterrechnung-6p.jpg\"}"
</code>```

No response to the stdout has been written but on

```<code>sudo podman logs -l
</code>```

Body:
I am trying to run the Microsoft Cognitive Services Form Recognizer on premise.
While the general layout analyzer works fine for me, the FR for the invoice model is constantly crashing:

The error message is:

fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known

or in detail:

status: SERVING
fail: formrecognizerinvoice[0]
      Unhandled exception in OcrHandlerService. System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
         at  .․. (HttpContent , Dictionary`2 , RequestCorrelation , Details , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , RequestCorrelation , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , CancellationToken ) Time='12/22/2022 9:35:57 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Process' sourceLineNumber='170' sourceFilePath='/source/src/OcrHandler/Handler/OcrHandler.cs' errorCode='1204' errorCode Description='Unhandled exception happened during running OCR handler.'
fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at  .․. (OcrVerticalQueueMessage , CancellationToken )
         at  .⁎. . .MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.QueueManager.<>c__DisplayClass9_0.<<RegisterConcurrentWorkScheduler>b__0>d.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.ConcurrentWorkScheduler`1.Work(T item, TaskCompletionSource`1 source) Time='12/22/2022 9:35:57 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Work' sourceLineNumber='138' sourceFilePath='/source/src/Common/Storage/Queue/Worker/ConcurrentWorkScheduler.cs' errorCode='1217' errorCode Description='Unhandled exception happened in queue worker.'
fail: formrecognizerinvoice[0]
      Unhandled exception in OcrHandlerService. System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
         at  .․. (HttpContent , Dictionary`2 , RequestCorrelation , Details , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , RequestCorrelation , CancellationToken )
         at  .․. (OcrVerticalQueueMessage , CancellationToken ) Time='12/22/2022 9:35:58 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Process' sourceLineNumber='170' sourceFilePath='/source/src/OcrHandler/Handler/OcrHandler.cs' errorCode='1204' errorCode Description='Unhandled exception happened during running OCR handler.'
fail: formrecognizerinvoice[0]
      System.Net.Http.HttpRequestException: Name or service not known
       ---> System.Net.Sockets.SocketException (0xFFFDFFFF): Name or service not known
         at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at  .․. (OcrVerticalQueueMessage , CancellationToken )
         at  .⁎. . .MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.QueueManager.<>c__DisplayClass9_0.<<RegisterConcurrentWorkScheduler>b__0>d.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.CloudAI.Containers.Storage.ConcurrentWorkScheduler`1.Work(T item, TaskCompletionSource`1 source) Time='12/22/2022 9:35:58 AM' EventId='Error' requestId='ddc2246b-2d15-42c5-807a-17e1e1591ed0' hostId='MSFR3_pod' serviceName='formrecognizerinvoice' methodName='Work' sourceLineNumber='138' sourceFilePath='/source/src/Common/Storage/Queue/Worker/ConcurrentWorkScheduler.cs' errorCode='1217' errorCode Description='Unhandled exception happened in queue worker.'

I was using a yaml file to run the container with

sudo podman play kube ./rech_container_only.yaml

# Created with podman-3.4.7
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2022-12-22T08:56:40Z"
  labels:
    app: xxxx
  name: xxxx
spec:
  containers:
  - args:
    - ./run.sh
    - eula=accept
    - Billing=https://frxxxx.cognitiveservices.azure.com/
    - ApiKey=XXXXX
    env:
    - name: EULA
      value: accept
    - name: Billing
      value: https://frxxxx.cognitiveservices.azure.com/
    - name: ApiKey
      value: xxxx
    image: mcr.microsoft.com/azure-cognitive-services/form-recognizer/invoice:latest
    name: xxxx
    ports:
    - containerPort: 5050
      hostPort: 5005
    securityContext:
      capabilities: {}
    stdin: true
    tty: true

The general service status is okay:

curl -X GET "http://localhost:5005/status" -H  "accept: application/json"
{"service":"formrecognizerinvoice","apiStatus":"Valid","apiStatusMessage":"Api Key is valid, no action needed."}

The call on the api was done via curl command:

curl -X POST "http://localhost:5005/formrecognizer/v2.1/prebuilt/invoice/analyze"
-H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"source\":\"https://rechnungen-muster.de/images/musterrechnung-6p.jpg\"}"

No response to the stdout has been written but on

sudo podman logs -l


问:
Function addDoc() called with invalid data. Unsupported field value: undefined
I'm trying to add my contact form details to my firebase database but I got error.
I run this project in expo. In web version, data is going to firebase but in mobile version
I am facing this error. Please help me I don't know why this error was coming.

Error

FirebaseError: Function addDoc() called with invalid data. Unsupported field value: undefined (found in field title in document posts/5TT9b7F0lkqxoivmsIiH)).

Here's my code:
Contact form.js

```<code>import React, { useEffect,useState } from "react";
import { View, TouchableOpacity, Text, Image, StyleSheet, SafeAreaView,TextInput,Button } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { FontAwesome } from '@expo/vector-icons';
import colors from '../colors';
import { Entypo } from '@expo/vector-icons';
//import { TextInput } from "react-native-web";
import { auth, database } from '../config/firebase';
import {collection,addDoc,orderBy,query,onSnapshot} from 'firebase/firestore';

const catImageUrl = "https://i.pravatar.cc/300";

const Home = () => {

    const navigation = useNavigation();
    const [name,setName ] =useState();
    const [email,setEmail ] =useState();
    const [message,setMessage] =useState();

    const userCollectionRef = collection(database,'contactdata')
    const handleSubmit = ()=>{
        addDoc(userCollectionRef,{
            name : name || null,
            email :email || null ,
            message: message || null

        });
    }

    useEffect(() => {
        navigation.setOptions({
            headerLeft: () => (
                <FontAwesome name="home" size={25} color={'#1C64D1'} style={{marginLeft: 15}}/>

            ),
            headerRight: () => (
                <FontAwesome name="user" size={24} color={'#1C64D1'} style={{marginRight: 25}}/>
            ),
        });
    }, [navigation]);

    return (
      <View style={styles.container}>
        <SafeAreaView style={styles.form}>
          <Text style={styles.heading}>Complaint Form</Text>
          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setName(event.target.value)
          }} />

          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setEmail(event.target.value)
          }} />

          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setMessage(event.target.value)
          }}/>

        <Button title="Press mee" onPress={handleSubmit} color={colors.primary}/>
        </SafeAreaView>

      </View>
    );
    };

    export default Home;

    const styles = StyleSheet.create({
        container: {
            backgroundColor: "#fff",
            flexDirection:"column",
          },
        container1: {
            flex: 1,
            justifyContent: 'flex-end',
            alignItems: 'flex-end',
            backgroundColor: "#fff",
        },
    });
</code>```

Body:
I'm trying to add my contact form details to my firebase database but I got error.
I run this project in expo. In web version, data is going to firebase but in mobile version
I am facing this error. Please help me I don't know why this error was coming.

Error

FirebaseError: Function addDoc() called with invalid data. Unsupported field value: undefined (found in field title in document posts/5TT9b7F0lkqxoivmsIiH)).

Here's my code:
Contact form.js

import React, { useEffect,useState } from "react";
import { View, TouchableOpacity, Text, Image, StyleSheet, SafeAreaView,TextInput,Button } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { FontAwesome } from '@expo/vector-icons';
import colors from '../colors';
import { Entypo } from '@expo/vector-icons';
//import { TextInput } from "react-native-web";
import { auth, database } from '../config/firebase';
import {collection,addDoc,orderBy,query,onSnapshot} from 'firebase/firestore';

const catImageUrl = "https://i.pravatar.cc/300";

const Home = () => {

    const navigation = useNavigation();
    const [name,setName ] =useState();
    const [email,setEmail ] =useState();
    const [message,setMessage] =useState();

    const userCollectionRef = collection(database,'contactdata')
    const handleSubmit = ()=>{
        addDoc(userCollectionRef,{
            name : name || null,
            email :email || null ,
            message: message || null

        });
    }

    useEffect(() => {
        navigation.setOptions({
            headerLeft: () => (
                <FontAwesome name="home" size={25} color={'#1C64D1'} style={{marginLeft: 15}}/>

            ),
            headerRight: () => (
                <FontAwesome name="user" size={24} color={'#1C64D1'} style={{marginRight: 25}}/>
            ),
        });
    }, [navigation]);

    return (
      <View style={styles.container}>
        <SafeAreaView style={styles.form}>
          <Text style={styles.heading}>Complaint Form</Text>
          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setName(event.target.value)
          }} />

          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setEmail(event.target.value)
          }} />

          <Text style={{ marginLeft: 15, marginTop: 20 }}>Name</Text>
          <TextInput style={styles.input} onChange={(event)=>{
            setMessage(event.target.value)
          }}/>

        <Button title="Press mee" onPress={handleSubmit} color={colors.primary}/>
        </SafeAreaView>

      </View>
    );
    };

    export default Home;

    const styles = StyleSheet.create({
        container: {
            backgroundColor: "#fff",
            flexDirection:"column",
          },
        container1: {
            flex: 1,
            justifyContent: 'flex-end',
            alignItems: 'flex-end',
            backgroundColor: "#fff",
        },
    });


问:
Tiptap editor focus last element present inside the content
The issue is when I click on the first <p> tag inside content of tiptap editor, it focuses the last <p> tag. When I click first time, otherwise working fine.

I tried with various focusing method to focus the first element but I want functionality to not focus when component is loaded.

here is my code, any help or suggestions will be appreciated.

```<code>const editor = useEditor({
extensions: [
  Document,
  StarterKit.configure({
    document: false,
    heading: {
      levels: [1, 2, 3, 4],
    },
  }),
  Image,
  Strike,
  Highlight.configure({ multicolor: true }),
  Link.configure({
    openOnClick: true,
  }),
  Emoji.configure({
    emojis: [...gitHubEmojis],
    enableEmoticons: true,
    forceFallbackImages: true,
  }),
  ReactComponent,
  ImageCustomExtension,
  MentionExtension,
  MentionTipTap.configure(),
],
editorProps: {
  attributes: {
    class: `prose custom-note sm:prose lg:prose-lg xl:prose-2xl mx-auto focus:outline-none ${
      isTaskNote ? "" : "pb-32"
    }`,
  },
},

// Events
onUpdate({ editor }) {
  const json = editor.getJSON();
  debouncedUpdate(json);
},
</code>```

});

Body:
The issue is when I click on the first <p> tag inside content of tiptap editor, it focuses the last <p> tag. When I click first time, otherwise working fine.

I tried with various focusing method to focus the first element but I want functionality to not focus when component is loaded.

here is my code, any help or suggestions will be appreciated.

const editor = useEditor({
extensions: [
  Document,
  StarterKit.configure({
    document: false,
    heading: {
      levels: [1, 2, 3, 4],
    },
  }),
  Image,
  Strike,
  Highlight.configure({ multicolor: true }),
  Link.configure({
    openOnClick: true,
  }),
  Emoji.configure({
    emojis: [...gitHubEmojis],
    enableEmoticons: true,
    forceFallbackImages: true,
  }),
  ReactComponent,
  ImageCustomExtension,
  MentionExtension,
  MentionTipTap.configure(),
],
editorProps: {
  attributes: {
    class: `prose custom-note sm:prose lg:prose-lg xl:prose-2xl mx-auto focus:outline-none ${
      isTaskNote ? "" : "pb-32"
    }`,
  },
},

// Events
onUpdate({ editor }) {
  const json = editor.getJSON();
  debouncedUpdate(json);
},

});


问:
Possible ways to flag lines from csv file
For a school assignment I am required to read a csv file, but not load it all in memory. After parsing the data I need to post them to an api. Now the requirement is that the data is only posted once. I want to flag the data before it is sent and again after it is posted. I am trying to research ways on how to do this but have not been successful. Any possible implementations?

I was looking in writing the flagged data on a separate file, then compare the two files and skip the lines that are flagged on the other file.

This is the main progam:

```<code>if (File.Exists(@"C:\Users\Desktop\Book1.csv"))
{
using (StreamReader sr = new StreamReader(@"C:\Users\Desktop\Book1.csv"))
{
    string line;
    while (!sr.EndOfStream)
    {
        //split the line by comma
        line = sr.ReadLine();
        string[] split = line.Split(',');

        Field f1 = new Field();
        Field f2 = new Field();

        Payload payload = new Payload(new List<Field>() { f1, f2 }, DateTime.UtcNow, DateTime.UtcNow);

        //Prepare the payload
        string json = JsonSerializer.Serialize(payload);

        var response = Request.Post(json);
        if (response.Result != true)
        {
            tsError.TraceEvent(TraceEventType.Error, 3, "Error Occured");
        }
        else
        {
            ts.TraceInformation("completed");
        }

        ts.Flush();
        tsError.Flush();
    }
}}
</code>```

Body:
For a school assignment I am required to read a csv file, but not load it all in memory. After parsing the data I need to post them to an api. Now the requirement is that the data is only posted once. I want to flag the data before it is sent and again after it is posted. I am trying to research ways on how to do this but have not been successful. Any possible implementations?

I was looking in writing the flagged data on a separate file, then compare the two files and skip the lines that are flagged on the other file.

This is the main progam:

if (File.Exists(@"C:\Users\Desktop\Book1.csv"))
{
using (StreamReader sr = new StreamReader(@"C:\Users\Desktop\Book1.csv"))
{
    string line;
    while (!sr.EndOfStream)
    {
        //split the line by comma
        line = sr.ReadLine();
        string[] split = line.Split(',');

        Field f1 = new Field();
        Field f2 = new Field();

        Payload payload = new Payload(new List<Field>() { f1, f2 }, DateTime.UtcNow, DateTime.UtcNow);

        //Prepare the payload
        string json = JsonSerializer.Serialize(payload);

        var response = Request.Post(json);
        if (response.Result != true)
        {
            tsError.TraceEvent(TraceEventType.Error, 3, "Error Occured");
        }
        else
        {
            ts.TraceInformation("completed");
        }

        ts.Flush();
        tsError.Flush();
    }
}}


问:
Create Workforce Integration using the graph API
I am using this endpoint in POSTMAN: Endpoint: https://graph.microsoft.com/v1.0/teamwork/workforceIntegrations

with requst body
Request body:

{
    "apiVersion": 1,
    "displayName": "samplename",
    "encryption": {
        "protocol": "sharedSecret",
        "secret": "someescretvalueasper the doc"
    },
    "isActive": true,
    "supportedEntities": "shift",
    "url": "sampleurl.com"
}
```
<p>I have followed all steps as mentioned in the documentation here https://learn.microsoft.com/en-us/graph/api/workforceintegration-post?view=graph-rest-1.0&tabs=http</p>
<p>however I am getting this error</p>
<pre class="lang-json prettyprint-override"><code>{
    "error": {
        "code": "BadRequest",
        "message": "{\"error\":{\"title\":\"Something went wrong\",\"externalErrorMessage\":\"Bad Request\",\"externalSource\":\"ShiftBookingsFlow\",\"externalImageLink\":null,\"externalData\":null,\"code\":\"BadRequest\",\"message\":\"Sorry your change couldn’t be completed.\",\"details\":[],\"innererror\":{\"code\":\"WorkforceIntegrationError\"}}}",
        "innerError": {
            "date": "2022-12-18T23:47:36",
            "request-id": "d8e370a1-1d63-4137-9b49-07c74df6861b",
            "client-request-id": "d8e370a1-1d63-4137-9b49-07c74df6861b"
        }
    }
}
</code>```

Can anyone help me understand what I am doing wrong over here?

I expect a 200 Ok response but it is giving 400 bad request.

Is there any pre-requirsite to this API?

Body:
I am using this endpoint in POSTMAN: Endpoint: https://graph.microsoft.com/v1.0/teamwork/workforceIntegrations

with requst body
Request body:

{
    "apiVersion": 1,
    "displayName": "samplename",
    "encryption": {
        "protocol": "sharedSecret",
        "secret": "someescretvalueasper the doc"
    },
    "isActive": true,
    "supportedEntities": "shift",
    "url": "sampleurl.com"
}

I have followed all steps as mentioned in the documentation here https://learn.microsoft.com/en-us/graph/api/workforceintegration-post?view=graph-rest-1.0&tabs=http

however I am getting this error

{
    "error": {
        "code": "BadRequest",
        "message": "{\"error\":{\"title\":\"Something went wrong\",\"externalErrorMessage\":\"Bad Request\",\"externalSource\":\"ShiftBookingsFlow\",\"externalImageLink\":null,\"externalData\":null,\"code\":\"BadRequest\",\"message\":\"Sorry your change couldn’t be completed.\",\"details\":[],\"innererror\":{\"code\":\"WorkforceIntegrationError\"}}}",
        "innerError": {
            "date": "2022-12-18T23:47:36",
            "request-id": "d8e370a1-1d63-4137-9b49-07c74df6861b",
            "client-request-id": "d8e370a1-1d63-4137-9b49-07c74df6861b"
        }
    }
}

Can anyone help me understand what I am doing wrong over here?

I expect a 200 Ok response but it is giving 400 bad request.

Is there any pre-requirsite to this API?


问:
Get current iframe from page with JS
I have a HTML page that can be opened in a different iframe depending on some conditions. In page execution I need to know in what iframe the page is running. How can I do this?

/* Page A: */
if (openinA)
  $("#frameA").attr("src", "pageb.php");
else
  $("#frameB").attr("src", "pageb.php");

/* Page B: */
// Which IFRAME i am?
```

Title: Get current iframe from page with JS


问:
php GD library sometimes generate blank image
I trying to generate a signature from a name using the GD library, and return the png image in base64 format.

With the following code, the function correctly returns the base64 image with the signature:

```<code><?php

function genSignature($name){
    // The text to draw
    $tamano = 15 * strlen($name);

    $fuentes = [
        '../fuentesFirma/HomemadeApple-Regular.ttf',
        '../fuentesFirma/Allura-Regular.ttf',
        '../fuentesFirma/DawningofaNewDay-Regular.ttf',
        '../fuentesFirma/HerrVonMuellerhoff-Regular.ttf',
        '../fuentesFirma/LaBelleAurore-Regular.ttf',
    ];

    $fuente = $fuentes[array_rand($fuentes, 1)];

    // Create the image
    $im = imagecreatetruecolor($tamano, 60);

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, $tamano, 60, $white);

    // Add the text
    imagettftext($im, 20, 0, 0, 30, $black, $fuente, $name);

    ob_start();
    imagepng($im);
    $buffer = ob_get_clean();
    ob_end_clean();
    return base64_encode($buffer);

}
echo genSignature('María'); //Commented line when calling from another script, for testing only.
</code>```

But if I include the file with the function, and call it from another script, it always returns the same image, a white square (base64). I don't understant where is the problem..

Other script:

```<code><?php
    include_once('generarFirma.php'); //in same folder
     //....
    //some operations...
    $signature = genSignature('María');
</code>```

Body:
I trying to generate a signature from a name using the GD library, and return the png image in base64 format.

With the following code, the function correctly returns the base64 image with the signature:

<?php

function genSignature($name){
    // The text to draw
    $tamano = 15 * strlen($name);

    $fuentes = [
        '../fuentesFirma/HomemadeApple-Regular.ttf',
        '../fuentesFirma/Allura-Regular.ttf',
        '../fuentesFirma/DawningofaNewDay-Regular.ttf',
        '../fuentesFirma/HerrVonMuellerhoff-Regular.ttf',
        '../fuentesFirma/LaBelleAurore-Regular.ttf',
    ];

    $fuente = $fuentes[array_rand($fuentes, 1)];

    // Create the image
    $im = imagecreatetruecolor($tamano, 60);

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, $tamano, 60, $white);

    // Add the text
    imagettftext($im, 20, 0, 0, 30, $black, $fuente, $name);

    ob_start();
    imagepng($im);
    $buffer = ob_get_clean();
    ob_end_clean();
    return base64_encode($buffer);

}
echo genSignature('María'); //Commented line when calling from another script, for testing only.

But if I include the file with the function, and call it from another script, it always returns the same image, a white square (base64). I don't understant where is the problem..

Other script:

<?php
    include_once('generarFirma.php'); //in same folder
     //....
    //some operations...
    $signature = genSignature('María');


问:
INTERNAL ERROR: cannot create temporary directory
I create the container useing golang reexec， golang executable binary can work, but python (pyinstaller -F ) executable binary not work.

python binary can work on host machine(ubuntu).

```<code>-[container]- # ls
123-file  functionA  functionA-mark  python-test  test  test22
-[container]- # ./python-test
[16] INTERNAL ERROR: cannot create temporary directory!
-[container]- # df -h
df: cannot read table of mounted file systems: No such file or directory

</code>```

I expect the Python binary to run inside the container.

I`m beginner and  don't know where to set it in the container.

I sincerely hope to get your help， thanks

Body:
I create the container useing golang reexec， golang executable binary can work, but python (pyinstaller -F ) executable binary not work.

python binary can work on host machine(ubuntu).

-[container]- # ls
123-file  functionA  functionA-mark  python-test  test  test22
-[container]- # ./python-test
[16] INTERNAL ERROR: cannot create temporary directory!
-[container]- # df -h
df: cannot read table of mounted file systems: No such file or directory

I expect the Python binary to run inside the container.

I`m beginner and  don't know where to set it in the container.

I sincerely hope to get your help， thanks


问:
Meta data about number of executors and their run time for a Spark application
I am trying to obtain metadata about creation and termination timestamp and how many executors that were launched for a job (i.e., spark application) I run on a spark cluster.

I am not certain that the information I can find in the event-log is correct since it does not correspond to the meta data about the job in the Spark history server Web GUI. For example, the event log shows many more executor IDs than present in the Spark history server Web GUI on the  and the "Executors" tab. In addition, the "Task Time (GC Time)" columns in that tab also show a longer running time of the executors than in the event log.

Is this the creation timestamp of an executor? (Tuesday, December 13, 2022 2:49:24.444 PM)

Is this the termination timestamp? (Tuesday, December 13, 2022 2:52:04.811 PM)

Also, the executor ID 10 was not present in the Web GUI. So I am a bit confused here.

So, the questions are: Is it possible to obtain information on when and how many executors that were launched and terminated. If so, where do I find that information? Is it via det REST API?


问:
Get top records by latest date in Azure CosmosDB
I have a table like this:

Assume there are lots of Names (i.e., E,F,G,H,I etc.,) and their respective Date and Produced Items in this table. It's a massive table, so I'd want to write an optimised query.

In this, I want to query the latest A,B,C,D records.

I was using the following query:

```<code>SELECT * FROM c WHERE c.Name IN ('A','B','C','D') ORDER BY c.Date DESC OFFSET 0 LIMIT 4
</code>```

But the problem with this query is, since I'm ordering by Date, the latest 4 records I'm getting are:

I want to get this result:

Please help me in modifying the query. Thanks.

Body:
I have a table like this:

Assume there are lots of Names (i.e., E,F,G,H,I etc.,) and their respective Date and Produced Items in this table. It's a massive table, so I'd want to write an optimised query.

In this, I want to query the latest A,B,C,D records.

I was using the following query:

SELECT * FROM c WHERE c.Name IN ('A','B','C','D') ORDER BY c.Date DESC OFFSET 0 LIMIT 4

But the problem with this query is, since I'm ordering by Date, the latest 4 records I'm getting are:

I want to get this result:

Please help me in modifying the query. Thanks.


问:
How to obtain reproducible runs in python?
I want to use random.seed() so that my runs will be reproducible.
I tried the following code to test if using a set seed value works, however it does not provide me with the same output after every run:

```<code>import numpy
import random

order = [1,2,3,4,5]
random.seed(1)
random_num = list(numpy.random.permutation(order))

print(random_num)
</code>```

Now what I want is that when I run the code, it would give me the same output every time. However, this is not what happens. Now I get [1, 3, 2, 4, 5], but the second run gives me [3, 1, 4, 2, 5], which is not the same.

How should I (can I) use the seed value to get reproducible runs?

Body:
I want to use random.seed() so that my runs will be reproducible.
I tried the following code to test if using a set seed value works, however it does not provide me with the same output after every run:

import numpy
import random

order = [1,2,3,4,5]
random.seed(1)
random_num = list(numpy.random.permutation(order))

print(random_num)

Now what I want is that when I run the code, it would give me the same output every time. However, this is not what happens. Now I get [1, 3, 2, 4, 5], but the second run gives me [3, 1, 4, 2, 5], which is not the same.

How should I (can I) use the seed value to get reproducible runs?


问:
Push Notification : Move to Specific View on Tap of Notification in Kill Mode in SwiftUI
I am using Push Notifications in my SwiftUI app. The thing I need is when I tap on the notification I have to open a specific View. This is working fine when the app is in foreground or in background mode. But when the app is been killed and then I tap on the notification, it only opens the app and it doesn't go to that specified View.

Here is what I tried.

My code in AppDelegate:

```<code>func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo

      if let messageID = userInfo[gcmMessageIDKey] {
          print("Message ID from userNotificationCenter didReceive: \(messageID)")
      }
      print(userInfo)

      DispatchQueue.main.asyncAfter(deadline: .now() + 1) {

              NotificationCenter.default.post(name: Notification.Name("request_notification"), object: nil, userInfo: userInfo)

      }

      completionHandler()
  }
</code>```

And in my ContentView:

```<code>struct ContentView: View {

  @State var msgId = ""
  @State var moveToNextView = false

     var body: some View {

           VStack {

                     Text("Content View")

                 }.background(hiddenNav())
             .onAppear {

                NotificationCenter.default.addObserver(forName: Notification.Name("message_notification"), object: nil, queue: .main) { notification in

                  print(notification)
                  let userInfo = notification.userInfo
                  self.msgId = userInfo["message_id"] as? String   // this gives me my message_id = 01
                  self.moveToNextView.toggle()
                 }
             }
    }

       func hiddenNav() -> some View {
            ZStack {
                NavigationLink("", destination: NotificationsView(msgId: self.msgId), isActive: $moveToNextView)

        }
    }
}
</code>```

What I need is, when the app is been killed and then I tap on notification, it should take me to my specified View.

Body:
I am using Push Notifications in my SwiftUI app. The thing I need is when I tap on the notification I have to open a specific View. This is working fine when the app is in foreground or in background mode. But when the app is been killed and then I tap on the notification, it only opens the app and it doesn't go to that specified View.

Here is what I tried.

My code in AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo

      if let messageID = userInfo[gcmMessageIDKey] {
          print("Message ID from userNotificationCenter didReceive: \(messageID)")
      }
      print(userInfo)

      DispatchQueue.main.asyncAfter(deadline: .now() + 1) {

              NotificationCenter.default.post(name: Notification.Name("request_notification"), object: nil, userInfo: userInfo)

      }

      completionHandler()
  }

And in my ContentView:

struct ContentView: View {

  @State var msgId = ""
  @State var moveToNextView = false

     var body: some View {

           VStack {

                     Text("Content View")

                 }.background(hiddenNav())
             .onAppear {

                NotificationCenter.default.addObserver(forName: Notification.Name("message_notification"), object: nil, queue: .main) { notification in

                  print(notification)
                  let userInfo = notification.userInfo
                  self.msgId = userInfo["message_id"] as? String   // this gives me my message_id = 01
                  self.moveToNextView.toggle()
                 }
             }
    }

       func hiddenNav() -> some View {
            ZStack {
                NavigationLink("", destination: NotificationsView(msgId: self.msgId), isActive: $moveToNextView)

        }
    }
}

What I need is, when the app is been killed and then I tap on notification, it should take me to my specified View.


问:
How to pass the entire DOM of the current page to background.js using contentScript?
How do I pass the entire DOM content of Codechef.com to the background.js via contentScript?
I just want to get the problem tag of codechef question. This will help me to fetch the problem code. For this I need to query the dom.

```<code>{
    "manifest_version": 3,
    "name": "CodechefNotifier",
    "version": "1.0",
    "description": "Notifier for CodeChef",
    "action": {
        "default_popup": "index.html"
    },
    "permissions": [
        "webRequest", "debugger", "tabs", "<all_urls>", "notifications", "scripting",
        "activeTab"
    ],
    "host_permissions": [
        "https://www.codechef.com/"
    ],
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts":[
        {
            "matches":["<all_urls>"],
            "js":["contentScript.js"]
        }
    ]

}
</code>```
```<code>

const button = document.createElement('button');
button.textContent = 'Greet me!'
document.body.insertAdjacentElement('afterbegin', button);
var tags = [ "h1" ];
var all_headings = [];

var h1s = document.querySelectorAll("h1");
all_headings.push(document.body.innerHTML);
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?codechef\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...w
window.addEventListener('load',function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
</code>```

I want to pass dom content to the background script

Body:
How do I pass the entire DOM content of Codechef.com to the background.js via contentScript?
I just want to get the problem tag of codechef question. This will help me to fetch the problem code. For this I need to query the dom.

{
    "manifest_version": 3,
    "name": "CodechefNotifier",
    "version": "1.0",
    "description": "Notifier for CodeChef",
    "action": {
        "default_popup": "index.html"
    },
    "permissions": [
        "webRequest", "debugger", "tabs", "<all_urls>", "notifications", "scripting",
        "activeTab"
    ],
    "host_permissions": [
        "https://www.codechef.com/"
    ],
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts":[
        {
            "matches":["<all_urls>"],
            "js":["contentScript.js"]
        }
    ]

}

const button = document.createElement('button');
button.textContent = 'Greet me!'
document.body.insertAdjacentElement('afterbegin', button);
var tags = [ "h1" ];
var all_headings = [];

var h1s = document.querySelectorAll("h1");
all_headings.push(document.body.innerHTML);
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?codechef\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...w
window.addEventListener('load',function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }

I want to pass dom content to the background script


问:
KryoConverters serializer in python
I want to develope this code in python:
Base64Encoder.encodeUrlSafe(ZipUtil.zlib(KryoConverters.serialize(this), 9))

i found kotlin code in this repo:
https://github.com/SagerNet/SagerNet/blob/dev/app/src/main/java/io/nekohasekai/sagernet/fmt/UniversalFmt.kt

base64encode and zlib will have no problem.
But i can't find any KryoConverters library.
How can i do that?

Title: KryoConverters serializer in python


问:
Adding .NET Core authorization policy based on conditions
I'm looking for a way to add an authorization policy based on a condition.

I have two policies added.

```<code>//Policy 1
 options.AddPolicy("MyPolicy1",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "internal");
   policy.Requirements.Add(new CustomInternalRequirement());
 });

//Policy 2
 options.AddPolicy("MyPolicy2",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "external");
   policy.RequireAuthnticatedUser();
   policy.Requirements.Add(new CustomExternalRequirement());
 });
</code>```

In my controller, I want to use the above policies based on the audience. If the audience is "internal" then I want to use "MyPolicy1" and if the audience is "external" then I want to use "MyPolicy2".

This is my controller.

```<code>//MyController
[HttpGet]
[Authorize(Policy = "MyPolicy1")] // OR // [Authorize(Policy = "MyPolicy2")]
public virtual async Task<IActionResult> GetMyData()
{
//
}
</code>```

Any idea how can I achieve this?

I tried to implement a "Combined" policy with RequireAssertion so that I can use the policy "Combined" in the controller. But it seems not working. Maybe I missed something or implemented it wrong.

```<code>   options.AddPolicy("Combined",
   policy =>
   {
   policy.RequireClaim("aud");

   policy.RequireAssertion(context =>
   {
       if(context.User.HasClaim(c=>c.Type=="aud" && c.Value == "internal")
       {
          policy.Requirements.Add(new CustomInternalRequirement());
       }
       else
       {
          policy.RequireAuthnticatedUser();
          policy.Requirements.Add(new CustomExternalRequirement());
       }
       return context.HasSucceeded;
   });
 });
</code>```

Body:
I'm looking for a way to add an authorization policy based on a condition.

I have two policies added.

//Policy 1
 options.AddPolicy("MyPolicy1",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "internal");
   policy.Requirements.Add(new CustomInternalRequirement());
 });

//Policy 2
 options.AddPolicy("MyPolicy2",
 policy =>
 {
   policy.RequireClaim("aud");
   policy.RequireClaim("aud", "external");
   policy.RequireAuthnticatedUser();
   policy.Requirements.Add(new CustomExternalRequirement());
 });

In my controller, I want to use the above policies based on the audience. If the audience is "internal" then I want to use "MyPolicy1" and if the audience is "external" then I want to use "MyPolicy2".

This is my controller.

//MyController
[HttpGet]
[Authorize(Policy = "MyPolicy1")] // OR // [Authorize(Policy = "MyPolicy2")]
public virtual async Task<IActionResult> GetMyData()
{
//
}

Any idea how can I achieve this?

I tried to implement a "Combined" policy with RequireAssertion so that I can use the policy "Combined" in the controller. But it seems not working. Maybe I missed something or implemented it wrong.

   options.AddPolicy("Combined",
   policy =>
   {
   policy.RequireClaim("aud");

   policy.RequireAssertion(context =>
   {
       if(context.User.HasClaim(c=>c.Type=="aud" && c.Value == "internal")
       {
          policy.Requirements.Add(new CustomInternalRequirement());
       }
       else
       {
          policy.RequireAuthnticatedUser();
          policy.Requirements.Add(new CustomExternalRequirement());
       }
       return context.HasSucceeded;
   });
 });


问:
Grant rights to the collection(Apache Solr)
I have this security.json configuration
How can I grant separate rights to the google.cloud.integration.1 collection?

With the current configuration, the google.cloud.integration.1 collection or alias cannot be deleted, I get error 403

solr version 8.11

```<code>{
    "authentication": {
        "class": "com.us.CustomSSLAuthenticationPlugin"
    },
    "authorization": {
        "class": "com.us.BasedAuthorizationPlugin",
        "user-role": {
            "CN=...": [
                "admin_ro"
            ]
        },
        "permissions": [
            {
                "collection": "google.cloud.integration.1",
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CREATEALIAS",
                        "DELETEALIAS",
                        "CLUSTERSTATUS",
                        "ADDREPLICA"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "admin_ro",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CLUSTERSTATUS"
                    ]
                },
                "role": [
                    "rb55_bhb_epkid_rw",
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CREATEALIAS",
                        "DELETEALIAS",
                        "CLUSTERSTATUS",
                        "ADDREPLICA"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/configs",
                "params": {
                    "action": [
                        "LIST"
                    ]
                },
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/configs",
                "params": {
                    "action": [
                        "LIST",
                        "CREATE",
                        "DELETE",
                        "UPDATE"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "update",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "config-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "schema-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "security-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "core-admin-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "collection-admin-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "config-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "schema-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "security-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "core-admin-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "collection-admin-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "metrics-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "jmx_ro",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "all",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "read",
                "role": "default-deny-all"
            },
            {
                "name": "schema-read",
                "role": "default-deny-all"
            },
            {
                "name": "config-read",
                "role": "default-deny-all"
            },
            {
                "name": "collection-admin-read",
                "role": "default-deny-all"
            },
            {
                "name": "metrics-read",
                "role": "default-deny-all"
            },
            {
                "name": "core-admin-read",
                "role": "default-deny-all"
            },
            {
                "name": "security-read",
                "role": "default-deny-all"
            },
            {
                "name": "update",
                "role": "default-deny-all"
            },
            {
                "name": "schema-edit",
                "role": "default-deny-all"
            },
            {
                "name": "config-edit",
                "role": "default-deny-all"
            },
            {
                "name": "collection-admin-edit",
                "role": "default-deny-all"
            },
            {
                "name": "core-admin-edit",
                "role": "default-deny-all"
            },
            {
                "name": "security-edit",
                "role": "default-deny-all"
            },
            {
                "name": "all",
                "role": "default-deny-all"
            }
        ]
    }
}
</code>```

I want to make the collection google.cloud.integration.1 could be deleted

Body:
I have this security.json configuration
How can I grant separate rights to the google.cloud.integration.1 collection?

With the current configuration, the google.cloud.integration.1 collection or alias cannot be deleted, I get error 403

solr version 8.11

{
    "authentication": {
        "class": "com.us.CustomSSLAuthenticationPlugin"
    },
    "authorization": {
        "class": "com.us.BasedAuthorizationPlugin",
        "user-role": {
            "CN=...": [
                "admin_ro"
            ]
        },
        "permissions": [
            {
                "collection": "google.cloud.integration.1",
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CREATEALIAS",
                        "DELETEALIAS",
                        "CLUSTERSTATUS",
                        "ADDREPLICA"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "admin_ro",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CLUSTERSTATUS"
                    ]
                },
                "role": [
                    "rb55_bhb_epkid_rw",
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/collections",
                "params": {
                    "action": [
                        "LIST",
                        "LISTALIASES",
                        "CREATEALIAS",
                        "DELETEALIAS",
                        "CLUSTERSTATUS",
                        "ADDREPLICA"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/configs",
                "params": {
                    "action": [
                        "LIST"
                    ]
                },
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "collection": null,
                "path": "/admin/configs",
                "params": {
                    "action": [
                        "LIST",
                        "CREATE",
                        "DELETE",
                        "UPDATE"
                    ]
                },
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "update",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "config-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "schema-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "security-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "core-admin-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "collection-admin-edit",
                "role": [
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "config-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "schema-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "security-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "core-admin-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "collection-admin-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "metrics-read",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "jmx_ro",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "all",
                "role": [
                    "admin_ro",
                    "admin_rw",
                    "admin_ow",
                    "solr-internal-traffic"
                ]
            },
            {
                "name": "read",
                "role": "default-deny-all"
            },
            {
                "name": "schema-read",
                "role": "default-deny-all"
            },
            {
                "name": "config-read",
                "role": "default-deny-all"
            },
            {
                "name": "collection-admin-read",
                "role": "default-deny-all"
            },
            {
                "name": "metrics-read",
                "role": "default-deny-all"
            },
            {
                "name": "core-admin-read",
                "role": "default-deny-all"
            },
            {
                "name": "security-read",
                "role": "default-deny-all"
            },
            {
                "name": "update",
                "role": "default-deny-all"
            },
            {
                "name": "schema-edit",
                "role": "default-deny-all"
            },
            {
                "name": "config-edit",
                "role": "default-deny-all"
            },
            {
                "name": "collection-admin-edit",
                "role": "default-deny-all"
            },
            {
                "name": "core-admin-edit",
                "role": "default-deny-all"
            },
            {
                "name": "security-edit",
                "role": "default-deny-all"
            },
            {
                "name": "all",
                "role": "default-deny-all"
            }
        ]
    }
}

I want to make the collection google.cloud.integration.1 could be deleted


问:
Java compiler -parameters flag and Jackson
I tried enabling the -parameters flag in a project in order to use the JDBI ConstructorMapper without having to annotate each parameter.

What I then discovered was that the Jackson serialization changed behavior. I have been able to identify two things that have changed, but I have been unable to find any documentation on it.

When using the JsonCreator with mode default it now defaults to mode PROPERTIES when before it defaulted to mode DELEGATING. I now have to set this explicitly.

When using JsonProperty on a constructor parameter, that name is also kept when serializing the object. It used to serialize to the getter name, unless anything else was specified.

Are these all the changes to Jackson behavior? Also, are there any global settings I can change, so that I don't have to add lots of new annotations to my codebase?

I have tried looking for documentation, but it is hard to find the correct search terms.


问:
C# make a Scar Divi equivalent
I'd like to write a tool in C# that make the Scar DIVI job.
I don't know if someone knows it, it automate repetitive tasks on a windows based machine, by writing some Pascal code, and basically he use bitmap to string function, to make several checks on the screen.
This tool is used for create macros/bots, but obviously it's limited just to this.
For that reason I'd like to make the same thing on C#, in order to be able to customize the tool with tons of other stuffs, but I have no idea on how do it.
Does anyone have suggestions?
Thanks in advance!

Title: C# make a Scar Divi equivalent


问:
How to insert image in excel using QAxObject in Qt c++
How to insert image in excel using QAxObject in Qt c++?

I am not able to add image in excel using QAxObject in Qt please help if any one is aware of it

I tried using :

```<code>Pixmap pixmap(imagePath);
sheet->querySubObject("Cells(int, int)", 2, 1).setProperty("Picture",pixmap);
</code>```

Body:
How to insert image in excel using QAxObject in Qt c++?

I am not able to add image in excel using QAxObject in Qt please help if any one is aware of it

I tried using :

Pixmap pixmap(imagePath);
sheet->querySubObject("Cells(int, int)", 2, 1).setProperty("Picture",pixmap);


问:
How to read large csv files of AIS data in Pandas and sort by mmsi?
I currently have a large (~2.5GB) csv file containing AIS data ('mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr') for all vessels within a specific area. However, when I try to use pandas to create dataframe, I get the following warning:

```<code> DtypeWarning: Columns (0,2,3,4,5,6,7,8) have mixed types.Specify dtype option on import or set low_memory=False.
  exec(compiled, ns_globals, ns_locals)
</code>```

and the this dataframe is cretaed:

```<code><bound method NDFrame.sample of                mmsi        date_time_utc  ... nav_status message_nr
0         219017214  2017-01-01 00:00:08  ...        0.0        1.0
1         219017214  2017-01-01 00:01:16  ...        0.0        1.0
2         219017214  2017-01-01 00:02:36  ...        0.0        1.0
3         219017214  2017-01-01 00:03:09  ...        0.0        1.0
4         219017214  2017-01-01 00:04:08  ...        0.0        1.0
            ...                  ...  ...        ...        ...
42340918  636092728  2017-12-31 21:41:10  ...        0.0        1.0
42340919  636092728  2017-12-31 21:42:42  ...        0.0        1.0
42340920  636092728  2017-12-31 21:43:11  ...        0.0        1.0
42340921  636092728  2017-12-31 21:44:50  ...        0.0        1.0
42340922  636092728  2017-12-31 21:45:21  ...        0.0        1.0

[42340923 rows x 9 columns]>
</code>```

further, when running this code:
dataGroup = df.sort_values(['mmsi']).groupby('mmsi')

the follwoing typer error occures:
'<' not supported between instances of 'int' and 'str'

What I have tried is:
Run

```<code>for column in df.columns:
    print(pd.api.types.infer_dtype(df[column][1:]))
</code>```

mixed-integer
string
mixed
mixed
mixed
mixed
mixed
mixed
mixed

I then tried to define the dtype when reading the csv:

```<code>f = pd.read_csv(fp, header=None,
                     names=['mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr'],
                     dtype={'mmsi':int, 'date_time_utc':str, 'lon':float, 'lat':float, 'sog':float, 'cog':float, 'true_heading':float, 'nav_status':float, 'message_nr':float})
</code>```

: invalid literal for int() with base 10: 'mmsi'

I then tried to limit the number of rows by running:

```<code> df = pd.read_csv(fp, header=None, nrows=10000,
                     names=['mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr'])
</code>```

and this one seems to work but don't understand why.

Body:
I currently have a large (~2.5GB) csv file containing AIS data ('mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr') for all vessels within a specific area. However, when I try to use pandas to create dataframe, I get the following warning:

 DtypeWarning: Columns (0,2,3,4,5,6,7,8) have mixed types.Specify dtype option on import or set low_memory=False.
  exec(compiled, ns_globals, ns_locals)

and the this dataframe is cretaed:

<bound method NDFrame.sample of                mmsi        date_time_utc  ... nav_status message_nr
0         219017214  2017-01-01 00:00:08  ...        0.0        1.0
1         219017214  2017-01-01 00:01:16  ...        0.0        1.0
2         219017214  2017-01-01 00:02:36  ...        0.0        1.0
3         219017214  2017-01-01 00:03:09  ...        0.0        1.0
4         219017214  2017-01-01 00:04:08  ...        0.0        1.0
            ...                  ...  ...        ...        ...
42340918  636092728  2017-12-31 21:41:10  ...        0.0        1.0
42340919  636092728  2017-12-31 21:42:42  ...        0.0        1.0
42340920  636092728  2017-12-31 21:43:11  ...        0.0        1.0
42340921  636092728  2017-12-31 21:44:50  ...        0.0        1.0
42340922  636092728  2017-12-31 21:45:21  ...        0.0        1.0

[42340923 rows x 9 columns]>

further, when running this code:
dataGroup = df.sort_values(['mmsi']).groupby('mmsi')

the follwoing typer error occures:
'<' not supported between instances of 'int' and 'str'

What I have tried is:
Run

for column in df.columns:
    print(pd.api.types.infer_dtype(df[column][1:]))

mixed-integer
string
mixed
mixed
mixed
mixed
mixed
mixed
mixed

I then tried to define the dtype when reading the csv:

f = pd.read_csv(fp, header=None,
                     names=['mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr'],
                     dtype={'mmsi':int, 'date_time_utc':str, 'lon':float, 'lat':float, 'sog':float, 'cog':float, 'true_heading':float, 'nav_status':float, 'message_nr':float})

: invalid literal for int() with base 10: 'mmsi'

I then tried to limit the number of rows by running:

 df = pd.read_csv(fp, header=None, nrows=10000,
                     names=['mmsi', 'date_time_utc', 'lon', 'lat', 'sog', 'cog', 'true_heading', 'nav_status', 'message_nr'])

and this one seems to work but don't understand why.


问:
Vulnerablities for tomcat-embed-core in OWASP DependencyTrack
We use OWASP DependencyTrack to keep track of vulnerablities in our Spring Boot apps.

SBOMs are generated using https://github.com/CycloneDX/cyclonedx-gradle-plugin and contain an entry for the embedded Tomcat server with a PURL such as

pkg:maven/org.apache.tomcat.embed/tomcat-embed-core@10.0.26?type=jar

Checking the standard databases DependencyTrack does not find vulnerabilities published only for "normal" Tomcat (e.g. https://nvd.nist.gov/vuln/detail/CVE-2022-42252).

Does anybody else face the same challenges? Do you have workarounds/solutions?

I am not sure where a solution for this might be applied (hint/additional information for enriching the generated SBOM?).