问:
Spring native heap dump
I have a spring-boot web application which uses spring native /graalvm. Is it possible to get a heap dump of such kind of application? I tried to use: visual vm, jconsole, spring-actuator but did not succeed. These 3 options work fine for a non spring native applications. I just want to compare heap utilization of graalvm application and vanilla one.

答:
You can not generate heap dump with jmap or visualVM but you can implement a code block to generate heap dump. here is example code

```<code>import java.text.DateFormat;
import java.util.Date;

public class SVMHeapDump extends Thread {
    static int i = 0;
    static int runs = 60;
    static int sleepTime = 1000;
    @Override
    public void run() {
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()) + ": Thread started, it will run for " + runs + " seconds");
        while (i < runs){
            System.out.println("Sleeping for " + (runs-i) + " seconds." );
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException ie){
                System.out.println("Sleep interrupted.");
            }
            i++;
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        StringBuffer sb1 = new StringBuffer(100);
        sb1.append(DateFormat.getDateTimeInstance().format(new Date()));
        sb1.append(": Hello GraalVM native image developer! \nGet PID of this process: ");
        sb1.append("'ps -C svmheapdump -o pid= '\n");
        sb1.append("then send it signal: ");
        sb1.append("'kill -SIGUSR1 <pid_printed_above>' \n");
        sb1.append("to get heap dump generated into working directory.\n");
        sb1.append("Starting thread!");
        System.out.println(sb1);
        SVMHeapDump t = new SVMHeapDump();
        t.start();
        while (t.isAlive()) {
            t.join(0);
        }
        sb1 = new StringBuffer(100);
        sb1.append(DateFormat.getDateTimeInstance().format(new Date()));
        sb1.append(": Thread finished after: ");
        sb1.append(i);
        sb1.append(" iterations.");
        System.out.println(sb1);
    }
}
</code>```

after you build and run that code you can send the signal with kill -SIGUSR1 100 command.

for further details please check https://www.graalvm.org/reference-manual/native-image/NativeImageHeapdump/

Title: Spring native heap dump

Body:
You can not generate heap dump with jmap or visualVM but you can implement a code block to generate heap dump. here is example code

import java.text.DateFormat;
import java.util.Date;

public class SVMHeapDump extends Thread {
    static int i = 0;
    static int runs = 60;
    static int sleepTime = 1000;
    @Override
    public void run() {
        System.out.println(DateFormat.getDateTimeInstance().format(new Date()) + ": Thread started, it will run for " + runs + " seconds");
        while (i < runs){
            System.out.println("Sleeping for " + (runs-i) + " seconds." );
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException ie){
                System.out.println("Sleep interrupted.");
            }
            i++;
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws InterruptedException {
        StringBuffer sb1 = new StringBuffer(100);
        sb1.append(DateFormat.getDateTimeInstance().format(new Date()));
        sb1.append(": Hello GraalVM native image developer! \nGet PID of this process: ");
        sb1.append("'ps -C svmheapdump -o pid= '\n");
        sb1.append("then send it signal: ");
        sb1.append("'kill -SIGUSR1 <pid_printed_above>' \n");
        sb1.append("to get heap dump generated into working directory.\n");
        sb1.append("Starting thread!");
        System.out.println(sb1);
        SVMHeapDump t = new SVMHeapDump();
        t.start();
        while (t.isAlive()) {
            t.join(0);
        }
        sb1 = new StringBuffer(100);
        sb1.append(DateFormat.getDateTimeInstance().format(new Date()));
        sb1.append(": Thread finished after: ");
        sb1.append(i);
        sb1.append(" iterations.");
        System.out.println(sb1);
    }
}

after you build and run that code you can send the signal with kill -SIGUSR1 100 command.

for further details please check https://www.graalvm.org/reference-manual/native-image/NativeImageHeapdump/


来源: stackexchange

问:
Auto update local webpage when image file is changed?
I'm working on a twitch.tv overlay that generates a word cloud live on-screen based on what I've been saying on stream.

I'm currently using Visual Studio Code with Live Server to display a file via an HTML file alongside a Python script that generates a new png file of the word cloud, using the same filename.

Using the Live Server extension is nice, but I can't help but feel like it's sort of a dirty solution. Any ideas on something more formal?

答: NodeJs and Express could be a good option. The server could be written in Javascript and you could use a sub-process to call your python script on an interval.</p>

ContentLicense: CC BY-SA 4.0


问:
What is suspendCoroutine?
I am a beginner studying coroutines.

Not exactly, but I have a little understanding of what a coroutine is.

The suspend function is also difficult, but with a little understanding.

I'm studying step by step, but there are parts I don't understand.

That's suspendCoroutine. In the sample code, suspendCoroutine and Continuation used in the block appear, but I have no idea what these two are.

I've looked on other sites, but I can't find anywhere that explains it easily.

Can you explain what suspendCoroutine and Continuation are used for easily and, if possible, with an example?

答:
suspendCoroutine is a builder function that mainly used to convert callbacks into suspend functions. Let's say for example you have some legacy (or not) Api, that uses callbacks. You can easily transform it into a suspend function to call it in a coroutine. For example:

```<code>suspend fun getUser(id: String): User  = suspendCoroutine { continuation ->
      Api.getUser(id) { user ->
          continuation.resume(user)
      }
}
</code>```

Here we have an Api function getUser, which defined in Api class for example like this:

```<code>fun getUser(id: String, callback: (User) -> Unit) {...}
</code>```

suspendCoroutine suspends coroutine in which it executed until we decide to continue by calling appropriate methods - Continuation.resume....
suspendCoroutine mainly used when we have some legacy code with callbacks.

Using suspendCoroutine to convert callbacks into suspend functions makes the code sequential when you work with suspend functions.

For example instead of having a callback hell like this:

```<code>Api.getUser(id) { user ->
      Api.getProfile(user) { profile ->
          Api.downloadImage(profile.imageId) { image ->
              // ...
          }
      }
}
</code>```

after you apply suspendCoroutine to those callbacks and convert them into suspend functions, the code will look like the following:

```<code>val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...
</code>```

Title: What is suspendCoroutine?

Body:
suspendCoroutine is a builder function that mainly used to convert callbacks into suspend functions. Let's say for example you have some legacy (or not) Api, that uses callbacks. You can easily transform it into a suspend function to call it in a coroutine. For example:

suspend fun getUser(id: String): User  = suspendCoroutine { continuation ->
      Api.getUser(id) { user ->
          continuation.resume(user)
      }
}

Here we have an Api function getUser, which defined in Api class for example like this:

fun getUser(id: String, callback: (User) -> Unit) {...}

suspendCoroutine suspends coroutine in which it executed until we decide to continue by calling appropriate methods - Continuation.resume....
suspendCoroutine mainly used when we have some legacy code with callbacks.

Using suspendCoroutine to convert callbacks into suspend functions makes the code sequential when you work with suspend functions.

For example instead of having a callback hell like this:

Api.getUser(id) { user ->
      Api.getProfile(user) { profile ->
          Api.downloadImage(profile.imageId) { image ->
              // ...
          }
      }
}

after you apply suspendCoroutine to those callbacks and convert them into suspend functions, the code will look like the following:

val user = getUser(id)
val profile = getProfile(user)
val image = downloadImage(profile.imageId)
//...


问:
Pandas dataframe group by 10 min intervals with different actions on other columns
I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:

```<code>              timestamp           |close_price|highest_price|volume| ...
              2018-09-29 00:00:20 |1809       |1811         |  ... |
              2018-09-29 00:00:34 |1823       |1832         |
              2018-09-29 00:00:59 |1832       |1863         |
              2018-09-29 00:01:09 |1800       |1802         |
              2018-09-29 00:01:28 |1832       |1845         |
              .
              .
              .
</code>```

I want to put the data into 10 min intervals and I want to do separate operations on each column, for example I want the 10 min intervals of close_price column to show the last value of the corresponding range in the real table, or for the highest_price column, I want the max value of the corresponding range, or for volume I want the mean of the values in that range. I already tried

```<code>dataTable = datefram.resample("10min").agg({'first_price':'first',
                                       'close_price':'last',
                                       'highest_price': 'max',
                                       'volume':'mean',
                                        #other attributes...
                                        })
</code>```

but the result seems to be incorrect.
Is there any other ways to do what I want to do?
I will appreciate any comments or thoughts.

Note that there is no specific pattern in timestamp values. In 1 minute, we can have 0 to 60 rows.

答:
Your approach is correct. The
 dataframe.resample("10min").agg() does the calculations for you.
You might get more outputs than what you expect and that is because of this: resample method continuously adds 10 minutes to the time and does the calculations that you asked. But if there was no data in any of the 10 min intervals, it creates a NULL row. Maybe your data is not continuous and causes this Null rows.

You can simply delete the NULL rows by using dataframe.dropna()

Body:
I have a pandas dataframe which includes a timestamp and 71 other columns, something like this:

              timestamp           |close_price|highest_price|volume| ...
              2018-09-29 00:00:20 |1809       |1811         |  ... |
              2018-09-29 00:00:34 |1823       |1832         |
              2018-09-29 00:00:59 |1832       |1863         |
              2018-09-29 00:01:09 |1800       |1802         |
              2018-09-29 00:01:28 |1832       |1845         |
              .
              .
              .

I want to put the data into 10 min intervals and I want to do separate operations on each column, for example I want the 10 min intervals of close_price column to show the last value of the corresponding range in the real table, or for the highest_price column, I want the max value of the corresponding range, or for volume I want the mean of the values in that range. I already tried

dataTable = datefram.resample("10min").agg({'first_price':'first',
                                       'close_price':'last',
                                       'highest_price': 'max',
                                       'volume':'mean',
                                        #other attributes...
                                        })

but the result seems to be incorrect.
Is there any other ways to do what I want to do?
I will appreciate any comments or thoughts.

Note that there is no specific pattern in timestamp values. In 1 minute, we can have 0 to 60 rows.


问:
SUMIFS where one of the conditions is at the top of table | Microsoft Excel
Sample: Two tables in one excel sheet.

Criteria 1:

```<code>ColumnA | ColumnB
Name    | Amount
John    | 3
Smith   | 2
John    | 6
</code>```

Criteria 2:

```<code>Name    | Amount
John    | 10
Smith   | 20
</code>```

I would like to perform => SUMIFS range is B:B and where the table name is "Criteria 1".

Note: there are a lot more names and criteria #.

答:
Formula in E2

```<code> =SUMIFS($B$2:$B$100;$A$2:$A$100;D2)
</code>```

Maybe good to convert your data to a standard table, so the formula will update when you add more data to it.

Body:
Sample: Two tables in one excel sheet.

Criteria 1:

ColumnA | ColumnB
Name    | Amount
John    | 3
Smith   | 2
John    | 6

Criteria 2:

Name    | Amount
John    | 10
Smith   | 20

I would like to perform => SUMIFS range is B:B and where the table name is "Criteria 1".

Note: there are a lot more names and criteria #.

Body:
Formula in E2

