问:
How to append to a DolphinDB database in-memory table with Python API?
I ran the following code in python to append to a DolphinDB database in-memory table:

```<code>import dolphindb as ddb
import pandas as pd
import numpy as np
s = ddb.session()
s.connect("localhost", 8848, "admin", "123456")
script = """t = table(1:0,`id`date`ticker`price, [INT,DATE,STRING,DOUBLE])
share t as tglobal"""
s.run(script)

tb=pd.DataFrame({'id': [1, 2, 2, 3],
                 'date': np.array(['2019-10-30', '2019-10-30', '2019-10-30', '2019-10-30'], dtype='datetime64[D]'),
                 'ticker': ['AAPL', 'AMZN', 'FB', 'GOOG'],
                 'price': [243.26, 1779.99, 188.25, 1261.29]})
s.run("append!{tglobal}",tb)
</code>```

However, I encountered an error:

```<code>pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: -1817286-04-17 00:00:00
</code>```

Does anyone know what I did wrong?

答:
Since all data types related to time in Python pandas are datetime64, after uploading a DataFrame to DolphinDB, all time type columns are of nanotimestamp type, so when appending a DataFrame with time column, we need to check the time on the DolphinDB server Column data type conversion: upload the DataFrame to the server first, select each column in the table through the select statement, and perform time type conversion (this example converts the nanotimestamp type to the date type), and then append it to the memory table Medium, as follows:</p>

```<code>tb=pd.DataFrame({'id': [1, 2, 2, 3],
                 'date': np.array(['2019-10-30', '2019-10-30', '2019-10-30', '2019-10-30'], dtype='datetime64[D]'),
                 'ticker': ['AAPL', 'AMZN', 'FB', 'GOOG'],
                 'price': [243.26, 1779.99, 188.25, 1261.29]})
s.upload({'tb':tb})
s.run("tableInsert(tglobal,(select id, date(date) as date, ticker, price from tb))")
</code>```

Body:
I ran the following code in python to append to a DolphinDB database in-memory table:

import dolphindb as ddb
import pandas as pd
import numpy as np
s = ddb.session()
s.connect("localhost", 8848, "admin", "123456")
script = """t = table(1:0,`id`date`ticker`price, [INT,DATE,STRING,DOUBLE])
share t as tglobal"""
s.run(script)

tb=pd.DataFrame({'id': [1, 2, 2, 3],
                 'date': np.array(['2019-10-30', '2019-10-30', '2019-10-30', '2019-10-30'], dtype='datetime64[D]'),
                 'ticker': ['AAPL', 'AMZN', 'FB', 'GOOG'],
                 'price': [243.26, 1779.99, 188.25, 1261.29]})
s.run("append!{tglobal}",tb)

However, I encountered an error:

pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: -1817286-04-17 00:00:00

Does anyone know what I did wrong?

Body:
Since all data types related to time in Python pandas are datetime64, after uploading a DataFrame to DolphinDB, all time type columns are of nanotimestamp type, so when appending a DataFrame with time column, we need to check the time on the DolphinDB server Column data type conversion: upload the DataFrame to the server first, select each column in the table through the select statement, and perform time type conversion (this example converts the nanotimestamp type to the date type), and then append it to the memory table Medium, as follows:

tb=pd.DataFrame({'id': [1, 2, 2, 3],
                 'date': np.array(['2019-10-30', '2019-10-30', '2019-10-30', '2019-10-30'], dtype='datetime64[D]'),
                 'ticker': ['AAPL', 'AMZN', 'FB', 'GOOG'],
                 'price': [243.26, 1779.99, 188.25, 1261.29]})
s.upload({'tb':tb})
s.run("tableInsert(tglobal,(select id, date(date) as date, ticker, price from tb))")


来源: stackexchange

问:
method works only in main class but not when called from its other class
Hi i wrote a method to calculate the number of times a number appears in an array .The problem is it works when written in the same class as the main program but does not work when its written in a different class.

```<code>public class Digits {

    public static void main(String[] args) {
        int []b={1,1,1,1,2};

    int c=  Digits.numberCount(b,5);
    System.out.println(c);
    }

      public static int numberCount(int[]numbers,int number){
    int count=0;
    for(int i=0;i<numbers.length;i++){
        if(number==numbers[i])
            count++;
    }
    return count;
          }

}
</code>```

it works in the above instance  but when not when i try to use the method from another class but in the same project

```<code>public class DigitsA {
    private int[]numbersrange;

    public DigitsA(){
        numbersrange=new int[9];

    }

    public static int numberCount(int[]numbers,int number){
        int count=0;
        for(int i=0;i<numbers.length;i++){
            if(number==numbers[i])
                count++;
        }
        return count;
    }

}
</code>```

答:
You seem confused... Here's how you would use it, plus see the use of the foreach loop to make you code cleaner:

```<code>public class Digits
{

    public static void main(String[] args)
    {
        int[] b = { 1, 1, 1, 1, 2 };
        int c = Digits.numberCount(b, 5);
        System.out.println(c);
    }

    public static int numberCount(int[] numbers, int number)
    {
        int count = 0;
        for (int element : numbers)
        {
            if (number == element)
                count++;
        }
        return count;
    }
}
</code>```

And then to call...

```<code>public class Caller {

    public static void main(String[] args)
    {
        int[] b = { 1, 2, 3};
        int c = Digits.numberCount(b, 2);
        System.out.println(c);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi i wrote a method to calculate the number of times a number appears in an array .The problem is it works when written in the same class as the main program but does not work when its written in a different class.

public class Digits {

    public static void main(String[] args) {
        int []b={1,1,1,1,2};

    int c=  Digits.numberCount(b,5);
    System.out.println(c);
    }

      public static int numberCount(int[]numbers,int number){
    int count=0;
    for(int i=0;i<numbers.length;i++){
        if(number==numbers[i])
            count++;
    }
    return count;
          }

}

it works in the above instance  but when not when i try to use the method from another class but in the same project

public class DigitsA {
    private int[]numbersrange;

    public DigitsA(){
        numbersrange=new int[9];

    }

    public static int numberCount(int[]numbers,int number){
        int count=0;
        for(int i=0;i<numbers.length;i++){
            if(number==numbers[i])
                count++;
        }
        return count;
    }

}

Body:
You seem confused... Here's how you would use it, plus see the use of the foreach loop to make you code cleaner:

public class Digits
{

    public static void main(String[] args)
    {
        int[] b = { 1, 1, 1, 1, 2 };
        int c = Digits.numberCount(b, 5);
        System.out.println(c);
    }

    public static int numberCount(int[] numbers, int number)
    {
        int count = 0;
        for (int element : numbers)
        {
            if (number == element)
                count++;
        }
        return count;
    }
}

And then to call...

public class Caller {

    public static void main(String[] args)
    {
        int[] b = { 1, 2, 3};
        int c = Digits.numberCount(b, 2);
        System.out.println(c);
    }
}


问:
Why are Bash conditions not symmetrical when using wildcards?
Suppose I have the following Bash snippet:

if [[ "$foo" == *"$bar"* ]] ; then
  echo 'condition is true'
fi
```

<p>In English, you might describe the above code with: <em>if <code>bar</code> is a substring of <code>foo</code> then...</em></p>

<p>However, how come when we switch the sides of the condition, we don't get the same results?</p>

<pre class="lang-sh prettyprint-override"><code>if [[ *"$bar"* == "$foo" ]] ; then
  echo 'condition is true'
