问:
pandas: how to get the sum of rows by grouping inside a DataFrame?
I am new to Data Science and I am currently using the Pandas library on the Jupyter notebook. Sorry for my poor English.

```<code>A,1,5,9
B,2,6,3
A,3,7,2
B,4,8,1
</code>```

How to group the above CSV values also adding the contents after creating the DataFrame?
I want the output something like this.

```<code>    A   B
0   4   6
1   12  14
2   11  4
</code>```

Thanks in advance :)

答:
This is groupby + sum with transpose:

```<code>print(df.groupby(0).sum().T.rename_axis(columns=None))
</code>```

```<code>    A   B
1   4   6
2  12  14
3  11   4
</code>```

Note: replace 0 in df.groupby(0) with the actual column name of the first column

Body:
I am new to Data Science and I am currently using the Pandas library on the Jupyter notebook. Sorry for my poor English.

A,1,5,9
B,2,6,3
A,3,7,2
B,4,8,1

How to group the above CSV values also adding the contents after creating the DataFrame?
I want the output something like this.

    A   B
0   4   6
1   12  14
2   11  4

Thanks in advance :)

Body:
This is groupby + sum with transpose:

print(df.groupby(0).sum().T.rename_axis(columns=None))

    A   B
1   4   6
2  12  14
3  11   4

Note: replace 0 in df.groupby(0) with the actual column name of the first column


来源: stackexchange

问:
Add column to table with Liquibase
I'm new to back-end development and currently trying to add a column to my app_user table. like below.

```<code>- changeSet:
      id: 300520202335
      author: Malindu De Alwis
      changes:
        - addColumn:
            tableName: app_user
              columns:
              -column:
                name: address
                type: VARCHAR(255)
</code>```

It gives this error

```<code>Caused by: org.yaml.snakeyaml.scanner.ScannerException: mapping values are not allowed here
</code>```

in 'reader', line 23, column 22:
                  columns:
                         ^

I use Spring boot and postgre sql. Please try to figureout the issue

答: I think the error results from missing whitespace between -column. Have you tried it with - column?

ContentLicense: CC BY-SA 4.0

Title: Add column to table with Liquibase

Body:
I'm new to back-end development and currently trying to add a column to my app_user table. like below.

- changeSet:
      id: 300520202335
      author: Malindu De Alwis
      changes:
        - addColumn:
            tableName: app_user
              columns:
              -column:
                name: address
                type: VARCHAR(255)

It gives this error

Caused by: org.yaml.snakeyaml.scanner.ScannerException: mapping values are not allowed here

in 'reader', line 23, column 22:
                  columns:
                         ^

I use Spring boot and postgre sql. Please try to figureout the issue


问:
Failed to compile. ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src'
I have this error Failed to compile.  ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src' but I have installed it

and this is my main.js

```<code>import Vue from 'vue';
import App from './App.vue';
import vuetify from '.plugins/vuetify';

Vue.config.productionTip = false;

new Vue({
 vuetify,
 render: (h) => h(App),
}).$mount('#app');
</code>```

答:
Seems like path issue. tryout below</p>

```<code>import vuetify from '@/plugins/vuetify'
</code>```

Body:
I have this error Failed to compile.  ./src/main.js Module not found: Error: Can't resolve '.plugins/vuetify' in 'C:\vue\testvueapp\src' but I have installed it

and this is my main.js

import Vue from 'vue';
import App from './App.vue';
import vuetify from '.plugins/vuetify';

Vue.config.productionTip = false;

new Vue({
 vuetify,
 render: (h) => h(App),
}).$mount('#app');

Body:
Seems like path issue. tryout below

import vuetify from '@/plugins/vuetify'


问:
TypeScript - How to ensure value is a certain string?
I have the following;

```<code>type AppDisplay = "MainMenu" | "Game" | "GameOver";

interface AppState {
  appDisplay: AppDisplay
}

const initialAppState : AppState = {
  appDisplay: "MainMenu"
}

type ActionType = {
  type: "DisplayMenu" | "DisplayGame" | "DisplayGameOver";
}

const appStateReducer = (state : AppState, action : ActionType) => {
  switch (action.type) {
    case "DisplayMenu":
      return {
        appDisplay: "MainMenu"
      }
    case "DisplayGame":
      return {
        appDisplay: "Game"
      }
    case "DisplayGameOver":
      return {
        appDisplay: "GameOver"
      }
  }
}
</code>```

The above code doesn't work, because the assignments in appStateReducer are of type String, and TS doesn't recognise them as being of type AppDisplay. How can I ensure that appDisplay can only be assigned as "Game", "GameOver" or "MainMenu"?

答:
You will need to add return type to this function:

```<code>const appStateReducer = (state : AppState, action : ActionType): AppState => {
  ...
}
</code>```

or you could also define returned object type as const:

```<code>return { ... } as const
</code>```

Body:
I have the following;

type AppDisplay = "MainMenu" | "Game" | "GameOver";

interface AppState {
  appDisplay: AppDisplay
}

const initialAppState : AppState = {
  appDisplay: "MainMenu"
}

type ActionType = {
  type: "DisplayMenu" | "DisplayGame" | "DisplayGameOver";
}

const appStateReducer = (state : AppState, action : ActionType) => {
  switch (action.type) {
    case "DisplayMenu":
      return {
        appDisplay: "MainMenu"
      }
    case "DisplayGame":
      return {
        appDisplay: "Game"
      }
    case "DisplayGameOver":
      return {
        appDisplay: "GameOver"
      }
  }
}

The above code doesn't work, because the assignments in appStateReducer are of type String, and TS doesn't recognise them as being of type AppDisplay. How can I ensure that appDisplay can only be assigned as "Game", "GameOver" or "MainMenu"?

Body:
You will need to add return type to this function:

const appStateReducer = (state : AppState, action : ActionType): AppState => {
  ...
}

or you could also define returned object type as const:

return { ... } as const


问:
Delete words between specific elements in a txt-file with python
I am a python beginner and have the following problem:

I have a text file ('demofile.txt') and want to cut out everything between two specific elements ({start} and {end}) multiple times.

As en example imagine the text file contains:

'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

The outcome should be:

'AAAA CCCC EEEE GGGG'

First I defined the two elements which work as the cutter

```<code>start = '{start}'
end = '{end}'
</code>```

The I tried to cut out the first part and used this code:

```<code>text_start = text.find(start)
text_new = text[0:text_start]
print(text_new)
</code>```

The outcome is : 'AAAA ', which is what I wanted

For the next part I tried this:

```<code>text_start = text.find(end)
text_end = text.find(start, text_start)
text_new = text[text_start+len(end):text_end]
print(text_new)
</code>```

The outcome is: 'CCCC ' which is again what I was looking for

Now I tried to put everything together and build a loop and failed :-)

```<code>text_start = text.find(start)
text_new = text[0:text_start]

text_end = 0

for parts in text.split("{"):
    text_start = text.find(end, text_end)
    text_end = text.find(start, text_start)
    text_new = text_new + text[text_start+len(end):text_end]
print(text_new)
</code>```

The outcome is:
'AAAA  CCCC  EEEE  GGG {start} BBBB {end} CCCC {start} DDDD {end}...'
 and lot more of that. Thus the Outcome was okay until "GGG", but one G is missing. And all the stuff afterwards should be deleted.
I guess the loop continued somehow and the start of the loop with the split statement is crap.
What is the solution here? I would like to understand what went wrong and change the code.
Of course I am also interested in a shorter and more elegant way. I am sure what I did is quite terrible ;-)
I found something with "regular expressions" but I was not able to get this going as well.
Thanks for any idea.

(PS: any idea how I could save everything I cut out in a seperate file?)

答:
You can simply do it like so:

```<code>import re

text = "AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG"

pattern = '(\s+{start} \w+ {end})'
text = re.sub(pattern, '', text)

print(text)
#AAAA CCCC EEEE GGGG
</code>```

Now, you can write text into a new text file named new_file.txt like so:

```<code># you can change the filename by replacing `new_file.txt` with any other name
with open("new_file.txt", "w") as fout:
    fout.write(text)
</code>```

Body:
I am a python beginner and have the following problem:

I have a text file ('demofile.txt') and want to cut out everything between two specific elements ({start} and {end}) multiple times.

As en example imagine the text file contains:

'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

The outcome should be:

'AAAA CCCC EEEE GGGG'

First I defined the two elements which work as the cutter

start = '{start}'
end = '{end}'

The I tried to cut out the first part and used this code:

text_start = text.find(start)
text_new = text[0:text_start]
print(text_new)

The outcome is : 'AAAA ', which is what I wanted

For the next part I tried this:

text_start = text.find(end)
text_end = text.find(start, text_start)
text_new = text[text_start+len(end):text_end]
print(text_new)

The outcome is: 'CCCC ' which is again what I was looking for

Now I tried to put everything together and build a loop and failed :-)

text_start = text.find(start)
text_new = text[0:text_start]

text_end = 0

for parts in text.split("{"):
    text_start = text.find(end, text_end)
    text_end = text.find(start, text_start)
    text_new = text_new + text[text_start+len(end):text_end]
print(text_new)

The outcome is:
'AAAA  CCCC  EEEE  GGG {start} BBBB {end} CCCC {start} DDDD {end}...'
 and lot more of that. Thus the Outcome was okay until "GGG", but one G is missing. And all the stuff afterwards should be deleted.