 =SUMIFS($B$2:$B$100;$A$2:$A$100;D2)

Maybe good to convert your data to a standard table, so the formula will update when you add more data to it.


问:
Question on R Shiny gets table click information from lineups
I am trying to get the table row information (such as row name. number, or cell value) when I click the lineup table, but I don;t know how. Can someonle help with it? Any input will be greatly appreciated.

The following is my sample code to show the problem

```<code>library(shiny)
library(crosstalk)
library(lineupjs)
library(magrittr)

ui <- fluidPage(
  splitLayout(
    column(12,
        lineupOutput("table1", height=300),
        textInput("val1", "Value1", "Tobeupdated1")
    ),
    column(12,
        DT::dataTableOutput("table2"),
        textInput("val2", "Value2", "Tobeupdated2")
    )
  )
)

server <- function(input, output,session) {
  dfshow <- head(iris,n=5)

  shared_iris <- SharedData$new(dfshow)
 t<-1

  output$table1 <- renderLineup({
    lineup(shared_iris)
  })

  output$table2<- DT::renderDT(dfshow, selection = 'single', rownames = FALSE,  editable = TRUE)

  observeEvent(input$table1_rows_selected,{
    rowIndex <- input$table1_rows_selected
    updateTextInput(session, "val1", value = as.character(input$table1_rows_selected))
  })

  observeEvent(input$table2_rows_selected,{
    rowIndex <- input$table2_rows_selected
    updateTextInput(session, "val2", value = as.character(input$table2_rows_selected))
  })

}
shinyApp(ui = ui, server = server)
</code>```

What I want is when I click the lineup table1, I want to update the value below the table1, like as the one on the right. Thanks.

答:
It's hidden in the shared_iris$selection() method.

Do something like this:

library(shiny)
library(crosstalk)
library(lineupjs)
library(magrittr)

ui <- fluidPage(
    splitLayout(
        column(12,
               lineupOutput("table1", height=300),
               textInput("val1", "Value1", "Tobeupdated1")
        ),
        column(12,
               DT::dataTableOutput("table2"),
               textInput("val2", "Value2", "Tobeupdated2")
        )
    )
)

server <- function(input, output,session) {
    dfshow <- head(iris,n=5)

    shared_iris <- SharedData$new(dfshow)
    t<-1

    output$table1 <- renderLineup({
        lineup(shared_iris)
    })

    output$table2<- DT::renderDT(dfshow, selection = 'single', rownames = FALSE,  editable = TRUE)

    observeEvent(shared_iris$selection(),{
        rowIndex <- which(shared_iris$selection())
        updateTextInput(session, "val1", value = as.character(rowIndex))
    })

    observeEvent(input$table2_rows_selected,{
        rowIndex <- input$table2_rows_selected
        updateTextInput(session, "val2", value = as.character(input$table2_rows_selected))
    })

}
shinyApp(ui = ui, server = server)
```

Body:
I am trying to get the table row information (such as row name. number, or cell value) when I click the lineup table, but I don;t know how. Can someonle help with it? Any input will be greatly appreciated.

The following is my sample code to show the problem

library(shiny)
library(crosstalk)
library(lineupjs)
library(magrittr)

ui <- fluidPage(
  splitLayout(
    column(12,
        lineupOutput("table1", height=300),
        textInput("val1", "Value1", "Tobeupdated1")
    ),
    column(12,
        DT::dataTableOutput("table2"),
        textInput("val2", "Value2", "Tobeupdated2")
    )
  )
)

server <- function(input, output,session) {
  dfshow <- head(iris,n=5)

  shared_iris <- SharedData$new(dfshow)
 t<-1

  output$table1 <- renderLineup({
    lineup(shared_iris)
  })

  output$table2<- DT::renderDT(dfshow, selection = 'single', rownames = FALSE,  editable = TRUE)

  observeEvent(input$table1_rows_selected,{
    rowIndex <- input$table1_rows_selected
    updateTextInput(session, "val1", value = as.character(input$table1_rows_selected))
  })

  observeEvent(input$table2_rows_selected,{
    rowIndex <- input$table2_rows_selected
    updateTextInput(session, "val2", value = as.character(input$table2_rows_selected))
  })

}
shinyApp(ui = ui, server = server)

What I want is when I click the lineup table1, I want to update the value below the table1, like as the one on the right. Thanks.


问:
Array reversal in C language using while loop
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}
</code>```

答:
Sound like you have an index out of bounds error.

Using -fsanitize=address immediately confirms this.

=================================================================
==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000020 at pc 0x000000401360 bp 0x7ffe26e3f5d0 sp 0x7ffe26e3f5c8
READ of size 4 at 0x602000000020 thread T0
    #0 0x40135f in main /app/example.c:21
    #1 0x7f3912c3f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x4010fd in _start (/app/output.s+0x4010fd)

0x602000000020 is located 0 bytes to the right of 16-byte region [0x602000000010,0x602000000020)
allocated by thread T0 here:
    #0 0x7f3912ec531f in malloc (/opt/compiler-explorer/gcc-snapshot/lib64/libasan.so.8+0xbb31f)
    #1 0x401282 in main /app/example.c:9
    #2 0x7f3912c3f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)

[snip]
```
<p>It even tells us which line the immediate cause of the problem is found (line 21).</p>
<hr />
<p>Adding</p>
<pre class="lang-c prettyprint-override"><code>fprintf(stderr, "Swapping %d and %d.\n", l_Count, h_Count);
</code>```

gives

Swapping 0 and 3.
Swapping 1 and 2.
Swapping 2 and 1.
Swapping 3 and 0.
Swapping 4 and -1.
```

So we found the immediate cause of the problem: The array has no elements at index 4 or -1. The program should have stopped after swapping 0 and 3. Why didn't it? As homework, the fix is left to you.

Body:
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}

Body:
Sound like you have an index out of bounds error.

Using -fsanitize=address immediately confirms this.

=================================================================
==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000020 at pc 0x000000401360 bp 0x7ffe26e3f5d0 sp 0x7ffe26e3f5c8
READ of size 4 at 0x602000000020 thread T0
    #0 0x40135f in main /app/example.c:21
    #1 0x7f3912c3f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x4010fd in _start (/app/output.s+0x4010fd)

0x602000000020 is located 0 bytes to the right of 16-byte region [0x602000000010,0x602000000020)
allocated by thread T0 here:
    #0 0x7f3912ec531f in malloc (/opt/compiler-explorer/gcc-snapshot/lib64/libasan.so.8+0xbb31f)
    #1 0x401282 in main /app/example.c:9
    #2 0x7f3912c3f0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)

[snip]

It even tells us which line the immediate cause of the problem is found (line 21).

Adding

fprintf(stderr, "Swapping %d and %d.\n", l_Count, h_Count);

gives

Swapping 0 and 3.
Swapping 1 and 2.
Swapping 2 and 1.
Swapping 3 and 0.
Swapping 4 and -1.

So we found the immediate cause of the problem: The array has no elements at index 4 or -1. The program should have stopped after swapping 0 and 3. Why didn't it? As homework, the fix is left to you.


问:
Error Connection Time Out after Certbot certificate installation
I have installed Certbot certificate using certbot --apache. Installation was successful, now i'm unable to access my site over https.

When I hit command openssl s_client -connect localhost:443 -servername on server itself it gives Connected (00000005)

My site accessible over http. But unable to access over https.

Any help would be helpful.

答:
Thanks Sodium for the solution! Here are the actual steps to follow:

[1] Log in to AWS > EC2 Dashboard > Instances

[2] Select your instance. Under the instance summary information, select the "Security" tab. Click the "Security groups" link.

[3] Under Inbound rules > select "edit inbound rules" > select "add rule"

[4] Select: Type = Custom TCP >> Port range = 443 >> Source = custom >> 0.0.0.0/0

[5] Select "save rules" >> Refresh your site.

I spent well over 6 hours on this to realize it was an AWS issue, not an Apache server configuration issue.


问:
Web Worker not working when importing module, even while using worker-loader
I'm trying to make a web worker to prevent stalling the React main thread.  The worker is supposed to read an image and do various things.

The app was created using create-react-app.

Currently I have

webpack.config.js

```<code>module.exports = {
    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                use: { loader: 'worker-loader' }
            }
        ]
    }
};
</code>```

WebWorker.js

```<code>export default class WebWorker {
    constructor(worker) {
        const code = worker.toString();
        const blob = new Blob(['('+code+')()'], {type: "text/javascript"});
        return new Worker(URL.createObjectURL(blob),  {type: 'module'});
    }
}
</code>```

readimage.worker.js

```<code>import Jimp from "jimp";

export default () => {
    self.addEventListener('message', e => { // eslint-disable-line no-restricted-globals
        if (!e) return;
        console.log('Worker reading pixels for url', e.data);
        let data = {};

        Jimp.read(e.data).then(image => {
            // jimp does stuff
            console.log('Worker Finished processing image');
        })

        postMessage(data);
    })
};
</code>```

And then in my React component AppContent.js I have

```<code>import WebWorker from "./workers/WebWorker";
import readImageWorker from './workers/readimage.worker.js';