fi
</code>```

Perhaps I have a misunderstanding of when the wildcard is evaluated?

答:
It's an explicit design decision. Here's man bash:

When  the  ==  and  !=  operators are used, the string to the right of the operator is considered a pattern and matched according to the
         rules described

Pathname expansion is not performed in [[ .. ]], so regular rules around that don't apply.

Treating both as a pattern would be pretty strange. Should [[ a* == [a]* ]] be true because the right pattern matches the left string, false because the left pattern does not match the right string, or true because both patterns match the same set of strings?

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have the following Bash snippet:

if [[ "$foo" == *"$bar"* ]] ; then
  echo 'condition is true'
fi

In English, you might describe the above code with: if bar is a substring of foo then...

However, how come when we switch the sides of the condition, we don't get the same results?

if [[ *"$bar"* == "$foo" ]] ; then
  echo 'condition is true'
fi

Perhaps I have a misunderstanding of when the wildcard is evaluated?


问:
TLS certificate is being provisioned. This may take up to 15 minutes to complete

I see this message when trying to enforce https on my github pages website with a custom domain, which I registered through GoDaddy. The message showed up when I first linked my custom domain, but it's still there a week later.

Other Context:

I added A records on GoDaddy pointing to the github pages IP addresses.

When I attempt to access my website on mobile, it says that the website is being parked by GoDaddy.

What might be preventing the certificate from going through?

答:
I found the solution here. The problem was that I hadn't deleted the A record that GoDaddy automatically includes, parking your website. I deleted this A record and the certificate went through within a few minutes.

This question describes a different problem with the same solution.


问:
how remove last special character from this string with preg_replace?
I want to remove this >

from

```<code>com.gau.go.launcherex.gowidget.weatherwidget>
</code>```

答:
To remove this > im used this code </p>

```<code>rtrim($string,'&gt');
</code>```

Body:
I want to remove this >

from

com.gau.go.launcherex.gowidget.weatherwidget>

Body:
To remove this > im used this code

rtrim($string,'&gt');


问:
What is the fastest way to find the bottleneck/optimize Magento?
Is there a way to identify quickly a faulty script in Magento that slows down the server?

Magento has something like 35 000 files, so there are so many places it can go wrong, I just need a way to find quickly where to optimize.

For example, could I install a script that would tell me all the files magento reads before outputing a page? And then tell me how much time it takes for each file to execute?

Thanks for your help

答:
There's always Magento's built-in profiler. It's a configuration change and a file edit away.

Enabling Magento Profiler


问:
How do I write the body of a function in a dll, but have the prototype in my main program
Sorry if the question is rudimentory, I'm new to .dll-s. Basically I want to allow my function to have access to the same global variables it does in the main program it's originally defined in while actually being written in the .dll

example: I have a ListView object into which I am printing messages from within the function

```<code>void example(){
//Display is my listview
Display->Items->Add("Hello world");
}
</code>```

in this example Display is a TListView object which is inicialized in my main.cpp from which I define the behavior of my VCL application form. This Display object is a global variable in the main cpp and because of it when I cut the example() and paste it into my new dll it breaks because within the range of the dll the Display doesn't exist.

My idea is to declare the function prototype void example(); in the main.h and SOMEHOW write the body in my dll, but when I include<"anything"> into the dll the compiler screams that idk what I'm trying to do...

What are my options?

I'm using c++ builder but I presume the same logical question would apply to any IDE

答:
You are going about this all wrong.  A DLL can't access variables that are outside of it, like in the main EXE, unless outside code gives the DLL pointers/references to them.  Which won't help you anyway in the example you provided.

A better design is to not have the DLL access the variables directly at all.  In your example, you should make the EXE pass a pointer to a callback function to the DLL, which the DLL can then call when needed. Internally, that function can use the EXE's variables as needed.

For example:

MyDLL.h

#ifndef MyDLL_H
#define MyDLL_H

#ifdef BUILDING_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif

typedef void (__stdcall *myTextCallback)(const char *text, void *userData);

MY_API void __stdcall dll_setTextCallback(myTextCallback userCallback, void *userData);

#endif
```

<p>MyDll.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#define BUILDING_DLL
#include "MyDll.h"

myTextCallback textCallback = NULL;
void *textCallbackData = NULL;

void __stdcall dll_setTextCallback(myTextCallback userCallback, void *userData)
{
    textCallback = userCallback;
    textCallbackData = userData;
}

void doSomething()
{
    ...
    if (textCallback)
        textCallback("Hello World", textCallbackData);
    ...
}
</code>```

EXE

#include "MyDll.h"

void __stdcall displayText(const char *text, void *userData)
{
    TListItem *Item = static_cast<TMainForm*>(userData)->Display->Items->Add();
    Item->Caption = text;
}

__fastcall TMainForm::TMainForm(TComponent *Owner)
    : TForm(Owner)
{
    dll_setTextCallback(&displayText, this);
}

__fastcall TMainForm::~TMainForm()
{
    dll_setTextCallback(NULL, NULL);
}
```

This way, the DLL doesn't have to know or care what what the EXE wants to do with the DLL's data.

Body:
Sorry if the question is rudimentory, I'm new to .dll-s. Basically I want to allow my function to have access to the same global variables it does in the main program it's originally defined in while actually being written in the .dll

example: I have a ListView object into which I am printing messages from within the function

void example(){
//Display is my listview
Display->Items->Add("Hello world");
}

in this example Display is a TListView object which is inicialized in my main.cpp from which I define the behavior of my VCL application form. This Display object is a global variable in the main cpp and because of it when I cut the example() and paste it into my new dll it breaks because within the range of the dll the Display doesn't exist.

My idea is to declare the function prototype void example(); in the main.h and SOMEHOW write the body in my dll, but when I include<"anything"> into the dll the compiler screams that idk what I'm trying to do...

What are my options?

I'm using c++ builder but I presume the same logical question would apply to any IDE

Body:
You are going about this all wrong.  A DLL can't access variables that are outside of it, like in the main EXE, unless outside code gives the DLL pointers/references to them.  Which won't help you anyway in the example you provided.

A better design is to not have the DLL access the variables directly at all.  In your example, you should make the EXE pass a pointer to a callback function to the DLL, which the DLL can then call when needed. Internally, that function can use the EXE's variables as needed.

For example:

MyDLL.h

#ifndef MyDLL_H
#define MyDLL_H

#ifdef BUILDING_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif

typedef void (__stdcall *myTextCallback)(const char *text, void *userData);

MY_API void __stdcall dll_setTextCallback(myTextCallback userCallback, void *userData);

#endif

MyDll.cpp

#define BUILDING_DLL
#include "MyDll.h"

myTextCallback textCallback = NULL;
void *textCallbackData = NULL;

void __stdcall dll_setTextCallback(myTextCallback userCallback, void *userData)
{
    textCallback = userCallback;
    textCallbackData = userData;
}

void doSomething()
{
    ...
    if (textCallback)
        textCallback("Hello World", textCallbackData);
    ...
}

EXE

#include "MyDll.h"

void __stdcall displayText(const char *text, void *userData)
{
    TListItem *Item = static_cast<TMainForm*>(userData)->Display->Items->Add();
    Item->Caption = text;
}

__fastcall TMainForm::TMainForm(TComponent *Owner)
    : TForm(Owner)
{
    dll_setTextCallback(&displayText, this);
}

__fastcall TMainForm::~TMainForm()
{
    dll_setTextCallback(NULL, NULL);
}

This way, the DLL doesn't have to know or care what what the EXE wants to do with the DLL's data.


问:
Using as keyword and then length in the same ngIf
I want to avoid multiple sync operations and would like to assign the async property with 'AS' keyword and further check the length.
I tried the following code, but it is giving error:

```<code><div *ngIf="(selectedNames$ | async as selectedNames)?.length"> {{selectedNames}}</div>
</code>```

I tried another option too and still it's the same:

```<code><div *ngIf="((selectedNames$ | async) as selectedNames)?.length"> {{selectedNames}}</div>
</code>```

Brackets do not seem to be at correct position. Is it even possible?

答:
One way to get the desired result is with two *ngIf directives. The first one, applied to an ng-container, defines the selectedNames variable. The second one applies the *ngIf condition, with selectedNames.length, to the div element:

```<code><ng-container *ngIf="(selectedNames$ | async) as selectedNames">
  <div *ngIf="selectedNames.length">
    {{selectedNames | json}}
  </div>
</ng-container>
</code>```

See this stackblitz for a demo.

Body:
I want to avoid multiple sync operations and would like to assign the async property with 'AS' keyword and further check the length.
I tried the following code, but it is giving error:

 {{selectedNames}}

I tried another option too and still it's the same:

 {{selectedNames}}

Brackets do not seem to be at correct position. Is it even possible?

Body:
One way to get the desired result is with two *ngIf directives. The first one, applied to an ng-container, defines the selectedNames variable. The second one applies the *ngIf condition, with selectedNames.length, to the div element:

<ng-container *ngIf="(selectedNames$ | async) as selectedNames">
  <div *ngIf="selectedNames.length">
    {{selectedNames | json}}
  </div>
</ng-container>

See this stackblitz for a demo.


问:
Cyclic splitting of execution into several threads (1-N-1-N-1...)
Consider this case:

```<code>for (...)
{
    const size_t count = ...

    for (size_t i = 0; i < count; ++i)
    {
        calculate(i); // thread-safe function
    }
}
</code>```

What is the most elegant solution to maximize performance using C++17 and/or boost?

Cyclic "create + join" threads makes no sense because of huge overhead (which in my case exactly equals possible gain).

So I have to create N threads only once and keep them synchronized with the main one (using: mutex, shared_mutex, condition_variable, atomic, etc.). It appeared to be quite difficult task for such common and clear situation (in order to make everything really safe and fast). Sticking with it during days I have a feeling of "inventing a bicycle"...

Update 1: calculate(x) and calculate(y) can (and should) run in
parallel

Update 2: std::atomic::fetch_add (or smth.) is more preferable
than queue (or smth.)

Update 3: extreme computations (i.e. millions of "outer" calls and hundreds of "inner")

Update 4: calculate() changes internal object's data without returning a value

Intermediate solution

For some reason "async + wait" is much faster then "create + join" threads. So these two examples make 100% speed increase:

Example 1

```<code>for (...)
{
    const size_t count = ...

    future<void> execution[cpu_cores];

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x] = async(launch::async, ref(*this), x, count);
    }

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x].wait();
    }
}

void operator()(const size_t x, const size_t count)
{
    for (size_t i = x; i < count; i += cpu_cores)
    {
        calculate(i);
    }
}
</code>```