I guess the loop continued somehow and the start of the loop with the split statement is crap.
What is the solution here? I would like to understand what went wrong and change the code.
Of course I am also interested in a shorter and more elegant way. I am sure what I did is quite terrible ;-)
I found something with "regular expressions" but I was not able to get this going as well.
Thanks for any idea.

(PS: any idea how I could save everything I cut out in a seperate file?)

Body:
You can simply do it like so:

import re

text = "AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG"

pattern = '(\s+{start} \w+ {end})'
text = re.sub(pattern, '', text)

print(text)
#AAAA CCCC EEEE GGGG

Now, you can write text into a new text file named new_file.txt like so:

# you can change the filename by replacing `new_file.txt` with any other name
with open("new_file.txt", "w") as fout:
    fout.write(text)


问:
Why std::count is slower that plain for loop with MSVC Compiler but equal with GCC?
I am testing the performance of the C++ standard library algorithms and encountered a weird thing.

Here is my code to compare the performance of std::count vs plain for loop:

```<code>#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int my_count(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i: v) {
        if (i == val)
            num++;
    }

    return num;
}

int main()
{
    int total_count = 0;

    std::vector<int> v;
    v.resize(100000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    {
        auto start = high_resolution_clock::now();
        total_count += std::count(v.begin(), v.end(), val);
        auto stop = high_resolution_clock::now();

        std::cout << "std::count time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    {
        auto start = high_resolution_clock::now();
        total_count += my_count(v, val);
        auto stop = high_resolution_clock::now();

        std::cout << "my_count   time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    // We need this so the compiler does not prune the code above
    std::cout << "Total items: " << total_count << std::endl;
}
</code>```

With MinGW I get this:

```<code>std::count time:   65827
my_count   time:   64861
</code>```

And with MSVC I get a pretty weird result:

```<code>std::count time:   65532
my_count   time:   28584
</code>```

The MinGW result seems reasonable since, as far as I know, STL count function if roughly equal to the plain for loop, but the MSVC result seems weird - why the plain for loop is more than 2x faster than std::count?

These results are reproducible on my machine - it's not something that occurs once, but it occurs each time I run the code. I even tried changing the function order, running multiple for loops to avoid caching or branch prediction bias, but I still get the same result.

Is there any reason for this?

答:
This is because MSVC vectorizes your manually written code, but is unable to do the same for std::count.

This is how vectorized code looks:

```<code>        movdqa  xmm5, XMMWORD PTR __xmm@00000001000000010000000100000001
        and     rcx, -8
        xorps   xmm3, xmm3
        xorps   xmm2, xmm2
        npad    3
$LL4@my_count:
        movdqu  xmm1, XMMWORD PTR [rax]
        add     r8, 8
        movdqa  xmm0, xmm5
        paddd   xmm0, xmm3
        pcmpeqd xmm1, xmm4
        pand    xmm0, xmm1
        pandn   xmm1, xmm3
        movdqa  xmm3, xmm0
        movdqa  xmm0, xmm5
        por     xmm3, xmm1
        paddd   xmm0, xmm2
        movdqu  xmm1, XMMWORD PTR [rax+16]
        add     rax, 32                             ; 00000020H
        pcmpeqd xmm1, xmm4
        pand    xmm0, xmm1
        pandn   xmm1, xmm2
        movdqa  xmm2, xmm0
        por     xmm2, xmm1
        cmp     r8, rcx
        jne     SHORT $LL4@my_count
</code>```

You can see how it load 4 ones in xmm5 register at the beginning. This value will be used to maintain 4 separate counters that track result for 1st, 2nd, 3rd and 4th DWORDs. Once counting is done, those 4 values will be added together to form the result of the function.

The issue with MSVC vectorizer seems to lie in the fact that counter, data type and argument type should be "compatible":

Return type should match in size the data type

Argument type should be equal or less in size to data type

If any of those constraints is not met, the code is not vectorized. This makes sense as if your data type is 32-bit wide you have to operate on 32-bit counters to make them work together, so if your return type is 64-bit wide instead some additional manipulations are required (which is what GCC is able to do, but this still slows down std::count compared to manually written loop).

This is the case where manually written loop should be preferred as subtle differences in semantic (int return type) make it easier to vectorize (even for GCC, which generates shorter code).

Body:
I am testing the performance of the C++ standard library algorithms and encountered a weird thing.

Here is my code to compare the performance of std::count vs plain for loop:

#include <algorithm>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std::chrono;

int my_count(const std::vector<int>& v, int val) {
    int num = 0;

    for (int i: v) {
        if (i == val)
            num++;
    }

    return num;
}

int main()
{
    int total_count = 0;

    std::vector<int> v;
    v.resize(100000000);

    // Fill vector
    for (int i = 0; i < v.size(); i++) {
        v[i] = i % 10000;
    }

    int val = 1;

    {
        auto start = high_resolution_clock::now();
        total_count += std::count(v.begin(), v.end(), val);
        auto stop = high_resolution_clock::now();

        std::cout << "std::count time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    {
        auto start = high_resolution_clock::now();
        total_count += my_count(v, val);
        auto stop = high_resolution_clock::now();

        std::cout << "my_count   time:   " << duration_cast<microseconds>(stop - start).count() << std::endl;
    }

    // We need this so the compiler does not prune the code above
    std::cout << "Total items: " << total_count << std::endl;
}

With MinGW I get this:

std::count time:   65827
my_count   time:   64861

And with MSVC I get a pretty weird result:

std::count time:   65532
my_count   time:   28584

The MinGW result seems reasonable since, as far as I know, STL count function if roughly equal to the plain for loop, but the MSVC result seems weird - why the plain for loop is more than 2x faster than std::count?

These results are reproducible on my machine - it's not something that occurs once, but it occurs each time I run the code. I even tried changing the function order, running multiple for loops to avoid caching or branch prediction bias, but I still get the same result.

Is there any reason for this?

Body:
This is because MSVC vectorizes your manually written code, but is unable to do the same for std::count.

This is how vectorized code looks:

        movdqa  xmm5, XMMWORD PTR __xmm@00000001000000010000000100000001
        and     rcx, -8
        xorps   xmm3, xmm3
        xorps   xmm2, xmm2
        npad    3
$LL4@my_count:
        movdqu  xmm1, XMMWORD PTR [rax]
        add     r8, 8
        movdqa  xmm0, xmm5
        paddd   xmm0, xmm3
        pcmpeqd xmm1, xmm4
        pand    xmm0, xmm1
        pandn   xmm1, xmm3
        movdqa  xmm3, xmm0
        movdqa  xmm0, xmm5
        por     xmm3, xmm1
        paddd   xmm0, xmm2
        movdqu  xmm1, XMMWORD PTR [rax+16]
        add     rax, 32                             ; 00000020H
        pcmpeqd xmm1, xmm4
        pand    xmm0, xmm1
        pandn   xmm1, xmm2
        movdqa  xmm2, xmm0
        por     xmm2, xmm1
        cmp     r8, rcx
        jne     SHORT $LL4@my_count

You can see how it load 4 ones in xmm5 register at the beginning. This value will be used to maintain 4 separate counters that track result for 1st, 2nd, 3rd and 4th DWORDs. Once counting is done, those 4 values will be added together to form the result of the function.

The issue with MSVC vectorizer seems to lie in the fact that counter, data type and argument type should be "compatible":

Return type should match in size the data type

Argument type should be equal or less in size to data type

If any of those constraints is not met, the code is not vectorized. This makes sense as if your data type is 32-bit wide you have to operate on 32-bit counters to make them work together, so if your return type is 64-bit wide instead some additional manipulations are required (which is what GCC is able to do, but this still slows down std::count compared to manually written loop).

This is the case where manually written loop should be preferred as subtle differences in semantic (int return type) make it easier to vectorize (even for GCC, which generates shorter code).


答:
You can use df.pivot_table

```<code>df
   0  1  2  3
0  A  1  5  9
1  B  2  6  3
2  A  3  7  2
3  B  4  8  1

df.pivot_table(columns=0,aggfunc='sum').rename_axis(columns=None)
    A   B
1   4   6
2  12  14
3  11   4
</code>```

Title: pandas: how to get the sum of rows by grouping inside a DataFrame?

Body:
You can use df.pivot_table

df
   0  1  2  3
0  A  1  5  9
1  B  2  6  3
2  A  3  7  2
3  B  4  8  1

df.pivot_table(columns=0,aggfunc='sum').rename_axis(columns=None)
    A   B
1   4   6
2  12  14
3  11   4


问:
defining a variable in a class
I am trying to place a method in a class that will replace null values with running average of non null values. Please refer to the code below:

```<code>class ElNinoData(object):
    # Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average

            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']
</code>```

While executing this class in a method, I am getting the following error:

```<code><ipython-input-40-c52c3ac6484b> in get_humidity(self)
     19             global average
     20
---> 21             add += self.object['humidity']
     22             counter += 1
     23             average = add/counter

NameError: name 'add' is not defined
</code>```

Could anyone please explain the error,I am relatively new to python?

答:
If you want the members to be specific to an object, change it to this

```<code>class ElNinoData(object):
    # Nothing here

    # methods
    def __init__(self , object):
        self.add = 0
        self.counter = 0
        self.average = 0
        self.object = object
</code>```

and continue to refer to them with self..

If you want them to be class-wide, leave them where they are, but refer to them via ElNinoData..

In any case, you shouldn't use global here.