export default function AppContent() {
    const readWorker = new ReadImageWorker(readImageWorker);
    readWorker.addEventListener('message', event => {
        console.log('returned data', event.data);
        setState(data);
    });

    // callback that is executed onClick from a button component
    const readImageContents = (url) => {
        readWorker.postMessage(url);
        console.log('finished reading pixels');
    };
}
</code>```

But when I run it, I get the error

Uncaught ReferenceError: jimp__WEBPACK_IMPORTED_MODULE_0__ is not defined

How can I properly import a module into a web worker?

答:
In my next.js typescript project, I use this code and answer in my use case:

function in onClick prop on the element at next.js

```<code>async () => {
  const testWorker = new Worker(
    new URL("./test.worker.ts", import.meta.url), {
      name: "test",
      type: "module",
    });
  testWorker.onmessage = function (event) {
    console.log("data:", event.data, "\n", "event:", event);
  };

  testWorker.postMessage([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
}

</code>```

test.worker.ts

```<code>self.onmessage = function ({ data }) {
  self.postMessage((data as number[]).map((d) => d * 10));
};

export {};
</code>```

Body:
I'm trying to make a web worker to prevent stalling the React main thread.  The worker is supposed to read an image and do various things.

The app was created using create-react-app.

Currently I have

webpack.config.js

module.exports = {
    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                use: { loader: 'worker-loader' }
            }
        ]
    }
};

WebWorker.js

export default class WebWorker {
    constructor(worker) {
        const code = worker.toString();
        const blob = new Blob(['('+code+')()'], {type: "text/javascript"});
        return new Worker(URL.createObjectURL(blob),  {type: 'module'});
    }
}

readimage.worker.js

import Jimp from "jimp";

export default () => {
    self.addEventListener('message', e => { // eslint-disable-line no-restricted-globals
        if (!e) return;
        console.log('Worker reading pixels for url', e.data);
        let data = {};

        Jimp.read(e.data).then(image => {
            // jimp does stuff
            console.log('Worker Finished processing image');
        })

        postMessage(data);
    })
};

And then in my React component AppContent.js I have

import WebWorker from "./workers/WebWorker";
import readImageWorker from './workers/readimage.worker.js';

export default function AppContent() {
    const readWorker = new ReadImageWorker(readImageWorker);
    readWorker.addEventListener('message', event => {
        console.log('returned data', event.data);
        setState(data);
    });

    // callback that is executed onClick from a button component
    const readImageContents = (url) => {
        readWorker.postMessage(url);
        console.log('finished reading pixels');
    };
}

But when I run it, I get the error

Uncaught ReferenceError: jimp__WEBPACK_IMPORTED_MODULE_0__ is not defined

How can I properly import a module into a web worker?

Body:
In my next.js typescript project, I use this code and answer in my use case:

function in onClick prop on the element at next.js

async () => {
  const testWorker = new Worker(
    new URL("./test.worker.ts", import.meta.url), {
      name: "test",
      type: "module",
    });
  testWorker.onmessage = function (event) {
    console.log("data:", event.data, "\n", "event:", event);
  };

  testWorker.postMessage([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
}

test.worker.ts

self.onmessage = function ({ data }) {
  self.postMessage((data as number[]).map((d) => d * 10));
};

export {};


问:
Discord bot problem, AttributeError: 'Bot' object has no attribute 'channel'
I cant really explain what all of this does, because ive been kinda learning over time and most of this is older code, however when i tried to make a leveling system it was giving me the error 'AttributeError: 'Bot' object has no attribute 'channel''

So far, i have figured out that (at least i think) that it is most likely related to this: client=commands.Bot(command_prefix="!") bot = client

and maybe this: @client.event async def on_message(message): if message.author == client.user: return print("{} sent a message".format(message.author.name)) if message.content.lower().startswith("!lvl"): msg = "You have {} points!".format(get_points(message.author)) await client.process_commands(client.channel,msg) add_points(message.author, 1)

but as i said before i really dont know how to fix this.

Here is the code if needed:

```<code>import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
#import _sqlite3
#import db_sqlite3
import sqlite3
import asyncio
import urlparse3

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client=commands.Bot(command_prefix="!")
bot = client
##### START LEVEL COMMAND #####

try:
    with open("users.json") as fp:
        users = json.load(fp)
except Exception:
    users = {}

def save_users():
    with open("users.json", "w+") as fp:
        json.dump(users, fp, sort_keys=True, indent=4)

def add_points(user: discord.User, points: int):
    id = user.id
    if id not in users:
        users[id] = {}
    users[id]["points"] = users[id].get("points", 0) + points
    print("{} now has {} points".format(user.name, users[id]["points"]))
    save_users()

def get_points(user: discord.User):
    id = user.id
    if id in users:
        return users[id].get("points", 0)
    return 0

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    print("{} sent a message".format(message.author.name))
    if message.content.lower().startswith("!lvl"):
        msg = "You have {} points!".format(get_points(message.author))
        await client.process_commands(client.channel,msg)
    add_points(message.author, 1)

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to Coded Chat, a place for having fun, and playing games!'
    )

client.run(TOKEN)
</code>```

答: The problem is, that you call process_commands with client.channel which doesn't exist. It should just be client.process_command(message)

Body:
I cant really explain what all of this does, because ive been kinda learning over time and most of this is older code, however when i tried to make a leveling system it was giving me the error 'AttributeError: 'Bot' object has no attribute 'channel''

So far, i have figured out that (at least i think) that it is most likely related to this: client=commands.Bot(command_prefix="!") bot = client

and maybe this: @client.event async def on_message(message): if message.author == client.user: return print("{} sent a message".format(message.author.name)) if message.content.lower().startswith("!lvl"): msg = "You have {} points!".format(get_points(message.author)) await client.process_commands(client.channel,msg) add_points(message.author, 1)

but as i said before i really dont know how to fix this.

Here is the code if needed:

import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import json
#import _sqlite3
#import db_sqlite3
import sqlite3
import asyncio
import urlparse3

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client=commands.Bot(command_prefix="!")
bot = client
##### START LEVEL COMMAND #####

try:
    with open("users.json") as fp:
        users = json.load(fp)
except Exception:
    users = {}

def save_users():
    with open("users.json", "w+") as fp:
        json.dump(users, fp, sort_keys=True, indent=4)

def add_points(user: discord.User, points: int):
    id = user.id
    if id not in users:
        users[id] = {}
    users[id]["points"] = users[id].get("points", 0) + points
    print("{} now has {} points".format(user.name, users[id]["points"]))
    save_users()

def get_points(user: discord.User):
    id = user.id
    if id in users:
        return users[id].get("points", 0)
    return 0

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    print("{} sent a message".format(message.author.name))
    if message.content.lower().startswith("!lvl"):
        msg = "You have {} points!".format(get_points(message.author))
        await client.process_commands(client.channel,msg)
    add_points(message.author, 1)

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to Coded Chat, a place for having fun, and playing games!'
    )

client.run(TOKEN)


问:
problem in TCPDF output in webview android with php
I got an apk output from my software as a web view. Everything works fine, but when I want to get a pdf output with this function, it gives me a blank pdf.

normally everything is fine and the pdf output is completely healthy and there is no problem

Has anyone ever had this problem to guide me

```<code>function pdfWorker($record)
{
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, array(400, 500), PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    $lg = array();
    $lg['a_meta_charset'] = 'UTF-8';
    $lg['a_meta_dir'] = 'rtl';
    $lg['a_meta_language'] = 'fa';
    $lg['w_page'] = 'page';
    $pdf->setLanguageArray($lg);
    $pdf->SetFont('xyekan', '', 12);
    $pdf->AddPage();
    $tbl_header = '<table cellspacing="0" cellpadding="2" border=".5" style="border-color:gray;">
                <tr style="background-color:#686D76;color:white;">
                <td width="10%">درخواست کننده</td>
                <td width="10%">تاریخ اعلام نیاز</td>
                <td width="10%">تعداد کارگران</td>
                <td width="10%">موقعیت کاری</td>
                <td width="40%">شرح کار</td>
                <td width="10%">تاریخ نیاز</td>
                <td width="10%">تاییده مدیریت</td>
                </tr>';
    $tbl_footer = '</table>';
    $tbl = '';
    foreach ($record as $row) {
        $userSender = $row['fullname'];
        $dateRequest = $row['dateRequest'];
        $workerNumber = $row['workerNumber'];
        $location = $row['location'];
        $description = $row['description'];
        $dateNeed = $row['dateNeed'];
        if ($row['confirm'] != null) {
            $confirm = $row['confirm'];
        } else {
            $confirm = "مورد تایید";
        }
        $tbl .=
            '
            <tr>
            <td>' . $userSender . '</td>
            <td>' . $dateRequest . '</td>
            <td>' . $workerNumber . '</td>
            <td>' . $location . '</td>
            <td>' . $description . '</td>
            <td>' . $dateNeed . '</td>
            <td>' . $confirm . '</td>
            </tr>
';
    }
    $fileName = generateHash(5);
    $pdf->writeHTML($tbl_header . $tbl . $tbl_footer, true, false, true, false);
    $pdf->Output($fileName, 'D');
    return;
}
</code>```

答:
For android app (and / or iOS app) using webview to display a pdf, please

save the pdf into your server (instead of forcing a download)

So , change this line

```<code> $pdf->Output($fileName, 'D');
</code>```

to

```<code> $pdf->Output($fileName, 'F');
</code>```

Then, please use the following code to trigger a pdf viewer
(make sure url=xxxxxx.pdf is valid, for example, change to url=http://www.yourdomainname.com/pdffilename.pdf) to view the generated pdf.

```<code><embed src="https://drive.google.com/viewerng/viewer?embedded=true&url=xxxxxx.pdf" with="100%" height="375"></embed>
</code>```

Body:
I got an apk output from my software as a web view. Everything works fine, but when I want to get a pdf output with this function, it gives me a blank pdf.

normally everything is fine and the pdf output is completely healthy and there is no problem

Has anyone ever had this problem to guide me

function pdfWorker($record)
{
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, array(400, 500), PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    $lg = array();
    $lg['a_meta_charset'] = 'UTF-8';
    $lg['a_meta_dir'] = 'rtl';
    $lg['a_meta_language'] = 'fa';
    $lg['w_page'] = 'page';
    $pdf->setLanguageArray($lg);
    $pdf->SetFont('xyekan', '', 12);
    $pdf->AddPage();
    $tbl_header = '

                درخواست کننده
                تاریخ اعلام نیاز
                تعداد کارگران
                موقعیت کاری
                شرح کار
                تاریخ نیاز
                تاییده مدیریت

';
    $tbl_footer = '
';
    $tbl = '';
    foreach ($record as $row) {
        $userSender = $row['fullname'];
        $dateRequest = $row['dateRequest'];
        $workerNumber = $row['workerNumber'];
        $location = $row['location'];
        $description = $row['description'];
        $dateNeed = $row['dateNeed'];
        if ($row['confirm'] != null) {
            $confirm = $row['confirm'];
        } else {
            $confirm = "مورد تایید";
        }
        $tbl .=
            '

            ' . $userSender . '
            ' . $dateRequest . '
            ' . $workerNumber . '
            ' . $location . '
            ' . $description . '
            ' . $dateNeed . '
            ' . $confirm . '

';
    }
    $fileName = generateHash(5);
    $pdf->writeHTML($tbl_header . $tbl . $tbl_footer, true, false, true, false);
    $pdf->Output($fileName, 'D');
    return;
}

Body:
For android app (and / or iOS app) using webview to display a pdf, please

save the pdf into your server (instead of forcing a download)

So , change this line

 $pdf->Output($fileName, 'D');

to

 $pdf->Output($fileName, 'F');

Then, please use the following code to trigger a pdf viewer
(make sure url=xxxxxx.pdf is valid, for example, change to url=http://www.yourdomainname.com/pdffilename.pdf) to view the generated pdf.

<embed src="https://drive.google.com/viewerng/viewer?embedded=true&url=xxxxxx.pdf" with="100%" height="375"></embed>


问:
Create different disconnected graphs from a set of fixed nodes in NetworkX
I have the following set of nodes:

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Using networkx package, I want to create 4 random connected graphs where each contain 5 nodes from the above list in such a way that the label of the node should appear in the newly formed graph.

For example:

subgraph_1 = [1, 5, 9, 13, 17]

subgraph_2 = [2, 6, 10, 14, 18]

subgraph_3 = [3, 7, 11, 15, 19]

subgraph_4 = [4, 8, 12, 16, 20]

Is there a way to accomplish this using the built in packages functions of networkx? I could not locate anything in the documentation.

Another way that this could work is that, I can create a random graph with 20 nodes using: G=nx.erdos_renyi_graph(n=20,p=0.1) but then I would be needing to divide this into random 4 subgraphs with each one having 5 nodes. The edges can be regenerated randomly and do not have to be linked or similar to the edges of the main graph G.

答:
A way to do that that is by creating 4 random networks of size 5 using the nx.erdos_renyi_graph function. For each network, you can randomly pick without replacement 5 nodes from your vector n and relabel the nodes of the network with the random nodes.

See code below:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

N=20
n=np.arange(N)+1

#randomly permuting nodes
random_n=np.random.permutation(n)

N_graphs=4
N_nodes=5
#assign the random modes to each graph
random_graphs_nodes=[random_n[N_nodes*i:N_nodes*(i+1)] for i in range(N_graphs)]

#create random graphs
r_g=[nx.erdos_renyi_graph(n=N_nodes,p=0.5) for _ in range(N_graphs)]

#relabel the nodes in each graph according to random_graphs_nodes
mappings=[]
for i in range(N_graphs):
  mappings.append({j:str(random_graphs_nodes[i][j]) for j in range(N_nodes)})
  r_g[i]=nx.relabel_nodes(r_g[i], mappings[i])

#plot result
fig=plt.figure(figsize=(15,6))
colors=['tab:blue','tab:orange','tab:green','tab:pink']
for i in range(N_graphs):
  plt.subplot(1,4,i+1)
  plt.title('Graph '+str(i+1))
  pos=nx.circular_layout(r_g[i])
  nx.draw(r_g[i],pos=pos,with_labels=True,node_color=colors[i])
```

And the output gives:

Body:
A way to do that that is by creating 4 random networks of size 5 using the nx.erdos_renyi_graph function. For each network, you can randomly pick without replacement 5 nodes from your vector n and relabel the nodes of the network with the random nodes.

See code below:

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

N=20
n=np.arange(N)+1

#randomly permuting nodes
random_n=np.random.permutation(n)

N_graphs=4
N_nodes=5
#assign the random modes to each graph
random_graphs_nodes=[random_n[N_nodes*i:N_nodes*(i+1)] for i in range(N_graphs)]

#create random graphs
r_g=[nx.erdos_renyi_graph(n=N_nodes,p=0.5) for _ in range(N_graphs)]

#relabel the nodes in each graph according to random_graphs_nodes
mappings=[]
for i in range(N_graphs):
  mappings.append({j:str(random_graphs_nodes[i][j]) for j in range(N_nodes)})
  r_g[i]=nx.relabel_nodes(r_g[i], mappings[i])

#plot result
fig=plt.figure(figsize=(15,6))
colors=['tab:blue','tab:orange','tab:green','tab:pink']
for i in range(N_graphs):
  plt.subplot(1,4,i+1)
  plt.title('Graph '+str(i+1))
  pos=nx.circular_layout(r_g[i])
  nx.draw(r_g[i],pos=pos,with_labels=True,node_color=colors[i])

And the output gives:


问:
Overlay of annotation circle in Map - SwiftUI
I want to add a circle with a certain radius in Map with SwiftUI only. I want to be able to show a circular overlay in the Map with e.g. 1 km. This is a picture what I want to achieve:

The problem with the code below, is that the circle has a fixed size on the map:

```<code>import SwiftUI
import MapKit

struct ContentView: View {
    static let usersLocation = CLLocationCoordinate2D(latitude: 52.0929779694589, longitude: 5.084964426384347)

    @State private var region = MKCoordinateRegion(
        center: ContentView.usersLocation,
        span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
    )
    let annotations = [CurrentUsersAnnotation()]

    var body: some View {
        Map(
            coordinateRegion: $region, annotationItems: annotations) { _ in
                MapAnnotation(coordinate: ContentView.usersLocation) {
                    Circle()
                            .strokeBorder(Color.red, lineWidth: 4)
                            .frame(width: 40, height: 40)
                }
            }
    }
}

struct CurrentUsersAnnotation: Identifiable {
    let id = UUID() // Always unique on map
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Is there a SwiftUI-only fix? I am not looking for UIKit answers, I want to do it fully in SwiftUI.

答:
Overlays aren't supported but you can easily size your View/Circle by figuring out the ratio between the View and the span

First, since you want kilometers you can calculate the distance between the upper and lower edge (latitude span) of the region.

```<code>extension MKCoordinateRegion{
    ///Identify the length of the span in meters north to south
    var spanLatitude: Measurement<UnitLength>{
        let loc1 = CLLocation(latitude: center.latitude - span.latitudeDelta * 0.5, longitude: center.longitude)
        let loc2 = CLLocation(latitude: center.latitude + span.latitudeDelta * 0.5, longitude: center.longitude)
        let metersInLatitude = loc1.distance(from: loc2)
        return Measurement(value: metersInLatitude, unit: UnitLength.meters)
    }
}
</code>```

using GeometryReader you can get the height of the View/Map, then the ratio. Once you have the size per meter just multiply to get kilometer.

```<code>//Size per meter
let ratio = (geo.size.height/region.spanLatitude.value)
//Size per kilometer
let kilometerSize = ratio * 1000
</code>```

Then use the kilometerSize in the frame.

It is likely not be a perfect kilometer given there are likely inconsistencies between the View and the Map but it is probably pretty close. If you can find something that is a known kilometer you can test it out.

```<code>struct ScaledAnnotationView: View {
    static let usersLocation = CLLocationCoordinate2D(latitude: 52.0929779694589, longitude: 5.084964426384347)

    @State private var region = MKCoordinateRegion(
        center: ScaledAnnotationView.usersLocation,latitudinalMeters: 1000, longitudinalMeters: 1000
    )
    let annotations = [CurrentUsersAnnotation()]

    var body: some View {
        //Get the size of the frame for scale
        GeometryReader{ geo in
            Map(
                coordinateRegion: $region, annotationItems: annotations) { _ in
                    MapAnnotation(coordinate: ScaledAnnotationView.usersLocation) {
                            //Size per kilometer or any unit, just change the converted unit.
                            let kilometerSize = (geo.size.height/region.spanLatitude.converted(to: .kilometers).value)
                        Circle()
                            .fill(Color.red.opacity(0.5))
                        //Keep it a circle
                            .frame(width: kilometerSize, height: kilometerSize)
                    }
                }
        }
    }
}
</code>```

Here is  Google maps distance measurement for confirmation of measurement

Body:
I want to add a circle with a certain radius in Map with SwiftUI only. I want to be able to show a circular overlay in the Map with e.g. 1 km. This is a picture what I want to achieve:

The problem with the code below, is that the circle has a fixed size on the map:

import SwiftUI
import MapKit

struct ContentView: View {
    static let usersLocation = CLLocationCoordinate2D(latitude: 52.0929779694589, longitude: 5.084964426384347)

    @State private var region = MKCoordinateRegion(
        center: ContentView.usersLocation,
        span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
    )
    let annotations = [CurrentUsersAnnotation()]

    var body: some View {
        Map(
            coordinateRegion: $region, annotationItems: annotations) { _ in
                MapAnnotation(coordinate: ContentView.usersLocation) {
                    Circle()
                            .strokeBorder(Color.red, lineWidth: 4)
                            .frame(width: 40, height: 40)
                }
            }
    }
}

struct CurrentUsersAnnotation: Identifiable {
    let id = UUID() // Always unique on map
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Is there a SwiftUI-only fix? I am not looking for UIKit answers, I want to do it fully in SwiftUI.

Body:
Overlays aren't supported but you can easily size your View/Circle by figuring out the ratio between the View and the span

First, since you want kilometers you can calculate the distance between the upper and lower edge (latitude span) of the region.

extension MKCoordinateRegion{
    ///Identify the length of the span in meters north to south
    var spanLatitude: Measurement<UnitLength>{
        let loc1 = CLLocation(latitude: center.latitude - span.latitudeDelta * 0.5, longitude: center.longitude)
        let loc2 = CLLocation(latitude: center.latitude + span.latitudeDelta * 0.5, longitude: center.longitude)
        let metersInLatitude = loc1.distance(from: loc2)
        return Measurement(value: metersInLatitude, unit: UnitLength.meters)
    }
}

using GeometryReader you can get the height of the View/Map, then the ratio. Once you have the size per meter just multiply to get kilometer.

//Size per meter
let ratio = (geo.size.height/region.spanLatitude.value)
//Size per kilometer
let kilometerSize = ratio * 1000

Then use the kilometerSize in the frame.

It is likely not be a perfect kilometer given there are likely inconsistencies between the View and the Map but it is probably pretty close. If you can find something that is a known kilometer you can test it out.

struct ScaledAnnotationView: View {
    static let usersLocation = CLLocationCoordinate2D(latitude: 52.0929779694589, longitude: 5.084964426384347)

    @State private var region = MKCoordinateRegion(
        center: ScaledAnnotationView.usersLocation,latitudinalMeters: 1000, longitudinalMeters: 1000
    )
    let annotations = [CurrentUsersAnnotation()]

    var body: some View {
        //Get the size of the frame for scale
        GeometryReader{ geo in
            Map(
                coordinateRegion: $region, annotationItems: annotations) { _ in
                    MapAnnotation(coordinate: ScaledAnnotationView.usersLocation) {
                            //Size per kilometer or any unit, just change the converted unit.
                            let kilometerSize = (geo.size.height/region.spanLatitude.converted(to: .kilometers).value)
                        Circle()
                            .fill(Color.red.opacity(0.5))
                        //Keep it a circle
                            .frame(width: kilometerSize, height: kilometerSize)
                    }
                }
        }
    }
}

Here is  Google maps distance measurement for confirmation of measurement


问:
Python web requests: Accessing json data from web response
I have a question with probably a well-known answer. However I couldnt articulate it well enough to find answers on google.

Lets say you are using the developer interface of Chrome browser (Press F12). If you click on the network tab and go to any website, a lot of files will be queried there for example images, stylesheets and JSON-responses.

I want to parse these JSON-responses using python now.

Thanks in advance!

答:
Perhaps you can try using Selenium.
Maybe the answers on this question can help you.</p>


问:
How to resolve TypeError using <= between 'float' and 'NoneType'?
```<code>def can_pay_bills(current_balance):
    monthly_bills=0
    monthly_bills=float(input("What is the sum of all of your monthly bills this month?"))

    if monthly_bills <= current_balance:
        print("There is enough money in your account to pay your bills this month.")
    elif monthly_bills > current_balance:
        print("You do not have enough money in your account to pay your bills this month.")
    elif monthly_bills == current_balance:
        print("You have exactly enough money in your account to pay your bills this month and not a cent to spare.")
</code>```

答:
You cannot make comparisons between numbers and a None object. Pass the value of the argument to the function at the time of the call

```<code>can_pay_bills(10)
</code>```

or specify a default value

```<code>def can_pay_bills(current_balance=10):
    monthly_bills=0
    ...
</code>```

The error traceback indicates that your internal function get_balance returns None

Body:
You cannot make comparisons between numbers and a None object. Pass the value of the argument to the function at the time of the call

can_pay_bills(10)

or specify a default value

def can_pay_bills(current_balance=10):
    monthly_bills=0
    ...

The error traceback indicates that your internal function get_balance returns None


问:
How to make button clickable only once in actionscript?
I have two scenes in Flash.

In the first I have a button and if somebody click on that button it goes to the second scene.

In the second scene I remove the button with an image so it is not clickable.

How to leave this button, but make it not clickable at all?

and the second case is what if I am using just one scene in flash and want the button be clickable only once? How the actionscript will look like?

Thanks in advance.

答:
```<code>var ft:Boolean = true;
myBtn.addEventListener(MouseEvent.CLICK, action);
function action (e:MouseEvent):void
{
    if(ft)
    {
        myBtn.enabled = false;
        //myBtn.visible = false;
        trace("licked");
        ft = false;
    }
}
</code>```

If as3, try this....

ContentLicense: CC BY-SA 3.0

Body:
var ft:Boolean = true;
myBtn.addEventListener(MouseEvent.CLICK, action);
function action (e:MouseEvent):void
{
    if(ft)
    {
        myBtn.enabled = false;
        //myBtn.visible = false;
        trace("licked");
        ft = false;
    }
}

If as3, try this....


问:
Remove the default option from image option of woocommerce "choose an option"
I am wondering how I can remove the "Choose an option" when you select image for an option. Please see this page.

http://omegahookahc.com/product/hookah-flavors/

All the options have an image and I have no way to remove these. I tried removing them, but CSS but the images gets messy when I click on it.

答:
First add the following css code to your themes css file.

```<code>.variations span.trx_addons_attrib_item.trx_addons_attrib_image.trx_addons_tooltip[data-tooltip="Choose an option"] { display: none; }
</code>```

Then make sure to set the default values in your variation.

Body:
First add the following css code to your themes css file.

.variations span.trx_addons_attrib_item.trx_addons_attrib_image.trx_addons_tooltip[data-tooltip="Choose an option"] { display: none; }

Then make sure to set the default values in your variation.


问:
Converting object to an encodable object failed
I am getting the following error:

```<code>Converting object to an encodable object failed: Instance of 'Patient'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:674)
#1      _JsonStringifier.writeList (dart:convert/json.dart:724)
#2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:706)
#3      _JsonStringifier.writeObject (dart:convert/json.dart:664)
#4      _JsonStringStringifier.printOn (dart:convert/json.dart:873)
#5      _JsonStringStringifier.stringify (dart:convert/json.dart:855)
#6      JsonEncoder.convert (dart:convert/json.dart:256)
#7      JsonCodec.encode (dart:convert/json.dart:155)
#8      Persistence.saveLatestPatients (/Users/dean/Library/Developer/CoreSimulator/Devices/570CC18D-95BF-4062-8523-9C78E106D0CF/data/Containers/Data/Application/70CAEFAA-4AE3-4CBF-A85F-39161E472C83/tmp/flutter_prototypev6jYbr/flutter_prototype/lib/utils/persistence.dart:32:23)
<asynchronous suspension>
#9      _HomeScreenState.fetchData.<anonymous closure> (/Users/dean/Librar<…>
</code>```

My 'Patient' class:

```<code>import 'package:simple_moment/simple_moment.dart';

