问:
After Mac OS update Pycharm django python console doesn't have right environmental variable but the "run server" works fine
I am using pycharm as editor of my django app. Everything was working fine until I updated my mac os. After that a lot of settings got messed up for the python interpreter.

I managed to fix most of the issue and now I can "run the server" correctly. However, I still can't get the python console to run properly.

When I open the console and I try to import a model, I get the following error:

```<code>django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

</code>```

The thing that kills me is that I have the DJANGO_SETTINGS_MODULE set in my django server environmental variables so it's if the python console was not picking that up.

答:
Yeah this is a bit of a pain, I suggest checking out the below settings and updating the options for both your settings file AS WELL as your manage.py file and make sure your manage.py file is pointing to your settings.

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mywebsite.settings")

https://www.jetbrains.com/help/pycharm/django-support.html#4902d6de

https://www.jetbrains.com/help/pycharm/console-django-console.html

Body:
I am using pycharm as editor of my django app. Everything was working fine until I updated my mac os. After that a lot of settings got messed up for the python interpreter.

I managed to fix most of the issue and now I can "run the server" correctly. However, I still can't get the python console to run properly.

When I open the console and I try to import a model, I get the following error:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

The thing that kills me is that I have the DJANGO_SETTINGS_MODULE set in my django server environmental variables so it's if the python console was not picking that up.


来源: stackexchange

问:
Using setTimeout on promise chain
Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next promise object.So i use setTimeout on it. But it gives me the following JSON error (without setTimeout() it works just fine)

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data

i would like to know why it fails?

```<code>let globalObj={};
function getLinks(url){
    return new Promise(function(resolve,reject){

       let http = new XMLHttpRequest();
       http.onreadystatechange = function(){
            if(http.readyState == 4){
              if(http.status == 200){
                resolve(http.response);
              }else{
                reject(new Error());
              }
            }
       }
       http.open("GET",url,true);
       http.send();
    });
}

getLinks('links.txt').then(function(links){
    let all_links = (JSON.parse(links));
    globalObj=all_links;

    return getLinks(globalObj["one"]+".txt");

}).then(function(topic){

    writeToBody(topic);
    setTimeout(function(){
         return getLinks(globalObj["two"]+".txt"); // without setTimeout it works fine
         },1000);
});
</code>```

答:
```<code>const myStuff = new Promise(function (resolve) {
  console.log("before timeout");
  setTimeout(
    function (x) {
      console.log("inside the timeout");
      resolve(x);
    },
    3000,
    "after timeout"
  );
}).then((response) => console.log(response));
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using setTimeout on promise chain

Body:
Here i am trying to wrap my head around promises.Here on first request i fetch a set of links.and on next request i fetch the content of first link.But i want to make a delay before returning next promise object.So i use setTimeout on it. But it gives me the following JSON error (without setTimeout() it works just fine)

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data

i would like to know why it fails?

let globalObj={};
function getLinks(url){
    return new Promise(function(resolve,reject){

       let http = new XMLHttpRequest();
       http.onreadystatechange = function(){
            if(http.readyState == 4){
              if(http.status == 200){
                resolve(http.response);
              }else{
                reject(new Error());
              }
            }
       }
       http.open("GET",url,true);
       http.send();
    });
}

getLinks('links.txt').then(function(links){
    let all_links = (JSON.parse(links));
    globalObj=all_links;

    return getLinks(globalObj["one"]+".txt");

}).then(function(topic){

    writeToBody(topic);
    setTimeout(function(){
         return getLinks(globalObj["two"]+".txt"); // without setTimeout it works fine
         },1000);
});


问:
How to avoid integer overflow in MiniZinc?
I am trying to solve a code-game from codingame website using MiniZinc for Python.
All I have to do is to find the number of the possible combination in a morse code, given a vocabulary (a set of possible words that, converted and concatenated, should precisely be equal to the input morse code).
I have been able to sort out a solution pretty fast, but the problem is that whatever solver I use, I get an integer overflow.
I tried to use OptiMathSAT but I could not manage to apply it.

Here, you can find my code (you will not find the count of the possible combination, but I think it would be straigth-forward):

```<code>MORSE_CODE_DICT = { 'A':'12', 'B':'2111',
                    'C':'2121', 'D':'211', 'E':'1',
                    'F':'1121', 'G':'221', 'H':'1111',
                    'I':'11', 'J':'1222', 'K':'212',
                    'L':'1211', 'M':'22', 'N':'21',
                    'O':'222', 'P':'1221', 'Q':'2212',
                    'R':'121', 'S':'111', 'T':'2',
                    'U':'112', 'V':'1112', 'W':'122',
                    'X':'2112', 'Y':'2122', 'Z':'2211'}

# Input vocabulary converter to number
def converter(vocabulary):
    for i in range(len(vocabulary)):
        var = ""
        for j in vocabulary[i]:
            var = var+MORSE_CODE_DICT[j]
        vocabulary[i]=int(var)
    return vocabulary

# Create a MiniZinc model

gecode = Solver.lookup("or-tools")
model=Model()
model.add_string("""
include "globals.mzn";

int: n;
int: lmax;
array[1..n] of int: c;
int: morse;
array [1..lmax] of var 1..n: frase;
var int: r;
array [1..n] of var int: len;
array [1..lmax] of var int: sa;

constraint forall(i in 1..n)(len[i]=string_length(mzn_version_to_string(c[i]))-4);
constraint sa[1]=c[frase[1]];
constraint forall(i in 2..lmax)(sa[i]=c[frase[i]]*pow(10,sum(j in 2..i)(len[frase[j-1]])));
constraint lmax>0 /\ lmax<100000;
constraint n>0 /\ n<100000;
constraint forall(i in len)(i>0 /\ i<20);
constraint r>=0 /\ r<pow(2,10);
constraint sum(sa) = morse;
""")

# Transform Model into a instance

inst = Instance(gecode, model)
inst["n"] = 6

vocabulary = ["HELL","HELLO","OWORLD","WORLD","TEST"]
vocabulary= np.array(converter(vocabulary))
vocabulary = np.append(vocabulary, 0)
print(vocabulary)
inst["c"] = vocabulary

morse = 11111121112112221222221211211211
inst["morse"] = morse

print(len(str(morse)));
inst["lmax"] = len(str(morse))

result = inst.solve()
</code>```

How would you solve this problem? Could you give me some advice about a possible solution or different approach to the problem?
I have already tried using strings rather than ints, but MiniZinc does not support them very well.

Thank you in advance to everyone.

答:
Most FlatZinc solvers don't support large integers and give overlflow errors, for example when detecting operations with integers larger than 2**32. The exact limit is solver dependent.

One problem in your model is that you have a lot of domains defined as var int which yield very large domains for the solver to work with. If you try to reduce these domains as much as possible, it might work.

In the MiniZinc model, I commented some of the constraints and gave all the var int some (but probably wrong) domains which gave a solution using the OR-tools solver:

```<code>include "globals.mzn";

int: n;
int: lmax;
array[1..n] of int: c;
int: morse;

array [1..lmax] of var 1..n: frase;
var 0..pow(2,10): r; % hakank
array [1..n] of var 0..20: len; % hakank
array [1..lmax] of var 0..100000000: sa; % hakank

% constraint forall(i in 1..n)(len[i]=string_length(mzn_version_to_string(c[i]))-4);
constraint sa[1]=c[frase[1]];
% constraint forall(i in 2..lmax)(sa[i]=c[frase[i]]*pow(10,sum(j in 2..i)(len[frase[j-1]])));
constraint lmax>0 /\ lmax<100000;
% constraint n>0 /\ n<100000;
% constraint forall(i in len)(i>0 /\ i<20);
% constraint r>=0 /\ r<pow(2,10);
constraint sum(sa) = morse;

solve satisfy;