Title: defining a variable in a class

Body:
I am trying to place a method in a class that will replace null values with running average of non null values. Please refer to the code below:

class ElNinoData(object):
    # Your implementation here
    add = 0
    counter = 0
    average = 0

    # methods
    def __init__(self , object):
        self.object = object

    def get_humidity(self):
        if not math.isnan(self.object['humidity']):
            global add
            global counter
            global average

            add += self.object['humidity']
            counter += 1
            average = add/counter
        else:
            self.object['humidity'] = average
        return self.object['humidity']

While executing this class in a method, I am getting the following error:

<ipython-input-40-c52c3ac6484b> in get_humidity(self)
     19             global average
     20
---> 21             add += self.object['humidity']
     22             counter += 1
     23             average = add/counter

NameError: name 'add' is not defined

Could anyone please explain the error,I am relatively new to python?

Body:
If you want the members to be specific to an object, change it to this

class ElNinoData(object):
    # Nothing here

    # methods
    def __init__(self , object):
        self.add = 0
        self.counter = 0
        self.average = 0
        self.object = object

and continue to refer to them with self..

If you want them to be class-wide, leave them where they are, but refer to them via ElNinoData..

In any case, you shouldn't use global here.


问:
Simple way to combine many observables into one object
I need to build an object from couple of observables that comes from the ngrx state.

```<code>    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );
</code>```

How can i make this more readable and better code?

答:
I'd recommend zipObject from the rxjs-etc package. It's an extension library by one of the main contributors of RxJS.

Usage:

```<code>zipObject({
    obs1: this.store$.select(selectObs1),
    obs2: this.store$.select(selectObs2),
    obs3: this.store$.select(selectObs3),

    ...

    obs9: this.store$.select(selectObs9)
})
</code>```

Body:
I need to build an object from couple of observables that comes from the ngrx state.

    public readonly comibiedToOneObject$ = zip(
    this.store$.select(selectObs1),
    this.store$.select(selectObs2),
    this.store$.select(selectObs3),

    ...

    this.store$.select(selectObsN),
  ).pipe(
    map(([
           obs1,
           obs2,
           obs3,

            ...

           obsN
         ]) => {
      return {
           obs1,
           obs2,
           obs3,

            ...

           obsN
      };
    }),
  );

How can i make this more readable and better code?

Body:
I'd recommend zipObject from the rxjs-etc package. It's an extension library by one of the main contributors of RxJS.

Usage:

zipObject({
    obs1: this.store$.select(selectObs1),
    obs2: this.store$.select(selectObs2),
    obs3: this.store$.select(selectObs3),

    ...

    obs9: this.store$.select(selectObs9)
})


问:
How to enable a button based on a TextBox in GridView in ASP.Net using JavaScript?
I have a TextBox in the TemplateField of a GridView. And I have one button below the GridView. I want to enable the Button when I enter some text in the TextBox in the GridView. How to do this? I am using ASP.Net and C#.Net.

My Source Code of the GridView:

```<code><table>
    <tr>
       <td>
<asp:GridView ID="gvQCAttribute" runat="server" AllowPaging="true" AutoGenerateColumns="false"
                        CellPadding="0" CssClass="datagrid" DataKeyNames="ItemID" EnableTheming="false"
                        PageSize="10" Width="100%">
                        <EmptyDataTemplate>
                            <table border="0" cellpadding="0" cellspacing="1" width="100%">
                                <tr>
                                    <tr>
                                        <th scope="col">
                                            QC Attribute Name
                                        </th>
                                        <th scope="col">
                                            PO Attribute Value
                                        </th>
                                        <th scope="col">
                                            Negative Tolerance
                                        </th>
                                        <th scope="col">
                                            Positive Tolerance
                                        </th>
                                        <th scope="col">
                                            Remarks
                                        </th>
                                    </tr>
                                </tr>
                            </table>
                        </EmptyDataTemplate>
                        <SelectedRowStyle CssClass="rowselect" />
                        <HeaderStyle ForeColor="White" />
                        <AlternatingRowStyle CssClass="table_oddrow" />
                        <RowStyle CssClass="table_evenrow" />
                        <PagerStyle CssClass="pager_style" />
                        <Columns>
                            <asp:TemplateField HeaderText="ItemID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvItemID" runat="server" Text='<%# Bind("ItemID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="QCAttributeID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvQCAttributeID" runat="server" Text='<%# Bind("QCAttributeID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Attribute Name">
                                <ItemTemplate>
                                    <asp:Label ID="txtQCAttributeName" runat="server" Text='<%# Bind("AttributeName") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="150px" />
                                <ControlStyle Width="100%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="POAttrubute Value">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPOAttributeValue" runat="server" Text='<%# Bind("POAttributeValue") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Negative Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtNegTolerance" runat="server" Text='<%# Bind("NegativeTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Positive Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPosTolerance" runat="server" Text='<%# Bind("PositiveTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Remarks">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtRemarks" runat="server" Text='<%# Bind("Remarks") %>' onkeyup="return EnableButton(this);"
                                        ValidationGroup="Modal"></asp:TextBox>
                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
        </td>
     </tr>
     <tr>
        <td>
         <asp:Button ID="btnmdeSave" runat="server" Text="Save" CssClass="ButtonClass" ValidationGroup="Modal"
                        OnClick="btnmdeSave_Click" />
        </td>
     </tr>
  </table>
</code>```

答:
use onkeypress or onkeyup event and check whether the textbox is empty.

if not, then make the button enable else disable.

```<code>function enableButton(){
  if(document.getElementById('txtPOAttributeValue').value != '' && document.getElementById('txtNegTolerance').value != '' && document.getElementById('txtPosTolerance').value != ''){
    document.getElementById('buttonId').disabled = false;
  }else{
    document.getElementById('buttonId').disabled = true;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a TextBox in the TemplateField of a GridView. And I have one button below the GridView. I want to enable the Button when I enter some text in the TextBox in the GridView. How to do this? I am using ASP.Net and C#.Net.

My Source Code of the GridView:

<asp:GridView ID="gvQCAttribute" runat="server" AllowPaging="true" AutoGenerateColumns="false"
                        CellPadding="0" CssClass="datagrid" DataKeyNames="ItemID" EnableTheming="false"
                        PageSize="10" Width="100%">
                        <EmptyDataTemplate>

                                            QC Attribute Name

                                            PO Attribute Value

                                            Negative Tolerance

                                            Positive Tolerance

                                            Remarks

                        </EmptyDataTemplate>
                        <SelectedRowStyle CssClass="rowselect" />
                        <HeaderStyle ForeColor="White" />
                        <AlternatingRowStyle CssClass="table_oddrow" />
                        <RowStyle CssClass="table_evenrow" />
                        <PagerStyle CssClass="pager_style" />
                        <Columns>
                            <asp:TemplateField HeaderText="ItemID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvItemID" runat="server" Text='<%# Bind("ItemID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="QCAttributeID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvQCAttributeID" runat="server" Text='<%# Bind("QCAttributeID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Attribute Name">
                                <ItemTemplate>
                                    <asp:Label ID="txtQCAttributeName" runat="server" Text='<%# Bind("AttributeName") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="150px" />
                                <ControlStyle Width="100%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="POAttrubute Value">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPOAttributeValue" runat="server" Text='<%# Bind("POAttributeValue") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Negative Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtNegTolerance" runat="server" Text='<%# Bind("NegativeTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Positive Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPosTolerance" runat="server" Text='<%# Bind("PositiveTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Remarks">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtRemarks" runat="server" Text='<%# Bind("Remarks") %>' onkeyup="return EnableButton(this);"
                                        ValidationGroup="Modal"></asp:TextBox>
                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

         <asp:Button ID="btnmdeSave" runat="server" Text="Save" CssClass="ButtonClass" ValidationGroup="Modal"
                        OnClick="btnmdeSave_Click" />

Body:
use onkeypress or onkeyup event and check whether the textbox is empty.

if not, then make the button enable else disable.

function enableButton(){
  if(document.getElementById('txtPOAttributeValue').value != '' && document.getElementById('txtNegTolerance').value != '' && document.getElementById('txtPosTolerance').value != ''){
    document.getElementById('buttonId').disabled = false;
  }else{
    document.getElementById('buttonId').disabled = true;
  }
}


问:
Get value from json in LogicApp
Rephrasing question entirely, as first attempt was unclear.

In my logic app I am reading a .json from blob which contains:

```<code>{
    "alpha": {
        "url": "https://linktoalpha.com",
        "meta": "This logic app does job aaaa"
    },
    "beta": {
        "url": "https://linktobeta.com",
        "meta": "This logic app does job beta"
    },
    "theta": {
        "url": "https://linktotheta.com",
        "meta": "This logic app does job theta"
    }
}
</code>```

I'm triggering the logic app with a http post which contains in the body:

```<code>{ "logicappname": "beta" }
</code>```

But the value for 'logicappname' could be alpha, beta or theta. I now need to set a variable which contains the url value for 'beta'. How can this be achieved without jsonpath support?

I am already json parsing the file contents from the blob and this IS giving me the tokens... but I cannot see how to select the value I need. Would appreciate any assistance, thank you.

答:
Not sure if I understand your question. But I believe you can use Pars Json action after the http trigger.
With this you will get a control over the incoming JSON message and you can choose the 'URL' value as a dynamic content in the subsequent actions.
Let me know if my understanding about your question is wrong.</p>

Title: Get value from json in LogicApp

Body:
Rephrasing question entirely, as first attempt was unclear.

In my logic app I am reading a .json from blob which contains:

{
    "alpha": {
        "url": "https://linktoalpha.com",
        "meta": "This logic app does job aaaa"
    },
    "beta": {
        "url": "https://linktobeta.com",
        "meta": "This logic app does job beta"
    },
    "theta": {
        "url": "https://linktotheta.com",
        "meta": "This logic app does job theta"
    }
}

I'm triggering the logic app with a http post which contains in the body:

{ "logicappname": "beta" }

But the value for 'logicappname' could be alpha, beta or theta. I now need to set a variable which contains the url value for 'beta'. How can this be achieved without jsonpath support?

I am already json parsing the file contents from the blob and this IS giving me the tokens... but I cannot see how to select the value I need. Would appreciate any assistance, thank you.


问:
How do I format a date with Dart?
I have an instance of DateTime and I would like to format that to a String. How do I do that? I want to turn the date into a string, something like "2013-04-20".

答:
pubspec.yaml:

```<code>dependencies:
  intl:
</code>```

main.dart:

```<code>import 'package:intl/intl.dart'; // for date format
import 'package:intl/date_symbol_data_local.dart'; // for other locales

void main() {
  var now = DateTime.now();
  print(DateFormat().format(now)); // This will return date using the default locale
  print(DateFormat('yyyy-MM-dd hh:mm:ss').format(now));
  print(DateFormat.yMMMMd().format(now)); // print long date
  print(DateFormat.yMd().format(now)); // print short date
  print(DateFormat.jms().format(now)); // print time

  initializeDateFormatting('es'); // This will initialize Spanish locale
  print(DateFormat.yMMMMd('es').format(now)); // print long date in Spanish format
  print(DateFormat.yMd('es').format(now)); // print short date in Spanish format
  print(DateFormat.jms('es').format(now)); // print time in Spanish format
}
</code>```

Result:

```<code>May 31, 2020 5:41:42 PM
2020-05-31 05:41:42
May 31, 2020
5/31/2020
5:41:42 PM
31 de mayo de 2020
31/5/2020
17:41:42
</code>```

Title: How do I format a date with Dart?

Body:
pubspec.yaml:

dependencies:
  intl:

main.dart:

import 'package:intl/intl.dart'; // for date format
import 'package:intl/date_symbol_data_local.dart'; // for other locales

void main() {
  var now = DateTime.now();
  print(DateFormat().format(now)); // This will return date using the default locale
  print(DateFormat('yyyy-MM-dd hh:mm:ss').format(now));
  print(DateFormat.yMMMMd().format(now)); // print long date
  print(DateFormat.yMd().format(now)); // print short date
  print(DateFormat.jms().format(now)); // print time

  initializeDateFormatting('es'); // This will initialize Spanish locale
  print(DateFormat.yMMMMd('es').format(now)); // print long date in Spanish format
  print(DateFormat.yMd('es').format(now)); // print short date in Spanish format
  print(DateFormat.jms('es').format(now)); // print time in Spanish format
}

Result:

May 31, 2020 5:41:42 PM
2020-05-31 05:41:42
May 31, 2020
5/31/2020
5:41:42 PM
31 de mayo de 2020
31/5/2020
17:41:42


答:
I think the problem is that your values add, counter and average are not global.

In order to set these values on your class instance, you have to use self instead.
Something like this:

```<code>def get_humidity(self):
    if not math.isnan(self.object['humidity']):
        self.add += self.object['humidity']
        self.counter += 1
        self.average = add/counter
    else:
        self.object['humidity'] = average
    return self.object['humidity']