class Patient {
  String guid;
  String _name;
  String _surname;
  DateTime _updated;

  Patient(String guid) {
    this.guid = guid;
  }

  String get name => _name;
  set name(v) => _name = v;

  String get surname => _surname;
  set surname(v) => _surname = v;

  DateTime get updated => _updated;
  set updated(v) => _updated = v;

  // Helper functions

  String getFullName() => '$_name $_surname';

  String getRelativeLastUpdated() {
    var moment = new Moment.now();
    return moment.from(_updated);
  }

}
</code>```

答:
Add a method named toJson()  to a class that you need to do the conversion. Put logic of converting in that method and use this.propety_name to reference properties. look at the example of a method here
String toJson() { return jsonEncode({}); }

Body:
I am getting the following error:

Converting object to an encodable object failed: Instance of 'Patient'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:674)
#1      _JsonStringifier.writeList (dart:convert/json.dart:724)
#2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:706)
#3      _JsonStringifier.writeObject (dart:convert/json.dart:664)
#4      _JsonStringStringifier.printOn (dart:convert/json.dart:873)
#5      _JsonStringStringifier.stringify (dart:convert/json.dart:855)
#6      JsonEncoder.convert (dart:convert/json.dart:256)
#7      JsonCodec.encode (dart:convert/json.dart:155)
#8      Persistence.saveLatestPatients (/Users/dean/Library/Developer/CoreSimulator/Devices/570CC18D-95BF-4062-8523-9C78E106D0CF/data/Containers/Data/Application/70CAEFAA-4AE3-4CBF-A85F-39161E472C83/tmp/flutter_prototypev6jYbr/flutter_prototype/lib/utils/persistence.dart:32:23)
<asynchronous suspension>
#9      _HomeScreenState.fetchData.<anonymous closure> (/Users/dean/Librar<…>

My 'Patient' class:

import 'package:simple_moment/simple_moment.dart';

class Patient {
  String guid;
  String _name;
  String _surname;
  DateTime _updated;

  Patient(String guid) {
    this.guid = guid;
  }

  String get name => _name;
  set name(v) => _name = v;

  String get surname => _surname;
  set surname(v) => _surname = v;

  DateTime get updated => _updated;
  set updated(v) => _updated = v;

  // Helper functions

  String getFullName() => '$_name $_surname';

  String getRelativeLastUpdated() {
    var moment = new Moment.now();
    return moment.from(_updated);
  }

}


问:
How to make each button send applicant details to a matching job record?
Without wasting time on a long intro, I have a major issue: I am currently stuck at one particular place in my project where a user can search for a job by entering keywords. After doing so, user will see matching jobs posted with an option to apply by clicking a button that is next to that job.

Here is the problem: how do I make each button correspond to THAT particular job and post the applicants details to an appropriate row in the database, say, where Job_ID = xyz?

This was the approach that I tried - assigning a unique Job_ID to a button based on the job that the button is linked to (making that the "name" of the button), but I have no idea how to pass that on and actually use it to achieve a result.

Help would be seriously appreciated. I have been stuck on this for a while now.

Here is my PHP code (embedded inside HTML) that outputs the search results in a table:

```<code>    <?php

        if (!empty($_POST['search-submit'])) {
            if (!preg_match("[/^$|\s+/]", $keywords)) {
                echo "<tr><td>" . "<b>Job Title</b>" . "</td><td>" . "<b>Job Description</b>" . "</td><td>" . "<b>Job Date</b>" . "</td></tr>";

                foreach ($search_query as $row) {
                    echo "<tr><td>" . $row['JobTitle'] . "</td><td>" . $row['JobDescription'] . "</td><td>" . $row['JobDate'] . "</td><td>" . '<input class = "btn btn-primary btn-sm" type = "submit" value = "Apply" name = ' . $row['Job_ID'] .'>' ."</td></tr>";
                }
            } elseif (preg_match("[/^$|\s+/]", $keywords)) {
                echo "<p>" . "No matches found." . "</p>";
            }
        }
    ?>