Example 2

```<code>for (...)
{
    index = 0;

    const size_t count = ...

    future<void> execution[cpu_cores];

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x] = async(launch::async, ref(*this), count);
    }

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x].wait();
    }
}

atomic<size_t> index;

void operator()(const size_t count)
{
    for (size_t i = index.fetch_add(1); i < count; i = index.fetch_add(1))
    {
        calculate(i);
    }
}
</code>```

Is it possible to make it even faster by creating threads only once and then synchronize them with a small overhead?

Final solution

Additional +20% of speed increase in comparison to std::async!

```<code>for (size_t i = 0; i < _countof(index); ++i) { index[i] = i; }

for_each_n(par_unseq, index, count, [&](const size_t i) { calculate(i); });
</code>```

Is it possible to avoid redundant array "index"?

Yes:

```<code>for_each_n(par_unseq, counting_iterator<size_t>(0), count,

    [&](const size_t i)
    {
        calculate(i);
    });
</code>```

答:
In the past, you'd use OpenMP, GNU Parallel, Intel TBB.¹

If you have c++17², I'd suggest using execution policies with standard algorithms.

It's really better than you can expect to do things yourself, although it

requires some fore-thought to choose your types to be amenable to standard algorithms

still helps if you know what will happen under the hood

Here's a simple example without further ado:

Live On Compiler Explorer

```<code>#include <thread>
#include <algorithm>
#include <random>
#include <execution>
#include <iostream>
using namespace std::chrono_literals;

static size_t s_random_seed = std::random_device{}();

static auto generate_param() {
    static std::mt19937 prng {s_random_seed};
    static std::uniform_int_distribution<> dist;
    return dist(prng);
}

struct Task {
    Task(int p = generate_param()) : param(p), output(0) {}

    int param;
    int output;

    struct ByParam  { bool operator()(Task const& a, Task const& b) const { return a.param < b.param; } };
    struct ByOutput { bool operator()(Task const& a, Task const& b) const { return a.output < b.output; } };
};

static void calculate(Task& task) {
    //std::this_thread::sleep_for(1us);
    task.output = task.param ^ 0xf0f0f0f0;
}

int main(int argc, char** argv) {
    if (argc>1) {
        s_random_seed = std::stoull(argv[1]);
    }

    std::vector<Task> jobs;

    auto now = std::chrono::high_resolution_clock::now;
    auto start = now();

    std::generate_n(
            std::execution::par_unseq,
            back_inserter(jobs),
            1ull << 28, // reduce for small RAM!
            generate_param);

    auto laptime = [&](auto caption) {
        std::cout << caption << " in " << (now() - start)/1.0s << "s" << std::endl;
        start = now();
    };
    laptime("generate randum input");

    std::sort(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        Task::ByParam{});

    laptime("sort by param");

    std::for_each(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        calculate);

    laptime("calculate");

    std::sort(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        Task::ByOutput{});

    laptime("sort by output");

    auto const checksum = std::transform_reduce(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        0, std::bit_xor<>{},
        std::mem_fn(&Task::output)
    );

    laptime("reduce");
    std::cout << "Checksum: " << checksum << "\n";
}
</code>```

When run with the seed 42, prints:

```<code>generate randum input in 10.8819s
sort by param in 8.29467s
calculate in 0.22513s
sort by output in 5.64708s
reduce in 0.108768s
Checksum: 683872090
</code>```

CPU utilization is 100% on all cores except for the first (random-generation) step.

¹  (I think I have answers demoing all of these on this site).

² See Are C++17 Parallel Algorithms implemented already?

Body:
Consider this case:

for (...)
{
    const size_t count = ...

    for (size_t i = 0; i < count; ++i)
    {
        calculate(i); // thread-safe function
    }
}

What is the most elegant solution to maximize performance using C++17 and/or boost?

Cyclic "create + join" threads makes no sense because of huge overhead (which in my case exactly equals possible gain).

So I have to create N threads only once and keep them synchronized with the main one (using: mutex, shared_mutex, condition_variable, atomic, etc.). It appeared to be quite difficult task for such common and clear situation (in order to make everything really safe and fast). Sticking with it during days I have a feeling of "inventing a bicycle"...

Update 1: calculate(x) and calculate(y) can (and should) run in
parallel

Update 2: std::atomic::fetch_add (or smth.) is more preferable
than queue (or smth.)

Update 3: extreme computations (i.e. millions of "outer" calls and hundreds of "inner")

Update 4: calculate() changes internal object's data without returning a value

Intermediate solution

For some reason "async + wait" is much faster then "create + join" threads. So these two examples make 100% speed increase:

Example 1

for (...)
{
    const size_t count = ...

    future<void> execution[cpu_cores];

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x] = async(launch::async, ref(*this), x, count);
    }

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x].wait();
    }
}

void operator()(const size_t x, const size_t count)
{
    for (size_t i = x; i < count; i += cpu_cores)
    {
        calculate(i);
    }
}

Example 2

for (...)
{
    index = 0;

    const size_t count = ...

    future<void> execution[cpu_cores];

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x] = async(launch::async, ref(*this), count);
    }

    for (size_t x = 0; x < cpu_cores; ++x)
    {
        execution[x].wait();
    }
}

atomic<size_t> index;

void operator()(const size_t count)
{
    for (size_t i = index.fetch_add(1); i < count; i = index.fetch_add(1))
    {
        calculate(i);
    }
}

Is it possible to make it even faster by creating threads only once and then synchronize them with a small overhead?

Final solution

Additional +20% of speed increase in comparison to std::async!

for (size_t i = 0; i < _countof(index); ++i) { index[i] = i; }

for_each_n(par_unseq, index, count, [&](const size_t i) { calculate(i); });

Is it possible to avoid redundant array "index"?

Yes:

for_each_n(par_unseq, counting_iterator<size_t>(0), count,

    [&](const size_t i)
    {
        calculate(i);
    });

Body:
In the past, you'd use OpenMP, GNU Parallel, Intel TBB.¹

If you have c++17², I'd suggest using execution policies with standard algorithms.

It's really better than you can expect to do things yourself, although it

requires some fore-thought to choose your types to be amenable to standard algorithms

still helps if you know what will happen under the hood

Here's a simple example without further ado:

Live On Compiler Explorer

#include <thread>
#include <algorithm>
#include <random>
#include <execution>
#include <iostream>
using namespace std::chrono_literals;

static size_t s_random_seed = std::random_device{}();

static auto generate_param() {
    static std::mt19937 prng {s_random_seed};
    static std::uniform_int_distribution<> dist;
    return dist(prng);
}

struct Task {
    Task(int p = generate_param()) : param(p), output(0) {}

    int param;
    int output;

    struct ByParam  { bool operator()(Task const& a, Task const& b) const { return a.param < b.param; } };
    struct ByOutput { bool operator()(Task const& a, Task const& b) const { return a.output < b.output; } };
};

static void calculate(Task& task) {
    //std::this_thread::sleep_for(1us);
    task.output = task.param ^ 0xf0f0f0f0;
}

int main(int argc, char** argv) {
    if (argc>1) {
        s_random_seed = std::stoull(argv[1]);
    }

    std::vector<Task> jobs;

    auto now = std::chrono::high_resolution_clock::now;
    auto start = now();

    std::generate_n(
            std::execution::par_unseq,
            back_inserter(jobs),
            1ull << 28, // reduce for small RAM!
            generate_param);

    auto laptime = [&](auto caption) {
        std::cout << caption << " in " << (now() - start)/1.0s << "s" << std::endl;
        start = now();
    };
    laptime("generate randum input");

    std::sort(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        Task::ByParam{});

    laptime("sort by param");

    std::for_each(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        calculate);

    laptime("calculate");

    std::sort(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        Task::ByOutput{});

    laptime("sort by output");

    auto const checksum = std::transform_reduce(
        std::execution::par_unseq,
        begin(jobs), end(jobs),
        0, std::bit_xor<>{},
        std::mem_fn(&Task::output)
    );

    laptime("reduce");
    std::cout << "Checksum: " << checksum << "\n";
}

When run with the seed 42, prints:

generate randum input in 10.8819s
sort by param in 8.29467s
calculate in 0.22513s
sort by output in 5.64708s
reduce in 0.108768s
Checksum: 683872090

CPU utilization is 100% on all cores except for the first (random-generation) step.

¹  (I think I have answers demoing all of these on this site).

² See Are C++17 Parallel Algorithms implemented already?


问:
How to generate a presigned URL with content-type disposition using GCS Ruby SDK
In the Amazon S3 SDK, when generating a presigned URL, I can generate a URL setting the content-disposition, but I cannot find a similar way of configuring these options using Google.

The method call available to us is:

```<code>https://www.rubydoc.info/gems/google-cloud-storage/0.20.0/Google/Cloud/Storage/File#signed_url-instance_method
</code>```

