问:
Why do I get wrong number of keys in loglikelihood dictionary. Expected: 9165. Got: 9161
```<code># Build the freqs dictionary for later uses
freqs = count_tweets({}, train_x, train_y)

# UNQ_C2 GRADED FUNCTION: train_naive_bayes

def train_naive_bayes(freqs, train_x, train_y):
    '''
    Input:
        freqs: dictionary from (word, label) to how often the word appears
        train_x: a list of tweets
        train_y: a list of labels correponding to the tweets (0,1)
    Output:
        logprior: the log prior. (equation 3 above)
        loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above)
    '''
    loglikelihood = {}
    logprior = 0

    ### START CODE HERE ###

    # calculate V, the number of unique words in the vocabulary
    vocab = set([pair[0] for pair in freqs.keys()])
    V = len(vocab)

    # calculate N_pos, N_neg, V_pos, V_neg
    N_pos = N_neg =  0
    for pair in freqs.keys():
        # if the label is positive (greater than zero)
        if pair[1] > 0:

            # Increment the number of positive words by the count for this (word, label) pair
            N_pos += freqs[pair]

        # else, the label is negative
        else:

            # increment the number of negative words by the count for this (word,label) pair
            N_neg += freqs[pair]

    # Calculate D, the number of documents
    D = len(train_y)

    # Calculate D_pos, the number of positive documents
    D_pos = sum(train_y)

    # Calculate D_neg, the number of negative documents
    D_neg = D - D_pos

    # Calculate logprior
    logprior = np.log(D_pos) - np.log(D_neg)

    # For each word in the vocabulary...
    for word in vocab:
        # get the positive and negative frequency of the word
        freq_pos = lookup(freqs,word,1)
        freq_neg = lookup(freqs,word,0)

        # calculate the probability that each word is positive, and negative
        p_w_pos = (freq_pos + 1) / (N_pos + V)
        p_w_neg = (freq_neg + 1) / (N_neg + V)

        # calculate the log likelihood of the word
        loglikelihood[word] = np.log(p_w_pos / p_w_neg)

    ### END CODE HERE ###

    return logprior, loglikelihood

# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
logprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y)
print(logprior)
print(len(loglikelihood))
</code>```

```<code>0.0
9161
Wrong number of keys in loglikelihood dictionary.
    Expected: 9165.
    Got: 9161.
</code>```

I've checked and tried over and over again but still got the wrong result, the methond is like below:

Instructions

Given a freqs dictionary, train_x (a list of tweets) and a train_y (a list of labels for each tweet), implement a naive bayes classifier.

Calculate
You can then compute the number of unique words that appear in the freqs dictionary to get your    (you can use the set function).

Calculate    and
Using your freqs dictionary, you can compute the positive and negative frequency of each word    and   .

Calculate   , and
Using freqs dictionary, you can also compute the total number of positive words and total number of negative words    and   .

Calculate   ,   ,
Using the train_y input list of labels, calculate the number of documents (tweets)   , as well as the number of positive documents (tweets)    and number of negative documents (tweets)   .

Calculate the probability that a document (tweet) is positive  () , and the probability that a document (tweet) is negative  ()

Calculate the logprior
the logprior is  ()−()

Calculate log likelihood
Finally, you can iterate over each word in the vocabulary, use your lookup function to get the positive frequencies,   , and the negative frequencies,   , for that specific word.

Compute the positive probability of each word  () , negative probability of each word  ()  using equations 4 & 5.
()=+1+(4)
()=+1+(5)

Note: We'll use a dictionary to store the log likelihoods for each word. The key is the word, the value is the log likelihood of that word).

You can then compute the loglikelihood:  (()()) .

Body:
# Build the freqs dictionary for later uses
freqs = count_tweets({}, train_x, train_y)

# UNQ_C2 GRADED FUNCTION: train_naive_bayes

def train_naive_bayes(freqs, train_x, train_y):
    '''
    Input:
        freqs: dictionary from (word, label) to how often the word appears
        train_x: a list of tweets
        train_y: a list of labels correponding to the tweets (0,1)
    Output:
        logprior: the log prior. (equation 3 above)
        loglikelihood: the log likelihood of you Naive bayes equation. (equation 6 above)
    '''
    loglikelihood = {}
    logprior = 0

    ### START CODE HERE ###

    # calculate V, the number of unique words in the vocabulary
    vocab = set([pair[0] for pair in freqs.keys()])
    V = len(vocab)

    # calculate N_pos, N_neg, V_pos, V_neg
    N_pos = N_neg =  0
    for pair in freqs.keys():
        # if the label is positive (greater than zero)
        if pair[1] > 0:

            # Increment the number of positive words by the count for this (word, label) pair
            N_pos += freqs[pair]

        # else, the label is negative
        else:

            # increment the number of negative words by the count for this (word,label) pair
            N_neg += freqs[pair]

    # Calculate D, the number of documents
    D = len(train_y)

    # Calculate D_pos, the number of positive documents
    D_pos = sum(train_y)

    # Calculate D_neg, the number of negative documents
    D_neg = D - D_pos

    # Calculate logprior
    logprior = np.log(D_pos) - np.log(D_neg)

    # For each word in the vocabulary...
    for word in vocab:
        # get the positive and negative frequency of the word
        freq_pos = lookup(freqs,word,1)
        freq_neg = lookup(freqs,word,0)

        # calculate the probability that each word is positive, and negative
        p_w_pos = (freq_pos + 1) / (N_pos + V)
        p_w_neg = (freq_neg + 1) / (N_neg + V)

        # calculate the log likelihood of the word
        loglikelihood[word] = np.log(p_w_pos / p_w_neg)

    ### END CODE HERE ###

    return logprior, loglikelihood

# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
logprior, loglikelihood = train_naive_bayes(freqs, train_x, train_y)
print(logprior)
print(len(loglikelihood))

0.0
9161
Wrong number of keys in loglikelihood dictionary.
    Expected: 9165.
    Got: 9161.

I've checked and tried over and over again but still got the wrong result, the methond is like below:

Instructions

Given a freqs dictionary, train_x (a list of tweets) and a train_y (a list of labels for each tweet), implement a naive bayes classifier.

Calculate
You can then compute the number of unique words that appear in the freqs dictionary to get your    (you can use the set function).

Calculate    and
Using your freqs dictionary, you can compute the positive and negative frequency of each word    and   .

Calculate   , and
Using freqs dictionary, you can also compute the total number of positive words and total number of negative words    and   .

Calculate   ,   ,
Using the train_y input list of labels, calculate the number of documents (tweets)   , as well as the number of positive documents (tweets)    and number of negative documents (tweets)   .

Calculate the probability that a document (tweet) is positive  () , and the probability that a document (tweet) is negative  ()

Calculate the logprior
the logprior is  ()−()

Calculate log likelihood
Finally, you can iterate over each word in the vocabulary, use your lookup function to get the positive frequencies,   , and the negative frequencies,   , for that specific word.

Compute the positive probability of each word  () , negative probability of each word  ()  using equations 4 & 5.
()=+1+(4)
()=+1+(5)

Note: We'll use a dictionary to store the log likelihoods for each word. The key is the word, the value is the log likelihood of that word).

You can then compute the loglikelihood:  (()()) .


来源: stackexchange

问:
Passing parameters to an SVG file from CSS?
Is there a way pass some data to a svg file when it's being used as background image. For example with something like this:

```<code>background-image:url("mysvg.svg?myparam=red")
</code>```

and in mysvg.svg receive red from myparam parameter?

I've seen Parameter Variables in SVG but it seems require use of <object> in html, so just adding into svg

```<code><defs>
  <ref id="myparam" param="myparam" default="blue"/>
</defs>
<rect x="5" y="5" width="100" height="30" rx="15" ry="15" fill="url(#myparam)" />
</code>```

doesn't work and I'm trying to avoid use any kind of inline-html inside CSS if all possible.

ContentLicense: CC BY-SA 4.0

Body:
Is there a way pass some data to a svg file when it's being used as background image. For example with something like this:

background-image:url("mysvg.svg?myparam=red")

and in mysvg.svg receive red from myparam parameter?

I've seen Parameter Variables in SVG but it seems require use of <object> in html, so just adding into svg

<defs>
  <ref id="myparam" param="myparam" default="blue"/>
</defs>
<rect x="5" y="5" width="100" height="30" rx="15" ry="15" fill="url(#myparam)" />

doesn't work and I'm trying to avoid use any kind of inline-html inside CSS if all possible.


问:
Unwanted Python auto-imports when typing complete function or class name
In Visual Studio code, when I type the full name of a Python function or class that the auto-import recognizes from some other module or package, it is auto-imported (see screen-capture below). In order to prevent this, I would need to hit esc. I would like to avoid this behavior (but still get auto-import when I autocomplete a function or class, which I have mapped to tab).


问:
Rename from failed( initial Git configuration error)
I was trying to make my first commit with Git and it appeared to configure the account and user, but when I try I get the following error

```<code>$ git config --global user.name "lomaferreira"
Rename from 'C:/Users/Loma/.gitconfig.lock' to 'C:/Users/Loma/.gitconfig' failed. Should I try again? (y/n)
</code>```

I have no idea what it is, and I've searched a lot with no solution.
Forgive me if anyone hears a typo, I don't speak English

what I already tried:

update git

edit ~/.gitconfig manually

delete /.gitconfig file

creating the .git directory and moving the file creating ~/.gitconfig there

Body:
I was trying to make my first commit with Git and it appeared to configure the account and user, but when I try I get the following error

$ git config --global user.name "lomaferreira"
Rename from 'C:/Users/Loma/.gitconfig.lock' to 'C:/Users/Loma/.gitconfig' failed. Should I try again? (y/n)

I have no idea what it is, and I've searched a lot with no solution.
Forgive me if anyone hears a typo, I don't speak English

what I already tried:

update git

edit ~/.gitconfig manually

delete /.gitconfig file

creating the .git directory and moving the file creating ~/.gitconfig there


问:
Overwrite or delete duplicate cookies
I am attempting a performance test using JMeter.
The first controller performs a POST  request to create a token en assign it to a variable.

The folloowing requests use this cookie to authenticate.