</code>```

答:
The solution was to add a form for each loop of the result produced from the search query and add a hidden field with the Job_ID attribute as its value.

Based on which button is clicked, the value assigned to the hidden field would be posted and later on accessible by default queries such as $_POST['name_of_field'].

```<code><?php
  if (!empty($_POST['search-submit'])) {
    if (!preg_match("[/^$|\s+/]", $keywords)) {
      echo "<tr><td>" . "<b>Job Title</b>" . "</td><td>" . "<b>Job Description</b>" . "</td><td>" . "<b>Job Date</b>" . "</td></tr>";

        foreach ($search_query as $row) {
          echo '<form method = "post" action = "">';

          echo '<input type = "hidden" name = "applyjob_id" value = "' . $row['Job_ID'] . '">  ';

          echo "<tr><td>" . $row['JobTitle'] . "</td><td>" . $row['JobDescription'] . "</td><td>" . $row['JobDate'] . "</td><td>" .
                                '<input class = "btn btn-primary btn-sm" name = "applyjob" type = "submit" value = "Apply" >' ."</td></tr>";

          echo '</form>';
        }
    } elseif (preg_match("[/^$|\s+/]", $keywords)) {
    echo "<p>" . "No matches found." . "</p>";
    }
}

  if (!empty($_POST['applyjob'])) {
    $applyjob_id = isset($_POST['applyjob_id']) ? $_POST['applyjob_id'] : '';

    $stick_info = "UPDATE `userjob` SET `Seeker_ID` = '$seekerjobid' WHERE `userjob`.`Job_ID` = '$applyjob_id'";
    mysqli_query($conn, $stick_info);
  }