</code>```

Here is one solution which - as mentioned above - don't look correct. But you can now work with the constraints and the domains.

```<code>Solution(frase=[5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
         r=0,
         len=[0, 0, 0, 0, 0, 0],
         sa=[211112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 47272535, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000],
         _checker='')

</code>```

Body:
I am trying to solve a code-game from codingame website using MiniZinc for Python.
All I have to do is to find the number of the possible combination in a morse code, given a vocabulary (a set of possible words that, converted and concatenated, should precisely be equal to the input morse code).
I have been able to sort out a solution pretty fast, but the problem is that whatever solver I use, I get an integer overflow.
I tried to use OptiMathSAT but I could not manage to apply it.

Here, you can find my code (you will not find the count of the possible combination, but I think it would be straigth-forward):

MORSE_CODE_DICT = { 'A':'12', 'B':'2111',
                    'C':'2121', 'D':'211', 'E':'1',
                    'F':'1121', 'G':'221', 'H':'1111',
                    'I':'11', 'J':'1222', 'K':'212',
                    'L':'1211', 'M':'22', 'N':'21',
                    'O':'222', 'P':'1221', 'Q':'2212',
                    'R':'121', 'S':'111', 'T':'2',
                    'U':'112', 'V':'1112', 'W':'122',
                    'X':'2112', 'Y':'2122', 'Z':'2211'}

# Input vocabulary converter to number
def converter(vocabulary):
    for i in range(len(vocabulary)):
        var = ""
        for j in vocabulary[i]:
            var = var+MORSE_CODE_DICT[j]
        vocabulary[i]=int(var)
    return vocabulary

# Create a MiniZinc model

gecode = Solver.lookup("or-tools")
model=Model()
model.add_string("""
include "globals.mzn";

int: n;
int: lmax;
array[1..n] of int: c;
int: morse;
array [1..lmax] of var 1..n: frase;
var int: r;
array [1..n] of var int: len;
array [1..lmax] of var int: sa;

constraint forall(i in 1..n)(len[i]=string_length(mzn_version_to_string(c[i]))-4);
constraint sa[1]=c[frase[1]];
constraint forall(i in 2..lmax)(sa[i]=c[frase[i]]*pow(10,sum(j in 2..i)(len[frase[j-1]])));
constraint lmax>0 /\ lmax<100000;
constraint n>0 /\ n<100000;
constraint forall(i in len)(i>0 /\ i<20);
constraint r>=0 /\ r<pow(2,10);
constraint sum(sa) = morse;
""")

# Transform Model into a instance

inst = Instance(gecode, model)
inst["n"] = 6

vocabulary = ["HELL","HELLO","OWORLD","WORLD","TEST"]
vocabulary= np.array(converter(vocabulary))
vocabulary = np.append(vocabulary, 0)
print(vocabulary)
inst["c"] = vocabulary

morse = 11111121112112221222221211211211
inst["morse"] = morse

print(len(str(morse)));
inst["lmax"] = len(str(morse))

result = inst.solve()

How would you solve this problem? Could you give me some advice about a possible solution or different approach to the problem?
I have already tried using strings rather than ints, but MiniZinc does not support them very well.

Thank you in advance to everyone.

Body:
Most FlatZinc solvers don't support large integers and give overlflow errors, for example when detecting operations with integers larger than 2**32. The exact limit is solver dependent.

One problem in your model is that you have a lot of domains defined as var int which yield very large domains for the solver to work with. If you try to reduce these domains as much as possible, it might work.

In the MiniZinc model, I commented some of the constraints and gave all the var int some (but probably wrong) domains which gave a solution using the OR-tools solver:

include "globals.mzn";

int: n;
int: lmax;
array[1..n] of int: c;
int: morse;

array [1..lmax] of var 1..n: frase;
var 0..pow(2,10): r; % hakank
array [1..n] of var 0..20: len; % hakank
array [1..lmax] of var 0..100000000: sa; % hakank

% constraint forall(i in 1..n)(len[i]=string_length(mzn_version_to_string(c[i]))-4);
constraint sa[1]=c[frase[1]];
% constraint forall(i in 2..lmax)(sa[i]=c[frase[i]]*pow(10,sum(j in 2..i)(len[frase[j-1]])));
constraint lmax>0 /\ lmax<100000;
% constraint n>0 /\ n<100000;
% constraint forall(i in len)(i>0 /\ i<20);
% constraint r>=0 /\ r<pow(2,10);
constraint sum(sa) = morse;

solve satisfy;

Here is one solution which - as mentioned above - don't look correct. But you can now work with the constraints and the domains.

Solution(frase=[5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
         r=0,
         len=[0, 0, 0, 0, 0, 0],
         sa=[211112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 47272535, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000, 100000000],
         _checker='')


问:
Onclick function only works when I Click twice
I have this Little list that should show different modals based on what the user select , and the problem is When I select the first time it doesn't work and I have to click on it again to work .

Here is my code :

```<code>const Mylist = props => {
    const [open2, setOpen2] = React.useState(false);
  const [open3, setOpen3] = React.useState(false);

const handleClose2 = () => {
    setOpen2(false);
  };

  const handleOpen2 = () => {
    setOpen2(true);
  };
  const handleClose3 = () => {
    setOpen3(false);
  };

  const handleOpen3 = () => {
    setOpen3(true);
  };
    const [isActive , SetIsActive] = useState(false);
    const option =["Paid" , "UnPaid"]
    return (
        <div>
            <i class="fas fa-ellipsis-v" onClick={(e) => SetIsActive(!isActive)}></i>
            {isActive && (
                <div>
                    {option.map((option) => (
                        <div
                        onClick={(e) => {
                            SetIsActive(false);
                            {option == 'Paid' && setOpen2(true)}
                            {option == 'UnPaid' && setOpen3(true)}
                        }}
                        >
                            {option}
                            </div>

                    ))}

 <Modal onClose={handleClose2} open={open2} >
                            <div>
Content
</div>
</Modal>

 <Modal onClose={handleClose3} open={open3} >
                            <div>
Content
</div>
</Modal>
</code>```

答:
Your code block is a bit messy with some brackets and closing tags missing (possibly some of the code was not copied in by mistake?).

In any case, I did my best at trying to fill in the missing parts and did some refactoring to your code. I hope that fixes your bug!

```<code>import React, { useState } from 'react';

const MyList = (props) => {
    const [isOpen1, setIsOpen1] = useState(false);
    const [isOpen2, setIsOpen2] = useState(false);
    const [isActive, setIsActive] = useState(false);

    const openOption = (option) => {
        setIsActive(false);
        if (option === "Paid") {
            setIsOpen1(true);
        }
        if (option === "UnPaid") {
            setIsOpen2(true);
        }
    };

    const options =["Paid", "UnPaid"]

    return (
        <div>
            <i class="fas fa-ellipsis-v" onClick={() => setIsActive(!isActive)}></i>
            {isActive && (
                <div>
                    {options.map((option) => (
                        <div onClick={() => openOption(option)}>
                            {option}
                        </div>
                    ))}
                </div>
            )}
            <Modal onClose={() => setIsOpen1(false)} open={isOpen1} >
                <div>
                    Content
                </div>
            </Modal>

            <Modal onClose={() => setIsOpen2(false)} open={isOpen2} >
                <div>
                    Content
                </div>
            </Modal>
        </div>
    );
};

</code>```

Body:
I have this Little list that should show different modals based on what the user select , and the problem is When I select the first time it doesn't work and I have to click on it again to work .

Here is my code :

const Mylist = props => {
    const [open2, setOpen2] = React.useState(false);
  const [open3, setOpen3] = React.useState(false);

const handleClose2 = () => {
    setOpen2(false);
  };

  const handleOpen2 = () => {
    setOpen2(true);
  };
  const handleClose3 = () => {
    setOpen3(false);
  };

  const handleOpen3 = () => {
    setOpen3(true);
  };
    const [isActive , SetIsActive] = useState(false);
    const option =["Paid" , "UnPaid"]
    return (

             SetIsActive(!isActive)}>
            {isActive && (

                    {option.map((option) => (

 {
                            SetIsActive(false);
                            {option == 'Paid' && setOpen2(true)}
                            {option == 'UnPaid' && setOpen3(true)}
                        }}
                        >
                            {option}

                    ))}

 <Modal onClose={handleClose2} open={open2} >

Content

</Modal>

 <Modal onClose={handleClose3} open={open3} >

Content

</Modal>

Body:
Your code block is a bit messy with some brackets and closing tags missing (possibly some of the code was not copied in by mistake?).

In any case, I did my best at trying to fill in the missing parts and did some refactoring to your code. I hope that fixes your bug!

import React, { useState } from 'react';

const MyList = (props) => {
    const [isOpen1, setIsOpen1] = useState(false);
    const [isOpen2, setIsOpen2] = useState(false);
    const [isActive, setIsActive] = useState(false);

    const openOption = (option) => {
        setIsActive(false);
        if (option === "Paid") {
            setIsOpen1(true);
        }
        if (option === "UnPaid") {
            setIsOpen2(true);
        }
    };

    const options =["Paid", "UnPaid"]

    return (
        <div>
            <i class="fas fa-ellipsis-v" onClick={() => setIsActive(!isActive)}></i>
            {isActive && (
                <div>
                    {options.map((option) => (
                        <div onClick={() => openOption(option)}>
                            {option}
                        </div>
                    ))}
                </div>
            )}
            <Modal onClose={() => setIsOpen1(false)} open={isOpen1} >
                <div>
                    Content
                </div>
            </Modal>

            <Modal onClose={() => setIsOpen2(false)} open={isOpen2} >
                <div>
                    Content
                </div>
            </Modal>
        </div>
    );
};


问:
Python: remove brackets of list elements while printing pandas dataframe
I have a pandas dataframe of this kind

```<code>d = {'col1': [1, [2,3]], 'col2': [[3,4,5], 4]}
d = pd.DataFrame(d)
print(d)
</code>```

output:

```<code>     col1       col2
0       1  [3, 4, 5]
1  [2, 3]          4
</code>```

what is the best way to remove the brackets of all the list elements while printing this dataframe?

答:
you can simply convert the column (list) to string and remove the brackets, such that:

```<code>for c in d.columns:
    d[c]= d.apply(lambda x: str(x[c]).replace("[",'').replace(']',''), axis=1)
</code>```

desired result

```<code>    col1    col2
0   1       3, 4, 5
1   2, 3    4
</code>```

Body:
I have a pandas dataframe of this kind

d = {'col1': [1, [2,3]], 'col2': [[3,4,5], 4]}
d = pd.DataFrame(d)
print(d)

output:

     col1       col2
0       1  [3, 4, 5]
1  [2, 3]          4

what is the best way to remove the brackets of all the list elements while printing this dataframe?

Body:
you can simply convert the column (list) to string and remove the brackets, such that:

for c in d.columns:
    d[c]= d.apply(lambda x: str(x[c]).replace("[",'').replace(']',''), axis=1)

desired result

    col1    col2
0   1       3, 4, 5
1   2, 3    4


问:
Is it possible to create a generic Int-to-Enum Converter?
I'd like to be able to say

```<code><DataTrigger Binding="{Binding SomeIntValue}"
             Value="{x:Static local:MyEnum.SomeValue}">
</code>```

and to have it resolve as True if the int value is equal to (int)MyEnum.Value

I know I could make a Converter that returns (MyEnum)intValue, however then I'd have to make a converter for every Enum type I use in my DataTriggers.

Is there a generic way to create a converter that would give me this kind of functionality?

答:
You could do a ToString() on the int value and then pass that into the static Enum.Parse or Enum.TryParse method which takes the enum type you care about and returns the appropriate value.

This isn't a perfect solution though because it won't work with integers that represent the binary ORing of multiple enum values

ContentLicense: CC BY-SA 3.0

Body:
I'd like to be able to say

<DataTrigger Binding="{Binding SomeIntValue}"
             Value="{x:Static local:MyEnum.SomeValue}">

and to have it resolve as True if the int value is equal to (int)MyEnum.Value

I know I could make a Converter that returns (MyEnum)intValue, however then I'd have to make a converter for every Enum type I use in my DataTriggers.

Is there a generic way to create a converter that would give me this kind of functionality?


问:
How to parse and scrape the content of WordPress
Is it possible to have a custom function to truncate the contents of a defined DIV on a blog post page to use as the summary on the blog index page. So rather than using $the_content or $the_excerpt - Is it possible to create $the_customContent and have some PHP which checks the blog post page and collects the content of the div with class "ThisIsTheContentToUse" - reason for this is that my blog posts have content on the page above the content I want to be included as the blog summary on the blog index page - so either want to tell WP to ignore those blocks of content, or, probably easier - just tell WP where the content to truncate is - e.g. in the "ThisIsTheContentToUse" div... possible?

If so... how? Can't seem to find anything online that defines this custom functionality - surely I can't be the first person to want to do this...?

Would apply_filters make this possible?

https://developer.wordpress.org/reference/hooks/the_content/

So, The blog post is structured as:

The title is here

Bullet 1

Bullet 2

Bullet 3

The content starts here

```

So, currently with the basic get_the_content, the result is:

"The title is here Bullet 1 Bullet 2 Bullet 3 The content starts here"

But what I want is just the content of the "ThisIsTheContentToUse" div.

So it would be:

"The content starts here"

答:
There are several ways we could set this up, two of which are popular. We could use the php DOMDocument class as well as the good old favorite of mine regular expressions!

Using DOMDocument:

First, we get the content using get_the_content function.

Then, we'll read the content using DOMDocument.

And finally parse it.

$test = get_the_content();

if (class_exists('DOMDocument'))
{
    $dom = new DOMDocument();

    $class_name = 'ThisIsTheContentToUse';// This is the class name of your div element

    @$dom->loadHTML($test);

    $nodes = $dom->getElementsByTagName('div');

    foreach ($nodes as $element)
    {
        $element_class = $element->getAttribute('class');

        if (substr_count($element_class, $class_name))
        {
            echo 'Using DOMDocument: ' . $element->nodeValue;
        }
    }
}
```
<p>Which will output this:</p>
<p><img src="https://i.stack.imgur.com/BdG84l.png" alt="enter image description here" /></p>
<hr />
<h3>Using <code>Regular Expressions</code>:</h3>
<ol>
<li>We use <code>preg_match</code> function.</li>
<li>This is the pattern <code><div class="ThisIsTheContentToUse">([^w]*?)<\/div></code>.</li>
</ol>
<pre class="lang-php prettyprint-override"><code>$test = get_the_content();

preg_match('/<div class="ThisIsTheContentToUse">([^w]*?)<\/div>/', $test, $match);

$new_excerpt = $match[1];

echo 'Using regular expressions: ' . $new_excerpt;
</code>```

Which will output this:

Body:
Is it possible to have a custom function to truncate the contents of a defined DIV on a blog post page to use as the summary on the blog index page. So rather than using $the_content or $the_excerpt - Is it possible to create $the_customContent and have some PHP which checks the blog post page and collects the content of the div with class "ThisIsTheContentToUse" - reason for this is that my blog posts have content on the page above the content I want to be included as the blog summary on the blog index page - so either want to tell WP to ignore those blocks of content, or, probably easier - just tell WP where the content to truncate is - e.g. in the "ThisIsTheContentToUse" div... possible?

If so... how? Can't seem to find anything online that defines this custom functionality - surely I can't be the first person to want to do this...?

Would apply_filters make this possible?

https://developer.wordpress.org/reference/hooks/the_content/

So, The blog post is structured as:

The title is here

Bullet 1

Bullet 2

Bullet 3

The content starts here

So, currently with the basic get_the_content, the result is:

"The title is here Bullet 1 Bullet 2 Bullet 3 The content starts here"

But what I want is just the content of the "ThisIsTheContentToUse" div.

So it would be:

"The content starts here"

Body:
There are several ways we could set this up, two of which are popular. We could use the php DOMDocument class as well as the good old favorite of mine regular expressions!

Using DOMDocument:

First, we get the content using get_the_content function.

Then, we'll read the content using DOMDocument.

And finally parse it.

$test = get_the_content();

if (class_exists('DOMDocument'))
{
    $dom = new DOMDocument();

    $class_name = 'ThisIsTheContentToUse';// This is the class name of your div element

    @$dom->loadHTML($test);

    $nodes = $dom->getElementsByTagName('div');

    foreach ($nodes as $element)
    {
        $element_class = $element->getAttribute('class');

        if (substr_count($element_class, $class_name))
        {
            echo 'Using DOMDocument: ' . $element->nodeValue;
        }
    }
}

Which will output this:

Using Regular Expressions:

We use preg_match function.

This is the pattern <div class="ThisIsTheContentToUse">([^w]*?)<\/div>.

$test = get_the_content();

preg_match('/<div class="ThisIsTheContentToUse">([^w]*?)<\/div>/', $test, $match);

$new_excerpt = $match[1];

echo 'Using regular expressions: ' . $new_excerpt;

Which will output this:


问:
Get encrypted data from HTTPS request to use certificate manually C#
I am trying for my project this:

I want to download the (root) certificate from given url (or from diff location in later stages)

i want then get data from given url and use certificate i download in step one to "decrypt them"

check response on given url if step 1 and 2 get me same results as just response from the server

Basically I am trying to create something that check that given certificates works on given url same as the one automatically given.

Preferably do all 3 steps in one request (so if given url has counter for access, whole procedure is just one access on website)

I can do quite nice step 1)

```<code>var client = new TcpClient(address.ToString(), 443);
var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate, X509Chain chainLocal, SslPolicyErrors sslPolicyErrors)
                {
                    return true; //Accept every certificate, even if it's invalid
                });

// Create an SSL stream and takeover client's stream
using (var sslStream = new SslStream(client.GetStream(), true, certValidation))
{
    sslStream.AuthenticateAsClient(InputWWW.Text);
    var serverCertificate = sslStream.RemoteCertificate;
    cert = new X509Certificate2(serverCertificate);
}
</code>```

But I am not able to find any tips hot to get that raw data locally.

So far I found only something like this, where I use certificate in request handler

```<code>WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };
handler.ClientCertificates.Add(certificate);
</code>```

which is usage of certificate.

I want something like this:

```<code>var binary/StringBlob = webRequest.getRawData(url,port);

var serverResponseManualy = applyCertificate/publicKey(binary/StringBlob, X509Certificate2 certificate );

checkBodyEquals(serverResponseManually, webRequest.GetResponse());
</code>```

Do you know how to do it, or what should I search for?

Is it possible to do all this in one request to server or not?

Thanks

答: So i was able to get more info about https, after that i discover that the way i ask this question is not correct. Because certificate (asymmetric cryptography) is used only to create symmetric key, which is used for encryption/description. So encrypted message by private key cannot be obtained</p>

Body:
I am trying for my project this:

I want to download the (root) certificate from given url (or from diff location in later stages)

i want then get data from given url and use certificate i download in step one to "decrypt them"

check response on given url if step 1 and 2 get me same results as just response from the server

Basically I am trying to create something that check that given certificates works on given url same as the one automatically given.

Preferably do all 3 steps in one request (so if given url has counter for access, whole procedure is just one access on website)

I can do quite nice step 1)

var client = new TcpClient(address.ToString(), 443);
var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate, X509Chain chainLocal, SslPolicyErrors sslPolicyErrors)
                {
                    return true; //Accept every certificate, even if it's invalid
                });

// Create an SSL stream and takeover client's stream
using (var sslStream = new SslStream(client.GetStream(), true, certValidation))
{
    sslStream.AuthenticateAsClient(InputWWW.Text);
    var serverCertificate = sslStream.RemoteCertificate;
    cert = new X509Certificate2(serverCertificate);
}

But I am not able to find any tips hot to get that raw data locally.

So far I found only something like this, where I use certificate in request handler

WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };
handler.ClientCertificates.Add(certificate);