I am trying to upload a file directly to a Google bucket and not via my Rails server, and want to set the content-disposition of the file being uploaded via the presigned URL. Is there a way of doing this? Is there a way of setting object meta data via a presigned URL?

```<code>require "google/cloud"

gcloud = Google::Cloud.new
storage = gcloud.storage

bucket = storage.bucket "my-todo-app"
file = bucket.file "avatars/heidi/400x400.png"
shared_url = file.signed_url
# The parameters it takes is: signed_url(method: nil, expires: nil, content_type: nil, content_md5: nil, issuer: nil, client_email: nil, signing_key: nil, private_key: nil)

# how do we add content_disposition?
# how do we add object meta data?
</code>```

答:
I'm looking for the same answer, and so far I have found this other Stack Overflow article, which doesn't directly address Ruby SDK, but it does offer a good piece of information.

Google Cloud Storage: download a file with a different name

You can also generate signed URLs that include the response-content-disposition query parameter. Then the users will be making authorized requests to download the resource.

So it appears that you can add the query parameter ?response-content-disposition=[disposition-string-urlencoded] to the resulting signed string.

So, I looked at the File object definition in the Ruby SDK and it appears you can do this:

file.content_dispostion = "attachment" # or whatever your disposition is
url = file.signed_url
```

NOTE: If you read my entry before I edited it, my apologies.

Body:
In the Amazon S3 SDK, when generating a presigned URL, I can generate a URL setting the content-disposition, but I cannot find a similar way of configuring these options using Google.

The method call available to us is:

https://www.rubydoc.info/gems/google-cloud-storage/0.20.0/Google/Cloud/Storage/File#signed_url-instance_method

I am trying to upload a file directly to a Google bucket and not via my Rails server, and want to set the content-disposition of the file being uploaded via the presigned URL. Is there a way of doing this? Is there a way of setting object meta data via a presigned URL?

require "google/cloud"

gcloud = Google::Cloud.new
storage = gcloud.storage

bucket = storage.bucket "my-todo-app"
file = bucket.file "avatars/heidi/400x400.png"
shared_url = file.signed_url
# The parameters it takes is: signed_url(method: nil, expires: nil, content_type: nil, content_md5: nil, issuer: nil, client_email: nil, signing_key: nil, private_key: nil)

# how do we add content_disposition?
# how do we add object meta data?

Body:
I'm looking for the same answer, and so far I have found this other Stack Overflow article, which doesn't directly address Ruby SDK, but it does offer a good piece of information.

Google Cloud Storage: download a file with a different name

You can also generate signed URLs that include the response-content-disposition query parameter. Then the users will be making authorized requests to download the resource.

So it appears that you can add the query parameter ?response-content-disposition=[disposition-string-urlencoded] to the resulting signed string.

So, I looked at the File object definition in the Ruby SDK and it appears you can do this:

file.content_dispostion = "attachment" # or whatever your disposition is
url = file.signed_url

NOTE: If you read my entry before I edited it, my apologies.


问:
How to link to user's profile on django
I have been trying to link to user's profile page but everytime I try it, it returns a 404 error. I dont know but maybe the error is on the urls.py file.

views.py

```<code>    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)

      else:
        post_owner = request.user

      args1 = {
        'post_owner': post_owner,
      }
      return render(request, 'profile.html', args1)
</code>```

urls.py

```<code>    urlpatterns = [
      path('<str:username>/', views.profile, name='profile'),
      path('login', views.login, name='login'),
      path('register', views.register, name='register'),
      path('logout', views.logout, name='logout'),

    ]
</code>```

index.html

```<code>    <a class="nav-link" href="{{ request.user }}">{{ user.username }}</a>
</code>```

答:
You should link it with:

```<code><a class="nav-link" href="{{ <b>request.user.username</b> }}">{{ user.username }}</a></code>```

but better would be to use an {% url … } template tag [Django-doc]:

```<code><a class="nav-link" href="<b>{% url 'profile' username=request.user.username %}</b>">{{ user.username }}</a></code>```

Your paths also overlap, this means that you will never be able to access login, register or logout, since the first path will "fire" with the idea that username='login'.

You better define non-overlapping paths, like:

```<code>urlpatterns = [
    path('<b>profile/</b><str:username>/', views.profile, name='profile'),
    path('login/', views.login, name='login'),
    path('register/', views.register, name='register'),
    path('logout/', views.logout, name='logout'),
]</code>```

Title: How to link to user's profile on django

Body:
I have been trying to link to user's profile page but everytime I try it, it returns a 404 error. I dont know but maybe the error is on the urls.py file.

views.py

    def profile(request, username=None):
      if username:
        post_owner = get_object_or_404(User, username=username)

      else:
        post_owner = request.user

      args1 = {
        'post_owner': post_owner,
      }
      return render(request, 'profile.html', args1)

urls.py

    urlpatterns = [
      path('<str:username>/', views.profile, name='profile'),
      path('login', views.login, name='login'),
      path('register', views.register, name='register'),
      path('logout', views.logout, name='logout'),

    ]

index.html

    {{ user.username }}

Body:
You should link it with:

<a class="nav-link" href="{{ request.user.username }}">{{ user.username }}</a>

but better would be to use an {% url … } template tag [Django-doc]:

<a class="nav-link" href="{% url 'profile' username=request.user.username %}">{{ user.username }}</a>

Your paths also overlap, this means that you will never be able to access login, register or logout, since the first path will "fire" with the idea that username='login'.

You better define non-overlapping paths, like:

urlpatterns = [
    path('profile/<str:username>/', views.profile, name='profile'),
    path('login/', views.login, name='login'),
    path('register/', views.register, name='register'),
    path('logout/', views.logout, name='logout'),
]


问:
Setting the name of an object in Firebase
I've got a React app that holds a survey and I'm trying to add results to database using Firebase. Basically I want each result set from a user taking the survey stored. I've created a variable that is the current date/time for when the survey is complete. So my plan was to have it look like for example 10/6/2020: result_set, but I'm getting an issue trying to set that, I think its just a basic syntax issue but I'm not entirely sure.

```<code>var moment = require('moment');
var now = moment().format();

database.ref('users/results').update({
   this.now: results_set
});
</code>```

It won't allow me to use 'this.now' but using 'now' just sets it to the string 'now' basically, is there a way to set it to a variable? Like I said it's probably just incorrect syntax but I'm stuck on it, any help would be appreciated.

答:
I think you're looking for:

```<code>database.ref('users/results').update({
   [this.now]: results_set
});
</code>```

By surrounding the variable in square brackets, the value of that variable ends up becoming the property name.

Body:
I've got a React app that holds a survey and I'm trying to add results to database using Firebase. Basically I want each result set from a user taking the survey stored. I've created a variable that is the current date/time for when the survey is complete. So my plan was to have it look like for example 10/6/2020: result_set, but I'm getting an issue trying to set that, I think its just a basic syntax issue but I'm not entirely sure.

var moment = require('moment');
var now = moment().format();

database.ref('users/results').update({
   this.now: results_set
});

It won't allow me to use 'this.now' but using 'now' just sets it to the string 'now' basically, is there a way to set it to a variable? Like I said it's probably just incorrect syntax but I'm stuck on it, any help would be appreciated.

Body:
I think you're looking for:

database.ref('users/results').update({
   [this.now]: results_set
});

By surrounding the variable in square brackets, the value of that variable ends up becoming the property name.


问:
CSV Filtering a column with mixed data types
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

```<code>awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv
</code>```

on

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

it returns what I want:

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

But, when I run that line of code on

```<code>71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
</code>```

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

```$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.```

答:
Not sure I see anything wrong what with filtering out nothing as that is in every array even before it is created.

But if you want to keep then all then adding an  "or nothing"
clause would do it.

```<code>awk -F ',' '!seen[$4]++||$4!=""'
</code>```

Body:
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv

on

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO

it returns what I want:

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO

But, when I run that line of code on

71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.

Body:
Not sure I see anything wrong what with filtering out nothing as that is in every array even before it is created.

But if you want to keep then all then adding an  "or nothing"
clause would do it.

awk -F ',' '!seen[$4]++||$4!=""'


问:
Get index of last occurence of matched string?
I want to get the index of the last occurrence of a character in a string which is part of a match string. What's the most efficient way to do this?

Something like match(/[\.,;]/g) but I want the index in the original string of the last element of the returned array, the way that match(/[\.,;]/) gives the index of the first match.

E.g., if string is Hello, this is a test. foo I want the index of the last period/comma/semicolon.

The best solution I've come up with is reversing the string and finding first match:

```<code>text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1
</code>```

答:
A bit of a hacky solution, but you can use a function as an argument to replace:

const matches = [];
const text = "foo.bar,qaz";
// don't use any capturing groups otherwise the function will be messed up
text.replace(/[\.,;]/g, (match, offset) => matches.push(offset));
console.log(matches[matches.length - 1]);
```

Body:
I want to get the index of the last occurrence of a character in a string which is part of a match string. What's the most efficient way to do this?