?>
</code>```

Body:
Without wasting time on a long intro, I have a major issue: I am currently stuck at one particular place in my project where a user can search for a job by entering keywords. After doing so, user will see matching jobs posted with an option to apply by clicking a button that is next to that job.

Here is the problem: how do I make each button correspond to THAT particular job and post the applicants details to an appropriate row in the database, say, where Job_ID = xyz?

This was the approach that I tried - assigning a unique Job_ID to a button based on the job that the button is linked to (making that the "name" of the button), but I have no idea how to pass that on and actually use it to achieve a result.

Help would be seriously appreciated. I have been stuck on this for a while now.

Here is my PHP code (embedded inside HTML) that outputs the search results in a table:

    <?php

        if (!empty($_POST['search-submit'])) {
            if (!preg_match("[/^$|\s+/]", $keywords)) {
                echo "
" . "Job Title" . "	" . "Job Description" . "	" . "Job Date" . "
";

                foreach ($search_query as $row) {
                    echo "
" . $row['JobTitle'] . "	" . $row['JobDescription'] . "	" . $row['JobDate'] . "	" . '<input class = "btn btn-primary btn-sm" type = "submit" value = "Apply" name = ' . $row['Job_ID'] .'>' ."
";
                }
            } elseif (preg_match("[/^$|\s+/]", $keywords)) {
                echo "
" . "No matches found." . "
";
            }
        }
    ?>

Body:
The solution was to add a form for each loop of the result produced from the search query and add a hidden field with the Job_ID attribute as its value.

Based on which button is clicked, the value assigned to the hidden field would be posted and later on accessible by default queries such as $_POST['name_of_field'].

<?php
  if (!empty($_POST['search-submit'])) {
    if (!preg_match("[/^$|\s+/]", $keywords)) {
      echo "<tr><td>" . "<b>Job Title</b>" . "</td><td>" . "<b>Job Description</b>" . "</td><td>" . "<b>Job Date</b>" . "</td></tr>";

        foreach ($search_query as $row) {
          echo '<form method = "post" action = "">';

          echo '<input type = "hidden" name = "applyjob_id" value = "' . $row['Job_ID'] . '">  ';

          echo "<tr><td>" . $row['JobTitle'] . "</td><td>" . $row['JobDescription'] . "</td><td>" . $row['JobDate'] . "</td><td>" .
                                '<input class = "btn btn-primary btn-sm" name = "applyjob" type = "submit" value = "Apply" >' ."</td></tr>";

          echo '</form>';
        }
    } elseif (preg_match("[/^$|\s+/]", $keywords)) {
    echo "<p>" . "No matches found." . "</p>";
    }
}

  if (!empty($_POST['applyjob'])) {
    $applyjob_id = isset($_POST['applyjob_id']) ? $_POST['applyjob_id'] : '';

    $stick_info = "UPDATE `userjob` SET `Seeker_ID` = '$seekerjobid' WHERE `userjob`.`Job_ID` = '$applyjob_id'";
    mysqli_query($conn, $stick_info);
  }

?>


问:
Why I cant JSON.parse a string from an API (Error msg: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>))
I am trying to fetch a joke using XMLHTTPRequest from a random joke generating API as practice.

Here is my code

```<code>    <script>
    const xhr = new XMLHttpRequest();

    xhr.open('get', 'https://icanhazdadjoke.com/', true);
    xhr.setRequestHeader('Accept', 'application/json')
        const joke = JSON.parse(xhr.response)

    xhr.onload = function () {console.log(xhr.responseText)}
    xhr.send();

</script>
</code>```

and the error message i get is:  Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()

Funny thing is if I do JSON.parse(xhr.response) and save it to a variable, it works perfectly fine. What am I doing wrong in my script?

答:
You're trying to parse the response before receiving the response.  (AJAX is asynchronous.)  You need to handle the response in the onload handler, just like you already are when you try to log it to the console:

const xhr = new XMLHttpRequest();

xhr.open('get', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json');

xhr.onload = function () {
  const joke = JSON.parse(xhr.response);
  console.log(joke);
}
xhr.send();```

Body:
I am trying to fetch a joke using XMLHTTPRequest from a random joke generating API as practice.

Here is my code

and the error message i get is:  Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ()

Funny thing is if I do JSON.parse(xhr.response) and save it to a variable, it works perfectly fine. What am I doing wrong in my script?


问:
Ability to draw lines with snap to angle KonvaJs
Is there any ability to draw lines with snap to angle?
I want to allow draw lines only with following angles: 0, 45, 90, 135, 180...</p>

答:
```<code>function checkAngle(shape) {
if (data.attrs.type === 'line') {
    var points = shape.points();
    // [x1, y1, x2, y2]
    var dy = points[3] - points[1];
    var dx = points[2] - points[0];

    var angle = Math.atan2(dy, dx);
    angle *= 180 / Math.PI;

    console.log('Angle is: ' + angle);
    if ((-5 <= angle && angle <= 5) || (175 <= angle && angle <= 185) || (-175 >= angle && angle >= -185)) {
        shape.attrs.points = [points[0], points[1], points[2], points[1]];
    } else if ((85 <= angle && angle <= 95) || (-85 >= angle && angle >= -95)) {
        shape.attrs.points = [points[0], points[1], points[0], points[3]];
    }
    return shape;
  }
}
</code>```

This function checks angle of line
and then according to angle value changed X and Y points to draws straight vertical or horizontal line

Body:
function checkAngle(shape) {
if (data.attrs.type === 'line') {
    var points = shape.points();
    // [x1, y1, x2, y2]
    var dy = points[3] - points[1];
    var dx = points[2] - points[0];

    var angle = Math.atan2(dy, dx);
    angle *= 180 / Math.PI;

    console.log('Angle is: ' + angle);
    if ((-5 <= angle && angle <= 5) || (175 <= angle && angle <= 185) || (-175 >= angle && angle >= -185)) {
        shape.attrs.points = [points[0], points[1], points[2], points[1]];
    } else if ((85 <= angle && angle <= 95) || (-85 >= angle && angle >= -95)) {
        shape.attrs.points = [points[0], points[1], points[0], points[3]];
    }
    return shape;
  }
}

This function checks angle of line
and then according to angle value changed X and Y points to draws straight vertical or horizontal line


问:
Shell script. what does it mean?
Do you know what does the shell script below??</p>
```<code>00 5 * * * file.sh --date="2020-08-03"
</code>```

答:
The script isn't shell script but probably CRON job script.

It runs a command /client/user/download_files.sh --date="2020-08-03" every day at 5:00 AM.

Title: Shell script. what does it mean?

Body:
Do you know what does the shell script below??

00 5 * * * file.sh --date="2020-08-03"


问:
What's the point of using wordy Time Zones?
I know this isn't specific to PHP, but what's the point of using timezones listed like this :http://us2.php.net/manual/en/timezones.america.php?  For example "America/Indianapolis" and  "America/New_York".  What is the problem with EST, EDT, CST, CDT, &c?</p>

答: All regions within a timezone don't follow the same rules. For example, Arizona does not observe Daylight Saving Time.</p>

OwnerDisplayName: jimktrains

LastEditorDisplayName: Brian Rasmussen

OwnerDisplayName: geetee

ContentLicense: CC BY-SA 2.5


问:
How to check if array contains string with Azure DevOps pipeline expressions
I have the following pipeline template that I want to use to conditionally execute stages based on the input parameter stages.

parameters:
- name: dryRun
  default: false
  type: boolean
- name: path
  type: string
  default: terraform
- name: stages
  type: object
  default:
  - test
  - prod

stages:
  - stage:
    pool:
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to test"
    condition: in('test', ${{ parameters.stages }})
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: test
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}
  - stage:
    pool:
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to production"
    condition: in('prod', '${{ join(', ', parameters.stages) }}')
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: production
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}
```

In the example you can see two of the approached I tried (I tried a lot...). The last one (in('prod', '${{ join(', ', parameters.stages) }}')) actually compiles but then the check only works partially as the array gets converted into a single string: 'test,prod' which will fail the in('test', 'test,prod') check.

And the first example (in('test', ${{ parameters.stages }})) is the one I think should work with logical thinking but I get the following error when compiling the template: /terraform-deployment.yml (Line: 19, Col: 16): Unable to convert from Array to String. Value: Array.

So now the question:

How do I check if a string is part of an array that was defined as a parameter?

答:
2022 update

You can now use containsValue:

condition: ${{ containsValue(parameters.stages, 'test') }}
```