which is usage of certificate.

I want something like this:

var binary/StringBlob = webRequest.getRawData(url,port);

var serverResponseManualy = applyCertificate/publicKey(binary/StringBlob, X509Certificate2 certificate );

checkBodyEquals(serverResponseManually, webRequest.GetResponse());

Do you know how to do it, or what should I search for?

Is it possible to do all this in one request to server or not?

Thanks


问:
Reuse X number of prototype beans
I'm building an application in spring boot that creates X number of Netty tcp socket servers based on my config.

I would like to have X number of MyChannelHandler beans (one for each tcp port). The idea is to have separate worlds/servers in my application and each world has X number of game channels (not related to netty channel). Each game channel is represented by a tcp socket server running on some port.

```<code>@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Sharable
@RequiredArgsConstructor
public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    private final int port;

    @Autowired
    private ContextAwareLogger logger;
    @Autowired
    private AppConfig config;
    @Autowired
    private GameService gameService;
    @Autowired
    private ObjectProvider<GameClient> clientObjectProvider;

    private Map<String, GameClient> connectedClients = Collections.synchronizedMap(new HashMap<>());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // logic omitted
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
       // logic omitted
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // logic omitted
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // logic omitted
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
        // logic omitted
    }

    public Map<String, GameClient> getConnectedClients() {
        return connectedClients;
    }

    private GameClient initClient(ChannelHandlerContext ctx) {
        // logic omitted
    }

}

</code>```

Servers created here:

```<code>@Component
@RequiredArgsConstructor
public class MySocketServer {

    public static final AttributeKey<Boolean> PACKET_START_KEY = AttributeKey.valueOf("PACKET_START");
    public static final AttributeKey<MyGameClient> CLIENT_ATTRIBUTE_KEY = AttributeKey.valueOf("CLIENT");
    public static final AttributeKey<String> CLIENT_ID_KEY = AttributeKey.valueOf("CLIENT_ID_KEY");
    public static final AttributeKey<Boolean> HANDSHAKE_KEY = AttributeKey.valueOf("HANDSHAKE");

    private final ContextAwareLogger logger;
    private final AppConfig config;
    private final ObjectProvider<MyGameClient> clientObjectProvider;

    @Qualifier("MyServerInitializer")
    @Autowired
    private ChannelInitializer<SocketChannel> serverInitializer;
    @Qualifier("MyChannelInitializer")
    @Autowired
    private ChannelInitializer<SocketChannel> channelInitializer;

    @Qualifier("serverBossGroup")
    @Autowired
    private NioEventLoopGroup bossGroup;

    @Qualifier("serverWorkerGroup")
    @Autowired
    private NioEventLoopGroup workerGroup;

    private Channel loginChannel;
    private List<Channel> worldChannels = new ArrayList<>();

    @PostConstruct
    public void start() {
        try {
            ServerBootstrap bootstrap = init(serverInitializer);
            loginChannel = bootstrap.bind(config.getServer().getSocketServerPort()).sync().channel(); // save the main channel so we can cleanly close it when app is shutdown
            logger.info("Netty server started...");

            initWorlds();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void stop() throws InterruptedException {
        logger.info("Shutting down Netty server");
        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
        loginChannel.closeFuture().sync();
        logger.info("Netty Server shutdown complete.");
    }

    private ServerBootstrap init(ChannelInitializer<SocketChannel> initializer) {
        return new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 5000) // todo: get from config
                //.attr(PACKET_START_ATTRIBUTE_KEY, true) // didnt work for some reason
                .childHandler(initializer);
    }

    // each world has X numberOfChannels
    private void initWorlds() throws InterruptedException {
        List<WorldConfig> activeWorlds = config.getWorlds().stream()
                .filter(w -> w.getActive() == 1)
                .toList();

        for (int i = 0; i < activeWorlds.size(); i++) {
            logger.info("Starting world: " + i);
            int startPort = config.getServer().getChannelPort() + i * 100; // 7575, 7675, etc
            for (int j = startPort; j < startPort + activeWorlds.get(i).getNumberOfChannels(); j++) {
                logger.info("Starting channel on port: " + j);
                ServerBootstrap bootstrap = init(channelInitializer);
                worldChannels.add(bootstrap.bind(j).sync().channel());
                logger.info("Channel started successfully");
            }
        }
    }

}
</code>```