Something like match(/[\.,;]/g) but I want the index in the original string of the last element of the returned array, the way that match(/[\.,;]/) gives the index of the first match.

E.g., if string is Hello, this is a test. foo I want the index of the last period/comma/semicolon.

The best solution I've come up with is reversing the string and finding first match:

text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1


问:
Stop LastPass filling out a form
Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?

This is an hidden field, so I don't want any software to use this field for their purposes:

```<code><input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">
</code>```

The solution should not be like "rename the input field".

答:
Here's what worked for me to prevent lastpass from filling a razor  @Html.EditorFor box in Chrome:

Click the active LastPass icon  in your toolbar, then go to Account Options > Extension Preferences.

On this screen check "Don't overwrite fields that are already filled" (at the bottom)

Next, click "advanced" on the left.

On this screen check "Respect AutoComplete=off: allow websites to disable Autofill".

I did not need to do anything special in my ASP cshtml form but I did have a default value in the form for the @Html.EditorFor box.

I hope this helps and works for someone.  I could not find any Razor-specific help on this problem on the web so I thought I'd add this since I figured it out with the help of above link and contributions.

Title: Stop LastPass filling out a form

Body:
Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?

This is an hidden field, so I don't want any software to use this field for their purposes:

<input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">

The solution should not be like "rename the input field".


答:
The == comparison operator behaves differently within a double-brackets :

```<code>[[ $foo == 0* ]]   # True if $foo starts with foo "0" (wildcard matching).
[[ $foo == "0" ]] # True if $foo is equal to 0* (literal matching).
</code>```

This works because bash's builtin [[ operator treats the right-hand-side of an == test as a pattern:

When the == and != operators are used, the string to the right of the operator is used as >a pattern and pattern matching is performed.

the test builtin tests wheather strings are equal the [[expression]] syntax adds comparison test for string operators, the > and < operators compare strings for oder (i.e :"aa" < "bb"). the operator tests for pattern match not just equality [[ string = pattern ]] is true if string matches pattern, this operator is not symmertical , the pattern must appear on the right side of the equal sign, i.e [[ foo = a* ]] is true (=0),whereas
[[ a* = foo ]] is false(=1)

```<code>[[ "foo" == f* ]] && echo $? # 0

[[ f* == "foo" ]] && echo $? || echo $? # 1
</code>```

How come [[ $foo == $bar ]] is true and [[ $bar == $foo ]] is false?

The == operator is not symmetrical.  It takes a string on the left
and a pattern on the right.  However, if you double quote the right
hand side, which removes the special meaning of pattern match
characters, then this becomes a string comparison so that
[[ "$foo" == "bar" ]] and [[ "$bar" == "$foo" ]] are equivalent.

Title: Why are Bash conditions not symmetrical when using wildcards?

Body:
Suppose I have the following Bash snippet:

if [[ "$foo" == *"$bar"* ]] ; then
  echo 'condition is true'
fi

In English, you might describe the above code with: if bar is a substring of foo then...

However, how come when we switch the sides of the condition, we don't get the same results?

if [[ *"$bar"* == "$foo" ]] ; then
  echo 'condition is true'
fi

Perhaps I have a misunderstanding of when the wildcard is evaluated?

Body:
The == comparison operator behaves differently within a double-brackets :

[[ $foo == 0* ]]   # True if $foo starts with foo "0" (wildcard matching).
[[ $foo == "0" ]] # True if $foo is equal to 0* (literal matching).

This works because bash's builtin [[ operator treats the right-hand-side of an == test as a pattern:

When the == and != operators are used, the string to the right of the operator is used as >a pattern and pattern matching is performed.

the test builtin tests wheather strings are equal the [[expression]] syntax adds comparison test for string operators, the > and < operators compare strings for oder (i.e :"aa" < "bb"). the operator tests for pattern match not just equality [[ string = pattern ]] is true if string matches pattern, this operator is not symmertical , the pattern must appear on the right side of the equal sign, i.e [[ foo = a* ]] is true (=0),whereas
[[ a* = foo ]] is false(=1)

[[ "foo" == f* ]] && echo $? # 0

[[ f* == "foo" ]] && echo $? || echo $? # 1

How come [[ $foo == $bar ]] is true and [[ $bar == $foo ]] is false?

The == operator is not symmetrical.  It takes a string on the left
and a pattern on the right.  However, if you double quote the right
hand side, which removes the special meaning of pattern match
characters, then this becomes a string comparison so that
[[ "$foo" == "bar" ]] and [[ "$bar" == "$foo" ]] are equivalent.


问:
d3.csv returns index.html content in console.log
I am using d3 v5 with reactJS. I am calling d3.csv inside react 'List' class like following:

```<code>import React from 'react';
import * as d3 from 'd3';

class List extends React.Component{

componentDidMount(){
d3.csv("./data/data.csv").then(function(d, error){
    console.log(d);
});
}

render(){
        return(
        <div> </div>
        );
    }
}
  export default List;
</code>```

and List is being imported in following 'App' class

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import List from './components/list/List';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <List/>
      </div>
    );
  }
}
 export default App;
</code>```

Following is the 'index.js' code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
</code>```

'root' is a div id in index.html. By calling console.log in List file inside d3.csv I am getting content of index.html file in the console. But I want CSV content.

答: I had the same issue and here's how I solved it. Check if the data is in the same directory as the index.html file. In my case, my index.html file is in the public/ folder, so I created public/data/data.csv. You can then try d3.csv('./data/data', function(data){...}) to read in the data.

Body:
I am using d3 v5 with reactJS. I am calling d3.csv inside react 'List' class like following:

import React from 'react';
import * as d3 from 'd3';

class List extends React.Component{

componentDidMount(){
d3.csv("./data/data.csv").then(function(d, error){
    console.log(d);
});
}

render(){
        return(

        );
    }
}
  export default List;

and List is being imported in following 'App' class

import React, { Component } from 'react';
import logo from './logo.svg';
import List from './components/list/List';
import './App.css';

class App extends Component {
  render() {
    return (

Welcome to React

        <List/>

    );
  }
}
 export default App;

Following is the 'index.js' code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

'root' is a div id in index.html. By calling console.log in List file inside d3.csv I am getting content of index.html file in the console. But I want CSV content.


问:
How to apply Opacity On A DIV container background only and not change the text and check boxes
Is there a better way to make this work in 2020 on all browsers?

I want to make the background of the div have a reduced opacity and allow the remaining content to stay normal...

```<code>#menu {
  display: grid;
  grid-template-columns:auto 1fr;
  background-color: black; opacity: 0.6;
  width: 180px;
  font-family: Arial, Helvetica, sans-serif;
  color: beige;
 }
</code>```

答:
background: rgba(0, 0, 0, 0.6);

sorry I am stupid

Body:
Is there a better way to make this work in 2020 on all browsers?

I want to make the background of the div have a reduced opacity and allow the remaining content to stay normal...

#menu {
  display: grid;
  grid-template-columns:auto 1fr;
  background-color: black; opacity: 0.6;
  width: 180px;
  font-family: Arial, Helvetica, sans-serif;
  color: beige;
 }


问:
Javascript Algorithm Maximum subarray
I get that question from leet code and I got this answer from YouTube tutorial, but I don't understand the part of max. Because max is arr[0] and the value is -2, and even it goes inside of the loop, it is just -2 but max returns value 6.

How it possible?

const givenArray = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const getMax = arr => {
  let sum = arr[0]; //-2
  let max = arr[0]; //-2
  for (let i = 1; i < arr.length; i++) {
    sum = Math.max(sum + arr[i], arr[i]);
    max = Math.max(max, sum);

  }

  console.log(sum);
  console.log(max);
};

getMax(givenArray);```

答:
max=-2 sum=-2

loop arr[1]=1: sum = max( -2 + 1, 1) = 1, max = max( sum=1 , max=-2 ) = 1

max=1 sum=1

loop arr[2]=-3: sum = max( 1 + -3, -3) = -2, max = max( sum=-2, max=1 ) = 1

max=1 sum=-2

loop arr[3]=4: sum = max( -3 + 4, 4) = 4, max = max( sum=4, max=1 ) = 4

max=4 sum=4

loop arr[4]=-1: sum = max( 4 + -1, -1) = 3, max = (3,4) = 4

max=4 sum=3

loop arr[5]=2: sum = max( 3 + 2, 2) = 5, max = max(5,4) = 5

So the iteration looks like this:

```
arr [-2, 1, -3, 4, -1, 2, 1, -5, 4]
sum   x, 1,  x, 4,  3, 5, 6,  1, 5

max  -2, 1,  1, 4,  4, 5, 6,  6, 6
```

It's like finding progressive sums, discarding negative sequences or starting off a new sequence when sum is negative, because any negative sequence would contribute negatively to the total sum of a sequence.

And, you use max = Math.max(max, sum), (set max to what's bigger, current max value or current sum) to find the largest value reached in the progressive sums (which is 6).

This also accounts for edge case of all negatives, where the maximal sum will be the largest negative number.

const givenArray = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const getMax = arr => {
  let sum = arr[0]; //-2
  let max = arr[0]; //-2
  for (let i = 1; i < arr.length; i++) {
    sum = Math.max(sum + arr[i], arr[i]);
    max = Math.max(max, sum);
    console.log(`max=${max}`, `sum=${sum}`);
  }

};

getMax(givenArray);```