</code>```

Title: defining a variable in a class

Body:
I think the problem is that your values add, counter and average are not global.

In order to set these values on your class instance, you have to use self instead.
Something like this:

def get_humidity(self):
    if not math.isnan(self.object['humidity']):
        self.add += self.object['humidity']
        self.counter += 1
        self.average = add/counter
    else:
        self.object['humidity'] = average
    return self.object['humidity']


问:
Plotting Previous day high and low (Pinescript)
Just learned to plot previous day high and low. And it plotted fine for the completed sessions but it keeps on plotting for every candle's high and low (for current session). I find it distracting.I use 5 min chart.  Code (v4):</p>
```<code>1. // Previous day high low
 2. plotDHL = input(title="Plot PDH PDL", type=input.bool, defval=true)
 3. pdh = security(syminfo.tickerid, 'D', high)
 4. pdl = security(syminfo.tickerid, 'D', low)
 5. cDHL = color.new(#f21bf2, 40)
 6. plot(series=plotDHL ? pdh : 0, title = "PDH", style = myStyle, linewidth = 1, color = cDHL)
 7. plot(series=plotDHL ? pdl : 0, title = "PDL", style = myStyle, linewidth = 1, color = cDHL)
</code>```

答:
I am not sure if my answer will be practical, but you can use :</p>

```<code>a = security(syminfo.tickerid, 'D', high)
b = 0.
b := barstate.islast ? b[1] : a
</code>```

Body:
Just learned to plot previous day high and low. And it plotted fine for the completed sessions but it keeps on plotting for every candle's high and low (for current session). I find it distracting.I use 5 min chart.  Code (v4):

1. // Previous day high low
 2. plotDHL = input(title="Plot PDH PDL", type=input.bool, defval=true)
 3. pdh = security(syminfo.tickerid, 'D', high)
 4. pdl = security(syminfo.tickerid, 'D', low)
 5. cDHL = color.new(#f21bf2, 40)
 6. plot(series=plotDHL ? pdh : 0, title = "PDH", style = myStyle, linewidth = 1, color = cDHL)
 7. plot(series=plotDHL ? pdl : 0, title = "PDL", style = myStyle, linewidth = 1, color = cDHL)

Body:
I am not sure if my answer will be practical, but you can use :

a = security(syminfo.tickerid, 'D', high)
b = 0.
b := barstate.islast ? b[1] : a


问:
Unable to run console consumer using a Kafka broker inside a Docker container
I'm having a problem running a Kafka broker in a Docker container.

I have downloaded and unpacked a tar archive of Kafka 2.12-2.4.1.

I can run Zookeeper and Kafka brokers from the command line, producing and consuming messages successfully. When I build a docker container with Zookeeper, I can run that with a Kafka broker running from the command line, again producing and consuming messages successfully. When I put the broker into a docker container, the consumers and producers can't find a broker to connect to.

I have checked to ensure that Zookeeper has a connected broker: the zookeeper "dump" command below

```echo dump | nc localhost 2181```

returns

```
SessionTracker dump:
Session Sets (3)/(1):
0 expire at Thu May 28 09:53:33 GMT 2020:
0 expire at Thu May 28 09:53:36 GMT 2020:
1 expire at Thu May 28 09:53:39 GMT 2020:
    0x10002dfed700008
ephemeral nodes dump:
Sessions with Ephemerals (1):
0x10002dfed700008:
    /controller
    /brokers/ids/0
Connections dump:
Connections Sets (2)/(2):
0 expire at Thu May 28 09:53:37 GMT 2020:
2 expire at Thu May 28 09:53:47 GMT 2020:
    ip: /172.18.0.1:55656 sessionId: 0x0
    ip: /172.18.0.5:48474 sessionId: 0x10002dfed700008
```

which, to my untrained eye, looks like Zookeeper has a registered broker.

I can successfully list topics with the command

```kafka-topics.sh --list --zookeeper localhost:2181```

and when I run the command

```netstat -plnt```

I can see that I have listeners on ports 2181 and 9092, as below

```
tcp6       0      0 :::9092                 :::*                    LISTEN      54661/docker-proxy
tcp6       0      0 :::2181                 :::*                    LISTEN      47872/docker-proxy
```

However, when I try to connect a consumer with the command

```kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic aaaa```

I get errors

```WARN [Consumer clientId=consumer-console-consumer-8228-1, groupId=console-consumer-8228] Bootstrap broker localhost:9092 (id: -1 rack: null) disconnected (org.apache.kafka.clients.NetworkClient)```

which would seem to indicate that the client can't contact the broker.

I've tried several different variations on the listeners and advertised.listeners in the broker config file, setting them to localhost and 127.0.0.1, but to no avail.

I'm sure that I'm missing something simple: can anyone help?

答:
So, I have solved the problem and I now have a working Docker/Kafka environment: I have a zookeeper, a broker and a consumer running in docker, and I can produce messages both from a producer running in docker and a consumer running from a command line.

As @GiorgosMyrianthous suspected, the problem was with the listeners and advertised listeners. I entered the following values in the Kafka broker properties file

listeners=PLAINTEXT://:29092,PLAINTEXT_HOST://:9092
advertised.listeners=PLAINTEXT://server:29092,PLAINTEXT_HOST://localhost:9092
listener.security.protocol.map=PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT

and I started the container with port 9092 exposed to the outside world.

I ran the Docker consumer with the bootstrap server set to server:29092.

I ran the Docker producer with the bootstrap server set to server:29092.

I ran the command line producer with the bootstrap server set to localhost:9092.

Messages typed in either of the producers appeared in the consumer.

Body:
I'm having a problem running a Kafka broker in a Docker container.

I have downloaded and unpacked a tar archive of Kafka 2.12-2.4.1.

I can run Zookeeper and Kafka brokers from the command line, producing and consuming messages successfully. When I build a docker container with Zookeeper, I can run that with a Kafka broker running from the command line, again producing and consuming messages successfully. When I put the broker into a docker container, the consumers and producers can't find a broker to connect to.

I have checked to ensure that Zookeeper has a connected broker: the zookeeper "dump" command below

echo dump | nc localhost 2181

returns

SessionTracker dump:
Session Sets (3)/(1):
0 expire at Thu May 28 09:53:33 GMT 2020:
0 expire at Thu May 28 09:53:36 GMT 2020:
1 expire at Thu May 28 09:53:39 GMT 2020:
    0x10002dfed700008
ephemeral nodes dump:
Sessions with Ephemerals (1):
0x10002dfed700008:
    /controller
    /brokers/ids/0
Connections dump:
Connections Sets (2)/(2):
0 expire at Thu May 28 09:53:37 GMT 2020:
2 expire at Thu May 28 09:53:47 GMT 2020:
    ip: /172.18.0.1:55656 sessionId: 0x0
    ip: /172.18.0.5:48474 sessionId: 0x10002dfed700008

which, to my untrained eye, looks like Zookeeper has a registered broker.

I can successfully list topics with the command

kafka-topics.sh --list --zookeeper localhost:2181

and when I run the command

netstat -plnt

I can see that I have listeners on ports 2181 and 9092, as below

tcp6       0      0 :::9092                 :::*                    LISTEN      54661/docker-proxy
tcp6       0      0 :::2181                 :::*                    LISTEN      47872/docker-proxy

However, when I try to connect a consumer with the command

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic aaaa

I get errors

WARN [Consumer clientId=consumer-console-consumer-8228-1, groupId=console-consumer-8228] Bootstrap broker localhost:9092 (id: -1 rack: null) disconnected (org.apache.kafka.clients.NetworkClient)

which would seem to indicate that the client can't contact the broker.

I've tried several different variations on the listeners and advertised.listeners in the broker config file, setting them to localhost and 127.0.0.1, but to no avail.

I'm sure that I'm missing something simple: can anyone help?


问:
How does S3 make public URLs unique
I have a bucket named video. I am making one of its objects 'cool.mp4' public.

now the object URL becomes: https://video.s3.ap-south-1.amazonaws.com/cool.mp4

And downloading this works.
My question is, what will happen if some one in the same region has a bucket video and has a file named cool.mp4. How will S3 differentiate the two public URLs.

答:
Based on the doc, bucket name should be globally unique.

An Amazon S3 bucket name is globally unique, and the namespace is shared by all AWS accounts.

In other words, there shouldn't exist two buckets with the same name.

Title: How does S3 make public URLs unique


问:
Numba "Use of unsupported opcode (CONTINUE_LOOP) found" error when using continue in for loop
I am getting an error trying to enable numba optimization on a defined function.

Here is the function simplified:

```<code>@jit
def monte_carlo(iterations):
    key1 = []
    key2 = []
    score = []
    for i in range(iterations):
        random.seed(i)
        temp_matrix = random.sample(matrix, length)

        for j in range(iterations):
            random.seed(j)
            key2.append(i)
            key1.append(j)

            for x in range(...):
                try: temp_matrix[x] = random.sample(matrix[x], len(matrix[x]))
                except: continue

        scores.append(...)
    return scores, keyA, keyB

monte_carlo(1000)
</code>```

Then I receive this as an error, also had issues using Cuda over Jit.

```<code>Traceback (most recent call last):
  File "..."
  File ...\numba\dispatcher.py", line 404, in _compile_for_args
    error_rewrite(e, 'unsupported_error')
  File "...\numba\dispatcher.py", line 344, in error_rewrite
    reraise(type(e), e, None)
  File "...\numba\six.py", line 668, in reraise
    raise value.with_traceback(tb)
numba.errors.UnsupportedError: Failed in nopython mode pipeline (step: analyzing bytecode)
**Use of unsupported opcode (CONTINUE_LOOP) found**

File "...py", line 32:
def monte_carlo(iterations):
    <source elided>
                try: temp_qa_matrix[x] = random.sample(input.qa_matrix[x], len(input.qa_matrix[x]))
                except: continue
                ^
</code>```

So, it is not really liking the continue in a loop, despite being a supported construct.

Nunba Supported Python features

答:
I think Numba's documentation is a little incomplete. It can handle ordinary continue statements, which use the Python opcode JUMP_ABSOLUTE under the hood, but not continue statements inside try/except blocks, which use the Python opcode CONTINUE_LOOP.

Here's an example of a simple function that (unnecessarily) uses continue and works with Numba. It cuts in half elements of an array that are greater than 0.5.

```<code>def halve(x):
    for i in range(len(x)):
        if x[i] <= 0.5:
            continue
        x[i] /= 2
</code>```

If we import the Python dis module and look at the output of dis.dis(halve), we see that there are two JUMP_ABSOLUTE opcodes. This is what Python normally uses for continue statements. If we use Numba jit this function and run it an array, we'll see that it works with no problem.

But if we rewrite halve to use try/except:

```<code>def halve(x):
    for i in range(len(x)):
        try:
            assert x[i] > 0.5
        except:
            continue
        x[i] /= 2
</code>```

and look at dis.dis(halve), we see that one of the JUMP_ABSOLUTE opcodes has been replaced by CONTINUE_LOOP. I don't know the Python details under the hood, but sure enough, if we try to jit this function, then Numba complains that there's an unsupported opcode.

So, TLDR: looks like you can't use continue inside try/except with Numba, for obscure reasons related to the Python implementation.

I suspect there's almost always a workaround to this, but since your code isn't fully self-contained it's hard for me to know.

(Side note: usually Numba will do much better if you use NumPy arrays rather than lists.)

Body:
I am getting an error trying to enable numba optimization on a defined function.

Here is the function simplified:

@jit
def monte_carlo(iterations):
    key1 = []
    key2 = []
    score = []
    for i in range(iterations):
        random.seed(i)
        temp_matrix = random.sample(matrix, length)

        for j in range(iterations):
            random.seed(j)
            key2.append(i)
            key1.append(j)

            for x in range(...):
                try: temp_matrix[x] = random.sample(matrix[x], len(matrix[x]))
                except: continue

        scores.append(...)
    return scores, keyA, keyB

monte_carlo(1000)

Then I receive this as an error, also had issues using Cuda over Jit.

Traceback (most recent call last):
  File "..."
  File ...\numba\dispatcher.py", line 404, in _compile_for_args
    error_rewrite(e, 'unsupported_error')
  File "...\numba\dispatcher.py", line 344, in error_rewrite
    reraise(type(e), e, None)
  File "...\numba\six.py", line 668, in reraise
    raise value.with_traceback(tb)
numba.errors.UnsupportedError: Failed in nopython mode pipeline (step: analyzing bytecode)
**Use of unsupported opcode (CONTINUE_LOOP) found**

File "...py", line 32:
def monte_carlo(iterations):
    <source elided>
                try: temp_qa_matrix[x] = random.sample(input.qa_matrix[x], len(input.qa_matrix[x]))
                except: continue
                ^

So, it is not really liking the continue in a loop, despite being a supported construct.

Nunba Supported Python features

Body:
I think Numba's documentation is a little incomplete. It can handle ordinary continue statements, which use the Python opcode JUMP_ABSOLUTE under the hood, but not continue statements inside try/except blocks, which use the Python opcode CONTINUE_LOOP.

Here's an example of a simple function that (unnecessarily) uses continue and works with Numba. It cuts in half elements of an array that are greater than 0.5.

def halve(x):
    for i in range(len(x)):
        if x[i] <= 0.5:
            continue
        x[i] /= 2

If we import the Python dis module and look at the output of dis.dis(halve), we see that there are two JUMP_ABSOLUTE opcodes. This is what Python normally uses for continue statements. If we use Numba jit this function and run it an array, we'll see that it works with no problem.

But if we rewrite halve to use try/except:

def halve(x):
    for i in range(len(x)):
        try:
            assert x[i] > 0.5
        except:
            continue
        x[i] /= 2

and look at dis.dis(halve), we see that one of the JUMP_ABSOLUTE opcodes has been replaced by CONTINUE_LOOP. I don't know the Python details under the hood, but sure enough, if we try to jit this function, then Numba complains that there's an unsupported opcode.

So, TLDR: looks like you can't use continue inside try/except with Numba, for obscure reasons related to the Python implementation.

I suspect there's almost always a workaround to this, but since your code isn't fully self-contained it's hard for me to know.

(Side note: usually Numba will do much better if you use NumPy arrays rather than lists.)


问:
Practical use of metaprogramming
I started to learn metaprogramming. So far I used it to read annotations in Java and create sql statements based on given class but I don't see any practical use in it. Can you give me an example where and how you used it in your programs?</p>

答:
Annotating a method to be recogonized as a unit test.

```<code>import static org.junit.jupiter.api.Assertions.assertEquals;
import example.util.Calculator;
import org.junit.jupiter.api.Test;

class MyFirstJUnitJupiterTests {

    private final Calculator calculator = new Calculator();

    @Test
    void addition() {
        assertEquals(2, calculator.add(1, 1));
    }
}
</code>```

Note that the annotation here @Test exists as a flag.  When the test runner launches, it registers a listener for annotated methods, and if it encounters an annotated method that is annotated with the Test annotation interface, it will register that test in the "list of tests to run"

See https://junit.org/junit5/docs/current/user-guide/ for more details.

There are many examples of annotations in the wild.  This is just but one of them.

Title: Practical use of metaprogramming

Body:
Annotating a method to be recogonized as a unit test.

import static org.junit.jupiter.api.Assertions.assertEquals;
import example.util.Calculator;
import org.junit.jupiter.api.Test;

class MyFirstJUnitJupiterTests {

    private final Calculator calculator = new Calculator();

    @Test
    void addition() {
        assertEquals(2, calculator.add(1, 1));
    }
}

Note that the annotation here @Test exists as a flag.  When the test runner launches, it registers a listener for annotated methods, and if it encounters an annotated method that is annotated with the Test annotation interface, it will register that test in the "list of tests to run"

See https://junit.org/junit5/docs/current/user-guide/ for more details.

There are many examples of annotations in the wild.  This is just but one of them.


答:
```<code>class ElNinoData(object):
    add = 0
</code>```

The add here is not a global variable,

```<code>            global add
</code>```

therefore this does not give access to it, but instead looks for that actual global.

```<code>            add += self.object['humidity']
</code>```

+= requires the variable to exist already (so that the old value can be added to), and you don't have a global add, nor a local one - you have a class attribute.

To access it directly, you can use ElNinoData.add, just as you would from code outside the class. Similarly for the other class attributes.

Looking up the class attribute via the instance - self.add - also succeeds. However, modifying the value then attaches a separate attribute to the instance, and leaves the class attribute unaffected.

Title: defining a variable in a class

Body:
class ElNinoData(object):
    add = 0

The add here is not a global variable,

            global add

therefore this does not give access to it, but instead looks for that actual global.

            add += self.object['humidity']

+= requires the variable to exist already (so that the old value can be added to), and you don't have a global add, nor a local one - you have a class attribute.

To access it directly, you can use ElNinoData.add, just as you would from code outside the class. Similarly for the other class attributes.

Looking up the class attribute via the instance - self.add - also succeeds. However, modifying the value then attaches a separate attribute to the instance, and leaves the class attribute unaffected.


问:
How to resolve instances with constructor parameters in custom IOC Container?
I'm trying to build my own inversion of control container. Right now I store the objects with their types in a dictionary and resolve a reference when asked. But I want to make it possible to resolve a reference  or a new instance. I can create a new instance with the Activator class. But, what if the constructor of the object to resolve takes 1, 2 or any parameters?

For example, I want to be able to say something like:

```<code>Container.register<IFoo>(new Foo(Proxy));
Container.register<IBar>(new Boo(Proxy, DataThing));
</code>```

and resolve it like

```<code>IFoo MyFoo = Resolver.resolve<IFoo>();
IBar MyBar = Resolver.resolve<IBar>();
</code>```

where MyFoo gets instanciated with the given parameter Proxy and MyBar with Proxy and DataThing.

What does resolve have to do to make that happen?

答: Checkout http://funq.codeplex.com.  This is a very tiny Container that uses lambda expressions to define the function to resolve.  Handles multiple parameters.</p>

OwnerDisplayName: Sorskoot

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to build my own inversion of control container. Right now I store the objects with their types in a dictionary and resolve a reference when asked. But I want to make it possible to resolve a reference  or a new instance. I can create a new instance with the Activator class. But, what if the constructor of the object to resolve takes 1, 2 or any parameters?

For example, I want to be able to say something like:

Container.register<IFoo>(new Foo(Proxy));
Container.register<IBar>(new Boo(Proxy, DataThing));

and resolve it like

IFoo MyFoo = Resolver.resolve<IFoo>();
IBar MyBar = Resolver.resolve<IBar>();

where MyFoo gets instanciated with the given parameter Proxy and MyBar with Proxy and DataThing.

What does resolve have to do to make that happen?

OwnerDisplayName: Matthew


问:
Converting a String to ASCII format and then to HEX format
I have to convert a normal string array with the value {"STX","ETX"} into hex value and I should get {2,3} according to http://www.asciitable.com/. </p>

答:
It sounds like you want a Map<String, Char> such as:

```<code>Map<String, Char> map = new HashMap<String, Char>();
map.put("STX", '\u0002');
map.put("ETX", '\u0003');
// etc
</code>```

I don't believe there's any such map built into the Java standard libraries.

Converting the Char into a hex string is then a separate step. There are lots of options there, partly depending on which version of Java you're using.

Body:
It sounds like you want a Map<String, Char> such as:

Map<String, Char> map = new HashMap<String, Char>();
map.put("STX", '\u0002');
map.put("ETX", '\u0003');
// etc

I don't believe there's any such map built into the Java standard libraries.

Converting the Char into a hex string is then a separate step. There are lots of options there, partly depending on which version of Java you're using.


问:
Not handling missing details, response False
How can one check if, let's say alert when a title does not exist?

Can this be achieved with Axios?

```<code>export const getMoviesImdb = async (title) => {
  title = encodeURIComponent(title);
  return fetch(`http://www.omdbapi.com/?s=${title}`)
  .then((response) => response.json()
      .then((data) => {
        if (data.Response != "False") {
          return data.Search
        }
        return Promise.reject(data.Message);
      }, [])
      .catch((error) => {
        return Promise.reject(error);
      })
  );
};
</code>```

答:
With axios, you can access result using response.data. Also, it already returns a promise, so you don't have to explicitely return promise. Instead make checks on api response and throw error and simply catch it in the usage(where you call the getMoviesImdb function). Finally, the getMoviesImdb fun need not to be an async fun.

Working demo (just add your api key in the url to test it)

Code snippet sample

export default function App() {
  useEffect(() => {
    let myMovies;
    getMoviesImdb("asdf")
      .then(res => {
        // make sure to use your api key to see results
        console.log("res", res);
        myMovies = res;
      })
      .catch(err => {
        // make sure to use your api key to see error message
        console.log("err", err);
      });
  }, []);

  const getMoviesImdb = title => {
    console.log("title", title);
    // title = encodeURIComponent(title);
    // use your api key below
    return axios(`http://www.omdbapi.com/?s=${title}`).then(response => {
      // console.log("response", response);
      if (response.data.Response !== "False") {
        return data.Search;
      }
      console.log("response.data", response.data.Error);
      throw new Error(response.data.Error);
    });
  };
  return (

Hello CodeSandbox

Start editing to see some magic happen!

  );
}