Initializer that will create the channel pipeline (The initChannel is called for each inbound client that connects)

```<code>
@Component
@Qualifier("MyChannelInitializer")
@RequiredArgsConstructor
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final MyPacketDecoder myPacketDecoder;
    //private final MyChannelHandler myChannelHandler;
    private final MyPacketEncoder myPacketEncoder;
    private final DefaultEventExecutorGroup eventExecutorGroup;

    private final BeanFactory beanFactory;
    private final ObjectProvider<MyChannelHandler> provider;

    /**
     * This creates the pipeline for every new channel created (every new client connection)
     * Inbound is handled top down (myPacketDecoder->myChannelHandler)
     * Outboud is handled bottom up (myPacketEncoder)
     *
     *
     * @param socketChannel
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        int port = socketChannel.localAddress().getPort();
        MyChannelHandler myChannelHandler = provider.getObject(port);
        MyChannelHandler myChannelHandler2 = provider.getObject(port); // this object should be the same as myChannelHandler
        socketChannel.pipeline()
                .addLast(eventExecutorGroup, "decoder", myPacketDecoder) // inbound
                .addLast("encoder", myPacketEncoder) // outbound
                .addLast(eventExecutorGroup, "inbound", myChannelHandler); // inbound
    }

}

</code>```

Example scenario..
config:

```<code>config:
  server: # properties that apply to the whole server
    socketServerPort: 8484 # login port
    channelPort: 7575 # channels start
    worlds: # configs per world
      -
        active: 1
        numberOfChannels: 5
      -
        active: 1
        numberOfChannels: 3
      -
        active: 0
        numberOfChannels: 3
</code>```

My server will start up login server followed by 2 worlds with 5 and 3 channels respectively

login server: 8484
world 1 channel 1: 7575
world 1 channel 2: 7576
world 1 channel 3: 7577
world 1 channel 4: 7578
world 1 channel 5: 7579
world 2 channel 1: 7675
world 2 channel 2: 7676
world 2 channel 3: 7677

client 1 connects to 7575, initChannel() should use instance of MyChannelHandler. However, because of the prototype definition, each call to provider.getObject(port) is returning a new instance. How can I get it to return and reuse the same instance for the same port?

The above scenarios should have 8 MyChannelHandler beans.
Maybe I can use some factory pattern to inject the 8 beans into a map and then access the map on the initChannel?

答:
I solved this by removing these two annotations from my handler class

```<code>@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
</code>```

I autowired GenericApplicationContext context inside my SocketServer class so I could register bean definition manually during my initWorlds logic:

```<code>for (int j = startPort; j < startPort + activeWorlds.get(i).getNumberOfChannels(); j++) {
                logger.info("Starting channel on port: " + j);
                context.registerBean(String.valueOf(j), MapleChannelHandler.class, createChannelHandler(j));
                ServerBootstrap bootstrap = init(channelInitializer);
                worldChannels.add(bootstrap.bind(j).sync().channel());
                logger.info("Channel started successfully");
            }

</code>```
```<code>private Supplier<MapleChannelHandler> createChannlerHandler(int port) {
        return () -> new MapleChannelHandler(port);
    }
</code>```

Now my initChannel is simple:

```<code>
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        int port = socketChannel.localAddress().getPort();
        MapleChannelHandler mapleChannelHandler = beanFactory.getBean(String.valueOf(port), MapleChannelHandler.class);
        socketChannel.pipeline()
                .addLast(eventExecutorGroup, "decoder", maplePacketDecoder) // inbound
                .addLast("encoder", maplePacketEncoder) // outbound
                .addLast(eventExecutorGroup, "inbound", mapleChannelHandler); // inbound
   }
</code>```

Now whenever a client connects on port X, it will use the bean that was registered with name of port X

Title: Reuse X number of prototype beans

Body:
I'm building an application in spring boot that creates X number of Netty tcp socket servers based on my config.

I would like to have X number of MyChannelHandler beans (one for each tcp port). The idea is to have separate worlds/servers in my application and each world has X number of game channels (not related to netty channel). Each game channel is represented by a tcp socket server running on some port.

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Sharable
@RequiredArgsConstructor
public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    private final int port;

    @Autowired
    private ContextAwareLogger logger;
    @Autowired
    private AppConfig config;
    @Autowired
    private GameService gameService;
    @Autowired
    private ObjectProvider<GameClient> clientObjectProvider;

    private Map<String, GameClient> connectedClients = Collections.synchronizedMap(new HashMap<>());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // logic omitted
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
       // logic omitted
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // logic omitted
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // logic omitted
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
        // logic omitted
    }

    public Map<String, GameClient> getConnectedClients() {
        return connectedClients;
    }

    private GameClient initClient(ChannelHandlerContext ctx) {
        // logic omitted
    }

}

Servers created here:

@Component
@RequiredArgsConstructor
public class MySocketServer {

    public static final AttributeKey<Boolean> PACKET_START_KEY = AttributeKey.valueOf("PACKET_START");
    public static final AttributeKey<MyGameClient> CLIENT_ATTRIBUTE_KEY = AttributeKey.valueOf("CLIENT");
    public static final AttributeKey<String> CLIENT_ID_KEY = AttributeKey.valueOf("CLIENT_ID_KEY");
    public static final AttributeKey<Boolean> HANDSHAKE_KEY = AttributeKey.valueOf("HANDSHAKE");

    private final ContextAwareLogger logger;
    private final AppConfig config;
    private final ObjectProvider<MyGameClient> clientObjectProvider;

    @Qualifier("MyServerInitializer")
    @Autowired
    private ChannelInitializer<SocketChannel> serverInitializer;
    @Qualifier("MyChannelInitializer")
    @Autowired
    private ChannelInitializer<SocketChannel> channelInitializer;

    @Qualifier("serverBossGroup")
    @Autowired
    private NioEventLoopGroup bossGroup;

    @Qualifier("serverWorkerGroup")
    @Autowired
    private NioEventLoopGroup workerGroup;

    private Channel loginChannel;
    private List<Channel> worldChannels = new ArrayList<>();

    @PostConstruct
    public void start() {
        try {
            ServerBootstrap bootstrap = init(serverInitializer);
            loginChannel = bootstrap.bind(config.getServer().getSocketServerPort()).sync().channel(); // save the main channel so we can cleanly close it when app is shutdown
            logger.info("Netty server started...");

            initWorlds();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void stop() throws InterruptedException {
        logger.info("Shutting down Netty server");
        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
        loginChannel.closeFuture().sync();
        logger.info("Netty Server shutdown complete.");
    }

    private ServerBootstrap init(ChannelInitializer<SocketChannel> initializer) {
        return new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 5000) // todo: get from config
                //.attr(PACKET_START_ATTRIBUTE_KEY, true) // didnt work for some reason
                .childHandler(initializer);
    }

    // each world has X numberOfChannels
    private void initWorlds() throws InterruptedException {
        List<WorldConfig> activeWorlds = config.getWorlds().stream()
                .filter(w -> w.getActive() == 1)
                .toList();

        for (int i = 0; i < activeWorlds.size(); i++) {
            logger.info("Starting world: " + i);
            int startPort = config.getServer().getChannelPort() + i * 100; // 7575, 7675, etc
            for (int j = startPort; j < startPort + activeWorlds.get(i).getNumberOfChannels(); j++) {
                logger.info("Starting channel on port: " + j);
                ServerBootstrap bootstrap = init(channelInitializer);
                worldChannels.add(bootstrap.bind(j).sync().channel());
                logger.info("Channel started successfully");
            }
        }
    }

}

Initializer that will create the channel pipeline (The initChannel is called for each inbound client that connects)

@Component
@Qualifier("MyChannelInitializer")
@RequiredArgsConstructor
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final MyPacketDecoder myPacketDecoder;
    //private final MyChannelHandler myChannelHandler;
    private final MyPacketEncoder myPacketEncoder;
    private final DefaultEventExecutorGroup eventExecutorGroup;

    private final BeanFactory beanFactory;
    private final ObjectProvider<MyChannelHandler> provider;