Title: Javascript Algorithm Maximum subarray

Body:
max=-2 sum=-2

loop arr[1]=1: sum = max( -2 + 1, 1) = 1, max = max( sum=1 , max=-2 ) = 1

max=1 sum=1

loop arr[2]=-3: sum = max( 1 + -3, -3) = -2, max = max( sum=-2, max=1 ) = 1

max=1 sum=-2

loop arr[3]=4: sum = max( -3 + 4, 4) = 4, max = max( sum=4, max=1 ) = 4

max=4 sum=4

loop arr[4]=-1: sum = max( 4 + -1, -1) = 3, max = (3,4) = 4

max=4 sum=3

loop arr[5]=2: sum = max( 3 + 2, 2) = 5, max = max(5,4) = 5

So the iteration looks like this:

arr [-2, 1, -3, 4, -1, 2, 1, -5, 4]
sum   x, 1,  x, 4,  3, 5, 6,  1, 5

max  -2, 1,  1, 4,  4, 5, 6,  6, 6

It's like finding progressive sums, discarding negative sequences or starting off a new sequence when sum is negative, because any negative sequence would contribute negatively to the total sum of a sequence.

And, you use max = Math.max(max, sum), (set max to what's bigger, current max value or current sum) to find the largest value reached in the progressive sums (which is 6).

This also accounts for edge case of all negatives, where the maximal sum will be the largest negative number.

const givenArray = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const getMax = arr => {
  let sum = arr[0]; //-2
  let max = arr[0]; //-2
  for (let i = 1; i < arr.length; i++) {
    sum = Math.max(sum + arr[i], arr[i]);
    max = Math.max(max, sum);
    console.log(`max=${max}`, `sum=${sum}`);
  }

};

getMax(givenArray);


问:
Can I make dataframes by for loop?
I want to make each 10 dataframes using a for loop.

But it just keeps being overwritten.

How can I make each dataframe using for loop?

```<code>for i in range(10):
    df = pd.DataFrame({'name' : list_name,
                       'year' : list_year,
                       'point' : list_point})
</code>```

答:
```<code>dict_dfs = {}

for i in range(10):
    dict_dfs[i] = pd.DataFrame({'name' : [list_name],
                       'year' : [list_year],
                       'point' : [list_point]})
print(dict_dfs.get(1))
</code>```

You cannot create multipe dataframes with the same name or a dynamic variable name, you can however .append() them (like mentioned by others) or create a dictionary of dataframes like this:

Title: Can I make dataframes by for loop?

Body:
I want to make each 10 dataframes using a for loop.

But it just keeps being overwritten.

How can I make each dataframe using for loop?

for i in range(10):
    df = pd.DataFrame({'name' : list_name,
                       'year' : list_year,
                       'point' : list_point})

Body:
dict_dfs = {}

for i in range(10):
    dict_dfs[i] = pd.DataFrame({'name' : [list_name],
                       'year' : [list_year],
                       'point' : [list_point]})
print(dict_dfs.get(1))

You cannot create multipe dataframes with the same name or a dynamic variable name, you can however .append() them (like mentioned by others) or create a dictionary of dataframes like this:


问:
next.js getStaticPaths list every path or only those in the immediate vicinity?
Using Next.js to export static pages, I get that in a dynamic route like pages/[id].js any path I put in the getStaticPaths section will be created. Cool.

Is it better to list every page:

```<code>getStaticPaths(){
  return (
    // some function to spit out a list of every possible page
  )
}
</code>```

or

```<code>getStaticPaths(){
  return (
    // some function to return the next and previous page
  )
}
</code>```

or does it matter?

答:
For dynamic routes example posts/[id].js getStaticPaths needs to define a list of paths so that Next.js pre-render all the specified paths at build time.

The function getStaticPaths needs to return an object with paths property which is an array with the route params and the property fallback which will be true or false. If fallback is set to false for any path that is not returned from the function getStaticPaths will not be pre-rendered hence resulting in a 404 page.

If you know all the paths that you need to render ahead of time you can set fallback to false.Here is an example..

 // getStaticPaths for /category/[slug] where slug can only be -
 // either 'category-slug-1', 'category-slug-2' or 'category-slug-3'

 export const getStaticPaths = async () => {

   return {
      paths: [
        { params: { slug: 'category-slug-1'} },
        { params: { slug: 'category-slug-2'} },
        { params: { slug: 'category-slug-3'} }
       ],
     fallback: false // fallback is set to false because we already know the slugs ahead of time
   }

 }

```
<p>Let's says you have a route <code>/posts/[id].js</code> and ids coming from a database, and new posts are created every day. In this case, you can return the paths which already exist to pre-render some pages. and set <code>fallback</code> to <code>true</code> and on request, Next.js will serve a fallback version of the page instead of showing <code>404</code> page for the paths that are not returned from the function <code>getStaticPaths</code>, then in the background, nextjs will call <code>getStaticProps</code> for the requested path and serve the data as JSON which will be used to render the page in the browser.</p>
<p>Here is an example,</p>
<pre class="lang-js prettyprint-override"><code>
export const getStaticPaths = async () => {
   const posts = await // your database query or fetch to remote API

   // generate the paths
   const paths = posts.map(post => ({
        params: { id: post.id } // keep in mind if post.id is a number you need to stringify post.id
      })
   );

   return {
      paths,
      fallback: true
   }

 }

</code>```

P.S. - When using fallback set to true you need to render some sort of fallback component in your NextPage component otherwise when you try to access the data from props, it will throw an error like cannot read property ...x of undefined

You can render a fallback like this,

// in your page component
import {useRouter} from 'next/router';

const router = useRouter();

if (router.isFallback) {
   return
loading...

}
```

Body:
Using Next.js to export static pages, I get that in a dynamic route like pages/[id].js any path I put in the getStaticPaths section will be created. Cool.

Is it better to list every page:

getStaticPaths(){
  return (
    // some function to spit out a list of every possible page
  )
}

or

getStaticPaths(){
  return (
    // some function to return the next and previous page
  )
}

or does it matter?

Body:
For dynamic routes example posts/[id].js getStaticPaths needs to define a list of paths so that Next.js pre-render all the specified paths at build time.

The function getStaticPaths needs to return an object with paths property which is an array with the route params and the property fallback which will be true or false. If fallback is set to false for any path that is not returned from the function getStaticPaths will not be pre-rendered hence resulting in a 404 page.

If you know all the paths that you need to render ahead of time you can set fallback to false.Here is an example..

 // getStaticPaths for /category/[slug] where slug can only be -
 // either 'category-slug-1', 'category-slug-2' or 'category-slug-3'

 export const getStaticPaths = async () => {

   return {
      paths: [
        { params: { slug: 'category-slug-1'} },
        { params: { slug: 'category-slug-2'} },
        { params: { slug: 'category-slug-3'} }
       ],
     fallback: false // fallback is set to false because we already know the slugs ahead of time
   }

 }

Let's says you have a route /posts/[id].js and ids coming from a database, and new posts are created every day. In this case, you can return the paths which already exist to pre-render some pages. and set fallback to true and on request, Next.js will serve a fallback version of the page instead of showing 404 page for the paths that are not returned from the function getStaticPaths, then in the background, nextjs will call getStaticProps for the requested path and serve the data as JSON which will be used to render the page in the browser.

Here is an example,

export const getStaticPaths = async () => {
   const posts = await // your database query or fetch to remote API

   // generate the paths
   const paths = posts.map(post => ({
        params: { id: post.id } // keep in mind if post.id is a number you need to stringify post.id
      })
   );

   return {
      paths,
      fallback: true
   }

 }

P.S. - When using fallback set to true you need to render some sort of fallback component in your NextPage component otherwise when you try to access the data from props, it will throw an error like cannot read property ...x of undefined

You can render a fallback like this,

// in your page component
import {useRouter} from 'next/router';

const router = useRouter();

if (router.isFallback) {
   return <div>loading...</div>
}


问:
Does wkwebview support HTML5 capture attribute?
As the title said, does it support it? Here is the MDN Documentation of it (Incomplete) and Here is the caniuse browsers support list.

However, none of them talked about wkwebview. Does it support this attribute? If so, it would help tremendously.

Thanks for answering this question beforehand.

答:
After some experiments, apparently it is supported, only if an UDID is registered (how this is registered don't ask me, it was through a vendor. I don't have the details.)

It opens the camera and after you took a pic or a video it behaves like any common file picker.

To implement this in one of those html qr/barcode scanners it needs to have the ability to scan an image. But hey, better than nothing right?


问:
How to force HTTPS in a Django project using Cloudinary?
I am using Cloudinary in my Django project to upload and store my images.

Something like this:

```<code>class MyModel(models.Model):
    logo = CloudinaryField('Logo', blank=True, null=True)
</code>```

In my serializers, if I call something like:

```<code>mymodel = MyModel.objects.get(pk=1)
return mymodel.logo.url
</code>```

What is being returned is a cloudinary url but only with http. How do I fix this? How do I get https?

答:
Set secure in settings:

```<code>cloudinary.config(cloud_name = "", api_key = "", api_secret = "", secure = True)
</code>```

Body:
I am using Cloudinary in my Django project to upload and store my images.

Something like this:

class MyModel(models.Model):
    logo = CloudinaryField('Logo', blank=True, null=True)

In my serializers, if I call something like:

mymodel = MyModel.objects.get(pk=1)
return mymodel.logo.url

What is being returned is a cloudinary url but only with http. How do I fix this? How do I get https?

Body:
Set secure in settings:

cloudinary.config(cloud_name = "", api_key = "", api_secret = "", secure = True)


问:
Problems getting stress.py to work with Cassandra
I am trying to run the stress.py stress test included with Cassandra. When I attempt to run ./stress.py I get the following output:

```<code>Traceback (most recent call last):
  File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap
    self.run()
  File "./stress.py", line 238, in run
    self.cclient.batch_mutate(cfmap, consistency)
  File "/opt/cassandra/apache-cassandra-0.7.6-2-src/contrib/py_stress/cassandra/Cassandra.py", line 784, in batch_mutate
    self.recv_batch_mutate()
  File "/opt/cassandra/apache-cassandra-0.7.6-2-src/contrib/py_stress/cassandra/Cassandra.py", line 808, in recv_batch_mutate
    raise result.ue
UnavailableException: UnavailableException()
Process Inserter-49:
</code>```

Any thoughts? Thanks

答:
UnavailableException means too many nodes are down. Use "nodetool ring" to find out which.

Also: unless you're customizing stress.py, the java stress tool is significantly faster.  (With python you need roughly 1:1 client machines to cassandra machines to fully saturate it; with java it's more like 1:5.)

Body:
I am trying to run the stress.py stress test included with Cassandra. When I attempt to run ./stress.py I get the following output:

Traceback (most recent call last):
  File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap
    self.run()
  File "./stress.py", line 238, in run
    self.cclient.batch_mutate(cfmap, consistency)
  File "/opt/cassandra/apache-cassandra-0.7.6-2-src/contrib/py_stress/cassandra/Cassandra.py", line 784, in batch_mutate
    self.recv_batch_mutate()
  File "/opt/cassandra/apache-cassandra-0.7.6-2-src/contrib/py_stress/cassandra/Cassandra.py", line 808, in recv_batch_mutate
    raise result.ue
UnavailableException: UnavailableException()
Process Inserter-49:

Any thoughts? Thanks


答:
Your solution is not efficient because this is go through every character  text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1.
You can simply using a for loop:
Run and check the code below:

const text = "Hello, this is a test. foo"
const validChecker = [".",",",";"] // any char you want
const findLast = (text,validChecker) =>{
  if(!text) return
  for(let i = text.length -1; i>=0; i--){
    if(validChecker.includes(text[i])){
      return i
    }
  }
}

console.log(findLast(text,validChecker))```

Title: Get index of last occurence of matched string?


问:
Jsdoc is not excluding paths
I'm using Jsdoc 3.6.2. I have this source configuration in conf.json:

```<code>"source": {
        "exclude":["MyProj/excludeFolder"],
        "includePattern": ".+\\.js(doc|x|xinc)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    }
</code>```

When I execute jsdoc -r -c pathToMy/conf.json on MyProj directory , Jsdoc is not excluding 'excludeFolder' folder. I know that it is using the correct config.json file because it's including all .jsxinc files. How can I fix that?

EDIT:
I'm working on Windows 10 and vscode. Jsdoc is installed globally on C:/Users/myUser/appData/Roaming/npm. I've created a toy project on C:/Users/myUser/myProject with the following structure:

```<code>myProject/
|-out/
    |-conf.json
|-src/
    |-includeFile.jsxinc
    |-excludeFolder/
        |-exludeFile.jsxinc
</code>```

This is the full conf.json:

```<code>{
    "tags": {
        "allowUnknownTags": true
    },
    "source": {
        "exclude":["myProject/src/excludeFolder"],
        "includePattern": ".+\\.js(doc|x|xinc)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    },
    "plugins": [],
    "templates": {
        "cleverLinks": false,
        "monospaceLinks": false,
        "default": {
            "outputSourceFiles": true
        }
    }
}
</code>```

This is the code in 'excludeFile.jsxinc':

```<code>/**
* @class
*/
function excludeClass(){}
</code>```

And this is the code in 'includeFile.jsxinc':

```<code>/**
* @class
*/
function includeClass(){}
</code>```

When I run the following comand on power shell at C:/Users/myUser/myProject: jsdoc -c C:/Users/myUser/myProject/out/conf.json -r., documentation is generated for both classes: includeClass and excludeClass. In the real project, the exclude folder contains third party libraries that use jsdoc.

答:
I was facing same issue and I resolved with this:

```<code>"excludePattern": "myProject/src/excludeFolder"
</code>```

and delete "exclude" attribute.

Title: Jsdoc is not excluding paths

Body:
I'm using Jsdoc 3.6.2. I have this source configuration in conf.json:

"source": {
        "exclude":["MyProj/excludeFolder"],
        "includePattern": ".+\\.js(doc|x|xinc)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    }

When I execute jsdoc -r -c pathToMy/conf.json on MyProj directory , Jsdoc is not excluding 'excludeFolder' folder. I know that it is using the correct config.json file because it's including all .jsxinc files. How can I fix that?

EDIT:
I'm working on Windows 10 and vscode. Jsdoc is installed globally on C:/Users/myUser/appData/Roaming/npm. I've created a toy project on C:/Users/myUser/myProject with the following structure:

myProject/
|-out/
    |-conf.json
|-src/
    |-includeFile.jsxinc
    |-excludeFolder/
        |-exludeFile.jsxinc

This is the full conf.json:

{
    "tags": {
        "allowUnknownTags": true
    },
    "source": {
        "exclude":["myProject/src/excludeFolder"],
        "includePattern": ".+\\.js(doc|x|xinc)?$",
        "excludePattern": "(^|\\/|\\\\)_"
    },
    "plugins": [],
    "templates": {
        "cleverLinks": false,
        "monospaceLinks": false,
        "default": {
            "outputSourceFiles": true
        }
    }
}

This is the code in 'excludeFile.jsxinc':

/**
* @class
*/
function excludeClass(){}

And this is the code in 'includeFile.jsxinc':

/**
* @class
*/
function includeClass(){}

When I run the following comand on power shell at C:/Users/myUser/myProject: jsdoc -c C:/Users/myUser/myProject/out/conf.json -r., documentation is generated for both classes: includeClass and excludeClass. In the real project, the exclude folder contains third party libraries that use jsdoc.

Body:
I was facing same issue and I resolved with this:

"excludePattern": "myProject/src/excludeFolder"

and delete "exclude" attribute.


问:
How to escape double qootes in Junit 5 a ParametrizedTest with CsvFileSource
When using @ParametrizedTest in Junit 5 with @CsvFileSource, i need a parameter containing double quotes. How do I escape these, i.e. how do i pass exatly "a test" as my parameter?

What I have tried:

```<code>"a test"
""a test""
\"a test\"
"\"a test\""
</code>```

What the parameter is converted to:

```<code>a test
""a test""
\"a test\"
"\"a test\""
</code>```

答:
Thanks to @markspace's comment, I noticed the problem is not Junit 5, but the CSV standard. So I tried editing it in LibreOffice instead of a text editor, which gave me the answer:

```<code>"""a test"""
</code>```

result:

```<code>"a test"
</code>```

Body:
When using @ParametrizedTest in Junit 5 with @CsvFileSource, i need a parameter containing double quotes. How do I escape these, i.e. how do i pass exatly "a test" as my parameter?

What I have tried:

"a test"
""a test""
\"a test\"
"\"a test\""

What the parameter is converted to:

a test
""a test""
\"a test\"
"\"a test\""

Body:
Thanks to @markspace's comment, I noticed the problem is not Junit 5, but the CSV standard. So I tried editing it in LibreOffice instead of a text editor, which gave me the answer:

"""a test"""

result:

"a test"


问:
Same notifications is repeated with user after each exit from application
I use Service in my app to send Notifications to user after the user exits the application; it's work but I have one problem after user exits from app every time he gets last notification received each time he enters and leaves, the same notice is repeated even if there is no new notice. This is problem. Notifications should only be sent from once time to user, and if he exit next time it should not be sent again. Just if he have a new notification with a new ID it must be sent once time to user.

This is class my service

```<code>public class MyService extends Service {

    public MyService() {
    }

    @Override
    public void onCreate(){
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Toast.makeText(this, "Start myServis", Toast.LENGTH_LONG).show();
    //    run_loop();
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        Toast.makeText(this, "Stopmyservci", Toast.LENGTH_LONG).show();
       super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

</code>```

I get data by this code ..

```<code> public void run_loop(){
        String url =  "http://00000000/testnet/android_register_login/ShowAllData.php";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");
                                JSONObject hit = jsonArray.getJSONObject(0);
                                String id = hit.getString("id");
                                int lastThread = Integer.parseInt(String.valueOf(id));
                                JSONObject jsonObject = null;
                                Toast.makeText(MainActivtiy.this, lastThread + "", Toast.LENGTH_SHORT).show();
                                if (app.getTotal_threads() < lastThread) {
                                    app.setTotal_threads(lastThread);
                                    Notification notification = new NotificationCompat.Builder(MainActivtiy.this)
                                            .setSmallIcon(android.R.drawable.ic_popup_reminder)
                                            .setContentTitle("title")
                                            .setContentText("message")
                                            .setAutoCancel(true)
                                            .setPriority(NotificationCompat.PRIORITY_HIGH)
                                            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                                            .build();

                                    notificationManager.notify(1, notification);

                            }
                            } catch(JSONException e){
                                e.printStackTrace();
                            }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);

        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                run_loop();
            }
        },10000);

    }

</code>```

```<code>public void onBackPressed() {
        Intent sr =new Intent(this, MyService.class);
        startService(sr);
        Toast.makeText(this, "Exit", Toast.LENGTH_SHORT).show();
        finish();
        run_loop();
        super.onBackPressed();
    }

</code>```

I store id here

```<code>public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    private int Total_threads;
    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }
    public int getTotal_threads() {
        return Total_threads;
    }
    public void setTotal_threads(int Total_threads) {
        this.Total_threads = Total_threads;
    }
    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}
</code>```

and I get it from here

```<code>
    private void JSON() {
        String url = "http://00000000/test/Showall.php";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                JSONObject jsonObject = null;

                                String id= hit.getString("id");

app.setTotal_threads(Integer.parseInt(String.valueOf(id)));

                            }
</code>```

What can I try next?

答:
There are a couple of reasons in my mind for that:

The first is that your condition if (app.getTotal_threads() < lastThread) is met twice because the value of the Total_threads is lost for some reason, so you need to persistently store it like using a shared preference. Here is a modification for the App class to do that.

```<code>public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    public static final String PREFS_NAME = "PREFS_NAME";
    public static final String N_THREADS = "nThreads";

    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }

    public int getTotal_threads() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return prefs.getInt(N_THREADS, 0);
    }

    public void setTotal_threads(int Total_threads) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(N_THREADS, Total_threads);
        editor.apply();
    }

    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}
</code>```

The other possible reason is that the server could send the same notification with different thread number .. in this case you've to fix the back end.

Body:
I use Service in my app to send Notifications to user after the user exits the application; it's work but I have one problem after user exits from app every time he gets last notification received each time he enters and leaves, the same notice is repeated even if there is no new notice. This is problem. Notifications should only be sent from once time to user, and if he exit next time it should not be sent again. Just if he have a new notification with a new ID it must be sent once time to user.

This is class my service

public class MyService extends Service {

    public MyService() {
    }

    @Override
    public void onCreate(){
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        Toast.makeText(this, "Start myServis", Toast.LENGTH_LONG).show();
    //    run_loop();
        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        Toast.makeText(this, "Stopmyservci", Toast.LENGTH_LONG).show();
       super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

I get data by this code ..

 public void run_loop(){
        String url =  "http://00000000/testnet/android_register_login/ShowAllData.php";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");
                                JSONObject hit = jsonArray.getJSONObject(0);
                                String id = hit.getString("id");
                                int lastThread = Integer.parseInt(String.valueOf(id));
                                JSONObject jsonObject = null;
                                Toast.makeText(MainActivtiy.this, lastThread + "", Toast.LENGTH_SHORT).show();
                                if (app.getTotal_threads() < lastThread) {
                                    app.setTotal_threads(lastThread);
                                    Notification notification = new NotificationCompat.Builder(MainActivtiy.this)
                                            .setSmallIcon(android.R.drawable.ic_popup_reminder)
                                            .setContentTitle("title")
                                            .setContentText("message")
                                            .setAutoCancel(true)
                                            .setPriority(NotificationCompat.PRIORITY_HIGH)
                                            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                                            .build();

                                    notificationManager.notify(1, notification);

                            }
                            } catch(JSONException e){
                                e.printStackTrace();
                            }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);

        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                run_loop();
            }
        },10000);

    }