Body:
I have the following pipeline template that I want to use to conditionally execute stages based on the input parameter stages.

parameters:
- name: dryRun
  default: false
  type: boolean
- name: path
  type: string
  default: terraform
- name: stages
  type: object
  default:
  - test
  - prod

stages:
  - stage:
    pool:
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to test"
    condition: in('test', ${{ parameters.stages }})
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: test
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}
  - stage:
    pool:
      vmImage: 'ubuntu-latest'
    displayName: "Deploy to production"
    condition: in('prod', '${{ join(', ', parameters.stages) }}')
    jobs:
    - template: terraform-job.yaml
      parameters:
        stage: production
        path: ${{ parameters.path }}
        dryRun: ${{ parameters.dryRun }}

In the example you can see two of the approached I tried (I tried a lot...). The last one (in('prod', '${{ join(', ', parameters.stages) }}')) actually compiles but then the check only works partially as the array gets converted into a single string: 'test,prod' which will fail the in('test', 'test,prod') check.

And the first example (in('test', ${{ parameters.stages }})) is the one I think should work with logical thinking but I get the following error when compiling the template: /terraform-deployment.yml (Line: 19, Col: 16): Unable to convert from Array to String. Value: Array.

So now the question:

How do I check if a string is part of an array that was defined as a parameter?


问:
use static files in poem webserver
I'm trying to use poem's static files:

cargo.toml:

```<code>poem = { version = "1.2.53", features = ["websocket", "static-files"]}
</code>```

main.rs (simplified):

```<code>use poem::{endpoint::StaticFileEndpoint, Route, Server, listener::TcpListener};
let app = Route::new().at("/", StaticFileEndpoint::new("index.html"));
Server::new(TcpListener::bind("127.0.0.1:3000"))
    .run(app)
    .await
</code>```

This works when I use an absolute path to index.html, but not with a path relative to my project folder: the browser displays not found.

Do I have to use rust-embed to include the static file in the binary ?  How ?

答:
You need to use StaticFilesEndpoint.

```<code>use poem::{endpoint::StaticFilesEndpoint, Route};

let app = Route::new().nest(
    "/",
    StaticFilesEndpoint::new("/path/to/dir")
        .show_files_listing()
        .index_file("index.html"),
);
</code>```

You are using StaticFileEndpoint which serves only the specific file in this case index.html.

rust-embed may be required if you are creating a portable binary but if you are using a tool like docker, you can keep the files in your git repo and copy them before running your container.

Learn more about StaticFilesEndpoint.

Title: use static files in poem webserver

Body:
I'm trying to use poem's static files:

cargo.toml:

poem = { version = "1.2.53", features = ["websocket", "static-files"]}

main.rs (simplified):

use poem::{endpoint::StaticFileEndpoint, Route, Server, listener::TcpListener};
let app = Route::new().at("/", StaticFileEndpoint::new("index.html"));
Server::new(TcpListener::bind("127.0.0.1:3000"))
    .run(app)
    .await

This works when I use an absolute path to index.html, but not with a path relative to my project folder: the browser displays not found.

Do I have to use rust-embed to include the static file in the binary ?  How ?

Body:
You need to use StaticFilesEndpoint.

use poem::{endpoint::StaticFilesEndpoint, Route};

let app = Route::new().nest(
    "/",
    StaticFilesEndpoint::new("/path/to/dir")
        .show_files_listing()
        .index_file("index.html"),
);

You are using StaticFileEndpoint which serves only the specific file in this case index.html.

rust-embed may be required if you are creating a portable binary but if you are using a tool like docker, you can keep the files in your git repo and copy them before running your container.

Learn more about StaticFilesEndpoint.


问:
Array reversal in C language using while loop
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}
</code>```

答:
In this while loop

```<code>h_Count = count - 1;
l_Count = 0;
while(l_Count != h_Count)
{
    temp = *(arr + l_Count);
    *(arr + l_Count) = *(arr + h_Count);
    *(arr + h_Count) = temp;
    h_Count--;
    l_Count++;
}
</code>```

when the number of elements is even (let's assume that it is equal to 2) then after these statements in the loop

```<code>    h_Count--;
    l_Count++;
</code>```

h_Count never will be equal to l_Count.

You could rewrite the loop for example like

```<code>h_Count = count;
l_Count = 0;
while( l_Count < --h_Count )
{
    temp = *(arr + l_Count);
    *(arr + l_Count) = *(arr + h_Count);
    *(arr + h_Count) = temp;
    l_Count++;
}
</code>```

If you want to use pointers in the loop the  it can look the following way

```<code>int *first = arr;
int *last  = arr + num;

while ( first < --last )
{
    temp     = *last;
    *last    = *first;
    *first++ = temp;
}
</code>```

Body:
I made this program to reverse an array but it only works when I put in an odd number of digits in the array. If I put in even number of digits it doesn't print anything.
For example: If I put {1,2,3,4,5} the program will print {5,4,3,2,1} but if the input is {1,2,3,4} it doesn't print anything.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, *arr, i, count;
    count = 0;
    scanf("%d", &num);
    arr = (int *)malloc(num * sizeof(int));
    for (i = 0; i < num; i++) {
        scanf("%d", arr + i);
        count++;
    }

    int l_Count, h_Count, temp;
    temp = 0;
    h_Count = count - 1;
    l_Count = 0;
    while (l_Count != h_Count) {
        temp = *(arr + l_Count);
        *(arr + l_Count) = *(arr + h_Count);
        *(arr + h_Count) = temp;
        h_Count--;
        l_Count++;
    }

    for (i = 0; i < num; i++) {
        printf("%d ", *(arr + i));
    }
    return 0;
}

Body:
In this while loop

h_Count = count - 1;
l_Count = 0;
while(l_Count != h_Count)
{
    temp = *(arr + l_Count);
    *(arr + l_Count) = *(arr + h_Count);
    *(arr + h_Count) = temp;
    h_Count--;
    l_Count++;
}

when the number of elements is even (let's assume that it is equal to 2) then after these statements in the loop

    h_Count--;
    l_Count++;

h_Count never will be equal to l_Count.

You could rewrite the loop for example like

h_Count = count;
l_Count = 0;
while( l_Count < --h_Count )
{
    temp = *(arr + l_Count);
    *(arr + l_Count) = *(arr + h_Count);
    *(arr + h_Count) = temp;
    l_Count++;
}

If you want to use pointers in the loop the  it can look the following way

int *first = arr;
int *last  = arr + num;

while ( first < --last )
{
    temp     = *last;
    *last    = *first;
    *first++ = temp;
}


问:
How to run Grunt Copy Task automatically when our project run
I want to copy some files from one folder to another automatically when my project start.Now I do it by run a command in cmd "grunt copy". Please help me on this.

My Gruntfile.js Code:

```<code>module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        copy: {
            t1: {
                src: 'Scripts/**',
                dest:'Target/'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.registerTask('default', 'copy:t1');
};
</code>```

答: I think you need to have grunt.registerTask('default', ['copy:t1']);</p>

Body:
I want to copy some files from one folder to another automatically when my project start.Now I do it by run a command in cmd "grunt copy". Please help me on this.

My Gruntfile.js Code:

module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        copy: {
            t1: {
                src: 'Scripts/**',
                dest:'Target/'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.registerTask('default', 'copy:t1');
};


问:
Get values from ID HTML and save in array
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

```<code>      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }
</code>```

VIEW

```<code>    <div class="container">
        <div class="row">
            <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
                <div id="reader" style="display: inline-block;"></div>
                <div class="empty"></div>

                <div id="scanned-result">
                   <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
                   <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div></div>
            </div>

        </div>
    </div>
</code>```

答:
I've changed the iteration to fill the array with the lines inside the ID scanned-result. Would that help ?

function SubmitCodes() {
        var QRCodeval = document.getElementById('scanned-result').children;
        var arr = [];

        for (var i = 0; i < QRCodeval.length; i++) {
            arr.push(QRCodeval[i].innerText)
        }

        console.log(arr)
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="row">
        <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
            <div id="reader" style="display: inline-block;"></div>
            <div class="empty"></div>

            <div id="scanned-result">
                <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
                <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
            </div>
        </div>

    </div>
</div></code>```

Body:
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }

VIEW