```

Body:
How can one check if, let's say alert when a title does not exist?

Can this be achieved with Axios?

export const getMoviesImdb = async (title) => {
  title = encodeURIComponent(title);
  return fetch(`http://www.omdbapi.com/?s=${title}`)
  .then((response) => response.json()
      .then((data) => {
        if (data.Response != "False") {
          return data.Search
        }
        return Promise.reject(data.Message);
      }, [])
      .catch((error) => {
        return Promise.reject(error);
      })
  );
};

Body:
With axios, you can access result using response.data. Also, it already returns a promise, so you don't have to explicitely return promise. Instead make checks on api response and throw error and simply catch it in the usage(where you call the getMoviesImdb function). Finally, the getMoviesImdb fun need not to be an async fun.

Working demo (just add your api key in the url to test it)

Code snippet sample

export default function App() {
  useEffect(() => {
    let myMovies;
    getMoviesImdb("asdf")
      .then(res => {
        // make sure to use your api key to see results
        console.log("res", res);
        myMovies = res;
      })
      .catch(err => {
        // make sure to use your api key to see error message
        console.log("err", err);
      });
  }, []);

  const getMoviesImdb = title => {
    console.log("title", title);
    // title = encodeURIComponent(title);
    // use your api key below
    return axios(`http://www.omdbapi.com/?s=${title}`).then(response => {
      // console.log("response", response);
      if (response.data.Response !== "False") {
        return data.Search;
      }
      console.log("response.data", response.data.Error);
      throw new Error(response.data.Error);
    });
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}


问:
Get all the mail with body using imap in python
I am new to python and want to get all the mails with the body in the gmail account , but i am able to get only the oldest email.
My code is given below , thanks for help in advance.</p>

```<code>#!/usr/bin/env python

import getpass
import imaplib
import email
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
add = raw_input("Email address: ")
password = getpass.getpass()
M.login(add, password)

M.select()
resp, data = M.FETCH(1, '(RFC822)')
mail = email.message_from_string(data[0][1])

for part in mail.walk():
  # multipart are just containers, so we skip them
  if part.get_content_maintype() == 'multipart':
      continue

  # we are interested only in the simple text messages
  if part.get_content_subtype() != 'plain':
    continue

  payload = part.get_payload()
  print payload
</code>```

答:
You can try high level library - https://github.com/ikvk/imap_tools</p>

```<code># get list of email body from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    body_set = [msg.body for msg in mailbox.fetch()]
</code>```

Body:
I am new to python and want to get all the mails with the body in the gmail account , but i am able to get only the oldest email.
My code is given below , thanks for help in advance.

#!/usr/bin/env python

import getpass
import imaplib
import email
from email.parser import HeaderParser

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
add = raw_input("Email address: ")
password = getpass.getpass()
M.login(add, password)

M.select()
resp, data = M.FETCH(1, '(RFC822)')
mail = email.message_from_string(data[0][1])

for part in mail.walk():
  # multipart are just containers, so we skip them
  if part.get_content_maintype() == 'multipart':
      continue

  # we are interested only in the simple text messages
  if part.get_content_subtype() != 'plain':
    continue

  payload = part.get_payload()
  print payload

Body:
You can try high level library - https://github.com/ikvk/imap_tools

# get list of email body from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'password') as mailbox:
    body_set = [msg.body for msg in mailbox.fetch()]


答:
You can do it like this:

```<code>text = 'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

start = '{start}'
end = '{end}'

while True:
    text_start = text.find(start)
    text_end = text.find(end) + len(end)
    if text_start == -1:
        break
    text = text[:text_start - 1] + text[text_end:]

print(text)
</code>```

Or by using regex:

```<code>import re
text = 'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

start = '{start}'
end = '{end}'
text = re.sub(fr"{start}.*?{end} ", "", text) # f string requires python3.6+
print(text)
</code>```

Output:

```<code>AAAA CCCC EEEE GGGG
</code>```

Title: Delete words between specific elements in a txt-file with python

Body:
I am a python beginner and have the following problem:

I have a text file ('demofile.txt') and want to cut out everything between two specific elements ({start} and {end}) multiple times.

As en example imagine the text file contains:

'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

The outcome should be:

'AAAA CCCC EEEE GGGG'

First I defined the two elements which work as the cutter

start = '{start}'
end = '{end}'

The I tried to cut out the first part and used this code:

text_start = text.find(start)
text_new = text[0:text_start]
print(text_new)

The outcome is : 'AAAA ', which is what I wanted

For the next part I tried this:

text_start = text.find(end)
text_end = text.find(start, text_start)
text_new = text[text_start+len(end):text_end]
print(text_new)

The outcome is: 'CCCC ' which is again what I was looking for

Now I tried to put everything together and build a loop and failed :-)