What I noticed is that after the first request with the cookies, the response contain a Set-Cookie header for each of the cookies.
Following requests use the old cookies (from the cookie manager) and the new cookies for the response.

I would like to overwrite the original cookie with the value of the new cookie.

I moved around the Cookie manager and edited the settings, but to no avail.

Title: Overwrite or delete duplicate cookies


问:
React, Uncaught RangeError: Maximum call stack size exceeded
I have an array of objects containing details about players (name, skill(number 0-10)),
I'm trying to split that array into two arrays Team1 and Team2 while making sure that the sum of skill in both teams is equal or close at least.
This is the way I came up with but it seems like I have some kind of recursion error and I can't see where the problem is.

```<code>const [team1, setTeam1] = useState([]);
const [team2, setTeam2] = useState([]);
const [team1Skill, setTeam1Skill] = useState(0);
const [team2Skill, setTeam2Skill] = useState(0);
const [skillGap, setSkillGap] = useState(0);

const randomize = () => {
    let randomNum1 = Math.floor(Math.random() * playersList.length);
    let randomNum2 = Math.floor(Math.random() * playersList.length);
    const pickedPlayer1 = playersList[randomNum1];
    const pickedPlayer2 = playersList[randomNum2];
    if (!team2.includes(pickedPlayer1) && !team1.includes(pickedPlayer1)) {
        team1.push(pickedPlayer1);
    }
    if (!team1.includes(pickedPlayer2) && !team2.includes(pickedPlayer2)) {
        team2.push(pickedPlayer2);
    }
    checkNumberEquality();
    if (team1.length + team2.length === playersList.length) {
        checkSkillSum();
    }
};

const checkNumberEquality = () => {
    if (team1.length + team2.length !== playersList.length) {
        randomize();
    }
};

const checkSkillSum = () => {
    team1.map((player) => {
        setTeam1Skill((value) => value + player.skill);
    });
    team2.map((player) => {
        setTeam2Skill((value) => value + player.skill);
    });
    if (team1Skill === team2Skill) {
        console.log("The teams are perfectly balanced.");
    } else if (
        team1Skill + 1 == team2Skill ||
        team1Skill + 2 == team2Skill
    ) {
        console.log(
            "The teams have been balanced as much as possible, but team 2 is slightly better than team 2"
        );
    } else if (
        team1Skill - 1 == team2Skill ||
        team1Skill - 2 == team2Skill
    ) {
        console.log(
            "The teams have been balanced as much as possible, but team 1 is slightly better than team 2"
        );
    } else if (team1Skill !== team2Skill) {
        setTeam1([]);
        setTeam2([]);
        randomize();
    }
};
</code>```

Here's a better and clearer image of the code

Also, in the app I have an input field (in another component) and whenever I type something there I notice that it keeps executing the commands and repeating things ( I kinda know how onChange and re-rendering work in react but it just seemed weird )

Body:
I have an array of objects containing details about players (name, skill(number 0-10)),
I'm trying to split that array into two arrays Team1 and Team2 while making sure that the sum of skill in both teams is equal or close at least.
This is the way I came up with but it seems like I have some kind of recursion error and I can't see where the problem is.

const [team1, setTeam1] = useState([]);
const [team2, setTeam2] = useState([]);
const [team1Skill, setTeam1Skill] = useState(0);
const [team2Skill, setTeam2Skill] = useState(0);
const [skillGap, setSkillGap] = useState(0);

const randomize = () => {
    let randomNum1 = Math.floor(Math.random() * playersList.length);
    let randomNum2 = Math.floor(Math.random() * playersList.length);
    const pickedPlayer1 = playersList[randomNum1];
    const pickedPlayer2 = playersList[randomNum2];
    if (!team2.includes(pickedPlayer1) && !team1.includes(pickedPlayer1)) {
        team1.push(pickedPlayer1);
    }
    if (!team1.includes(pickedPlayer2) && !team2.includes(pickedPlayer2)) {
        team2.push(pickedPlayer2);
    }
    checkNumberEquality();
    if (team1.length + team2.length === playersList.length) {
        checkSkillSum();
    }
};

const checkNumberEquality = () => {
    if (team1.length + team2.length !== playersList.length) {
        randomize();
    }
};

const checkSkillSum = () => {
    team1.map((player) => {
        setTeam1Skill((value) => value + player.skill);
    });
    team2.map((player) => {
        setTeam2Skill((value) => value + player.skill);
    });
    if (team1Skill === team2Skill) {
        console.log("The teams are perfectly balanced.");
    } else if (
        team1Skill + 1 == team2Skill ||
        team1Skill + 2 == team2Skill
    ) {
        console.log(
            "The teams have been balanced as much as possible, but team 2 is slightly better than team 2"
        );
    } else if (
        team1Skill - 1 == team2Skill ||
        team1Skill - 2 == team2Skill
    ) {
        console.log(
            "The teams have been balanced as much as possible, but team 1 is slightly better than team 2"
        );
    } else if (team1Skill !== team2Skill) {
        setTeam1([]);
        setTeam2([]);
        randomize();
    }
};

Here's a better and clearer image of the code

Also, in the app I have an input field (in another component) and whenever I type something there I notice that it keeps executing the commands and repeating things ( I kinda know how onChange and re-rendering work in react but it just seemed weird )


问:
How do i encrypt a password for Tuya Smart Lock Open API
Keep in mind that I'm very new and lost when it comes to coding.

I'm trying to generate a temporary for a smart lock that uses the Tuya App using Postman.
I am currently stuck on the password as it requires it to be encrypted.
password requirements from tuya
It says that i need to decrypt the "ticket_key" (which i manage get through the "Get a temporary key for password encryption" request) using the "accessKey". Can anyone help me locate this accessKey and explain how i am supposed to encrypt and decrypt (do i need to create a program for it or is there one already available).

Thanks in advance!

I tried using ChatGPT to write me a program that encrypts and decrypts but didnt manage to get anything usable out of it.


问:
matplotlib's contourf producing error in tikzplotlib
could someone point out to what is wrong with the following code?

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib

max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)

X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)

fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()
</code>```

I get errors from tikzplotlib, namely

```<code>Traceback (most recent call last):
  File ".../to_pgfplot.py", line 19, in <module>
    print(tikzplotlib.get_tikz_code())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
    data, content = _recurse(data, figure)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
    data, children_content = _recurse(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
    data, cont = _draw_collection(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
    return _path.draw_pathcollection(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
    p = obj.get_paths()[0]
IndexError: list index out of range
</code>```

Body:
could someone point out to what is wrong with the following code?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib

max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)

X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)

fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()

I get errors from tikzplotlib, namely

Traceback (most recent call last):
  File ".../to_pgfplot.py", line 19, in <module>
    print(tikzplotlib.get_tikz_code())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
    data, content = _recurse(data, figure)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
    data, children_content = _recurse(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
    data, cont = _draw_collection(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
    return _path.draw_pathcollection(data, child)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
    p = obj.get_paths()[0]
IndexError: list index out of range


问:
spring kafka metrics value mismatch
i have a kafka consumer and i'm using spring-kafka 2.8.6. I consume batch wise and my consumer looks like below.

```<code> @KafkaListener(topics = "mytopic", groupId = "mygroup",
          autoStartup = "true", concurrency = "3", id = "my-listener",
          containerFactory = "KafkaListenerContainerFactory")
  public void consume(List<ConsumerRecord> records) {

    // process messages

  }
</code>```

For consumer i wrote a load test and i checked the metrics using defauls spring-kafka metrics. I kept a variable and got the number of messages consumed from the consumer and i checked the consumed count from the spring-kafka defauls metrics using prometheus endpoint.
I was able to find the correct metric under the name of spring.kafka.listener .

But when o compared the number of consumed messages from the consumer and compared it with the prometheus count, there is a small mismatch (for 3000 consumed messages, 70-100 messages were missing).

I checked the dlt topics and nothing has gone to dlt. Even if it has gone to dlt, i could have seen it in the prometheus metrics.

Is this a known issue or am i missing something ?

btw my application properties file for prometheus looks like below

```<code>management:
  endpoints:
    web:
      exposure:
        include: health,prometheus,env
      base-path: /
  endpoint:
    health:
      show-details: always
  metrics:
    web:
      server:
        request:
          autotime:
            enabled: true
            percentiles-histogram: true
    distribution:
      sla:
        http:
          server:
            requests: 300ms,500ms
</code>```

and part of my prometheus endpoint metric looks like below

```<code>spring_kafka_listener_seconds Kafka Listener Timer
spring_kafka_listener_seconds summary
spring_kafka_listener_seconds_count{exception="none",name="my-listener-1",result="success",} 4730.0
spring_kafka_listener_seconds_sum{exception="none",name="my-listener-1",result="success",} 2.941328279
</code>```

I use below dependencies

```<code>        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.9.3</version>
        </dependency>
</code>```

Title: spring kafka metrics value mismatch

Body:
i have a kafka consumer and i'm using spring-kafka 2.8.6. I consume batch wise and my consumer looks like below.

 @KafkaListener(topics = "mytopic", groupId = "mygroup",
          autoStartup = "true", concurrency = "3", id = "my-listener",
          containerFactory = "KafkaListenerContainerFactory")
  public void consume(List<ConsumerRecord> records) {

    // process messages

  }

For consumer i wrote a load test and i checked the metrics using defauls spring-kafka metrics. I kept a variable and got the number of messages consumed from the consumer and i checked the consumed count from the spring-kafka defauls metrics using prometheus endpoint.
I was able to find the correct metric under the name of spring.kafka.listener .

But when o compared the number of consumed messages from the consumer and compared it with the prometheus count, there is a small mismatch (for 3000 consumed messages, 70-100 messages were missing).

I checked the dlt topics and nothing has gone to dlt. Even if it has gone to dlt, i could have seen it in the prometheus metrics.

Is this a known issue or am i missing something ?

btw my application properties file for prometheus looks like below

management:
  endpoints:
    web:
      exposure:
        include: health,prometheus,env
      base-path: /
  endpoint:
    health:
      show-details: always
  metrics:
    web:
      server:
        request:
          autotime:
            enabled: true
            percentiles-histogram: true
    distribution:
      sla:
        http:
          server:
            requests: 300ms,500ms

and part of my prometheus endpoint metric looks like below

spring_kafka_listener_seconds Kafka Listener Timer
spring_kafka_listener_seconds summary
spring_kafka_listener_seconds_count{exception="none",name="my-listener-1",result="success",} 4730.0
spring_kafka_listener_seconds_sum{exception="none",name="my-listener-1",result="success",} 2.941328279

I use below dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
            <version>1.9.3</version>
        </dependency>


问:
how to modify response status code in chrome extension?
using chrome.webRequest I can modify request or response headers, however I also need modify Response.statusCode, is it possible? I do not see anything in documentation.

https://developer.chrome.com/docs/extensions/reference/webRequest/

I see something interesting here:
https://tweak-extension.com/blog/how-to-override-http-status-code#lets-override

It seems the request is not sent but a mock response has been applied but I'm not sure how.


问:
Cluster validation and kriging interpolation in R
I am stuck with the kriging interpolation analysis and colour-coding the silhouette output for correct representation of clusters. Any assistance in this regard is greatly appreciated

For the kriging, I don't know how to proceed on this. For the cluster validation, I did the cluster analysis using hkmeans, but the cluster validation output swapped the colours for the cluster


问:
Chrome API extension not intentionally downloading all Download History
I have created a Chrome Extension that reroutes downloads from a given website and places them into a specific folder with an extracted number from the URL. It does this
by listening for the "onCreated" event for downloads in Chrome, and it modifies the download URL and file name if the URL starts with the given website.

My issue is, when this Extension is active and I start up Chrome the Download History automatically starts downloading. The only way I was able to fix this was to clear the Download History, which is not ideal if I want to pass this out to people and I am not sure if this will crop up again. I have tried adding a "chrome.downloads.erase" into my code but this did not help unfortunately.

I'm really confused as to why this happens, my code doesn't touch the Download History. Does anyone with a better understanding of Chrome and it's API have any idea's to why this is happening?

Thanks,

Jordan

My code:

service-worker.js

```<code>chrome.downloads.onCreated.addListener(function(downloadItem) {

    console.log("Download has been triggered");

    //Checks for downloads from Example.com
  if (downloadItem.url.startsWith("https.www.example.com")){
        console.log("The download is from Example.com");

        //need to cancel original download
        chrome.downloads.cancel(downloadItem.id)

        //Gets ID of Current Tab
        var currentTab
        chrome.tabs.query({currentWindow: true, active: true }, function(tabs1){
        currentTab = tabs1[0];

        //Splits URL into an Array so it can pull Case Number
        const myArray = currentTab.url.split("/");
        let CaseNumber = myArray[myArray.length - 1];
        console.log("Case Number:", CaseNumber);

        //Splits URL into an Array so it can pull File Name
        const myArray1 = downloadItem.url.split("/")
        let NewFileName = myArray1[myArray1.length - 1]

        //Sets Directory and adds Case Number to it
        const dir = "Cases\\"
        let FullPath = dir.concat(CaseNumber);
        //console.log(FullPath);

        //Adds the Filename to the Path
        let FileNameAndPath = FullPath.concat("\\");
        FileNameAndPath = FileNameAndPath.concat(NewFileName)

        //remove File from Downloads of Chrome
        chrome.downloads.erase({id: downloadItem.id}, function() {
        });

        console.log("Path:", FileNameAndPath);

            //Sets download location and filename

            chrome.downloads.download({
                url: downloadItem.finalUrl,
                filename: FileNameAndPath,
            });

        });

    }

});
</code>```

Body:
I have created a Chrome Extension that reroutes downloads from a given website and places them into a specific folder with an extracted number from the URL. It does this
by listening for the "onCreated" event for downloads in Chrome, and it modifies the download URL and file name if the URL starts with the given website.

My issue is, when this Extension is active and I start up Chrome the Download History automatically starts downloading. The only way I was able to fix this was to clear the Download History, which is not ideal if I want to pass this out to people and I am not sure if this will crop up again. I have tried adding a "chrome.downloads.erase" into my code but this did not help unfortunately.

I'm really confused as to why this happens, my code doesn't touch the Download History. Does anyone with a better understanding of Chrome and it's API have any idea's to why this is happening?

Thanks,

Jordan

My code:

service-worker.js

chrome.downloads.onCreated.addListener(function(downloadItem) {

    console.log("Download has been triggered");

    //Checks for downloads from Example.com
  if (downloadItem.url.startsWith("https.www.example.com")){
        console.log("The download is from Example.com");

        //need to cancel original download
        chrome.downloads.cancel(downloadItem.id)

        //Gets ID of Current Tab
        var currentTab
        chrome.tabs.query({currentWindow: true, active: true }, function(tabs1){
        currentTab = tabs1[0];

        //Splits URL into an Array so it can pull Case Number
        const myArray = currentTab.url.split("/");
        let CaseNumber = myArray[myArray.length - 1];
        console.log("Case Number:", CaseNumber);

        //Splits URL into an Array so it can pull File Name
        const myArray1 = downloadItem.url.split("/")
        let NewFileName = myArray1[myArray1.length - 1]

        //Sets Directory and adds Case Number to it
        const dir = "Cases\\"
        let FullPath = dir.concat(CaseNumber);
        //console.log(FullPath);

        //Adds the Filename to the Path
        let FileNameAndPath = FullPath.concat("\\");
        FileNameAndPath = FileNameAndPath.concat(NewFileName)

        //remove File from Downloads of Chrome
        chrome.downloads.erase({id: downloadItem.id}, function() {
        });

        console.log("Path:", FileNameAndPath);

            //Sets download location and filename

            chrome.downloads.download({
                url: downloadItem.finalUrl,
                filename: FileNameAndPath,
            });

        });

    }

});


问:
Can't split the page horizontally from html to pdf conversion with Apache velocity and itextpdf in Spring Boot,Java
I have a function to get data from the database and fill them into a prepared HTML template then export them to a pdf file. I'm using Apache Velocity vm file and itextpdf for that purpose. I need to do this on one page because users will print the pdf file. Traditional CSS codes to split the page doesn't work because of the itextpdf version.

Here is the expected output:

And here is my result (It creates the pages in one column flow):

Here is my pom.xml:

```<code><dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.11</version>
</dependency>
</code>```

And here is my controller class to create and download pdf files:

```<code>@GetMapping("/genpdf/{fileName}")
HttpEntity<byte[]> createPdf(
        @PathVariable("fileName") String fileName) throws IOException {

    /* first, get and initialize an engine */
    VelocityEngine ve = new VelocityEngine();

    /* next, get the Template */
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class",
            ClasspathResourceLoader.class.getName());
    ve.init();
    Template t = ve.getTemplate("templates/helloworld.vm");
    /* create a context and add data */
    VelocityContext context = new VelocityContext();
    context.put("name", "World");
    context.put("genDateTime", LocalDateTime.now().toString());
    /* now render the template into a StringWriter */
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    /* show the World */
    System.out.println(writer.toString());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    baos = generatePdf(writer.toString());

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(baos.toByteArray().length);

    return new HttpEntity<byte[]>(baos.toByteArray(), header);

}

public ByteArrayOutputStream generatePdf(String html) {

    String pdfFilePath = "";
    PdfWriter pdfWriter = null;

    // create a new document
    Document document = new Document();
    try {

        document = new Document();
        // document header attributes
        document.addCreationDate();
        document.addTitle("HTML to PDF using itext");
        document.setPageCount(1);
        document.addLanguage("tr");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(document, baos);
        // open document
        document.open();
        pdfWriter.addPageDictEntry(PdfName.PDF, PdfPage.LANDSCAPE);
        XMLWorkerHelper xmlWorkerHelper = XMLWorkerHelper.getInstance();
        xmlWorkerHelper.parseXHtml(pdfWriter, document, new StringReader(
                html));
        // close the document
        document.close();
        System.out.println("PDF generated successfully");

        return baos;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}
</code>```

And this is my test.vm file to produce the pdf file :

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//TR"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="tr">
<head>
    <style >
        p {
            font-size: 10px;
        }

        span {
            font-size: 10px
        }
        .split {
            height: 100%;
            width: 50%;
            position: fixed;
            z-index: 1;
            top: 0;
            overflow-x: hidden;
            padding-top: 20px;
        }

        /* Control the left side */
        .left {
            left: 0;
            background-color: #111;
        }

        /* Control the right side */
        .right {
            right: 0;
            background-color: darkblue;
        }
    </style>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Sceda Techniqa</title>
</head>
<body>
<div class="split left">
    <div style="display: flex;flex-direction: row">
        <p>test</p>
        <span><strong>test</strong></span>
    </div>
    <div style="display: flex;flex-direction: row">
        <p>test</p>
    </div>

    </div>
</div>
<div class="split right">
    <div style="display: flex;flex-direction: row">
        <span><strong>test</strong></span>
    </div>
    <div style="display: flex;flex-direction: column">
        <div style="display: flex;flex-direction: row">
            <p>test</p>
            <span><strong>2</strong></span>
        </div>
        <div style="display: flex;flex-direction: row">
            <p>test</p>
            <span><strong>4</strong></span>
        </div>
    </div>

</div>

</body>
</html>
</code>```

I tried using different HTML to pdf libraries for Maven but could not accomplish the desired result. What I need is a fully configurable css and html to pdf converter for Java.

Thanks so much for the help.

Body:
I have a function to get data from the database and fill them into a prepared HTML template then export them to a pdf file. I'm using Apache Velocity vm file and itextpdf for that purpose. I need to do this on one page because users will print the pdf file. Traditional CSS codes to split the page doesn't work because of the itextpdf version.

Here is the expected output:

And here is my result (It creates the pages in one column flow):

Here is my pom.xml:

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.0.6</version>
</dependency>

<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.10</version>
</dependency>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.11</version>
</dependency>

And here is my controller class to create and download pdf files:

@GetMapping("/genpdf/{fileName}")
HttpEntity<byte[]> createPdf(
        @PathVariable("fileName") String fileName) throws IOException {

    /* first, get and initialize an engine */
    VelocityEngine ve = new VelocityEngine();

    /* next, get the Template */
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class",
            ClasspathResourceLoader.class.getName());
    ve.init();
    Template t = ve.getTemplate("templates/helloworld.vm");
    /* create a context and add data */
    VelocityContext context = new VelocityContext();
    context.put("name", "World");
    context.put("genDateTime", LocalDateTime.now().toString());
    /* now render the template into a StringWriter */
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    /* show the World */
    System.out.println(writer.toString());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    baos = generatePdf(writer.toString());

    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.APPLICATION_PDF);
    header.set(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=" + fileName.replace(" ", "_"));
    header.setContentLength(baos.toByteArray().length);

    return new HttpEntity<byte[]>(baos.toByteArray(), header);

}

public ByteArrayOutputStream generatePdf(String html) {

    String pdfFilePath = "";
    PdfWriter pdfWriter = null;

    // create a new document
    Document document = new Document();
    try {

        document = new Document();
        // document header attributes
        document.addCreationDate();
        document.addTitle("HTML to PDF using itext");
        document.setPageCount(1);
        document.addLanguage("tr");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(document, baos);
        // open document
        document.open();
        pdfWriter.addPageDictEntry(PdfName.PDF, PdfPage.LANDSCAPE);
        XMLWorkerHelper xmlWorkerHelper = XMLWorkerHelper.getInstance();
        xmlWorkerHelper.parseXHtml(pdfWriter, document, new StringReader(
                html));
        // close the document
        document.close();
        System.out.println("PDF generated successfully");

        return baos;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

And this is my test.vm file to produce the pdf file :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//TR"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Sceda Techniqa</title>

test

        test

test

        test

test

            2

test

            4

I tried using different HTML to pdf libraries for Maven but could not accomplish the desired result. What I need is a fully configurable css and html to pdf converter for Java.

Thanks so much for the help.


问:
Mapping not working use "async" in Flutter
I'm trying to add "async" in my generated "mapping" from firebase in flutter

```<code>...data.docs.map(
            (doc) async { // here I try to add async, but it doesn't work
              Map<String, dynamic> dt = doc.data()! as Map<String, dynamic>;
              print("Oy");
              number++;
              dataCostumer.value = await getCostumer("${dt['id_customer']}");
              return pw.TableRow(
                children: [
                  pw.Expanded(
                    child: pw.Text("$number", textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Text("${dt['id_customer']}", textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Padding(
                      padding: const pw.EdgeInsets.only(left: 5),
                      child: pw.Text("${dt['id_CUSTOMER']}", textAlign: tLeft),
                    ),
                  ),
                  pw.Expanded(
                    child: pw.Text('Analog', textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Text('01-01-2023', textAlign: tCenter),
                  ),
                ],
              );
            },
          ),
</code>```

I tried using await inside the mapping, but it didn't work. I've tried a few things like Future.wait() but it doesn't work, I've also tried casting it but it doesn't work either. Is there anything I can try or is there something I should change??

Body:
I'm trying to add "async" in my generated "mapping" from firebase in flutter

...data.docs.map(
            (doc) async { // here I try to add async, but it doesn't work
              Map<String, dynamic> dt = doc.data()! as Map<String, dynamic>;
              print("Oy");
              number++;
              dataCostumer.value = await getCostumer("${dt['id_customer']}");
              return pw.TableRow(
                children: [
                  pw.Expanded(
                    child: pw.Text("$number", textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Text("${dt['id_customer']}", textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Padding(
                      padding: const pw.EdgeInsets.only(left: 5),
                      child: pw.Text("${dt['id_CUSTOMER']}", textAlign: tLeft),
                    ),
                  ),
                  pw.Expanded(
                    child: pw.Text('Analog', textAlign: tCenter),
                  ),
                  pw.Expanded(
                    child: pw.Text('01-01-2023', textAlign: tCenter),
                  ),
                ],
              );
            },
          ),

I tried using await inside the mapping, but it didn't work. I've tried a few things like Future.wait() but it doesn't work, I've also tried casting it but it doesn't work either. Is there anything I can try or is there something I should change??


问:
optional parameter in Angular service
I have this service in my Angular Project

```<code>getActividades(usuarioId: number, año: number, mes: number, quincena?: number): Observable<IActividad[]> {
return this.http.get<IActividad[]>(`${this.urlWebApi}/empleados/${usuarioId}/actividades?year=${año}&mes=${mes}&quincena=${quincena}`)
  .pipe(
    //tap(data => console.log('Listado Empleados', JSON.stringify(data))),
    tap(data => console.log('Listado actividades', data)),
    catchError(this.handleError)
  );
</code>```

}

where the last parameter quincena is optional, but this call gets me an error

Any idea, please?

Title: optional parameter in Angular service

Body:
I have this service in my Angular Project

getActividades(usuarioId: number, año: number, mes: number, quincena?: number): Observable<IActividad[]> {
return this.http.get<IActividad[]>(`${this.urlWebApi}/empleados/${usuarioId}/actividades?year=${año}&mes=${mes}&quincena=${quincena}`)
  .pipe(
    //tap(data => console.log('Listado Empleados', JSON.stringify(data))),
    tap(data => console.log('Listado actividades', data)),
    catchError(this.handleError)
  );

}

where the last parameter quincena is optional, but this call gets me an error

Any idea, please?


问:
How to avoid triggering Dash Interval event at every reload of the app
I have a Dash app running on a server, that contains an Interval call which triggers an event periodically. Essentially every time this event is triggered, a certain function is executed and it sends a summary file. The code is as follows on the app.py file:

```<code>app.layout = html.Div([
    html.Div([
        dcc.Interval(id='interval-trigger', interval=3600*1000, n_intervals=0),
        html.H1(id='event-trigger', children=''),
    ]),
])

@app.callback(dash.dependencies.Output('event-trigger', 'children'),
              dash.dependencies.Input('interval-trigger', 'n_intervals'))
def trigger_event(n):
     check_summary()

</code>```

At the moment this event is triggered every hour. The problem that I have is that every time this app is reloaded on the server by other people, the event gets triggered which is obviously outside of the period within which it should be triggered.

Is there a way to avoid having the event (Interval) being triggered every time the app reloads (mostly when other people open the Dash app on the server).

Body:
I have a Dash app running on a server, that contains an Interval call which triggers an event periodically. Essentially every time this event is triggered, a certain function is executed and it sends a summary file. The code is as follows on the app.py file:

app.layout = html.Div([
    html.Div([
        dcc.Interval(id='interval-trigger', interval=3600*1000, n_intervals=0),
        html.H1(id='event-trigger', children=''),
    ]),
])

@app.callback(dash.dependencies.Output('event-trigger', 'children'),
              dash.dependencies.Input('interval-trigger', 'n_intervals'))
def trigger_event(n):
     check_summary()

At the moment this event is triggered every hour. The problem that I have is that every time this app is reloaded on the server by other people, the event gets triggered which is obviously outside of the period within which it should be triggered.

Is there a way to avoid having the event (Interval) being triggered every time the app reloads (mostly when other people open the Dash app on the server).


问:
Is there a way to remove the Google watermark in the paid version of Google Maps API?
I'm trying out providers of satellite/aerial images for a computer vision task.

I'm trying the Google Maps API. In all images, if I use a high level of zoom, I get a watermark in various parts of the picture (in addition to the watermark on the bottom).

Here's an example. I've highlighted in red in the top right corner one of the watermarks.

Is there any way to get the images without these (even by paying extra if necessary)?

It's weird that a paid service adds watermarks...


问:
Why can tcpdump receive UDP broadcasts that netcat or socat can't?
I have a separate modem and router, configured with the modem as a bridge.  The modem hosts a LAN where it has IP address of 192.186.2.1.  In order to be able to access the modem's web UI, the router has an extra interface on the WAN port with a fixed IP address (192.168.2.10) in the modem's LAN.

The modem broadcasts VDSL status data via UDP.  I would like to listen to these packets on my router but I can't capture them using netcat or socat.  They are definitely there, though, because they show up in TCP dump.

# tcpdump -i wan broadcast -v
tcpdump: listening on wan, link-type EN10MB (Ethernet), capture size 262144 bytes
14:19:25.579815 IP (tos 0x0, ttl 254, id 54981, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13253 > 255.255.255.255.4944: UDP, length 116
14:19:35.580363 IP (tos 0x0, ttl 254, id 54982, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13306 > 255.255.255.255.4944: UDP, length 116
14:19:45.580894 IP (tos 0x0, ttl 254, id 54983, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13368 > 255.255.255.255.4944: UDP, length 116
```
<p>but <code>socat</code> (using so-bindtodevice described here: https://unix.stackexchange.com/a/663180) doesn't see anything...</p>
<pre class="lang-bash prettyprint-override"><code># socat -v udp-recv:4944,so-bindtodevice=wan -

<nothing happens>

</code>```

...and neither does netcat (specifying the interface as here: https://unix.stackexchange.com/q/368690).

# netcat -v -ul 4944 -s 192.168.2.10

<nothing happens>

```
<p>Why doesn't <code>socat</code> receive the broadcast packets?  How can I configure things so that it does?</p>
<h4>Background info</h4>
<ul>
<li>Modem: Draytek Vigor 130 (3.8.5_BT)</li>
<li>Router: Linksys WRT1900ACS (OpenWrt 22.03.2)</li>
</ul>
<p>WAN and bridge interfaces on the router, WAN port is connected to modem:</p>
<pre class="lang-bash prettyprint-override"><code># ip a
...
7: wan@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 5a:ef:68:b7:05:bc brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.10/24 brd 192.168.2.255 scope global wan
       valid_lft forever preferred_lft forever
    inet 79.71.35.166/19 brd 79.71.63.255 scope global wan
       valid_lft forever preferred_lft forever
    inet6 fe80::58ef:68ff:feb7:5bc/64 scope link
       valid_lft forever preferred_lft forever
10: br-lan: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 58:ef:68:b7:05:bc brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.1/24 brd 192.168.1.255 scope global br-lan
       valid_lft forever preferred_lft forever
    inet6 fde7:9501:870b::1/60 scope global noprefixroute
       valid_lft forever preferred_lft forever
    inet6 fe80::5aef:68ff:feb7:5bc/64 scope link
       valid_lft forever preferred_lft forever
</code>```

Routing table shows 192.168.2.0 uses WAN interface.

# ip route
default via 79.71.32.1 dev wan  src 79.71.35.166
79.71.32.0/19 dev wan scope link  src 79.71.35.166
192.168.1.0/24 dev br-lan scope link  src 192.168.1.1
192.168.2.0/24 dev wan scope link  src 192.168.2.10
```
<p>Software versions.</p>
<pre class="lang-bash prettyprint-override"><code># tcpdump --version
tcpdump version 4.9.3
libpcap version 1.10.1 (with TPACKET_V3)

# netcat --version
netcat (The GNU Netcat) 0.7.1
Copyright (C) 2002 - 2003  Giovanni Giacobbi

This program comes with NO WARRANTY, to the extent permitted by law.
You may redistribute copies of this program under the terms of
the GNU General Public License.
For more information about these matters, see the file named COPYING.

Original idea and design by Avian Research <hobbit@avian.org>,
Written by Giovanni Giacobbi <giovanni@giacobbi.net>.

# socat -V
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
socat version 1.7.4.1 on 1672494323
   running on Linux version #0 SMP Fri Oct 14 22:44:41 2022, release 5.10.146, machine armv7l
features:
  #define WITH_STDIO 1
  #define WITH_FDNUM 1
  #define WITH_FILE 1
  #define WITH_CREAT 1
  #define WITH_GOPEN 1
  #define WITH_TERMIOS 1
  #define WITH_PIPE 1
  #define WITH_UNIX 1
  #define WITH_ABSTRACT_UNIXSOCKET 1
  #define WITH_IP4 1
  #define WITH_IP6 1
  #define WITH_RAWIP 1
  #define WITH_GENERICSOCKET 1
  #define WITH_INTERFACE 1
  #define WITH_TCP 1
  #define WITH_UDP 1
  #define WITH_SCTP 1
  #define WITH_LISTEN 1
  #define WITH_SOCKS4 1
  #define WITH_SOCKS4A 1
  #define WITH_VSOCK 1
  #define WITH_PROXY 1
  #define WITH_SYSTEM 1
  #define WITH_EXEC 1
  #undef WITH_READLINE
  #define WITH_TUN 1
  #define WITH_PTY 1
  #undef WITH_OPENSSL
  #undef WITH_FIPS
  #undef WITH_LIBWRAP
  #define WITH_SYCLS 1
  #define WITH_FILAN 1
  #define WITH_RETRY 1
  #define WITH_MSGLEVEL 0 /*debug*/
</code>```

Reverse path filtering is disabled (e.g. https://stackoverflow.com/a/48256271/3508733)

# cat /proc/sys/net/ipv4/conf/all/rp_filter
0
# cat /proc/sys/net/ipv4/conf/wan/rp_filter
0
# cat /proc/sys/net/ipv4/conf/eth0/rp_filter
0
```
<p>Adding broadcast options to <code>netcat</code> and <code>socat</code> didn't help:</p>
<pre class="lang-bash prettyprint-override"><code># netcat -v -ul 4944 -s 192.168.2.10 -b
netcat: unrecognized option: b
Try `netcat --help' for more information.
</code>```

# socat -v -d -d udp4-recv:4944,so-bindtodevice=wan,so-broadcast -
2023/01/03 16:42:17 socat[10747] N reading from and writing to stdio
2023/01/03 16:42:17 socat[10747] N starting data transfer loop with FDs [5,5] and [0,1]

<nothing happens>
```

Body:
I have a separate modem and router, configured with the modem as a bridge.  The modem hosts a LAN where it has IP address of 192.186.2.1.  In order to be able to access the modem's web UI, the router has an extra interface on the WAN port with a fixed IP address (192.168.2.10) in the modem's LAN.

The modem broadcasts VDSL status data via UDP.  I would like to listen to these packets on my router but I can't capture them using netcat or socat.  They are definitely there, though, because they show up in TCP dump.

# tcpdump -i wan broadcast -v
tcpdump: listening on wan, link-type EN10MB (Ethernet), capture size 262144 bytes
14:19:25.579815 IP (tos 0x0, ttl 254, id 54981, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13253 > 255.255.255.255.4944: UDP, length 116
14:19:35.580363 IP (tos 0x0, ttl 254, id 54982, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13306 > 255.255.255.255.4944: UDP, length 116
14:19:45.580894 IP (tos 0x0, ttl 254, id 54983, offset 0, flags [none], proto UDP (17), length 144)
    0.0.0.0.13368 > 255.255.255.255.4944: UDP, length 116

but socat (using so-bindtodevice described here: https://unix.stackexchange.com/a/663180) doesn't see anything...

# socat -v udp-recv:4944,so-bindtodevice=wan -

<nothing happens>

...and neither does netcat (specifying the interface as here: https://unix.stackexchange.com/q/368690).

# netcat -v -ul 4944 -s 192.168.2.10

<nothing happens>

Why doesn't socat receive the broadcast packets?  How can I configure things so that it does?

Background info

Modem: Draytek Vigor 130 (3.8.5_BT)

Router: Linksys WRT1900ACS (OpenWrt 22.03.2)

WAN and bridge interfaces on the router, WAN port is connected to modem:

# ip a
...
7: wan@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 5a:ef:68:b7:05:bc brd ff:ff:ff:ff:ff:ff
    inet 192.168.2.10/24 brd 192.168.2.255 scope global wan
       valid_lft forever preferred_lft forever
    inet 79.71.35.166/19 brd 79.71.63.255 scope global wan
       valid_lft forever preferred_lft forever
    inet6 fe80::58ef:68ff:feb7:5bc/64 scope link
       valid_lft forever preferred_lft forever
10: br-lan: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP qlen 1000
    link/ether 58:ef:68:b7:05:bc brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.1/24 brd 192.168.1.255 scope global br-lan
       valid_lft forever preferred_lft forever
    inet6 fde7:9501:870b::1/60 scope global noprefixroute
       valid_lft forever preferred_lft forever
    inet6 fe80::5aef:68ff:feb7:5bc/64 scope link
       valid_lft forever preferred_lft forever

Routing table shows 192.168.2.0 uses WAN interface.

# ip route
default via 79.71.32.1 dev wan  src 79.71.35.166
79.71.32.0/19 dev wan scope link  src 79.71.35.166
192.168.1.0/24 dev br-lan scope link  src 192.168.1.1
192.168.2.0/24 dev wan scope link  src 192.168.2.10

Software versions.

# tcpdump --version
tcpdump version 4.9.3
libpcap version 1.10.1 (with TPACKET_V3)

# netcat --version
netcat (The GNU Netcat) 0.7.1
Copyright (C) 2002 - 2003  Giovanni Giacobbi

This program comes with NO WARRANTY, to the extent permitted by law.
You may redistribute copies of this program under the terms of
the GNU General Public License.
For more information about these matters, see the file named COPYING.

Original idea and design by Avian Research <hobbit@avian.org>,
Written by Giovanni Giacobbi <giovanni@giacobbi.net>.

# socat -V
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
socat version 1.7.4.1 on 1672494323
   running on Linux version #0 SMP Fri Oct 14 22:44:41 2022, release 5.10.146, machine armv7l
features:
  #define WITH_STDIO 1
  #define WITH_FDNUM 1
  #define WITH_FILE 1
  #define WITH_CREAT 1
  #define WITH_GOPEN 1
  #define WITH_TERMIOS 1
  #define WITH_PIPE 1
  #define WITH_UNIX 1
  #define WITH_ABSTRACT_UNIXSOCKET 1
  #define WITH_IP4 1
  #define WITH_IP6 1
  #define WITH_RAWIP 1
  #define WITH_GENERICSOCKET 1
  #define WITH_INTERFACE 1
  #define WITH_TCP 1
  #define WITH_UDP 1
  #define WITH_SCTP 1
  #define WITH_LISTEN 1
  #define WITH_SOCKS4 1
  #define WITH_SOCKS4A 1
  #define WITH_VSOCK 1
  #define WITH_PROXY 1
  #define WITH_SYSTEM 1
  #define WITH_EXEC 1
  #undef WITH_READLINE
  #define WITH_TUN 1
  #define WITH_PTY 1
  #undef WITH_OPENSSL
  #undef WITH_FIPS
  #undef WITH_LIBWRAP
  #define WITH_SYCLS 1
  #define WITH_FILAN 1
  #define WITH_RETRY 1
  #define WITH_MSGLEVEL 0 /*debug*/

Reverse path filtering is disabled (e.g. https://stackoverflow.com/a/48256271/3508733)

# cat /proc/sys/net/ipv4/conf/all/rp_filter
0
# cat /proc/sys/net/ipv4/conf/wan/rp_filter
0
# cat /proc/sys/net/ipv4/conf/eth0/rp_filter
0

Adding broadcast options to netcat and socat didn't help:

# netcat -v -ul 4944 -s 192.168.2.10 -b
netcat: unrecognized option: b
Try `netcat --help' for more information.

# socat -v -d -d udp4-recv:4944,so-bindtodevice=wan,so-broadcast -
2023/01/03 16:42:17 socat[10747] N reading from and writing to stdio
2023/01/03 16:42:17 socat[10747] N starting data transfer loop with FDs [5,5] and [0,1]

<nothing happens>


问:
Laravel SSO using codegreencreative/laravel-samlidp
i am using codegreencreative/laravel-samlidp for SSO in Laravel.

what i am receiving is:
The response was received at http://abc.test.com/saml2/74bb02aa-fc9e-48eb-990e-549f27e0e107/acs instead of https://abc.test.com/saml2/74bb02aa-fc9e-48eb-990e-549f27e0e107/acs

receiving response at http instead of https


问:
ESP8266 tcp recv returning errno 11 (EAGAIN) when handling large amounts of data
I am running ESP8266_RTOS_SDK_3.4 for an app that uses TCP to talk to a private port on a local server. In normal operation, it uploads large amounts of data to the server and receives acknowledgements that are usually less than 200 bytes: this always works fine. When I do an OTA update, where it's mainly receiving data, TCP recv fails on attempting to read the first block, and errno is set to 11 (EAGAIN).  Even if I make the server send just 1024 bytes, the same thing happens.

This is the TCP connect and recv code:

```<code>bool net_tcp_connect (SENDER_DESTINATION * dest) {
    struct sockaddr_in destAddr;

    if (!find_host (dest->hostname)) {
        return false;
    }

    memset(&destAddr, 0, sizeof(destAddr));
    memcpy (&destAddr.sin_addr, findhost_ip (), sizeof (destAddr.sin_addr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons (dest->port);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        LOGEF("Create: errno %d", errno);
        return false;
    }

    struct timeval tv;
    tv.tv_sec = dest->timeout;
    tv.tv_usec = 0;
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));

    if (connect(sock, (struct sockaddr *)&destAddr, sizeof(destAddr)) != 0) {
        LOGEF("Connect: %s %d errno %d", findhost_str (), dest->port, errno);
        EVENT_HERE ( );
        net_tcp_close ();
        return false;
    }

    return true;
}

// --------------------------------------------------------------------------------------------

int net_tcp_recv (void * buffer, int max_length) {

    if (sock < 0)
        return false;

    int bytes_received = recv (sock, buffer, max_length, 0);
    if (bytes_received < 0) {
         LOGEF("Receive: errno= %d", errno);
         net_tcp_close ();
         bytes_received = 0;
    }
    return bytes_received;
}
</code>```

EAGAIN can be a sign of a receive timeout, but the timeout is set to 30 seconds and the server usually sends out the first 32k bytes in less than a second.

The ESP8266 code does run OK on some access points and, as far as I can tell, the same code on an ESP32 runs OK on all access points.

Any suggestions for why this might happen, or things that I could try changing in the code or the ESP setup to make it work reliably on any access point?

Body:
I am running ESP8266_RTOS_SDK_3.4 for an app that uses TCP to talk to a private port on a local server. In normal operation, it uploads large amounts of data to the server and receives acknowledgements that are usually less than 200 bytes: this always works fine. When I do an OTA update, where it's mainly receiving data, TCP recv fails on attempting to read the first block, and errno is set to 11 (EAGAIN).  Even if I make the server send just 1024 bytes, the same thing happens.

This is the TCP connect and recv code:

bool net_tcp_connect (SENDER_DESTINATION * dest) {
    struct sockaddr_in destAddr;

    if (!find_host (dest->hostname)) {
        return false;
    }

    memset(&destAddr, 0, sizeof(destAddr));
    memcpy (&destAddr.sin_addr, findhost_ip (), sizeof (destAddr.sin_addr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons (dest->port);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        LOGEF("Create: errno %d", errno);
        return false;
    }

    struct timeval tv;
    tv.tv_sec = dest->timeout;
    tv.tv_usec = 0;
    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));

    if (connect(sock, (struct sockaddr *)&destAddr, sizeof(destAddr)) != 0) {
        LOGEF("Connect: %s %d errno %d", findhost_str (), dest->port, errno);
        EVENT_HERE ( );
        net_tcp_close ();
        return false;
    }

    return true;
}

// --------------------------------------------------------------------------------------------

int net_tcp_recv (void * buffer, int max_length) {

    if (sock < 0)
        return false;

    int bytes_received = recv (sock, buffer, max_length, 0);
    if (bytes_received < 0) {
         LOGEF("Receive: errno= %d", errno);
         net_tcp_close ();
         bytes_received = 0;
    }
    return bytes_received;
}

EAGAIN can be a sign of a receive timeout, but the timeout is set to 30 seconds and the server usually sends out the first 32k bytes in less than a second.

The ESP8266 code does run OK on some access points and, as far as I can tell, the same code on an ESP32 runs OK on all access points.

Any suggestions for why this might happen, or things that I could try changing in the code or the ESP setup to make it work reliably on any access point?


问:
Concat function returns the error "is not valid in the context where it is used" (SQLSTATE=42703)
I have a table - let's call it 'table1'. Within this table is a column in the varchar format - let's call it 'column1'.

I want to insert the date from two days ago into column1 in dd/mm/yyyy format, with " - UK" appended to the end. In other words, the desired result for today would look like this:

```<code>column1
---------------
01/01/2023 - UK
</code>```

I've written the following code to do this:

```<code>INSERT INTO TABLE1 VALUES
(
CONCAT(VARCHAR_FORMAT((CURRENT DATE - 3 DAYS), 'DD/MM/YYYY'), " - UK")
)
;
</code>```

However, running the code results in this error message:

```<code>" - UK" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=3.69.56
</code>```

Could anyone tell me where I'm going wrong, please?

Body:
I have a table - let's call it 'table1'. Within this table is a column in the varchar format - let's call it 'column1'.

I want to insert the date from two days ago into column1 in dd/mm/yyyy format, with " - UK" appended to the end. In other words, the desired result for today would look like this:

column1
---------------
01/01/2023 - UK

I've written the following code to do this:

INSERT INTO TABLE1 VALUES
(
CONCAT(VARCHAR_FORMAT((CURRENT DATE - 3 DAYS), 'DD/MM/YYYY'), " - UK")
)
;

However, running the code results in this error message:

" - UK" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=3.69.56

Could anyone tell me where I'm going wrong, please?


问:
How can I solve the error in the below code that is a custom implementation of the deformable convolution?
I am trying to build a M-net that involves deformable convolution with multiscale attention and residual mechanism for Retinal Blood Vessel segmentation. Trying this code, led to some errors I can't solve regarding the custom layer.

I have the custom code in TensorFlow for deformable convolution with multiscale attention and residual mechanism.

```<code>import tensorflow as tf

def deformable_conv2d(inputs, filters, kernel_size, strides=1, padding='valid', use_bias=True, data_format='channels_last',
                      deformable_groups=1, num_deformable_group_conv_filters=64, multiscale_attention=False, residual=False):
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size)
    if isinstance(strides, int):
        strides = (strides, strides)

    def _offset_filters(inputs, filters, num_deformable_group_conv_filters, kernel_size, deformable_groups):
      x = inputs
      x = tf.keras.layers.Conv2D(num_deformable_group_conv_filters, kernel_size=3, use_bias=True, padding='same', kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
      x = tf.keras.layers.Conv2D(filters, kernel_size=3, use_bias=True, padding='same', kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
      x = tf.keras.layers.Reshape([tf.shape(inputs)[0], kernel_size[0], kernel_size[1], filters], name='offset_group_%d' % i)(x)
      return x

    def _deform_conv(inputs, filters, kernel_size, strides, padding, use_bias, data_format):
        if isinstance(kernel_size, int):
            kernel_size = (kernel_size, kernel_size)
        if isinstance(strides, int):
            strides = (strides, strides)

        x = inputs
        x = tf.keras.layers.Conv2D(filters, kernel_size=kernel_size, strides=strides, padding=padding, use_bias=use_bias, data_format=data_format, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        return x

    def _multiscale_attention(inputs, filters, kernel_size, strides, padding, use_bias, data_format):
        if isinstance(kernel_size, int):
            kernel_size = (kernel_size, kernel_size)
        if isinstance(strides, int):
            strides = (strides, strides)
        x = inputs
        # 1x1 convolution
        x1 = tf.keras.layers.Conv2D(filters, kernel_size=1, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # 3x3 convolution
        x3 = tf.keras.layers.Conv2D(filters, kernel_size=3, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # 5x5 convolution
        x5 = tf.keras.layers.Conv2D(filters, kernel_size=5, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # Average pooling
        x_avg = tf.keras.layers.AveragePooling2D(3, strides=1, padding='same')(x)
        x_avg = tf.keras.layers.Conv2D(filters, kernel_size=1, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x_avg)
        # Concatenate all feature maps
        x = tf.keras.layers.concatenate([x1, x3, x5, x_avg])
        return x

    # Deformable convolution block
    offsets = []
    for i in range(deformable_groups):
        offsets.append(_offset_filters(inputs, filters, num_deformable_group_conv_filters, kernel_size, deformable_groups))
    x = inputs
    x = tf.keras.layers.DeformableConv2D(filters, kernel_size, strides=strides, padding=padding, use_bias=use_bias, data_format=data_format, deformable_groups=deformable_groups, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4), offset_layer=offsets)(x)
    if multiscale_attention:
        x = _multiscale_attention(x, filters, kernel_size, strides, padding, use_bias, data_format)
    if residual:
        x = tf.keras.layers.add([x, inputs])
    return x

</code>```

I have used the layer in my network as follows:

```<code>conv_2d_01 = deformable_conv2d(inputs, 32,(3,3),multiscale_attention=True, residual=True)

</code>```

And I have ended up in this error:

```<code>TypeError: Exception encountered when calling layer "offset_group_0" (type Reshape).

Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.

Call arguments received by layer "offset_group_0" (type Reshape):
  • inputs=tf.Tensor(shape=(None, 56, 56, 32), dtype=float32)
</code>```

Please anyone spot the mistakes and rectify my code!

Body:
I am trying to build a M-net that involves deformable convolution with multiscale attention and residual mechanism for Retinal Blood Vessel segmentation. Trying this code, led to some errors I can't solve regarding the custom layer.

I have the custom code in TensorFlow for deformable convolution with multiscale attention and residual mechanism.

import tensorflow as tf

def deformable_conv2d(inputs, filters, kernel_size, strides=1, padding='valid', use_bias=True, data_format='channels_last',
                      deformable_groups=1, num_deformable_group_conv_filters=64, multiscale_attention=False, residual=False):
    if isinstance(kernel_size, int):
        kernel_size = (kernel_size, kernel_size)
    if isinstance(strides, int):
        strides = (strides, strides)

    def _offset_filters(inputs, filters, num_deformable_group_conv_filters, kernel_size, deformable_groups):
      x = inputs
      x = tf.keras.layers.Conv2D(num_deformable_group_conv_filters, kernel_size=3, use_bias=True, padding='same', kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
      x = tf.keras.layers.Conv2D(filters, kernel_size=3, use_bias=True, padding='same', kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
      x = tf.keras.layers.Reshape([tf.shape(inputs)[0], kernel_size[0], kernel_size[1], filters], name='offset_group_%d' % i)(x)
      return x

    def _deform_conv(inputs, filters, kernel_size, strides, padding, use_bias, data_format):
        if isinstance(kernel_size, int):
            kernel_size = (kernel_size, kernel_size)
        if isinstance(strides, int):
            strides = (strides, strides)

        x = inputs
        x = tf.keras.layers.Conv2D(filters, kernel_size=kernel_size, strides=strides, padding=padding, use_bias=use_bias, data_format=data_format, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        return x

    def _multiscale_attention(inputs, filters, kernel_size, strides, padding, use_bias, data_format):
        if isinstance(kernel_size, int):
            kernel_size = (kernel_size, kernel_size)
        if isinstance(strides, int):
            strides = (strides, strides)
        x = inputs
        # 1x1 convolution
        x1 = tf.keras.layers.Conv2D(filters, kernel_size=1, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # 3x3 convolution
        x3 = tf.keras.layers.Conv2D(filters, kernel_size=3, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # 5x5 convolution
        x5 = tf.keras.layers.Conv2D(filters, kernel_size=5, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x)
        # Average pooling
        x_avg = tf.keras.layers.AveragePooling2D(3, strides=1, padding='same')(x)
        x_avg = tf.keras.layers.Conv2D(filters, kernel_size=1, padding='same', use_bias=use_bias, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4))(x_avg)
        # Concatenate all feature maps
        x = tf.keras.layers.concatenate([x1, x3, x5, x_avg])
        return x

    # Deformable convolution block
    offsets = []
    for i in range(deformable_groups):
        offsets.append(_offset_filters(inputs, filters, num_deformable_group_conv_filters, kernel_size, deformable_groups))
    x = inputs
    x = tf.keras.layers.DeformableConv2D(filters, kernel_size, strides=strides, padding=padding, use_bias=use_bias, data_format=data_format, deformable_groups=deformable_groups, kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01), kernel_regularizer=tf.keras.regularizers.l2(5e-4), offset_layer=offsets)(x)
    if multiscale_attention:
        x = _multiscale_attention(x, filters, kernel_size, strides, padding, use_bias, data_format)
    if residual:
        x = tf.keras.layers.add([x, inputs])
    return x

I have used the layer in my network as follows:

conv_2d_01 = deformable_conv2d(inputs, 32,(3,3),multiscale_attention=True, residual=True)

And I have ended up in this error:

TypeError: Exception encountered when calling layer "offset_group_0" (type Reshape).

Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.

Call arguments received by layer "offset_group_0" (type Reshape):
  • inputs=tf.Tensor(shape=(None, 56, 56, 32), dtype=float32)

Please anyone spot the mistakes and rectify my code!


问:
Want to stop a specific IIS Site with powershell
Using get-website and save to csv fil. But how to use that data to a list so I can stop a specific IIS site if I got many sites running on same server?

ex a list like this of running websites!

abc.com

def.com

ghi.com

and then run Stop-IISSite -Name $website

Br
Hans

I only no how Get-website to a csv to run!


问:
Firebase/Firestore cloud get year and month from timestamp field
I am trying to get a few fields from a document when its created and save it to a second one. I am succeeding with fields like uid, eventtypeid etc. I also try to save the year and month in the second document. The year and the month are coming from the first documents Idopont field (timestamp type). The code below results NaN-s as a value of the newly created fields.

I have this function so far.

```<code>export const incrementParticipations = functions.firestore
    .document("esemenylatogatasok/{documentId}")
    .onCreate(async (snapshot, context) => {
      const data = snapshot.data();
      if (!data) {
        return;
      }

      const uid = data.uid;
      const eventTypeId = data.EventTypeId;
      const timestamp = data.Idopont;
      if (!uid || !eventTypeId || !timestamp) {
        return;
      }
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = date.getMonth()-1;

      const statsRef = admin.firestore().collection("stats-eventtype");
      const query = statsRef
          .where("uid", "==", uid)
          .where("eventtypeid", "==", eventTypeId)
          .where("year", "==", year)
          .where("month", "==", month)
          .where("period", "==", "month");
      const querySnapshot = await query.get();
      if (querySnapshot.empty) {
        await statsRef.add({
          period: "month",
          uid: uid,
          eventtypeid: eventTypeId,
          year: year,
          month: month,
          participations: 1,
        });
      } else {
        const doc = querySnapshot.docs[0];
        await doc.ref.update({participations: doc.data().participations + 1});
      }
    });

</code>```

Body:
I am trying to get a few fields from a document when its created and save it to a second one. I am succeeding with fields like uid, eventtypeid etc. I also try to save the year and month in the second document. The year and the month are coming from the first documents Idopont field (timestamp type). The code below results NaN-s as a value of the newly created fields.

I have this function so far.

export const incrementParticipations = functions.firestore
    .document("esemenylatogatasok/{documentId}")
    .onCreate(async (snapshot, context) => {
      const data = snapshot.data();
      if (!data) {
        return;
      }

      const uid = data.uid;
      const eventTypeId = data.EventTypeId;
      const timestamp = data.Idopont;
      if (!uid || !eventTypeId || !timestamp) {
        return;
      }
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = date.getMonth()-1;

      const statsRef = admin.firestore().collection("stats-eventtype");
      const query = statsRef
          .where("uid", "==", uid)
          .where("eventtypeid", "==", eventTypeId)
          .where("year", "==", year)
          .where("month", "==", month)
          .where("period", "==", "month");
      const querySnapshot = await query.get();
      if (querySnapshot.empty) {
        await statsRef.add({
          period: "month",
          uid: uid,
          eventtypeid: eventTypeId,
          year: year,
          month: month,
          participations: 1,
        });
      } else {
        const doc = querySnapshot.docs[0];
        await doc.ref.update({participations: doc.data().participations + 1});
      }
    });


问:
axios ignores false value in request header while doing PUT operation
I am trying to pass Boolean variable in the request header of axios like below,

```<code>const var = (data, env, isRetry = false) =>  axios.put(url, data, {
   headers: {
   locale: navigator.language,
  'request-id': new Date().getTime().toString(),
   Authorization: `Bearer ${token}`,
   isRetry: isRetry //true or false
}
});
</code>```

but when isRetry variable is false, it's not appearing in header. Is there any way we can send the false value in header?

```<code>axios-version: 1.1.3
</code>```

Body:
I am trying to pass Boolean variable in the request header of axios like below,

const var = (data, env, isRetry = false) =>  axios.put(url, data, {
   headers: {
   locale: navigator.language,
  'request-id': new Date().getTime().toString(),
   Authorization: `Bearer ${token}`,
   isRetry: isRetry //true or false
}
});

but when isRetry variable is false, it's not appearing in header. Is there any way we can send the false value in header?

axios-version: 1.1.3


问:
Googletrans - AttributeError: 'NoneType' object has no attribute 'group' (python)
Trying to detect language code in Python using googletrans. But it generating ERROR (Refer error block for info).

I read the article below about google trans and did it same thing but still same error occurred.

Python (googletrans) - AttributeError: 'NoneType' object has no attribute 'group'

Version of googletrans is 4.0.0rc1

Code :

```<code>from googletrans import Translator
translator = Translator()

a = translator.translate("hi")
translated_text = a.__dict__()["text"]

print(translated_text)
</code>```

Error:

```<code>File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py:62, in TokenAcquirer._update(self)
     59     return
     61 # this will be the same as python code after stripping out a reserved word 'var'
---> 62 code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
     63 # unescape special ascii characters such like a \x3d(=)
     64 code = code.encode().decode('unicode-escape')

AttributeError: 'NoneType' object has no attribute 'group'
</code>```

Body:
Trying to detect language code in Python using googletrans. But it generating ERROR (Refer error block for info).

I read the article below about google trans and did it same thing but still same error occurred.

Python (googletrans) - AttributeError: 'NoneType' object has no attribute 'group'

Version of googletrans is 4.0.0rc1

Code :

from googletrans import Translator
translator = Translator()

a = translator.translate("hi")
translated_text = a.__dict__()["text"]

print(translated_text)

Error:

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py:62, in TokenAcquirer._update(self)
     59     return
     61 # this will be the same as python code after stripping out a reserved word 'var'
---> 62 code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
     63 # unescape special ascii characters such like a \x3d(=)
     64 code = code.encode().decode('unicode-escape')

AttributeError: 'NoneType' object has no attribute 'group'


问:
How can I use a property defined in a ".properties" file in my "log4j2.json"?
I have an application built using the Spring Framework and written in Java.

I am using the 'log4j' library for logging and have already defined a property, fr.xyz.pathLog = mypath, in my 'dev.properties' file that specifies the file path for my log files.

I would like to use this property in my 'log4j2.json' configuration file to specify the file path for my log files.

However, when I try to use the property in the 'log4j2.json', it does not seem to be recognized.

Is there a way to use properties defined in my 'dev.properties' file in my 'log4j2.json' configuration file ?

I tried using the '${fr.xyz.path}' syntax in the 'log4j2.json' to specify the file path for my log files, but the property was not recognized when I ran the application.

I expected the property to be recognized and used in the configuration, but this did not happen.


问:
When creating a foreign key in firebird, the error violation of the FOREIGN KEY restriction "PK_ROLES1" in the "roles" table comes out?
I am trying to create a foreign key in the user_roles table.It has a user_id and a roles_id. I created a foreign key for user_id. And for roles_id it is not possible to create. I work at ibexpert.
An error comes out: violation of FOREIGN KEY constraint "PK_RULES 1" on table "rules".I will be glad of any help.

alter table "users_roles"
add constraint FK_USERS_ROLES_2
foreign key (ROLE_ID)
references "roles"(ID)
on delete CASCADE
on update CASCADE
using index FK_USERS_ROLES_2
```


问:
How to use config file while generating certificate in .NET?
I have a .cnf file for certificate generating, but i didn't find method, which can help me to use it in certificate generating. How i can do it?

I've tried to import it into X509CertificateBasicConstraintExtension, but i got exception of bad asn1 encoding data...


问:
function which generate random points in polygon in c++ and postgresql

installing PostgreSQL database with spatial extension (POST GIS)

create a table points (X,Y,Z) in the database

in C # or C ++ write a program that will connect to the database

please write a function that will generate random points within the Polish borders and save them in the table
points (at least 1000 points, for the Z value, i.e. the height, please assume the range from 0 to 300 meters)

please write a test that will check if the generated points are at least 3 km apart

please create a voivodship table and import the voivodeship borders there

please write a function that will list all generated points for each province
are included in its outline

SHP FILES with country borders and voivodeship borders:
https://gis-support.pl/baza-wiedzy-2/dane-do-pobrania/granice-administracyjne/
Additional task:

please draw all voivodeships and points in the program window

please color the points in different colors for each province

for the generated points, please perform the triangulation operation and show the result in the program window
main

My question is how am I supposed to write this function in qt by plugin QGIS to c++ or how? I don't understand how I am supposed to do this task. Thanks in advance

I added files with Polish borders and voivodship to postgresql and created x,y,z table.
Then I connected to database via pqxx library.

```<code>
#include <string>
#include <iostream>
#include <pqxx/pqxx>
#include <random>
#include <pqxx/stream_to.hxx>
#include <pqxx/transaction_base.hxx>
#include <pqxx/stream_from.hxx>

int main()
{

    std::string connectionString = "host=localhost port=5432 dbname=test user=postgres password =Kotarba2020";

    try
    {
        pqxx::connection connectionObject(connectionString.c_str());
        pqxx::work worker(connectionObject);

        pqxx::result response = worker.exec("SELECT * FROM Wojewodztwa");

        for (size_t i = 0; i < response.size(); i++)
        {
            std::cout << "Id: " << response[i][0] << " X: " << response[i][1] << " Y: " << response[i][2] << " Z: " << response[i][3] << std::endl;
        }
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
    system("pause");
}

</code>```

Body:
installing PostgreSQL database with spatial extension (POST GIS)

create a table points (X,Y,Z) in the database

in C # or C ++ write a program that will connect to the database

please write a function that will generate random points within the Polish borders and save them in the table
points (at least 1000 points, for the Z value, i.e. the height, please assume the range from 0 to 300 meters)

please write a test that will check if the generated points are at least 3 km apart

please create a voivodship table and import the voivodeship borders there

please write a function that will list all generated points for each province
are included in its outline

SHP FILES with country borders and voivodeship borders:
https://gis-support.pl/baza-wiedzy-2/dane-do-pobrania/granice-administracyjne/
Additional task:

please draw all voivodeships and points in the program window

please color the points in different colors for each province

for the generated points, please perform the triangulation operation and show the result in the program window
main

My question is how am I supposed to write this function in qt by plugin QGIS to c++ or how? I don't understand how I am supposed to do this task. Thanks in advance

I added files with Polish borders and voivodship to postgresql and created x,y,z table.
Then I connected to database via pqxx library.

#include <string>
#include <iostream>
#include <pqxx/pqxx>
#include <random>
#include <pqxx/stream_to.hxx>
#include <pqxx/transaction_base.hxx>
#include <pqxx/stream_from.hxx>

int main()
{

    std::string connectionString = "host=localhost port=5432 dbname=test user=postgres password =Kotarba2020";

    try
    {
        pqxx::connection connectionObject(connectionString.c_str());
        pqxx::work worker(connectionObject);

        pqxx::result response = worker.exec("SELECT * FROM Wojewodztwa");

        for (size_t i = 0; i < response.size(); i++)
        {
            std::cout << "Id: " << response[i][0] << " X: " << response[i][1] << " Y: " << response[i][2] << " Z: " << response[i][3] << std::endl;
        }
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
    system("pause");
}


问:
Save BERTopic model from my vm instance in GCP to my bucket in Google storage
I have trained and saved a Bertopic model in my virtual machine instance in Google Cloud Platform. I want now to move the model to my bucket in Google Cloud Storage.

I have tried to download the model and then upload it on GCS manually but the model is not working. The size of the initial saved model and the downloaded one are different so I assume I ruin the model while downloading it. Did anyone have the same issue?

I am now trying to save the model directly to my bucket in GCS. Has anyone done something similar?


问:
I want to return the top 3 best doing stocks for a selected time period using alphavantage API. is this possible?
I'm working on some project and I would like to make a method that shows the top 3 best doing stocks. However when going through the alphaavantage documentation I don't see a possibility to get all the stocks their information without have to ask them separately with their tokens/symbols.

What would be the best way to handle this?

Thank you


问:
Issues with deeplink with default message
We developed an app for MS Teams that utilizes a bot to interact with users.
One of the cards the bot sends includes a button that opens a chat with another person and fills in a default message. This is the form of the button URL:

https://teams.microsoft.com/l/chat/0/0?users=someone@email.com&message=Hello

It used to work well in the past year and in the last couple of weeks, all of the sudden, it seemed to have stopped working. What happens is, that a new chat is opened with the user as expected, but the message is not filled.

After a short investigation, we discovered that when inputting the URL above directly to the URL bar in the browser - it does work, and the default message appears. Moreover - if go and click on the button in the bot - it will now work as expected and fill the default message. This will continue working until we refresh the page - then it stops working again.

Feel free to watch this screen recording demonstrating the issue (sorry for the foreign language in the first 10 seconds ): https://myquestworld-my.sharepoint.com/:v:/g/personal/roy_myquest_co/EWGmLFZ49r5KlurOsMBeXIYBU1gBmhHmL2n-Cbo144JsOQ?e=2lXKAW

We contacted Office 365 support, and they directed us to this forum. We believe this is a bug in MS Teams, but so far we're not able to get MS to do anything about it.

Does anyone else experience this issue? Anything we can do about it?

Any advice would be appreciated.


问:
How to extract multiple values into select form and then add them again into new table?
```<code>//Connects to the database
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DB);
if($mysqli->connect_errno){
    echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}

if (isset($_POST['points']) & isset($_POST['user'])) {
    if(!($stmt = $mysqli->prepare("INSERT INTO penalty (user_id, first_name, last_name, name, value) VALUES (?, ?, ?, ?, ?);"))){
        echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
    }

    if(!($stmt->bind_param("sssss",$_POST['points'],$_POST['user']))){
        echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
    }

    if(!$stmt->execute()){
        echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
    } else {
        $stmt->close();
        header('Location: GivePoints1.php');
        echo "Added successfully";
        exit();
    }

    $stmt->close();

}
</code>```
```<code><form class="form-horizontal" action="GivePoints1.php" method="post">

    <div class="form-group">
        <label class="control-label col-sm-2">Penalty:</label>
        <select name="points[]" id="points">
            <?php

            //Prepare SELECT statement for user's name
            if(!($stmt = $mysqli->prepare("SELECT name, value FROM points"))){
                echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
            }

            //Execute the SELECT statement
            if(!$stmt->execute()){
                echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Bind values to variables
            if(!$stmt->bind_result($name, $value)){
                echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Output name
            while($stmt->fetch()){
                echo'<option value=" '.$name.' "> '.$name.' - ' . $value .' Pts </option>';
            }

            $stmt->close();
            ?>
            </select>
    </div>

    <div class="form-group">
         <label class="control-label col-sm-2">Give To:</label>
        <select name="user[]" id="user">
            <?php

            //Prepare SELECT statement for user's name
            if(!($stmt = $mysqli->prepare("SELECT id, first_name, last_name FROM award_user"))){
                echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
            }

            //Execute the SELECT statement
            if(!$stmt->execute()){
                echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Bind values to variables
            if(!$stmt->bind_result($id, $first_name, $last_name)){
                echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Output name
            while($stmt->fetch()){
                echo'<option value=" '.$id.' "> '.$first_name.' ' . $last_name .' </option>';
            }

            $stmt->close();
            ?>
            </select>
    </div>

    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-lg btn-primary ">Submit</button>
        </div>
    </div>
</form>
</code>```

Can someone guide me to the right road?

I need to add those values into new table where id  would be user_id (id extracted from award_user table change into user_id in penalty table)

I need to inser id - as user_id, first_name, last_name, name and value into table penalty. it prints select no problem but wouldn't add anything to new table

im trying to do it for a good while now and no luck. i will appriciate some explanation

Body:
//Connects to the database
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DB);
if($mysqli->connect_errno){
    echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}

if (isset($_POST['points']) & isset($_POST['user'])) {
    if(!($stmt = $mysqli->prepare("INSERT INTO penalty (user_id, first_name, last_name, name, value) VALUES (?, ?, ?, ?, ?);"))){
        echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
    }

    if(!($stmt->bind_param("sssss",$_POST['points'],$_POST['user']))){
        echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
    }

    if(!$stmt->execute()){
        echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
    } else {
        $stmt->close();
        header('Location: GivePoints1.php');
        echo "Added successfully";
        exit();
    }

    $stmt->close();

}

<form class="form-horizontal" action="GivePoints1.php" method="post">

        Penalty:
        <select name="points[]" id="points">
            <?php

            //Prepare SELECT statement for user's name
            if(!($stmt = $mysqli->prepare("SELECT name, value FROM points"))){
                echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
            }

            //Execute the SELECT statement
            if(!$stmt->execute()){
                echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Bind values to variables
            if(!$stmt->bind_result($name, $value)){
                echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Output name
            while($stmt->fetch()){
                echo'<option value=" '.$name.' "> '.$name.' - ' . $value .' Pts </option>';
            }

            $stmt->close();
            ?>
            </select>

         Give To:
        <select name="user[]" id="user">
            <?php

            //Prepare SELECT statement for user's name
            if(!($stmt = $mysqli->prepare("SELECT id, first_name, last_name FROM award_user"))){
                echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
            }

            //Execute the SELECT statement
            if(!$stmt->execute()){
                echo "Execute failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Bind values to variables
            if(!$stmt->bind_result($id, $first_name, $last_name)){
                echo "Bind failed: "  . $mysqli->connect_errno . " " . $mysqli->connect_error;
            }

            //Output name
            while($stmt->fetch()){
                echo'<option value=" '.$id.' "> '.$first_name.' ' . $last_name .' </option>';
            }

            $stmt->close();
            ?>
            </select>

            <button type="submit" class="btn btn-lg btn-primary ">Submit</button>

</form>

Can someone guide me to the right road?

I need to add those values into new table where id  would be user_id (id extracted from award_user table change into user_id in penalty table)

I need to inser id - as user_id, first_name, last_name, name and value into table penalty. it prints select no problem but wouldn't add anything to new table

im trying to do it for a good while now and no luck. i will appriciate some explanation