    /**
     * This creates the pipeline for every new channel created (every new client connection)
     * Inbound is handled top down (myPacketDecoder->myChannelHandler)
     * Outboud is handled bottom up (myPacketEncoder)
     *
     *
     * @param socketChannel
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        int port = socketChannel.localAddress().getPort();
        MyChannelHandler myChannelHandler = provider.getObject(port);
        MyChannelHandler myChannelHandler2 = provider.getObject(port); // this object should be the same as myChannelHandler
        socketChannel.pipeline()
                .addLast(eventExecutorGroup, "decoder", myPacketDecoder) // inbound
                .addLast("encoder", myPacketEncoder) // outbound
                .addLast(eventExecutorGroup, "inbound", myChannelHandler); // inbound
    }

}

Example scenario..
config:

config:
  server: # properties that apply to the whole server
    socketServerPort: 8484 # login port
    channelPort: 7575 # channels start
    worlds: # configs per world
      -
        active: 1
        numberOfChannels: 5
      -
        active: 1
        numberOfChannels: 3
      -
        active: 0
        numberOfChannels: 3

My server will start up login server followed by 2 worlds with 5 and 3 channels respectively

login server: 8484
world 1 channel 1: 7575
world 1 channel 2: 7576
world 1 channel 3: 7577
world 1 channel 4: 7578
world 1 channel 5: 7579
world 2 channel 1: 7675
world 2 channel 2: 7676
world 2 channel 3: 7677

client 1 connects to 7575, initChannel() should use instance of MyChannelHandler. However, because of the prototype definition, each call to provider.getObject(port) is returning a new instance. How can I get it to return and reuse the same instance for the same port?

The above scenarios should have 8 MyChannelHandler beans.
Maybe I can use some factory pattern to inject the 8 beans into a map and then access the map on the initChannel?

Body:
I solved this by removing these two annotations from my handler class

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

I autowired GenericApplicationContext context inside my SocketServer class so I could register bean definition manually during my initWorlds logic:

for (int j = startPort; j < startPort + activeWorlds.get(i).getNumberOfChannels(); j++) {
                logger.info("Starting channel on port: " + j);
                context.registerBean(String.valueOf(j), MapleChannelHandler.class, createChannelHandler(j));
                ServerBootstrap bootstrap = init(channelInitializer);
                worldChannels.add(bootstrap.bind(j).sync().channel());
                logger.info("Channel started successfully");
            }

private Supplier<MapleChannelHandler> createChannlerHandler(int port) {
        return () -> new MapleChannelHandler(port);
    }

Now my initChannel is simple:

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        int port = socketChannel.localAddress().getPort();
        MapleChannelHandler mapleChannelHandler = beanFactory.getBean(String.valueOf(port), MapleChannelHandler.class);
        socketChannel.pipeline()
                .addLast(eventExecutorGroup, "decoder", maplePacketDecoder) // inbound
                .addLast("encoder", maplePacketEncoder) // outbound
                .addLast(eventExecutorGroup, "inbound", mapleChannelHandler); // inbound
   }

Now whenever a client connects on port X, it will use the bean that was registered with name of port X


问:
Move text next to logo; get rid of a hard rule
Here's the site:  www.red-tuxedo.com

I want the "Red Tuxedo" text to sit next to the logo, not below, and I want to get rid of that hard rule that runs through the logo.  My CSS / HTML skills aren't up to it.  I completely destroy the column layout when I change the text and I can't find the hard rule in the code.  Tried adjusting the gif (cut off the bottom in Photoshop) and that didn't help.

I did write to the person who created the template; haven't heard back after several days.  Would like to get this fixed before I start adding more pages.

thx

答:
One way is to move the logo within the #logo div:</p>

```<code><div id="header-logo">
    <div id="logo"><img height="60" width="60" alt="Red Tuxedo Logo" src="logo_red_tuxedo.gif" id="logo_red_tuxedo"/><span class="red">Red</span>Tuxedo</div>
    <form action="#" class="search" method="post">
        <p><input type="text" class="textbox" name="search_query"/>
        <input type="submit" value="Search" class="searchbutton" name="search"/></p>
    </form>
</div>
</code>```

OwnerDisplayName: Karen

ContentLicense: CC BY-SA 2.5

Body:
One way is to move the logo within the #logo div:

<div id="header-logo">
    <div id="logo"><img height="60" width="60" alt="Red Tuxedo Logo" src="logo_red_tuxedo.gif" id="logo_red_tuxedo"/><span class="red">Red</span>Tuxedo</div>
    <form action="#" class="search" method="post">
        <p><input type="text" class="textbox" name="search_query"/>
        <input type="submit" value="Search" class="searchbutton" name="search"/></p>
    </form>
</div>

OwnerDisplayName: dmondark


问:
How to use flash.sampler.getSamples to test garbage collection
I'm trying to unit test memory management. So far I have a semi-workable solution using flash.sampler.getSamples to get the difference between the number of NewObjectSamples and DeleteObjectSamples which have the same id value.

The test looks something like this:

```<code>startSampling();
new Foo();
new Foo();
new Foo();
forceGC();
pauseSampling();
countAllocations(Foo); // returns 1, should return 0
</code>```

The countAllocations() method gets the difference between the number of NewObjectSamples and DeleteObjectSamples for a specific class:

```<code>    public static function countAllocations(type:Class):int
    {
        var count:int = 0;
        var allocations:Dictionary = new Dictionary();
        for each (var sample:Sample in getSamples()) {
            if (sample is NewObjectSample) {
                var newObjectSample:NewObjectSample = sample as NewObjectSample;
                if ((newObjectSample.type == type) && (newObjectSample.object != null)) {
                    allocations[newObjectSample.id] = true;
                    count ++;
                }
            }
            else if (sample is DeleteObjectSample) {
                var deleteObjectSample:DeleteObjectSample = sample as DeleteObjectSample;
                if (allocations[deleteObjectSample.id])
                    count --;
            }
        }
        return count;
    }
</code>```

The forceGC() method uses the LocalConnection hack to force garbage collection:

```<code>public static function forceGC():void {
        try {
            new LocalConnection().connect("bdebdd96-7bf8-407b-bec9-8336b2b0c329");
            new LocalConnection().connect("bdebdd96-7bf8-407b-bec9-8336b2b0c329");
        }
        catch (error:Error) {
        }
}
</code>```

Stepping through the code shows that:

```<code>NewObjectSample Foo id=1 (count = 1)
NewObjectSample Foo id=2 (count = 2)
NewObjectSample Foo id=3 (count = 3)
// NewObjectSamples related to the LocalConnection hack
DeleteObjectSample id=2 (count = 2)
DeleteObjectSample id=1 (count = 1)
// Where's wally #3??
</code>```

Since there are no references to Foo I'm assuming that all instances are being garbage collected, and my code is simply wrong due to my lack of understanding how sampling works. I am trying this instead of using weakly keyed dictionary because it seems it should be less of a hack, but now I'm starting to wonder if it's worth the trouble.

答: Try running the gc over consecutive frames. I have the same problem. I spent about 2 days trying to track down a memory leak that I thought I had (I use the weak key Dictionary method to check it). Turns out it just didn't get collected the first time</p>

Body:
I'm trying to unit test memory management. So far I have a semi-workable solution using flash.sampler.getSamples to get the difference between the number of NewObjectSamples and DeleteObjectSamples which have the same id value.

The test looks something like this:

startSampling();
new Foo();
new Foo();
new Foo();
forceGC();
pauseSampling();
countAllocations(Foo); // returns 1, should return 0

The countAllocations() method gets the difference between the number of NewObjectSamples and DeleteObjectSamples for a specific class:

    public static function countAllocations(type:Class):int
    {
        var count:int = 0;
        var allocations:Dictionary = new Dictionary();
        for each (var sample:Sample in getSamples()) {
            if (sample is NewObjectSample) {
                var newObjectSample:NewObjectSample = sample as NewObjectSample;
                if ((newObjectSample.type == type) && (newObjectSample.object != null)) {
                    allocations[newObjectSample.id] = true;
                    count ++;
                }
            }
            else if (sample is DeleteObjectSample) {
                var deleteObjectSample:DeleteObjectSample = sample as DeleteObjectSample;
                if (allocations[deleteObjectSample.id])
                    count --;
            }
        }
        return count;
    }

The forceGC() method uses the LocalConnection hack to force garbage collection:

public static function forceGC():void {
        try {
            new LocalConnection().connect("bdebdd96-7bf8-407b-bec9-8336b2b0c329");
            new LocalConnection().connect("bdebdd96-7bf8-407b-bec9-8336b2b0c329");
        }
        catch (error:Error) {
        }
}

Stepping through the code shows that:

NewObjectSample Foo id=1 (count = 1)
NewObjectSample Foo id=2 (count = 2)
NewObjectSample Foo id=3 (count = 3)
// NewObjectSamples related to the LocalConnection hack
DeleteObjectSample id=2 (count = 2)
DeleteObjectSample id=1 (count = 1)
// Where's wally #3??

Since there are no references to Foo I'm assuming that all instances are being garbage collected, and my code is simply wrong due to my lack of understanding how sampling works. I am trying this instead of using weakly keyed dictionary because it seems it should be less of a hack, but now I'm starting to wonder if it's worth the trouble.


问:
Why isn't Python recognizing my declared variable as a global variable?
I am new to Python. I declared a variable named 'total' outside the function and then I called it inside my function called 'my_function'. But it is giving me an error because my variable 'total' is not global. Why is that? I thought variables declared outside were already considered global.

```<code>total = 1

def my_function(list):
    for i in list:
        total = total + 1
        print (total)

my_function([1,2,3])
</code>```

答:
You need to use the global keyword in your function

total = 1

def my_function(list):
    global total
    for i in list:
        total = total + 1
        print(total)

my_function([1, 2, 3])
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>2
3
4
</code>```

Body:
I am new to Python. I declared a variable named 'total' outside the function and then I called it inside my function called 'my_function'. But it is giving me an error because my variable 'total' is not global. Why is that? I thought variables declared outside were already considered global.

total = 1

def my_function(list):
    for i in list:
        total = total + 1
        print (total)

my_function([1,2,3])

Body:
You need to use the global keyword in your function

total = 1

def my_function(list):
    global total
    for i in list:
        total = total + 1
        print(total)

my_function([1, 2, 3])

Output:

2
3
4


问:
Python help to extract rows by column value
What I am looking to do is extract rows based on value in the "Code" column.  I am needing to create 5 different CSV files from each beginning file.  I will need 5 separate files when this is complete and the files will be: CC, Mortgage, HELOC, Auto, Other.

Here is a table showing which code numbers should go to each file.

Code
Loan Type

180, 302
Auto

Mortgage
Mortgage

303, 112
HELOC

126, 110
CC

201, 150, 262
Other

Here is a small sample of the Data File that I am needing to manipulate. This screenshot is substantially smaller than the full file.  The full file has 200k rows and 100ish columns.

I will also need to replicate this process for about 50 others files, as this is a monthly file and I have 4 years worth of data.

Not sure if it matters, but I do have pandas enabled on my computer inside VS code.

Example of Data File

答:
Try the following code to separate table into the structure you want:

df_Auto = df.loc[df['Code'].isin([180,302])]
df_Mortgage = df.loc[df['Code'].isin(["Mortgage"])]
df_HELOC = df.loc[df['Code'].isin([303,112])]
df_CC = df.loc[df['Code'].isin([126,110])]
df_Other = df.loc[df['Code'].isin([201,150,262])]
```
<p>then you can save the files using <code>df.to_csv("FileName.csv")</code> function.</p>
<p>You use the following script to iterate over files you have and save the new csvs.</p>
<pre class="lang-py prettyprint-override"><code>file_names = ["file1", "file2"]

for i in file_names:
    # read the file
    df= pd.read_csv(i+".csv")
    # if you need preprocessing
    # ...
    # create new files
    df_Auto = df.loc[df['Code'].isin([180,302])]
    df_Mortgage = df.loc[df['Code'].isin(["Mortgage"])]
    df_HELOC = df.loc[df['Code'].isin([303,112])]
    df_CC = df.loc[df['Code'].isin([126,110])]
    df_Other = df.loc[df['Code'].isin([201,150,262])]

    # save files
    df_Auto.to_csv(i+"_Auto.csv")
    df_Mortgage.to_csv(i+"_Mortgage.csv")
    df_HELOC.to_csv(i+"_HELOC.csv")
    df_CC.to_csv(i+"_CC.csv")
    df_Other.to_csv(i+"_Other.csv")
</code>```

Body:
Try the following code to separate table into the structure you want:

df_Auto = df.loc[df['Code'].isin([180,302])]
df_Mortgage = df.loc[df['Code'].isin(["Mortgage"])]
df_HELOC = df.loc[df['Code'].isin([303,112])]
df_CC = df.loc[df['Code'].isin([126,110])]
df_Other = df.loc[df['Code'].isin([201,150,262])]

then you can save the files using df.to_csv("FileName.csv") function.

You use the following script to iterate over files you have and save the new csvs.

file_names = ["file1", "file2"]

for i in file_names:
    # read the file
    df= pd.read_csv(i+".csv")
    # if you need preprocessing
    # ...
    # create new files
    df_Auto = df.loc[df['Code'].isin([180,302])]
    df_Mortgage = df.loc[df['Code'].isin(["Mortgage"])]
    df_HELOC = df.loc[df['Code'].isin([303,112])]
    df_CC = df.loc[df['Code'].isin([126,110])]
    df_Other = df.loc[df['Code'].isin([201,150,262])]

    # save files
    df_Auto.to_csv(i+"_Auto.csv")
    df_Mortgage.to_csv(i+"_Mortgage.csv")
    df_HELOC.to_csv(i+"_HELOC.csv")
    df_CC.to_csv(i+"_CC.csv")
    df_Other.to_csv(i+"_Other.csv")


问:
Bootstrap 4 - how to add a toggle inline to a form input label
I have the following Bootstrap 4 form

```<code><div class="form-layout">
            <div class="row mg-b-25">
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-control-label">Status: <span class="tx-danger">*</span></label>
                        <input class="form-control" type="text" name="status" value="" placeholder="Enter status">
                    </div>
                </div><!-- col-4 -->
      </div>
</div>
</code>```

What I want to achieve is the following.

I'm using this for toggles: https://simontabor.com/labs/toggles/

答:
You can wrap the Estatus and the toggle inside a div and then use the Bootstrap 4 flexbox classes d-flex and justify-content-between to achieve it.

Fiddle: https://jsfiddle.net/kongallis/r5pc2nq3/9

Toggle code source: https://www.w3schools.com/howto/howto_css_switch.asp

Body:
I have the following Bootstrap 4 form

                        Status: *
                        <input class="form-control" type="text" name="status" value="" placeholder="Enter status">

What I want to achieve is the following.

I'm using this for toggles: https://simontabor.com/labs/toggles/


问:
Add a 1-hour expiration to the current time/date
```<code>//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration
</code>```

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

```<code>$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");
</code>```

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

答:
```<code>$expire = date("F j, Y, H:i", time()+3600); // 3600 sec in hour
</code>```

Body:
//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking


问:
How best to make my scroll controllers available throughout the app?
Context: I'll be having a couple of scrollable lists in my app and I always want to scroll them to the latest item whenever an item is added.

Problem: My ListView.builders and the places where items are added are going to be quite far apart in my widget tree. Passing around all those scroll controllers via constructors seems to be super awkward.

My Solution:As I'm practising with Provider at the moment, I came up with a working solution using Provider:

```<code>class ScrollControllerProvider with ChangeNotifier {
  ScrollController _paneController = ScrollController();
  //setting up all other controllers here later

  get paneController {
    return _paneController;
  }

  void scrollHistory() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if (_paneController.hasClients) {
        _paneController.jumpTo(_paneController.position.maxScrollExtent);
      }
    });
  }
}
</code>```

I'll add all scroll controllers to that provider and grab what I need, where I need it. It already works with one, but someone on reddit told me it's not a good idea, as scroll controllers should be disposed. Im not super knowledgeable on the topic of life cycle yet and find it difficult to assess this.

Questions: Is it really a bad idea to use Provider here? Can you help me to understand why? If yes, what is the best approach to solve this issue?

答:
For posterity, Payam Asefi pointed me in the right direction.

How I'm doing it now.

tldr; Provider contains a value that can be toggled and a method to toggle it. I provide the value where I can also access the scroll controler. If it is toggled, the scroll conroler is used. I provide the method to toggle the value where I add new items to the list.

item is added > value in provider is triggered > listeners realized the value has changed calling the build method > scroll controller is used to go to maxscrollextend.

Long answer with code:

Provider with a) a bool that can be toggled b) a method to toggle the bool c) a getter for the bool

Code:

```<code>class ScrollControllerToggles with ChangeNotifier {
  bool _historyPaneSwitch = true;

  get getTogglePaneSwitch {
    return _historyPaneSwitch;
  }

  void toggleHistoryPane() {
    _historyPaneSwitch = !_historyPaneSwitch;
    notifyListeners();
  }
}
</code>```

In the widget I'm using the Listview.builder: a) I define a scroll controller, b) I use a function dependent on the _historyPaneSwitch inside that Provider. That funtion also uses the scroll controller to scroll the list to the end.

```<code>    void triggerScrollController() {
  bool scrollHistoryPane =
      Provider.of<ScrollControllerToggles>(context).getTogglePaneSwitch;
  WidgetsBinding.instance?.addPostFrameCallback((_) {
    if (paneController.hasClients) {
      paneController.jumpTo(paneController.position.maxScrollExtent);
    }
  });
}
</code>```

In the widget adding new items to the list, I access the Provider again and grab the method to toggle "_historyPaneSwitch".

```<code>    Function scrollHistoryPane =
    Provider.of<ScrollControllerToggles>(context).toggleHistoryPane;

    void dayChange(Function scrollHistoryPane) {
    mainElementList.insert(0, MainElement(false, DateTime.now().toString()));
    scrollHistoryPane;
  }
</code>```

Body:
Context: I'll be having a couple of scrollable lists in my app and I always want to scroll them to the latest item whenever an item is added.

Problem: My ListView.builders and the places where items are added are going to be quite far apart in my widget tree. Passing around all those scroll controllers via constructors seems to be super awkward.

My Solution:As I'm practising with Provider at the moment, I came up with a working solution using Provider:

class ScrollControllerProvider with ChangeNotifier {
  ScrollController _paneController = ScrollController();
  //setting up all other controllers here later

  get paneController {
    return _paneController;
  }

  void scrollHistory() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if (_paneController.hasClients) {
        _paneController.jumpTo(_paneController.position.maxScrollExtent);
      }
    });
  }
}

I'll add all scroll controllers to that provider and grab what I need, where I need it. It already works with one, but someone on reddit told me it's not a good idea, as scroll controllers should be disposed. Im not super knowledgeable on the topic of life cycle yet and find it difficult to assess this.

Questions: Is it really a bad idea to use Provider here? Can you help me to understand why? If yes, what is the best approach to solve this issue?

Body:
For posterity, Payam Asefi pointed me in the right direction.

How I'm doing it now.

tldr; Provider contains a value that can be toggled and a method to toggle it. I provide the value where I can also access the scroll controler. If it is toggled, the scroll conroler is used. I provide the method to toggle the value where I add new items to the list.

item is added > value in provider is triggered > listeners realized the value has changed calling the build method > scroll controller is used to go to maxscrollextend.

Long answer with code:

Provider with a) a bool that can be toggled b) a method to toggle the bool c) a getter for the bool

Code:

class ScrollControllerToggles with ChangeNotifier {
  bool _historyPaneSwitch = true;

  get getTogglePaneSwitch {
    return _historyPaneSwitch;
  }

  void toggleHistoryPane() {
    _historyPaneSwitch = !_historyPaneSwitch;
    notifyListeners();
  }
}

In the widget I'm using the Listview.builder: a) I define a scroll controller, b) I use a function dependent on the _historyPaneSwitch inside that Provider. That funtion also uses the scroll controller to scroll the list to the end.

    void triggerScrollController() {
  bool scrollHistoryPane =
      Provider.of<ScrollControllerToggles>(context).getTogglePaneSwitch;
  WidgetsBinding.instance?.addPostFrameCallback((_) {
    if (paneController.hasClients) {
      paneController.jumpTo(paneController.position.maxScrollExtent);
    }
  });
}

In the widget adding new items to the list, I access the Provider again and grab the method to toggle "_historyPaneSwitch".

    Function scrollHistoryPane =
    Provider.of<ScrollControllerToggles>(context).toggleHistoryPane;

    void dayChange(Function scrollHistoryPane) {
    mainElementList.insert(0, MainElement(false, DateTime.now().toString()));
    scrollHistoryPane;
  }


问:
How do I compare the date from the user with the date in the database? in symfony
I use symfony 4.when i compare date i can only compare years as below not days or months. if it is in different months and days in the same year, it shows equal to each other. i want to compare with days, month and years.
"p.createdAt" type is datetime</p>
```<code>    if (!empty($filter['startDate'])) {
        $qb->andWhere($qb->expr()->gte('p.createdAt',':startDate'))
        ->setParameter('startDate',$filter['startDate']);
    }
</code>```

答:
I use code like this:

```<code>$qb->andWhere('p.createdAt >= :queryDate')
    ->setParameter('queryDate', $queryDate);
</code>```

without problem.

Body:
I use symfony 4.when i compare date i can only compare years as below not days or months. if it is in different months and days in the same year, it shows equal to each other. i want to compare with days, month and years.
"p.createdAt" type is datetime

    if (!empty($filter['startDate'])) {
        $qb->andWhere($qb->expr()->gte('p.createdAt',':startDate'))
        ->setParameter('startDate',$filter['startDate']);
    }

Body:
I use code like this:

$qb->andWhere('p.createdAt >= :queryDate')
    ->setParameter('queryDate', $queryDate);

without problem.


问:
tf.round() to a specified precision
tf.round(x) rounds the values of x to integer values.

Is there any way to round to, say, 3 decimal places instead?

答:
The Solution of gdelab is very Good moving the required decimal point numbers to left for "." then get them later like "0.78969 * 100" will move 78.969 "2 numbers" then Tensorflow round will make it 78 then you divide it by 100 again making it 0.78 it smart one There is another workaround I would like to share for the Community.

You Can just use the NumPy round method by taking the NumPy matrix or vector then applying the method then convert the result to tensor again

```<code>#Creating Tensor
x=tf.random.normal((3,3),mean=0,stddev=1)
x=tf.cast(x,tf.float64)
x

#Grabing the Numpy array from tensor
x.numpy()

#use the numpy round method then convert the result to tensor again
value=np.round(x.numpy(),3)
Result=tf.convert_to_tensor(temp,dtype=tf.float64)
Result
</code>```

Title: tf.round() to a specified precision

Body:
The Solution of gdelab is very Good moving the required decimal point numbers to left for "." then get them later like "0.78969 * 100" will move 78.969 "2 numbers" then Tensorflow round will make it 78 then you divide it by 100 again making it 0.78 it smart one There is another workaround I would like to share for the Community.

You Can just use the NumPy round method by taking the NumPy matrix or vector then applying the method then convert the result to tensor again

#Creating Tensor
x=tf.random.normal((3,3),mean=0,stddev=1)
x=tf.cast(x,tf.float64)
x

#Grabing the Numpy array from tensor
x.numpy()

#use the numpy round method then convert the result to tensor again
value=np.round(x.numpy(),3)
Result=tf.convert_to_tensor(temp,dtype=tf.float64)
Result


问:
how to properly type zoom on d3 svg with typescript?
i have this code:

```<code>if (svg) {
    // zoom
    // svg type = d3.Selection<SVGSVGElement, unknown, null, undefined>
    const zoomBehavior = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .translateExtent([
        [0, 0],
        [containerWidth, containerHeight],
      ])
      .on("zoom", (event) => {
        const zoomState = event.transform;
        console.log("zoomState", zoomState);
      });
    svg.call(zoomBehavior);
  }
</code>```

I am getting this error type:

```<code>Argument of type 'ZoomBehavior<Element, unknown>' is not assignable to parameter of type '(selection: Selection<SVGSVGElement, unknown, null, undefined>, ...args: any[]) => void'.
</code>```

i don't want to use ts-ignore

答:
If nothing else works, you can cast zoomBehavior as any

```<code>if (svg) {
    const zoomBehavior = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .translateExtent([
        [0, 0],
        [containerWidth, containerHeight],
      ])
      .on("zoom", (event) => {
        const zoomState = event.transform;
        console.log("zoomState", zoomState);
      }) as any; //as any

    svg.call(zoomBehavior);

  }
</code>```

Body:
i have this code:

if (svg) {
    // zoom
    // svg type = d3.Selection<SVGSVGElement, unknown, null, undefined>
    const zoomBehavior = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .translateExtent([
        [0, 0],
        [containerWidth, containerHeight],
      ])
      .on("zoom", (event) => {
        const zoomState = event.transform;
        console.log("zoomState", zoomState);
      });
    svg.call(zoomBehavior);
  }

I am getting this error type:

Argument of type 'ZoomBehavior<Element, unknown>' is not assignable to parameter of type '(selection: Selection<SVGSVGElement, unknown, null, undefined>, ...args: any[]) => void'.

i don't want to use ts-ignore

Body:
If nothing else works, you can cast zoomBehavior as any

if (svg) {
    const zoomBehavior = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .translateExtent([
        [0, 0],
        [containerWidth, containerHeight],
      ])
      .on("zoom", (event) => {
        const zoomState = event.transform;
        console.log("zoomState", zoomState);
      }) as any; //as any

    svg.call(zoomBehavior);

  }


问:
Numpy uint8_t arrays to vtkImageData
I am attempting to take 2D images of either one or three channels and display them in VTK using vtkImageActor. As I understand it, the current frame to be displayed can be updated by invoking SetImageData on vtkImageActor and providing an instance of vtkImageData.

I have set up my visualiser as shown below. However, I am unsure how to build the vtkImageData object from the numpy arrays(this would go in the updateFrames method). The type of my numpy arrays is np.uint8_t.

I am using VTK8.0, Python 3.6 and Numpy 1.13.1

```<code>class VTKStreamVisualiser:
    def __init__(self, displayRGB):
        self.__displayRGB = displayRGB
        self.__started = False

        #Setup window.
        self.__renderWindow = vtk.vtkRenderWindow()
        self.__renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self.__renderWindowInteractor.SetRenderWindow(self.__renderWindow)

        #To store renderers and actors.
        self.__renderers = []
        self.__actors = []

        #Initialise to None to check if ready when invoking start()
        self.__depthImageData = None
        self.__rgbImageData = None

        #Determine viewport ranges for depth and setup renderer.
        xMinDepth = 0.0
        xMaxDepth = 0.5 if displayRGB else 1.0
        yMin = 0.0
        yMax = 1.0
        self.__setupRenderer(xMinDepth, yMin, xMaxDepth, yMax)

        #Determine viewport ranges for rgb and setup renderer.
        if self.__displayRGB:
            xMinRGB = xMaxDepth
            xMaxRGB = 2.0 * xMinRGB
            self.__setupRenderer(xMinRGB, yMin, xMaxRGB, yMax)

    def __setupRenderer(self, xMin, yMin, xMax, yMax):
        #Setup renderer.
        self.__renderers.append(vtk.vtkRenderer())
        idx = len(self.__renderers) - 1
        self.__renderWindow.AddRenderer(self.__renderers[idx])
        self.__renderers[idx].SetViewport(xMin, yMin, xMax, yMax)
        self.__actors.append(vtk.vtkImageActor())
        self.__renderers[idx].AddActor(self.__actors[idx])
        self.__renderers[idx].ResetCamera()

    def start(self):
        self.__depthImageData is None or (self.__rgbImageData is None and self.__displayRGB):
            return None

        if self.__started:
            return

        self.__renderWindowInteractor.Initialize()
        self.__renderWindow.Render()
        self.__renderWindowInteractor.Start()
        self.__started = True

    def stop(self):
        if not self.__started:
            return

        self.__renderWindowInteractor.Stop()
        self.__renderWindow.Finalize()
        self.__renderWindowInteractor.TerminateApp()
        self.__started = False

    def updateFrames(self, depthFrame, rgbFrame=None):
        #Build vtkImageData here from the given numpy uint8_t arrays.
        pass
</code>```

EDIT: I realise that I can manually copy the data over as demonstrated here, which wouldn't be too bad with Cython(assuming I am able to work with vtkImageData in Cython), however it would be preferable to use the numpy arrays directly.

答:
In case you came looking for code compatible with VTK version 9 and up. Here is this answer modified:

import vtk
import numpy as np
from vtkmodules.vtkCommonDataModel import vtkImageData
from vtkmodules.util import numpy_support

def numpy_array_as_vtk_image_data(source_numpy_array):
    """
    :param source_numpy_array: source array with 2-3 dimensions. If used, the third dimension represents the channel count.
    Note: Channels are flipped, i.e. source is assumed to be BGR instead of RGB (which works if you're using cv2.imread function to read three-channel images)
    Note: Assumes array value at [0,0] represents the upper-left pixel.
    :type source_numpy_array: np.ndarray
    :return: vtk-compatible image, if conversion is successful. Raises exception otherwise
    :rtype vtk.vtkImageData
    """

    if len(source_numpy_array.shape) > 2:
        channel_count = source_numpy_array.shape[2]
    else:
        channel_count = 1

    output_vtk_image = vtkImageData()
    output_vtk_image.SetDimensions(source_numpy_array.shape[1], source_numpy_array.shape[0], channel_count)

    vtk_type_by_numpy_type = {
        np.uint8: vtk.VTK_UNSIGNED_CHAR,
        np.uint16: vtk.VTK_UNSIGNED_SHORT,
        np.uint32: vtk.VTK_UNSIGNED_INT,
        np.uint64: vtk.VTK_UNSIGNED_LONG if vtk.VTK_SIZEOF_LONG == 64 else vtk.VTK_UNSIGNED_LONG_LONG,
        np.int8: vtk.VTK_CHAR,
        np.int16: vtk.VTK_SHORT,
        np.int32: vtk.VTK_INT,
        np.int64: vtk.VTK_LONG if vtk.VTK_SIZEOF_LONG == 64 else vtk.VTK_LONG_LONG,
        np.float32: vtk.VTK_FLOAT,
        np.float64: vtk.VTK_DOUBLE
    }
    vtk_datatype = vtk_type_by_numpy_type[source_numpy_array.dtype.type]

    source_numpy_array = np.flipud(source_numpy_array)

    # Note: don't flip (take out next two lines) if input is RGB.
    # Likewise, BGRA->RGBA would require a different reordering here.
    if channel_count > 1:
        source_numpy_array = np.flip(source_numpy_array, 2)

    depth_array = numpy_support.numpy_to_vtk(source_numpy_array.ravel(), deep=True, array_type=vtk_datatype)
    depth_array.SetNumberOfComponents(channel_count)
    output_vtk_image.SetSpacing([1, 1, 1])
    output_vtk_image.SetOrigin([-1, -1, -1])
    output_vtk_image.GetPointData().SetScalars(depth_array)

    output_vtk_image.Modified()
    return output_vtk_image
```

Title: Numpy uint8_t arrays to vtkImageData

Body:
I am attempting to take 2D images of either one or three channels and display them in VTK using vtkImageActor. As I understand it, the current frame to be displayed can be updated by invoking SetImageData on vtkImageActor and providing an instance of vtkImageData.

I have set up my visualiser as shown below. However, I am unsure how to build the vtkImageData object from the numpy arrays(this would go in the updateFrames method). The type of my numpy arrays is np.uint8_t.

I am using VTK8.0, Python 3.6 and Numpy 1.13.1

class VTKStreamVisualiser:
    def __init__(self, displayRGB):
        self.__displayRGB = displayRGB
        self.__started = False

        #Setup window.
        self.__renderWindow = vtk.vtkRenderWindow()
        self.__renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self.__renderWindowInteractor.SetRenderWindow(self.__renderWindow)

        #To store renderers and actors.
        self.__renderers = []
        self.__actors = []

        #Initialise to None to check if ready when invoking start()
        self.__depthImageData = None
        self.__rgbImageData = None

        #Determine viewport ranges for depth and setup renderer.
        xMinDepth = 0.0
        xMaxDepth = 0.5 if displayRGB else 1.0
        yMin = 0.0
        yMax = 1.0
        self.__setupRenderer(xMinDepth, yMin, xMaxDepth, yMax)

        #Determine viewport ranges for rgb and setup renderer.
        if self.__displayRGB:
            xMinRGB = xMaxDepth
            xMaxRGB = 2.0 * xMinRGB
            self.__setupRenderer(xMinRGB, yMin, xMaxRGB, yMax)

    def __setupRenderer(self, xMin, yMin, xMax, yMax):
        #Setup renderer.
        self.__renderers.append(vtk.vtkRenderer())
        idx = len(self.__renderers) - 1
        self.__renderWindow.AddRenderer(self.__renderers[idx])
        self.__renderers[idx].SetViewport(xMin, yMin, xMax, yMax)
        self.__actors.append(vtk.vtkImageActor())
        self.__renderers[idx].AddActor(self.__actors[idx])
        self.__renderers[idx].ResetCamera()

    def start(self):
        self.__depthImageData is None or (self.__rgbImageData is None and self.__displayRGB):
            return None

        if self.__started:
            return

        self.__renderWindowInteractor.Initialize()
        self.__renderWindow.Render()
        self.__renderWindowInteractor.Start()
        self.__started = True

    def stop(self):
        if not self.__started:
            return

        self.__renderWindowInteractor.Stop()
        self.__renderWindow.Finalize()
        self.__renderWindowInteractor.TerminateApp()
        self.__started = False

    def updateFrames(self, depthFrame, rgbFrame=None):
        #Build vtkImageData here from the given numpy uint8_t arrays.
        pass

EDIT: I realise that I can manually copy the data over as demonstrated here, which wouldn't be too bad with Cython(assuming I am able to work with vtkImageData in Cython), however it would be preferable to use the numpy arrays directly.


问:
Trying to format dates column from chr to Date but returning NA
I've imported and xlsx file and I have a column of dates as characters:

```<code>Jan 08
Feb 08
Mar 08
Apr 08
</code>```

etc...

I want to convert this column into dates. I've tried some suggestions I've seen on other threads but I can't get it to not return NA

Here's the latest attempt:

```<code>dates <- format(as.Date(MonthlyUKFigures$Date,format="%b-%y"),format="%b-%y")
</code>```

答:
You can simply use lubridate package:

```<code>my("Jan 08")
[1] "2008-01-01"
</code>```

Body:
I've imported and xlsx file and I have a column of dates as characters:

Jan 08
Feb 08
Mar 08
Apr 08

etc...

I want to convert this column into dates. I've tried some suggestions I've seen on other threads but I can't get it to not return NA

Here's the latest attempt:

dates <- format(as.Date(MonthlyUKFigures$Date,format="%b-%y"),format="%b-%y")

Body:
You can simply use lubridate package:

my("Jan 08")
[1] "2008-01-01"


问:
Docker Load key "/root/.ssh/id_rsa": invalid format
I am trying to clone a repo that has submodules in it. The main repo is cloning fine but when I do git submodule update --init --recursive in the dockerfile the submodules throws and error.

```<code>fatal: clone of 'git@github.com:jkeys089/lua-resty-hmac.git' into submodule path '/tmp/third-party/lua-resty-hmac' failed
Failed to clone 'third-party/lua-resty-hmac'. Retry scheduled
Cloning into '/tmp/third-party/lua-resty-jwt'...
load pubkey "/root/.ssh/id_rsa": invalid format
Warning: Permanently added the RSA host key for IP address '140.82.118.3' to the list of known hosts.
Load key "/root/.ssh/id_rsa": invalid format
git@github.com: Permission denied (publickey).
</code>```

In the image I have this

```<code># authorise ssh host
RUN mkdir /root/.ssh/ \
    && chmod 700 /root/.ssh \
    && ssh-keyscan github.com > /root/.ssh/known_hosts

# add key and set permission
RUN echo "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa \
    && echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub \
    && chmod 600 /root/.ssh/id_rsa.pub \
    && chmod 600 /root/.ssh/id_rsa
</code>```

I have no control of the submodules. I am not sure if I can change from git@github.comto https to get submodules.

I even tried using the GITHUB_TOKEN route

```<code># start up git and clone
RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/" \
    && git clone https://github.com/GluuFederation/gluu-gateway.git /tmp \
    && cd /tmp/ \
    && git submodule update --init --recursive
</code>```

And below is the part of the build command.
build --build-arg GITHUB_TOKEN=${GITHUB_TOKEN} --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)"

Please help out on this. It's very frustrating. :(

答:
Make sure there is a \n after the last line.
Took me too long to figure this out.</p>

Body:
I am trying to clone a repo that has submodules in it. The main repo is cloning fine but when I do git submodule update --init --recursive in the dockerfile the submodules throws and error.

fatal: clone of 'git@github.com:jkeys089/lua-resty-hmac.git' into submodule path '/tmp/third-party/lua-resty-hmac' failed
Failed to clone 'third-party/lua-resty-hmac'. Retry scheduled
Cloning into '/tmp/third-party/lua-resty-jwt'...
load pubkey "/root/.ssh/id_rsa": invalid format
Warning: Permanently added the RSA host key for IP address '140.82.118.3' to the list of known hosts.
Load key "/root/.ssh/id_rsa": invalid format
git@github.com: Permission denied (publickey).

In the image I have this

# authorise ssh host
RUN mkdir /root/.ssh/ \
    && chmod 700 /root/.ssh \
    && ssh-keyscan github.com > /root/.ssh/known_hosts

# add key and set permission
RUN echo "${SSH_PRIVATE_KEY}" >> /root/.ssh/id_rsa \
    && echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub \
    && chmod 600 /root/.ssh/id_rsa.pub \
    && chmod 600 /root/.ssh/id_rsa

I have no control of the submodules. I am not sure if I can change from git@github.comto https to get submodules.

I even tried using the GITHUB_TOKEN route

# start up git and clone
RUN git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/" \
    && git clone https://github.com/GluuFederation/gluu-gateway.git /tmp \
    && cd /tmp/ \
    && git submodule update --init --recursive

And below is the part of the build command.
build --build-arg GITHUB_TOKEN=${GITHUB_TOKEN} --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)"

Please help out on this. It's very frustrating. :(


问:
Propagating details of an error upwards in Rust
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

```<code>use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }
</code>```

The error i am getting is:

```<code>invalid digit found in string
</code>```

I would need the error message to have the key details, including at the point of failure, for example:

```<code>- main: invalid digit found in string
- fail: "Some String" is not a valid digit
</code>```

What's the best way of doing this?

答:
anyhow provides the context() and with_context() methods for that:

use anyhow::{Context, Result};
use std::str::FromStr;

fn fail() -> Result<u64> {
    let s = "Some String";
    Ok(u64::from_str(s).with_context(|| format!("\"{s}\" is not a valid digit"))?)
}

fn main() {
    if let Err(e) = fail() {
        println!("{:?}", e);
    }
}
```
```"Some String" is not a valid digit

Caused by:
    invalid digit found in string
```
<p>If you want custom formatting, you can use the <code>Error::chain()</code> method:</p>
<pre class="lang-rust prettyprint-override"><code>if let Err(e) = fail() {
    for err in e.chain() {
        println!("{err}");
    }
}
</code>```
```<code>"Some String" is not a valid digit
invalid digit found in string
</code>```

And if you want additional details (e.g. where the error happened), you can use a custom error type and downcast it (for error source you can also capture a backtrace).

Body:
I would like to have the details of an error be propagated upwards. I used error-chain previously, but that has not been maintained or kept compatible with the rest of the ecosystem as far as i can tell.

For example, in this example:

use std::str::FromStr;
use anyhow::Result;

fn fail() -> Result<u64> {
  Ok(u64::from_str("Some String")?)
}

fn main() {

  if let Err(e) = fail(){
    println!("{:?}", e);
  }

The error i am getting is:

invalid digit found in string

I would need the error message to have the key details, including at the point of failure, for example:

- main: invalid digit found in string
- fail: "Some String" is not a valid digit

What's the best way of doing this?

Body:
anyhow provides the context() and with_context() methods for that:

use anyhow::{Context, Result};
use std::str::FromStr;

fn fail() -> Result<u64> {
    let s = "Some String";
    Ok(u64::from_str(s).with_context(|| format!("\"{s}\" is not a valid digit"))?)
}

fn main() {
    if let Err(e) = fail() {
        println!("{:?}", e);
    }
}

"Some String" is not a valid digit

Caused by:
    invalid digit found in string

If you want custom formatting, you can use the Error::chain() method:

if let Err(e) = fail() {
    for err in e.chain() {
        println!("{err}");
    }
}

"Some String" is not a valid digit
invalid digit found in string

And if you want additional details (e.g. where the error happened), you can use a custom error type and downcast it (for error source you can also capture a backtrace).


问:
How do I provide an informal string representation of a python Class (not instance)
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

```<code>>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.
</code>```

答:
To change the class' string representation:

```<code>class MC(type):
    def __repr__(cls):
        return 'I am Test'

class Test:
    __metaclass__ = MC
   pass

print Test
</code>```

works fine.

If repr(Test) is called when you define __str__ it won't use your custimized message.

However, if you define __repr__ like I did, and str(Test) is called, it will use your custimized message, because __repr__ is the fallback and __str__ isn't defined in type.

If all you want to do is change it's name:

```<code>def renamer(name):
    def wrapper(func):
        func.__name__ = name
        return func
    return wrapper

@renamer('Not Test')
class Test: pass
print Test.__name__

Test.__name__ = 'Test Again'
print Test.__name__
</code>```

will both work to change the class' name.

Body:
I understand how I can provide an informal representation of an instance of the object, but I am interested in providing an informal string representation of the Class name.

So specifically, I want to override what is returned when I print the Class (__main__.SomeClass).

>>> class SomeClass:
...   def __str__(self):
...     return 'I am a SomeClass instance.'
...
>>> SomeClass
<class __main__.SomeClass at 0x2ba2f0fd3b30>
>>> print SomeClass
__main__.SomeClass
>>>
>>> x = SomeClass()
>>> x
<__main__.SomeClass instance at 0x2ba2f0ff3f38>
>>> print x
I am a SomeClass instance.

Body:
To change the class' string representation:

class MC(type):
    def __repr__(cls):
        return 'I am Test'

class Test:
    __metaclass__ = MC
   pass

print Test

works fine.

If repr(Test) is called when you define __str__ it won't use your custimized message.

However, if you define __repr__ like I did, and str(Test) is called, it will use your custimized message, because __repr__ is the fallback and __str__ isn't defined in type.

If all you want to do is change it's name:

def renamer(name):
    def wrapper(func):
        func.__name__ = name
        return func
    return wrapper

@renamer('Not Test')
class Test: pass
print Test.__name__

Test.__name__ = 'Test Again'
print Test.__name__

will both work to change the class' name.