text_start = text.find(start)
text_new = text[0:text_start]

text_end = 0

for parts in text.split("{"):
    text_start = text.find(end, text_end)
    text_end = text.find(start, text_start)
    text_new = text_new + text[text_start+len(end):text_end]
print(text_new)

The outcome is:
'AAAA  CCCC  EEEE  GGG {start} BBBB {end} CCCC {start} DDDD {end}...'
 and lot more of that. Thus the Outcome was okay until "GGG", but one G is missing. And all the stuff afterwards should be deleted.
I guess the loop continued somehow and the start of the loop with the split statement is crap.
What is the solution here? I would like to understand what went wrong and change the code.
Of course I am also interested in a shorter and more elegant way. I am sure what I did is quite terrible ;-)
I found something with "regular expressions" but I was not able to get this going as well.
Thanks for any idea.

(PS: any idea how I could save everything I cut out in a seperate file?)

Body:
You can do it like this:

text = 'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

start = '{start}'
end = '{end}'

while True:
    text_start = text.find(start)
    text_end = text.find(end) + len(end)
    if text_start == -1:
        break
    text = text[:text_start - 1] + text[text_end:]

print(text)

Or by using regex:

import re
text = 'AAAA {start} BBBB {end} CCCC {start} DDDD {end} EEEE {start} FFFF {end} GGGG'

start = '{start}'
end = '{end}'
text = re.sub(fr"{start}.*?{end} ", "", text) # f string requires python3.6+
print(text)

Output:

AAAA CCCC EEEE GGGG


问:
Why do type specs in OTP repeat parameter names?
In type specs for the Erlang standard library, there are almost never any types in the spec until the when clause. For example, the spec for lists:member/2 is like this:

-spec member(Elem, List) -> boolean() when
      Elem :: T,
      List :: [T],
      T :: term().
```

<p>instead of:</p>

<pre class="lang-erlang prettyprint-override"><code>-spec member(Elem :: T, List :: [T]) -> boolean() when
      T :: term().
</code>```

Is there a reason for this? Are these two styles equivalent from the dialyzer's point of view?

答: It is done that way because the documentation that is generated from the specs looks better if done like that.</p>

Body:
In type specs for the Erlang standard library, there are almost never any types in the spec until the when clause. For example, the spec for lists:member/2 is like this:

-spec member(Elem, List) -> boolean() when
      Elem :: T,
      List :: [T],
      T :: term().

instead of:

-spec member(Elem :: T, List :: [T]) -> boolean() when
      T :: term().

Is there a reason for this? Are these two styles equivalent from the dialyzer's point of view?


问:
Symfony and API Platform: custom URL for default implementation of CRUD operations
I am trying to set up an API. I would like to use the default implementation of CRUD operations for GET requests and override the operations for POST, PUT and DELETE. That works actually very well already.

But my problem now is, that I would like to change the URL of the default implementation, so it fits to the URLs of my custom operations.

My Code looks something like that:

```<code>@ApiResource(
    itemOperations={
        "get",
        "put"={
            "path"="/my/very/important/URL/{id}",
            "schemes"={"https"},
        }
    }
)
</code>```

And I would now like to make the GET operation available through /my/very/important/URL too, without implementing the GET operation.

答:
I found a workaround for what I actually wanted to do: adding a route prefix at the entity.

```<code>     * @ApiResource(
     *     routePrefix="/my/very/important/URL"
     * )
</code>```

But unfortunately I can still not prevent API Platform from using the plural of my entity name as URL.

If I have an entity Publication, than API Platform exposes my API with the URL /my/very/important/URL/publications. I still don't know how to fix that.

Body:
I am trying to set up an API. I would like to use the default implementation of CRUD operations for GET requests and override the operations for POST, PUT and DELETE. That works actually very well already.

But my problem now is, that I would like to change the URL of the default implementation, so it fits to the URLs of my custom operations.

My Code looks something like that:

@ApiResource(
    itemOperations={
        "get",
        "put"={
            "path"="/my/very/important/URL/{id}",
            "schemes"={"https"},
        }
    }
)

And I would now like to make the GET operation available through /my/very/important/URL too, without implementing the GET operation.

Body:
I found a workaround for what I actually wanted to do: adding a route prefix at the entity.

     * @ApiResource(
     *     routePrefix="/my/very/important/URL"
     * )

But unfortunately I can still not prevent API Platform from using the plural of my entity name as URL.

If I have an entity Publication, than API Platform exposes my API with the URL /my/very/important/URL/publications. I still don't know how to fix that.


问:
Print list in terminal on multiple lines
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

```<code>list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')
</code>```

Output:

```<code>3 5 6 9 10 12 15 18 20 21 24 25 etc...
</code>```

But i want this one:

```<code>3 5 6 9 10
12 15 18 20 21
</code>```

答:
You can change your print statement to:

```<code>print(x)
</code>```

If you would print some results in the same line, you can do a logic to print some characters inline and after some iteration print in next line.

```<code>list1 = list(range(1,100))
for num, x in enumerate(list1):
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')
    if num % 10 == 0:
        print()
</code>```

Body:
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')

Output:

3 5 6 9 10 12 15 18 20 21 24 25 etc...

But i want this one:

3 5 6 9 10
12 15 18 20 21

Body:
You can change your print statement to:

print(x)

If you would print some results in the same line, you can do a logic to print some characters inline and after some iteration print in next line.

list1 = list(range(1,100))
for num, x in enumerate(list1):
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')
    if num % 10 == 0:
        print()


问:
How to fix this error? This is already live site now
www-widgetapi.js:363 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient window's origin.</p>

答: The issue must be a conflict between http and https. Try changing the url of the file you are trying to embed to be https. Checkout this solution Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000</p>


问:
What am I doing wrong with this JS array?
I have the following code snippet for my Discord bot.  The first part works and outputs the URL to the console so I know what the output is.  I believe the issue is with my array and if statement.  Am I either not settup the array up correctly or checking of the array includes correct?

My test is that I have an empty Discord server and a test account with no profile pic.  I join that server and the out put to the console is the URL with the 4 down there so I know it's included in the list and matches it exactly.  The problem is that the ban never happens and no errors are thrown so I'm not sure if the includes part is throwing it off or not.  Any help would be appreciated!

Edit: I have a feeling that it's checking to see if all of the URLs in the array are there and that I need to change the code to check if any of them are in there but I might be wrong.

client.on("guildMemberAdd", (member) => {
 console.log(member.user.defaultAvatarURL)
});