public void onBackPressed() {
        Intent sr =new Intent(this, MyService.class);
        startService(sr);
        Toast.makeText(this, "Exit", Toast.LENGTH_SHORT).show();
        finish();
        run_loop();
        super.onBackPressed();
    }

I store id here

public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    private int Total_threads;
    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }
    public int getTotal_threads() {
        return Total_threads;
    }
    public void setTotal_threads(int Total_threads) {
        this.Total_threads = Total_threads;
    }
    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}

and I get it from here

    private void JSON() {
        String url = "http://00000000/test/Showall.php";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                JSONObject jsonObject = null;

                                String id= hit.getString("id");

app.setTotal_threads(Integer.parseInt(String.valueOf(id)));

                            }

What can I try next?

Body:
There are a couple of reasons in my mind for that:

The first is that your condition if (app.getTotal_threads() < lastThread) is met twice because the value of the Total_threads is lost for some reason, so you need to persistently store it like using a shared preference. Here is a modification for the App class to do that.

public class App extends Application {
    public static final String CHANNEL_1_ID = "channel1";
    public static final String CHANNEL_2_ID = "channel2";
    public static final String PREFS_NAME = "PREFS_NAME";
    public static final String N_THREADS = "nThreads";

    @Override
    public void onCreate() {
        super.onCreate();

        createNotificationChannels();
    }