[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp

[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0

Body:
I've changed the iteration to fill the array with the lines inside the ID scanned-result. Would that help ?

function SubmitCodes() {
        var QRCodeval = document.getElementById('scanned-result').children;
        var arr = [];

        for (var i = 0; i < QRCodeval.length; i++) {
            arr.push(QRCodeval[i].innerText)
        }

        console.log(arr)
    }

<div class="container">
    <div class="row">
        <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
            <div id="reader" style="display: inline-block;"></div>
            <div class="empty"></div>

            <div id="scanned-result">
                <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
                <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
            </div>
        </div>

    </div>
</div>


问:
AWS Glue jobs not writing to S3
I have just been playing around with Glue but have yet to get it to successfully create a new table in an existing S3 bucket. The job will execute without error but there is never any output in S3.

Here's what the auto generated code is:

```<code>glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path":
"s3://glueoutput/output/"}, format = "json", transformation_ctx =
"datasink2")
</code>```

Have tried all variations of this - with name of file (that doesn't exist yet), in root folder of bucket, trailing slash and without. The role being used has full access to S3.  Tried creating buckets in different regions. No file is ever created though. Again console says its successful.

答:
Had the same issue. After a few days of what seemed like Glue jobs randomly write to s3 and sometimes don't I found this thread.
@Sinan Erdem suggestion resolved my issue.

From the aws docs:

Job bookmarks are used to track the source data that has already been
processed, preventing the reprocessing of old data. Job bookmarks can
be used with JDBC data sources and some Amazon Simple Storage Service
(Amazon S3) sources. Job bookmarks are tied to jobs. If you delete a
job, then its job bookmark is also deleted.

You can rewind your job bookmarks for your Glue Spark ETL jobs to any
previous job run, which allows your job to reprocess the data. If you
want to reprocess all the data using the same job, you can reset the
job bookmark

Also found this:
How to rewind Job Bookmarks on Glue Spark ETL job?

Title: AWS Glue jobs not writing to S3

Body:
I have just been playing around with Glue but have yet to get it to successfully create a new table in an existing S3 bucket. The job will execute without error but there is never any output in S3.

Here's what the auto generated code is:

glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path":
"s3://glueoutput/output/"}, format = "json", transformation_ctx =
"datasink2")

Have tried all variations of this - with name of file (that doesn't exist yet), in root folder of bucket, trailing slash and without. The role being used has full access to S3.  Tried creating buckets in different regions. No file is ever created though. Again console says its successful.


问:
How to extract a table from a website using BeautifulSoup?
I'm wanting to extract the FIPS code for each county in Louisiana from this website using beautiful soup and create a Pandas Dataframe: https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697

The columns would be FIPS, Name, and State. I've tried finding by tr, td, and table when I inspect the element, but I don't know how to single out just the main data and then put it into a pandas dataframe. Once I find the specific table, it should be easy to do something like:

if state == 'LA':
     # put data into a dataframe
```
<pre class="lang-py prettyprint-override"><code>
import requests
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'html.parser')
# print(soup)
for county in soup.find_all('table'):
    print(county.text)
</code>```

答:
You can select
 with class="data" and then use pd.read_html. For example:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
df = pd.read_html(str(soup.select_one(".data")))[0]
# filter State == 'LA'
print(df[df.State == "LA"].head())
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>       FIPS        Name State
1109  22001      Acadia    LA
1110  22003       Allen    LA
1111  22005   Ascension    LA
1112  22007  Assumption    LA
1113  22009   Avoyelles    LA
</code>```

Body:
I'm wanting to extract the FIPS code for each county in Louisiana from this website using beautiful soup and create a Pandas Dataframe: https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697

The columns would be FIPS, Name, and State. I've tried finding by tr, td, and table when I inspect the element, but I don't know how to single out just the main data and then put it into a pandas dataframe. Once I find the specific table, it should be easy to do something like:

if state == 'LA':
     # put data into a dataframe

import requests
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'html.parser')
# print(soup)
for county in soup.find_all('table'):
    print(county.text)

Body:
You can select <table> with class="data" and then use pd.read_html. For example:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
df = pd.read_html(str(soup.select_one(".data")))[0]
# filter State == 'LA'
print(df[df.State == "LA"].head())

Prints:

       FIPS        Name State
1109  22001      Acadia    LA
1110  22003       Allen    LA
1111  22005   Ascension    LA
1112  22007  Assumption    LA
1113  22009   Avoyelles    LA


问:
Reduce time /space complexity of simple loop
So basically if i have an iteration like this in python
Ive editted the question to include my full code

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]
</code>```

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp
</code>```

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

答:
A simple naive solution might be:

def myPow(x: float, n: int) -> float:
    ## -----------------------
    ## if we have a negative n then invert x and take the absolute value of n
    ## -----------------------
    if n < 0:
        x = 1/x
        n = -n
    ## -----------------------

    retval = 1
    for _ in range(n):
        retval *= x
    return retval
```
<p>While this technically works, you will wait until the cows come home to get a result for:</p>
```x = 0.00001 and n = 2147483647
```
<p>So we need to find a shortcut. Lets' consider 2^5. Our naïve method would calculate that as:</p>
```(((2 * 2) * 2) * 2) * 2 == 32
```
<p>However, what might we observe about the problem if we group some stuff together in a different way:</p>
```(2 * 2) * (2 * 2) * 2 == 32
```
<p>similarly:</p>
```((2 * 2) * (2 * 2) * 2) * ((2 * 2) * (2 * 2) * 2) == 32 * 32 = 1024
```
<p>We might observe that we only technically need to calculate</p>
```(2 * 2) * (2 * 2) * 2 == 32
```
<p>once and use it twice to get 2^10.</p>
<p>Similarly we only need to calcuate:</p>
```2 * 2 = 4
```
<p>once and use it twice to get 2^5....</p>
<p>This suggests a recursion to me.</p>
<p>Let's modify our first attempt to use this divide and concur method.</p>
<pre class="lang-py prettyprint-override"><code>def myPow2(x: float, n: int) -> float:
    ## -----------------------
    ## if we have a negative n then invert x and take the absolute value of n
    ## -----------------------
    if n < 0:
        x = 1/x
        n = -n
    ## -----------------------

    ## -----------------------
    ## We only need to calculate approximately half the work and use it twice
    ## at any step.
    ## -----------------------
    def _recurse(x, n):
        if n == 0:
            return 1
        res = _recurse(x, n//2) # calculate it once
        res = res * res # use it twice
        return res * x if n % 2 else res # if n is odd, multiple by x one more time (see 2^5 above)
    ## -----------------------

    return _recurse(x, n)
</code>```

Now let's try:

```<code>print(myPow2(2.0, 0))
print(myPow2(2.0, 1))
print(myPow2(2.0, 5))
print(myPow2(2.1, 3))
print(myPow2(2.0, -2))
print(myPow2(0.00001, 2147483647))
</code>```

That gives me:

```<code>1
2.0
32.0
9.261000000000001
0.25
0.0
</code>```

Body:
So basically if i have an iteration like this in python
Ive editted the question to include my full code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

Body:
A simple naive solution might be:

def myPow(x: float, n: int) -> float:
    ## -----------------------
    ## if we have a negative n then invert x and take the absolute value of n
    ## -----------------------
    if n < 0:
        x = 1/x
        n = -n
    ## -----------------------

    retval = 1
    for _ in range(n):
        retval *= x
    return retval

While this technically works, you will wait until the cows come home to get a result for:

x = 0.00001 and n = 2147483647

So we need to find a shortcut. Lets' consider 2^5. Our naïve method would calculate that as:

(((2 * 2) * 2) * 2) * 2 == 32

However, what might we observe about the problem if we group some stuff together in a different way:

(2 * 2) * (2 * 2) * 2 == 32

similarly:

((2 * 2) * (2 * 2) * 2) * ((2 * 2) * (2 * 2) * 2) == 32 * 32 = 1024

We might observe that we only technically need to calculate

(2 * 2) * (2 * 2) * 2 == 32

once and use it twice to get 2^10.

Similarly we only need to calcuate:

2 * 2 = 4

once and use it twice to get 2^5....

This suggests a recursion to me.

Let's modify our first attempt to use this divide and concur method.

def myPow2(x: float, n: int) -> float:
    ## -----------------------
    ## if we have a negative n then invert x and take the absolute value of n
    ## -----------------------
    if n < 0:
        x = 1/x
        n = -n
    ## -----------------------

    ## -----------------------
    ## We only need to calculate approximately half the work and use it twice
    ## at any step.
    ## -----------------------
    def _recurse(x, n):
        if n == 0:
            return 1
        res = _recurse(x, n//2) # calculate it once
        res = res * res # use it twice
        return res * x if n % 2 else res # if n is odd, multiple by x one more time (see 2^5 above)
    ## -----------------------

    return _recurse(x, n)

Now let's try:

print(myPow2(2.0, 0))
print(myPow2(2.0, 1))
print(myPow2(2.0, 5))
print(myPow2(2.1, 3))
print(myPow2(2.0, -2))
print(myPow2(0.00001, 2147483647))

That gives me:

1
2.0
32.0
9.261000000000001
0.25
0.0


问:
RedirecToAction doesnt call the expected view
I have successfully created a product but the page doesn't redirects to the view I want...and I don't really know why...
[HttpPost]
public async Task AddProduct([FromForm] AddProductViewModel model)

The jquery call:

 $.ajax({
        url: '/' + 'Product' + '/' + 'AddProduct',
        type: 'POST',
        contentType: false,
        processData: false,
        data: formData,
        success: console.log('success'),

    });
//edit

   $.ajax({
        url: '/Product/AddProduct',
        type: 'POST',
        contentType: false,
        processData: false,
        data: formData,
        success: window.location.href = "/Product/ProductList"

    });

```

答:
HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

You can return the name of the view you want instead of the redirect, write as below:

```<code>[HttpPost]
public IActionResult AddProduct()
{
  bool isFoo = handleBar();

  if (isFoo)
  {
    return View();
  }

   return View("ProductList");
 }
</code>```

if you are using ajax  you can redirect user in client side such as the following code:

```<code>$.ajax({
   //settings
 }).done(function (r) {
    window.location.href = '/Product/ProductList';
 });
</code>```

or use success

```<code>$.ajax({
//settings
success: function(res) {
    window.location.href = '/Product/ProductList';
   }
});
</code>```

Body:
HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

You can return the name of the view you want instead of the redirect, write as below:

[HttpPost]
public IActionResult AddProduct()
{
  bool isFoo = handleBar();

  if (isFoo)
  {
    return View();
  }

   return View("ProductList");
 }

if you are using ajax  you can redirect user in client side such as the following code:

$.ajax({
   //settings
 }).done(function (r) {
    window.location.href = '/Product/ProductList';
 });

or use success

$.ajax({
//settings
success: function(res) {
    window.location.href = '/Product/ProductList';
   }
});


问:
Running Firebase TestLab XCTest on iOS 15 devices
I wonder if it's possible to run XCTest via Firebase TestLab on iOS15+ devices/simulators.
 I will describe my problem with gcloud command line first:

When running this command in terminal:

gcloud firebase test ios models list

It returns me this devices and os versions list:

And looks like the latest available OS version to run is 14.7 which is available on iPhone8 only.

However, this command:

gcloud firebase test ios versions list

returns me a lot more available versions, including 15.1 as the latest iOS version:

Also, here is the image from Firebase TestLab console, which lists the only available devices just like the first command I mentioned:

... So, is there any way to run my tests on iOS 15 via Firebase TestLab?

答: iOS 15+ is not yet supported on Firebase Test Lab. It's in the works, but there's currently no ETA.</p>