client.on("guildMemberAdd", (member) => {
 const defaultURLs = ["https://cdn.discordapp.com/embed/avatars/0.png",
  "https://cdn.discordapp.com/embed/avatars/1.png",
  "https://cdn.discordapp.com/embed/avatars/2.png",
  "https://cdn.discordapp.com/embed/avatars/3.png",
  "https://cdn.discordapp.com/embed/avatars/4.png"]
 if (member.user.defaultAvatarURL.includes(defaultURLs)) {
        member.ban({ days: 7, reason: 'No Profile Pic' })
    }
});```

答:
Answering about the includes method. It should have been other way around. You can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

```<code>client.on("guildMemberAdd", (member) => {
    const defaultURLs = ["https://cdn.discordapp.com/embed/avatars/0.png",
        "https://cdn.discordapp.com/embed/avatars/1.png",
        "https://cdn.discordapp.com/embed/avatars/2.png",
        "https://cdn.discordapp.com/embed/avatars/3.png",
        "https://cdn.discordapp.com/embed/avatars/4.png"]
     if (defaultURLs.includes(member.user.defaultAvatarURL)) {
    member.ban({ days: 7, reason: 'No Profile Pic' }) }

});
</code>```

Body:
Answering about the includes method. It should have been other way around. You can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

client.on("guildMemberAdd", (member) => {
    const defaultURLs = ["https://cdn.discordapp.com/embed/avatars/0.png",
        "https://cdn.discordapp.com/embed/avatars/1.png",
        "https://cdn.discordapp.com/embed/avatars/2.png",
        "https://cdn.discordapp.com/embed/avatars/3.png",
        "https://cdn.discordapp.com/embed/avatars/4.png"]
     if (defaultURLs.includes(member.user.defaultAvatarURL)) {
    member.ban({ days: 7, reason: 'No Profile Pic' }) }

});


问:
Github Pages Unsupported Jekyll Theme
I've been trying to use a Jekyll theme from bootstrap called jekyll-theme-clean-blog, and everytime I publish it on Github I receive an email saying,
 "You are attempting to use a Jekyll theme, "jekyll-theme-clean-blog", which is not supported by GitHub Pages."
 I tried deleting the "theme" line in my _config.yml, but the page ends up with only the basic HTML and not the template. I have also installed the gem "Jekyll-remote-theme", but it doesn't seem to help. Can someone help me to figure this out?? Or does this mean that I can't use github pages to host the site?? Thank you very much I am a noob.

答:
I found this answer in adding a theme in the help docs, hope it helps. In the  _config.yml file:

To use a supported theme, type theme: THEME-NAME, replacing THEME-NAME with the name of the theme as shown in the README of the theme's repository

To use any other Jekyll theme hosted on GitHub, type remote_theme: THEME-NAME, replacing THEME-NAME with the name of the theme as shown in the README of the theme's repository.

Title: Github Pages Unsupported Jekyll Theme


问:
having problems using typed.js
i recently tried to use typed.js but it does not work the html page code is listed below, if there are any alternatives or any other way to get a similar effect then please share or help me to fix this issue

code -

```<code><html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://raw.githubusercontent.com/mattboldt/typed.js/master/dist/typed.min.js"></script>

    <script>
        var heading = $(".typed");
        if(heading.length){
            heading.typed({
                strings: ["Startups", "Business", "Agencies"],
                // Optionally use an HTML element to grab strings from (must wrap each string in a <p>)
                stringsElement: null,
                typeSpeed: 100,
                startDelay: 500,
                backSpeed: 100,
                backDelay: 500,
                loop: true,
                showCursor: true,
                cursorChar: "|",
                attr: null,
                contentType: 'html',
                callback: function() {},
                preStringTyped: function() {},
                onStringTyped: function() {},
                resetCallback: function() {}
            });
        }
</script>
</head>
<body>
<h2>We are <span class="typed"></span> </h2>
</body>
</html>
</code>```

答:
There are 2 issues with your code: The URL from where you trying to import typed.js is broken and you initialize typed in a wrong way. Here's a working example:

 var heading = $(".typed");
        if(heading.length){
 var typed1 = new Typed('.typed', {
                strings: ["Startups", "Business", "Agencies"],
                // Optionally use an HTML element to grab strings from (must wrap each string in a
)
                stringsElement: null,
                typeSpeed: 100,
                startDelay: 500,
                backSpeed: 100,
                backDelay: 500,
                loop: true,
                showCursor: true,
                cursorChar: "|",
                attr: null,
                contentType: 'html',
                callback: function() {},
                preStringTyped: function() {},
                onStringTyped: function() {},
                resetCallback: function() {}
            });
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.9"></script>
<h2>We are <span class="typed"></span> </h2></code>```

Title: having problems using typed.js

Body:
i recently tried to use typed.js but it does not work the html page code is listed below, if there are any alternatives or any other way to get a similar effect then please share or help me to fix this issue

code -

We are

Body:
There are 2 issues with your code: The URL from where you trying to import typed.js is broken and you initialize typed in a wrong way. Here's a working example:

 var heading = $(".typed");
        if(heading.length){
 var typed1 = new Typed('.typed', {
                strings: ["Startups", "Business", "Agencies"],
                // Optionally use an HTML element to grab strings from (must wrap each string in a <p>)
                stringsElement: null,
                typeSpeed: 100,
                startDelay: 500,
                backSpeed: 100,
                backDelay: 500,
                loop: true,
                showCursor: true,
                cursorChar: "|",
                attr: null,
                contentType: 'html',
                callback: function() {},
                preStringTyped: function() {},
                onStringTyped: function() {},
                resetCallback: function() {}
            });
        }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.9"></script>
<h2>We are <span class="typed"></span> </h2>


问:
Mask for BackgroundSubtractorMOG2
How can I tell BackgroundSubtractorMOG2 which pixels to update to the background model and which pixels shouldn't.

I am facing problem when there's an object entered the scene and stopped for a few ten seconds,  the object will be absorbed into the background model.

I wanted to decrease the learning rate or stop the learning around the particular stopped object but how can I do that? Does BackgroundSubtractorMOG2 support using mask in its update function?

I am using OpenCV 2.4.1.

答:
you can replace masked parts with background image:

BackgroundSubtractorMOG2 mog_bgs;
.
.
void my_apply(const cv::Mat& img, cv::Mat& fg, const cv::Mat& mask){
  cv::Mat last_bg;
  cv::Mat masked_img = img.clone();
  mog_bgs.getBackgroundImage(last_bg);
  last_bg.copyTo(masked_img, mask);
  mog_bgs.apply(masked_img, fg);
}
```

<p>or weight masked parts:</p>

<pre class="lang-cpp prettyprint-override"><code>BackgroundSubtractorMOG2 mog_bgs;
.
.
void my_apply(const cv::Mat& img, cv::Mat& fg, const cv::Mat& mask){
  cv::Mat last_bg;
  cv::Mat masked_img = img.clone();
  mog_bgs.getBackgroundImage(last_bg);
  masked_img.forEach<Vec3b>([&](Vec3b& p, const int* position) -> void
    {
        if (mask.at<uchar>(position[0], position[1]) > 0) {
            auto b = last_bg.at<Vec3b>(position[0], position[1]);
            p[0] = p[0]*0.2 + b[0]*0.8;
            p[1] = p[1]*0.2 + b[1]*0.8;
            p[2] = p[2]*0.2 + b[2]*0.8;
        }
    });
  mog_bgs.apply(masked_img, fg);
}
</code>```

Title: Mask for BackgroundSubtractorMOG2

Body:
you can replace masked parts with background image:

BackgroundSubtractorMOG2 mog_bgs;
.
.
void my_apply(const cv::Mat& img, cv::Mat& fg, const cv::Mat& mask){
  cv::Mat last_bg;
  cv::Mat masked_img = img.clone();
  mog_bgs.getBackgroundImage(last_bg);
  last_bg.copyTo(masked_img, mask);
  mog_bgs.apply(masked_img, fg);
}

or weight masked parts:

BackgroundSubtractorMOG2 mog_bgs;
.
.
void my_apply(const cv::Mat& img, cv::Mat& fg, const cv::Mat& mask){
  cv::Mat last_bg;
  cv::Mat masked_img = img.clone();
  mog_bgs.getBackgroundImage(last_bg);
  masked_img.forEach<Vec3b>([&](Vec3b& p, const int* position) -> void
    {
        if (mask.at<uchar>(position[0], position[1]) > 0) {
            auto b = last_bg.at<Vec3b>(position[0], position[1]);
            p[0] = p[0]*0.2 + b[0]*0.8;
            p[1] = p[1]*0.2 + b[1]*0.8;
            p[2] = p[2]*0.2 + b[2]*0.8;
        }
    });
  mog_bgs.apply(masked_img, fg);
}


问:
Trouble compiling helloworld.cu
While compiling this hello world sample in Ubuntu 10.10

This is from CUDA by Example, chapter 3 (No compile instructions provided >:@)

```<code>#include <iostream>

__global__ void kernel (void){

}

int main(void){

    kernel <<<1,1>>>();
        printf("Hellow World!\n");
    return 0;

}
</code>```

I got this:

$ nvcc -lcudart hello.cu hello.cu(11): error: identifier "printf" is
  undefined

1 error detected in the compilation of
  "/tmp/tmpxft_00007812_00000000-4_hello.cpp1.ii".

Why? How should this code be compiled?

答:
The issue is that the compiler does not know where to find printf function. It
needs to know where to find it. The include directive is used to tell the compiler where to find it.

#include "stdio.h"

int main(void) {
  printf("Hello World!\n");
  return 0;
}
```

<p>After the fix, it would work:</p>

<pre class="lang-sh prettyprint-override"><code>$ nvcc hello_world.cu
$ ls
a.out  hello_world.cu
$ a.out
Hello World!
</code>```

Title: Trouble compiling helloworld.cu

Body:
While compiling this hello world sample in Ubuntu 10.10

This is from CUDA by Example, chapter 3 (No compile instructions provided >:@)

#include <iostream>

__global__ void kernel (void){

}

int main(void){

    kernel <<<1,1>>>();
        printf("Hellow World!\n");
    return 0;

}

I got this:

$ nvcc -lcudart hello.cu hello.cu(11): error: identifier "printf" is
  undefined

1 error detected in the compilation of
  "/tmp/tmpxft_00007812_00000000-4_hello.cpp1.ii".

Why? How should this code be compiled?

Body:
The issue is that the compiler does not know where to find printf function. It
needs to know where to find it. The include directive is used to tell the compiler where to find it.

#include "stdio.h"

int main(void) {
  printf("Hello World!\n");
  return 0;
}

After the fix, it would work:

$ nvcc hello_world.cu
$ ls
a.out  hello_world.cu
$ a.out
Hello World!