    public int getTotal_threads() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return prefs.getInt(N_THREADS, 0);
    }

    public void setTotal_threads(int Total_threads) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(N_THREADS, Total_threads);
        editor.apply();
    }

    private void createNotificationChannels() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(CHANNEL_1_ID, "Channel 1", NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is Channel 1");

            NotificationChannel channel2 = new NotificationChannel(CHANNEL_2_ID, "Channel 2", NotificationManager.IMPORTANCE_LOW
            );
            channel2.setDescription("This is Channel 2");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}

The other possible reason is that the server could send the same notification with different thread number .. in this case you've to fix the back end.


问:
Sum is not being defined as a sum
I'm beginning to learn coding on vscode with python and my code is this and it stacks the numbers.

```<code>num1 = input("Enter the first number:")

num2 = input("Enter the second number:")

sum = num1 + num2

print(sum)
</code>```

and my terminal is

```<code>Enter the first number:10

Enter the second number:10
1010
PS C:\Users\Big Chungus\Desktop\python>
</code>```

答:
Require an integer input.

```<code>num1 = int(input("Enter the first number:"))
num2 = int(input("Enter the second number:"))

sum = num1 + num2

print(sum)
</code>```

You can't add strings together and get the same result as integers.

Title: Sum is not being defined as a sum

Body:
I'm beginning to learn coding on vscode with python and my code is this and it stacks the numbers.

num1 = input("Enter the first number:")

num2 = input("Enter the second number:")

sum = num1 + num2

print(sum)

and my terminal is

Enter the first number:10

Enter the second number:10
1010
PS C:\Users\Big Chungus\Desktop\python>

Body:
Require an integer input.

num1 = int(input("Enter the first number:"))
num2 = int(input("Enter the second number:"))

sum = num1 + num2

print(sum)

You can't add strings together and get the same result as integers.


问:
R.id Cannot be resolved
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.</p>

```<code>public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>
</code>```

答:
If you are using eclipse, this question has already been asked

R cannot be resolved - Android error

Title: R.id Cannot be resolved

Body:
I guess something should be done with the Android-Manifest.xml file or something in the layout folder. I am new to Android so I don't know what I should write.

public class AndroidPong extends Activity implements  OnClickListener {
    static String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super .onCreate(savedInstanceState);

        tag = getResources().getString(R.string.app_name);
        fullScreen();
        splashScreen();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        return super .onCreateDialog(id);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super .onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super .onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super .onStop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super .onDestroy();
    }

    void startGame() {
        setContentView(R.layout.game);// error
        this .findViewById(R.id.Button01).setOnClickListener(this );//error
        this .findViewById(R.id.Button02).setOnClickListener(this );//Error
    }

    void splashScreen() {
        setContentView(R.layout.splash);// error
        this .findViewById(R.id.pongtable).setOnClickListener(this );//error
    }

    void gameMenu() {

    }

    void fullScreen() {
        this .requestWindowFeature(Window.FEATURE_NO_TITLE);
        this .getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void debug(String debug) {
        Log.d(tag, debug);
    }

<?xml version="1.0" encoding="utf-8"?>
<absoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

<Button android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"

<Button android:id="+id/Button02"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
 </absoluteLayout>