问:
Bar chart with bars from two different dataframes
I have the following dataframes:

```<code>      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt

      df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                             'Qtd_Instrumentation': [18, 5, 25, 10]})

     df_Two = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                   'Qtd_Instrumentation': [14, 1, 22, 10]})
</code>```

I would like to build a bar graph that contains the information from the two data frames, that is, the blue bars indicate the datadrame_One and the vertical red bars indicate the information of the dataframe_Two.

I tried to implement it as follows:

```<code>       fig, ax = plt.subplots()
       n_group = len(df_One['Category'])
       index = np.arange(n_group)
       bar_width = 0.35
       opacity = 0.8

       rects1 = df_One.plot.bar(x='Category', y='Qtd_Instrumentation', color='r', label = 'Station
                                One')
       rects2 = df_Two.plot.bar(x='Category', y='Qtd_Instrumentation', color='b', label = 'Station
                                Two')

       plt.xlabel('Category Instrumentation')
       plt.ylabel('Qtd Instrumentation')

       plt.show()
</code>```

However, this code is wrong, as it designs two bar graphs instead of building just one graph with the two representations.

Does anyone know how I can build this described chart? Tks

答:
This is one way to do it by choosing the align='edge' option and then using positive width for one bar and negative width for another. This will make them aligned next to each other. Also, you have to call plt.legend() to display the legends

```<code>fig, ax = plt.subplots()

index = np.arange(len(df_One['Category']))
bar_width = 0.35
opacity = 0.8

ax.bar(index, df_One['Qtd_Instrumentation'], color='r', align='edge', width=bar_width, label = 'Station One')
ax.bar(index, df_Two['Qtd_Instrumentation'], color='b', align='edge', width=-bar_width,label = 'Station Two')

# Assign the tick labels
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'], rotation=90)

plt.xlabel('Category Instrumentation')
plt.ylabel('Qtd Instrumentation')
plt.legend()
plt.show()
</code>```

Alternative method is the following by using the keyword position to place the bars next to each other as shown here

```<code>df_One.Qtd_Instrumentation.plot(kind='bar', color='red', ax=ax, width=bar_width, position=1)
df_Two.Qtd_Instrumentation.plot(kind='bar', color='blue', ax=ax, width=bar_width, position=0)

ax.set_xlim(-0.5, 3.5)
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'])
</code>```

Body:
I have the following dataframes:

      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt

      df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                             'Qtd_Instrumentation': [18, 5, 25, 10]})

     df_Two = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'],
                   'Qtd_Instrumentation': [14, 1, 22, 10]})

I would like to build a bar graph that contains the information from the two data frames, that is, the blue bars indicate the datadrame_One and the vertical red bars indicate the information of the dataframe_Two.

I tried to implement it as follows:

       fig, ax = plt.subplots()
       n_group = len(df_One['Category'])
       index = np.arange(n_group)
       bar_width = 0.35
       opacity = 0.8

       rects1 = df_One.plot.bar(x='Category', y='Qtd_Instrumentation', color='r', label = 'Station
                                One')
       rects2 = df_Two.plot.bar(x='Category', y='Qtd_Instrumentation', color='b', label = 'Station
                                Two')

       plt.xlabel('Category Instrumentation')
       plt.ylabel('Qtd Instrumentation')

       plt.show()

However, this code is wrong, as it designs two bar graphs instead of building just one graph with the two representations.

Does anyone know how I can build this described chart? Tks

Body:
This is one way to do it by choosing the align='edge' option and then using positive width for one bar and negative width for another. This will make them aligned next to each other. Also, you have to call plt.legend() to display the legends

fig, ax = plt.subplots()

index = np.arange(len(df_One['Category']))
bar_width = 0.35
opacity = 0.8

ax.bar(index, df_One['Qtd_Instrumentation'], color='r', align='edge', width=bar_width, label = 'Station One')
ax.bar(index, df_Two['Qtd_Instrumentation'], color='b', align='edge', width=-bar_width,label = 'Station Two')

# Assign the tick labels
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'], rotation=90)

plt.xlabel('Category Instrumentation')
plt.ylabel('Qtd Instrumentation')
plt.legend()
plt.show()

Alternative method is the following by using the keyword position to place the bars next to each other as shown here

df_One.Qtd_Instrumentation.plot(kind='bar', color='red', ax=ax, width=bar_width, position=1)
df_Two.Qtd_Instrumentation.plot(kind='bar', color='blue', ax=ax, width=bar_width, position=0)

ax.set_xlim(-0.5, 3.5)
ax.set_xticks(index)
ax.set_xticklabels(df_One['Category'])


来源: stackexchange

问:
Having trouble splitting a dataframe into fixed chunks (per row)
I've read several topics on this site about splitting a pandas dataframe into fixed size chunks, but I'm having a problem that I didn't see adressed here. So here's the process: I ask user for inputs as to how many chunks he wishes to have, then ask for the percentage of the dataframe to allocate per chunk, I verify that the percentages given do not go above 1, then proceed to split accordingly. The following is the last part, the one I'm struggling with:

```<code>def dataframe_splitting(df:pd.DataFrame, fracs:list):
    split_frac = []
    print('Size of the dataframe:', df.shape)
    print('fracs:', fracs)
    for i in fracs:
        x = int(i*len(df))
        split_frac.append(x)
    print('split_frac:', split_frac)
    chunks = np.array_split(df, split_frac)
    for x in chunks:
        print(x.shape)
    return chunks
</code>```

And here is the result given when parameters were: 5 chunks and fracs = [0.1, 0.1, 0.3, 0.2]

```<code>Size of the dataframe: (2122905, 79)
fracs: [0.1, 0.1, 0.3, 0.2]
split_fracs: [212290, 212290, 636871, 424581]
(212290, 79)
(0, 79)
(424581, 79)
(0, 79)
(1698324, 79)
</code>```

As you can see, for the same parameter (0.1) I have one dataframe whose number of rows is 212290 and the one after it is empty. I tried using np.split at first and the results were no different. I really don't know where I'm wrong with this code and why the behaviour is like this.

答:
According to np.array_split documentation, the second argument indices_or_sections specifies chunks boundaries rather than chunks sizes. I.e., if we pass an array with a first axis of length N and a list fracs with K elements, the resulting chunks will correspond to indexes [0, fracs[0]), [fracs[0], fracs[1]), ..., [fracs[K-1], N). So, if two consecutive elements of fracs are equal, this will result in a chunk of size 0.

The minimal modification of your code to achieve the expected result is to call np.cumsum on the resulting split_frac variable:

def dataframe_splitting(df:pd.DataFrame, fracs:list):
    split_frac = []
    print('Size of the dataframe:', df.shape)
    print('fracs:', fracs)
    for i in fracs:
        x = int(i*len(df))
        split_frac.append(x)
    chunks = np.array_split(df, np.cumsum(split_frac))  # note the cumsum here
    for x in chunks:
        print(x.shape)
    return chunks
```

ContentLicense: CC BY-SA 4.0

Body:
I've read several topics on this site about splitting a pandas dataframe into fixed size chunks, but I'm having a problem that I didn't see adressed here. So here's the process: I ask user for inputs as to how many chunks he wishes to have, then ask for the percentage of the dataframe to allocate per chunk, I verify that the percentages given do not go above 1, then proceed to split accordingly. The following is the last part, the one I'm struggling with:

def dataframe_splitting(df:pd.DataFrame, fracs:list):
    split_frac = []
    print('Size of the dataframe:', df.shape)
    print('fracs:', fracs)
    for i in fracs:
        x = int(i*len(df))
        split_frac.append(x)
    print('split_frac:', split_frac)
    chunks = np.array_split(df, split_frac)
    for x in chunks:
        print(x.shape)
    return chunks

And here is the result given when parameters were: 5 chunks and fracs = [0.1, 0.1, 0.3, 0.2]

Size of the dataframe: (2122905, 79)
fracs: [0.1, 0.1, 0.3, 0.2]
split_fracs: [212290, 212290, 636871, 424581]
(212290, 79)
(0, 79)
(424581, 79)
(0, 79)
(1698324, 79)

As you can see, for the same parameter (0.1) I have one dataframe whose number of rows is 212290 and the one after it is empty. I tried using np.split at first and the results were no different. I really don't know where I'm wrong with this code and why the behaviour is like this.


问:
Angular JS Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed
I am facing an issue of [ngRepeat:dupes].

systemService.getAllSystemSettings().then(
  function (obj) {
    $scope.project.meta.franchise = obj.find(item => item.keyword === "Program");
    console.log($scope.project.meta.franchise);
    $scope.project.meta.franchise = $scope.project.meta.franchise['keywordValue'].split(';');
    console.log($scope.project.meta.franchise);
    return $scope.project.meta.franchise);
  });
```

<p>in my HTML page :</p>

<pre class="lang-html prettyprint-override"><code><select class="form-control" ng-model="project.meta.franchise" ng-disabled="readOnlyUser">
  <option ng-repeat="option in project.meta.franchise" value="{{option}}">{{option}}</option>
</select>
</code>```

Output in console :

{ keyword: "Program", keywordValue: "test_abc;abc_&xyz;efg_&_hij"
}
[
  "test_abc",
  "abc_&xyz",
  "efg_&_hij"
]
```

error in console:

Please help me out in solving I tried putting track by $ index but no solution with that too. By using $track by it does not show the list in options. ThankYou in advance.

答:
try to make a custom unique index like this</p>

```<code><select class="form-control" ng-model="project.meta.franchise)" ng-disabled="readOnlyUser">
   <option ng-repeat="option in project.meta.franchise track by ($index + ':' + option)" value="{{option}}">{{option}}</option>
 </select>
</code>```

Body:
I am facing an issue of [ngRepeat:dupes].

systemService.getAllSystemSettings().then(
  function (obj) {
    $scope.project.meta.franchise = obj.find(item => item.keyword === "Program");
    console.log($scope.project.meta.franchise);
    $scope.project.meta.franchise = $scope.project.meta.franchise['keywordValue'].split(';');
    console.log($scope.project.meta.franchise);
    return $scope.project.meta.franchise);
  });

in my HTML page :

<select class="form-control" ng-model="project.meta.franchise" ng-disabled="readOnlyUser">
  <option ng-repeat="option in project.meta.franchise" value="{{option}}">{{option}}</option>
</select>

Output in console :

{ keyword: "Program", keywordValue: "test_abc;abc_&xyz;efg_&_hij"
}
[
  "test_abc",
  "abc_&xyz",
  "efg_&_hij"
]

error in console:

Please help me out in solving I tried putting track by $ index but no solution with that too. By using $track by it does not show the list in options. ThankYou in advance.

Body:
try to make a custom unique index like this

<select class="form-control" ng-model="project.meta.franchise)" ng-disabled="readOnlyUser">
   <option ng-repeat="option in project.meta.franchise track by ($index + ':' + option)" value="{{option}}">{{option}}</option>
 </select>


问:
Laravel returning object to javascript getting Uncaught SyntaxError: Unexpected token '&' error
I am making a call to my db, saving the results in an array.
When I try to use my results in the front end I get a Uncaught SyntaxError: Unexpected token '&' error
I have been trying different combinations of decode or encode on the backend and JSON.parse and stringify on the front end.  What am I doing wrong?

My backend code

```<code>        $data = [];
        $data['service'] = DB::table('servicingdata')->get();
        $data['loans'] = DB::table('loandata')->get();
        return view('welcome', $data);
</code>```

My front end code

```<code><script type="text/javascript">

            console.log({{$loans}})
        </script>
</code>```

答:
Use {!! $loans !!} to display the unescaped data. By using {{ }} your data will be processed by htmlspecialchars to prevent XSS attacks.

```<code><script type="text/javascript">
    console.log({!! $loans !!});
</script>
</code>```

Body:
I am making a call to my db, saving the results in an array.
When I try to use my results in the front end I get a Uncaught SyntaxError: Unexpected token '&' error
I have been trying different combinations of decode or encode on the backend and JSON.parse and stringify on the front end.  What am I doing wrong?

My backend code

        $data = [];
        $data['service'] = DB::table('servicingdata')->get();
        $data['loans'] = DB::table('loandata')->get();
        return view('welcome', $data);

My front end code

Body:
Use {!! $loans !!} to display the unescaped data. By using {{ }} your data will be processed by htmlspecialchars to prevent XSS attacks.

<script type="text/javascript">
    console.log({!! $loans !!});
</script>


问:
SPARQL Query: A sets of breeds cat along with the cats that belong to
I am trying to query all the cats breeds (wd:Q43577) along with the list of cats that belong to. Below, you will find my solution. The result of my solution is not relevant and contains a redundancy. Therefore, I need your help to find the best solution. (to execute this query, you have to use this link).  </p>

```<code>     SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName ?CatsID ?CatsName  where {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName.
    }
    }
</code>```

答:
You should use the GROUP_CONCAT function if I understand your question correctly.

Try a query like this:

```<code>    SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName
           (GROUP_CONCAT(DISTINCT ?CatsID; SEPARATOR=', ') AS ?CatsID_List)
           (GROUP_CONCAT(DISTINCT ?CatsName; SEPARATOR=', ') AS ?CatsName_List)
WHERE {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName.
    }
    } GROUP BY ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName
</code>```

Body:
I am trying to query all the cats breeds (wd:Q43577) along with the list of cats that belong to. Below, you will find my solution. The result of my solution is not relevant and contains a redundancy. Therefore, I need your help to find the best solution. (to execute this query, you have to use this link).

     SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName ?CatsID ?CatsName  where {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName.
    }
    }

Body:
You should use the GROUP_CONCAT function if I understand your question correctly.

Try a query like this:

    SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName
           (GROUP_CONCAT(DISTINCT ?CatsID; SEPARATOR=', ') AS ?CatsID_List)
           (GROUP_CONCAT(DISTINCT ?CatsName; SEPARATOR=', ') AS ?CatsName_List)
WHERE {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName.
    }
    } GROUP BY ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName


问:
R: Loop should return numeric element from string
I have a question how to write a loop in r which goes checks if a certain expression occurs in a string . So I want to check if the the expression “i-sty” occurs in my variable for each i between 1:200 and, if this is true, it should give the corresponding i.

For example if we have “4-sty” the loop should give me 4 and if there is no “i-sty” in the variable it should give me . for the observation.

I used

```<code>for (i in 1:200){
  datafram$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}
</code>```

But it did not work. I literally only receive points. Attached I show a picture of the string variable.
enter image description here

答:
"i-sty" is just a string with the letter i in it. To you use a regex pattern with your variable i, you need to paste together a string, e.g., grepl(paste0(i, "-sty"), ...). I'd also recommend using NA rather than "." for the "else" result - that way the resulting height variable can be numeric.

```<code>for (i in 1:200){
  dataframe$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}
</code>```

The above works syntactically, but not logically. You also have a problem that  you are overwriting height each time through the loop - when i is 2, you erase the results from when i is 1, when i is 3, you erase the results from when i is 2... I think a better approach would be to extract the match, which is easy using stringr (but also possible in base). As a benefit, with the right pattern we can skip the loop entirely:

```<code>library(stringr)

dataframe$height = str_match(string = dataframe$Description, pattern = "[0-9]+-sty")[, 2]
# might want to wrap in `as.numeric`
</code>```

You use both datafram and dataframe. I've assumed dataframe is correct.

Body:
I have a question how to write a loop in r which goes checks if a certain expression occurs in a string . So I want to check if the the expression “i-sty” occurs in my variable for each i between 1:200 and, if this is true, it should give the corresponding i.

For example if we have “4-sty” the loop should give me 4 and if there is no “i-sty” in the variable it should give me . for the observation.

I used

for (i in 1:200){
  datafram$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}

But it did not work. I literally only receive points. Attached I show a picture of the string variable.
enter image description here

Body:
"i-sty" is just a string with the letter i in it. To you use a regex pattern with your variable i, you need to paste together a string, e.g., grepl(paste0(i, "-sty"), ...). I'd also recommend using NA rather than "." for the "else" result - that way the resulting height variable can be numeric.

for (i in 1:200){
  dataframe$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}

The above works syntactically, but not logically. You also have a problem that  you are overwriting height each time through the loop - when i is 2, you erase the results from when i is 1, when i is 3, you erase the results from when i is 2... I think a better approach would be to extract the match, which is easy using stringr (but also possible in base). As a benefit, with the right pattern we can skip the loop entirely:

library(stringr)

dataframe$height = str_match(string = dataframe$Description, pattern = "[0-9]+-sty")[, 2]
# might want to wrap in `as.numeric`

You use both datafram and dataframe. I've assumed dataframe is correct.


问:
Getting VSCode Marketplace to update Readme
I have a vscode extension that I've published before and never had an issue but in the last 2 versions of the extension, the readme does not seem to be updating in the vscode marketplace.

Extension Snippet

Snippet Github

Anyone facing any similar issues, and found a solution?

答: Not really sure what the problem was here, but publishing a new version today seemed to update the readme.</p>


问:
How i can capture the screen with an image that loaded from server using angular
How I can capture the screen with an image that loaded from the server using angular. Now I can capture the screen with only text data that load from the back-end, But the image is missed.

Note: I can load the text and image from the backend. But this code can't capture the image

This is the HTML Code

```<code><div #screen id="cards">
<div class="row justify-content-center">
<div class=" col-12 col-md-6 box mt-4">
<img class="img-layer" src="{{url}}/xxxx/xxxx/{{xxxxx}}/xxxx/front.jpg" style="height: 100%; width:
100%; border: 1px solid black;">
<div class="row  justify-content-center avatar">
<div class="col-md-8 text-center d-flex">
<img src="{{url}}/xxxxx/profile/{{xxxxxxx}}/student/{{xxxxxx}}.jpg" style="height: 200px; width:
200px; border-radius: 5px;">
</div>
</div>

<div class="row mt-7 clg-details space">{{aaaa}}</div>
<div class="row">{{aaaa}}</div>
<div class="row">{{aaa}}</div>
<div class="row">{{aaaa}}</div>
</div>
</div>
<div id="download">
<img #canvas>
<a #downloadLink></a>
</div>
</code>```

This is the TS Code

```<code>@ViewChild('screen', { static: false }) screen: ElementRef;
@ViewChild('canvas', { static: false }) canvas: ElementRef;
@ViewChild('downloadLink', { static: false }) downloadLink: ElementRef;

captureImage() {
console.log((this.screen.nativeElement));
html2canvas(this.screen.nativeElement).then(canvas => {
this.canvas.nativeElement.src = canvas.toDataURL();
this.downloadLink.nativeElement.href = canvas.toDataURL('image/png');
this.downloadLink.nativeElement.download = 'id-card.png';
this.downloadLink.nativeElement.click();
});
}
</code>```

This is the image what I need after render and save

This is the image that I get. note that background image is missed

答:
First of all you need to create an img [src]'s value in the front end.
e.g.in your HTML.

In component :

```<code> myImage : any;
     createImage(image : blob){
     let reader = new FileReader();
     reader.addEventListener("load" => {
     this.myImage = reader.result;
}, false);
if(image){
 reader.readAsDataURL(image);
}
}
</code>```

assuming you are getting blob from backend.

Body:
How I can capture the screen with an image that loaded from the server using angular. Now I can capture the screen with only text data that load from the back-end, But the image is missed.

Note: I can load the text and image from the backend. But this code can't capture the image

This is the HTML Code

{{aaaa}}

{{aaaa}}

{{aaa}}

{{aaaa}}

This is the TS Code

@ViewChild('screen', { static: false }) screen: ElementRef;
@ViewChild('canvas', { static: false }) canvas: ElementRef;
@ViewChild('downloadLink', { static: false }) downloadLink: ElementRef;

captureImage() {
console.log((this.screen.nativeElement));
html2canvas(this.screen.nativeElement).then(canvas => {
this.canvas.nativeElement.src = canvas.toDataURL();
this.downloadLink.nativeElement.href = canvas.toDataURL('image/png');
this.downloadLink.nativeElement.download = 'id-card.png';
this.downloadLink.nativeElement.click();
});
}

This is the image what I need after render and save

This is the image that I get. note that background image is missed

Body:
First of all you need to create an img [src]'s value in the front end.
e.g.<img [src]="myImage">in your HTML.

In component :

 myImage : any;
     createImage(image : blob){
     let reader = new FileReader();
     reader.addEventListener("load" => {
     this.myImage = reader.result;
}, false);
if(image){
 reader.readAsDataURL(image);
}
}

assuming you are getting blob from backend.


问:
Get the length of messages storage Django
I am using messages framework of django (https://docs.djangoproject.com/en/3.0/ref/contrib/messages/)

When a user register, i do some check and add messages error to my storage :

```<code> messages.error(request, gettext("username_already_exists"))
</code>```

In my code i would like to know the length of messages.error, like that i can check if there is error or not in my form.

I tried this :

```<code>    if len(messages.error) <= 0:
      User.objects.create_user(
          username,
          email,
          password,
      )
</code>```

But i can't because message 'object of type 'module' has no len()'

Do you know a way to check if there is messages errors stored in the messages Framework please ?

Thank you !

答:
Ok my bad i didn't look enough on document.
Here the answer :

you have to use get_messages from django.contrib.messages import get_messages

then you can do if len(get_messages(request)) <= 0:

Body:
I am using messages framework of django (https://docs.djangoproject.com/en/3.0/ref/contrib/messages/)

When a user register, i do some check and add messages error to my storage :

 messages.error(request, gettext("username_already_exists"))

In my code i would like to know the length of messages.error, like that i can check if there is error or not in my form.

I tried this :

    if len(messages.error) <= 0:
      User.objects.create_user(
          username,
          email,
          password,
      )

But i can't because message 'object of type 'module' has no len()'

Do you know a way to check if there is messages errors stored in the messages Framework please ?

Thank you !


问:
mongodb push values into array with $reduce
I have an document structure like this:

```<code>_id: 123,
posts: [
   {
      _id: 234,
      likesUser: [345, 456, 567, 678]
   }
]
</code>```

I want to use $reduce here so my expected output should look like this:

```<code>   output: {
      likes: [23, 31, 12, 32],  //each element is the size of the "likesUser" array
      ids: ["14312", "2342", "2312", "235234"]  //each element is the "_id" in the posts array
   }
</code>```

I have try it like this:

```<code>  let result = await Post.aggregate([
    {
      $match: {
        _id: USER
      }
    },
    {
      $project: {
        posts: {
          $reduce: {
            input: "$posts",
            initialValue: { likes: [], ids: [] },
            in: {
              likes: {
                $push: { $size: "$$this.likesUser" }
              },
              ids: {
                $push: "$$this._id"
              }
            }
          }
        }
      }
    }
  ]);
</code>```

In my frontend i use chart.js. The yAxsis are the likes and the xAxsis are the ID's. So for every element in my posts array i need the length of likesUser and _id
But it doenst work. Has anybody an idea how to achive this?

答:
You are very close, you just have a minor syntax error in your $reduce, Try this:</p>

```<code>let result = await Post.aggregate([
    {
        $match: {
            _id: USER
        }
    },
    {
        $project: {
            posts: {
                $reduce: {
                    input: "$posts",
                    initialValue: {likes: [], ids: []},
                    in: {
                        likes: {
                            $concatArrays: ["$$value.likes", [{$size: "$$this.likesUser"}]]
                        },
                        ids: {
                            $concatArrays: ["$$value.ids", ["$$this._id"]]
                        }
                    }
                }
            }
        }
    }
]);
</code>```

Body:
I have an document structure like this:

_id: 123,
posts: [
   {
      _id: 234,
      likesUser: [345, 456, 567, 678]
   }
]

I want to use $reduce here so my expected output should look like this:

   output: {
      likes: [23, 31, 12, 32],  //each element is the size of the "likesUser" array
      ids: ["14312", "2342", "2312", "235234"]  //each element is the "_id" in the posts array
   }

I have try it like this:

  let result = await Post.aggregate([
    {
      $match: {
        _id: USER
      }
    },
    {
      $project: {
        posts: {
          $reduce: {
            input: "$posts",
            initialValue: { likes: [], ids: [] },
            in: {
              likes: {
                $push: { $size: "$$this.likesUser" }
              },
              ids: {
                $push: "$$this._id"
              }
            }
          }
        }
      }
    }
  ]);

In my frontend i use chart.js. The yAxsis are the likes and the xAxsis are the ID's. So for every element in my posts array i need the length of likesUser and _id
But it doenst work. Has anybody an idea how to achive this?

Body:
You are very close, you just have a minor syntax error in your $reduce, Try this:

let result = await Post.aggregate([
    {
        $match: {
            _id: USER
        }
    },
    {
        $project: {
            posts: {
                $reduce: {
                    input: "$posts",
                    initialValue: {likes: [], ids: []},
                    in: {
                        likes: {
                            $concatArrays: ["$$value.likes", [{$size: "$$this.likesUser"}]]
                        },
                        ids: {
                            $concatArrays: ["$$value.ids", ["$$this._id"]]
                        }
                    }
                }
            }
        }
    }
]);


问:
How to test django app without giving an app_name
My project structure looks like this: backend/src/apps/app_name/tests/foo.py and when I'm trying to run the tests by entering a command python manage.py test it runs 0 tests. The only correct way to test is python manage.py test src.apps.app_name but I'm to lazy to do it with every app.

答:
Change

```<code>backend/src/apps/app_name/tests/foo.py
</code>```

to

```<code>backend/src/apps/app_name/tests/test_foo.py
</code>```

Make sure all your test files and functions start with test

Body:
Change

backend/src/apps/app_name/tests/foo.py

to

backend/src/apps/app_name/tests/test_foo.py

Make sure all your test files and functions start with test


问:
Use loop for create multiple columns from another columns in dataframe in R
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

```<code>library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)
</code>```

答:
Here's an approach with mutate_at from dplyr:

```<code>library(dplyr)
data <- read.csv("https://docs.google.com/uc?id=1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4&export=download")

data %>%
  mutate_at(vars(JAN:DEC),
            .funs = list(R = ~ 67.355 * ((.)^2 / TOTAL_pa)^0.85))
</code>```

The only difference between yours and this is that the new columns end with _R instead of starting with R..

If you're really excited about the names you chose, you can add rename_at:

```<code>library(stringr)
data %>%
  mutate_at(vars(JAN:DEC),
            .funs = list(R = ~ 67.355 * ((.)^2 / TOTAL_pa)^0.85)) %>%
  rename_at(vars(JAN_R:DEC_R),
            .funs = list(~ paste0("R.",str_remove(.,"_R"))))
</code>```

Body:
I have a CSV file with 19 columns and 9 lines about average of rain months from pluviometers and coordinates (LongLat) of them. The columns are averages and the lines are the pluviometers. The CSV file can be acessed here:  https://drive.google.com/file/d/1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4/view?usp=sharing

The aim is create more columns to calculate rainfall factor by months applying a equation from average columns. The rainfall factor for January for each pluviometer (9 lines) will be calculate using column 7, rainfall for february using column 8, march by column 9...

I'm trying this code for each column and it works, but this code can be reduce and made with a loop?

library(tidyverse)

setwd("C:/scriptsr/R_postos_pluviometricos_interp_FUNCEME/")

#Code
pluviometros <- read.csv("postos_fatorR.csv",
                                 header = T,
                                 sep = ",",
                                 stringsAsFactors = FALSE)

View(pluviometros)

pluviometros <- mutate(.data=pluviometros,R.JAN=67.355*((pluviometros[1:nrow(pluviometros),7]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.FEV=67.355*((pluviometros[1:nrow(pluviometros),8]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAR=67.355*((pluviometros[1:nrow(pluviometros),9]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.APR=67.355*((pluviometros[1:nrow(pluviometros),10]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.MAY=67.355*((pluviometros[1:nrow(pluviometros),11]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUN=67.355*((pluviometros[1:nrow(pluviometros),12]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.JUL=67.355*((pluviometros[1:nrow(pluviometros),13]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.AGO=67.355*((pluviometros[1:nrow(pluviometros),14]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.SEP=67.355*((pluviometros[1:nrow(pluviometros),15]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.OCT=67.355*((pluviometros[1:nrow(pluviometros),16]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.NOV=67.355*((pluviometros[1:nrow(pluviometros),17]^2)/pluviometros[1:nrow(pluviometros),19])^0.85,
                                       R.DEC=67.355*((pluviometros[1:nrow(pluviometros),18]^2)/pluviometros[1:nrow(pluviometros),19])^0.85
                                       )
View(pluviometros)

Body:
Here's an approach with mutate_at from dplyr:

library(dplyr)
data <- read.csv("https://docs.google.com/uc?id=1wGVT5etZomYW-Cb6R3KgHaV4mXrTjlu4&export=download")

data %>%
  mutate_at(vars(JAN:DEC),
            .funs = list(R = ~ 67.355 * ((.)^2 / TOTAL_pa)^0.85))

The only difference between yours and this is that the new columns end with _R instead of starting with R..

If you're really excited about the names you chose, you can add rename_at:

library(stringr)
data %>%
  mutate_at(vars(JAN:DEC),
            .funs = list(R = ~ 67.355 * ((.)^2 / TOTAL_pa)^0.85)) %>%
  rename_at(vars(JAN_R:DEC_R),
            .funs = list(~ paste0("R.",str_remove(.,"_R"))))


问:
How to return multiple data types from a C# method?
I have a method that needs to return different data types based on a search. I'm considering two approaches, since I'm new to C# I don't know which is best, so please help me make my mind.

the first approach is to overload the method like this:

```<code>public int Get(string name){
   //...
   return intValue;
}

public double Get(string name){
   //...
   return doubleValue;
}

public string Get(string name){
   //...
   return stringValue;
}
</code>```

the second approach is to have different methods for each data type like this:

```<code>public int GetInt(string name){
   //...
   return intValue;
}

public double GetDouble(string name){
   //...
   return doubleValue;
}

public string GetString(string name){
   //...
   return stringValue;
}
</code>```

which one is the safest for C# considering this code will be published from a DLL?

答:
To return multiple data types to a C# method you could also try a way in which you compound the method return types into a method and retrieve them individually.

Observe

```<code>   public ( int, double, string) Get(string name) {
             //...
             return (intValue, doubleValue, stringValue);
     }
     // Once returned to the main method the code is disassembled into smaller code //variables
 public static void Main(string args[])  {

          (int Ivals, double Dvals, string Svals) = Get(name);
          Console.WriteLine(Ivals);
          Console.WriteLine(Dvals);
          Console.WriteLine(Svals);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a method that needs to return different data types based on a search. I'm considering two approaches, since I'm new to C# I don't know which is best, so please help me make my mind.

the first approach is to overload the method like this:

public int Get(string name){
   //...
   return intValue;
}

public double Get(string name){
   //...
   return doubleValue;
}

public string Get(string name){
   //...
   return stringValue;
}

the second approach is to have different methods for each data type like this:

public int GetInt(string name){
   //...
   return intValue;
}

public double GetDouble(string name){
   //...
   return doubleValue;
}

public string GetString(string name){
   //...
   return stringValue;
}

which one is the safest for C# considering this code will be published from a DLL?

Body:
To return multiple data types to a C# method you could also try a way in which you compound the method return types into a method and retrieve them individually.

Observe

   public ( int, double, string) Get(string name) {
             //...
             return (intValue, doubleValue, stringValue);
     }
     // Once returned to the main method the code is disassembled into smaller code //variables
 public static void Main(string args[])  {

          (int Ivals, double Dvals, string Svals) = Get(name);
          Console.WriteLine(Ivals);
          Console.WriteLine(Dvals);
          Console.WriteLine(Svals);
}


问:
No module named osgeo.ogr
I need to import osgeo.ogr module to virtualenv python program.

Global python has this module:

```<code>user@ubuntu:~/$ python
Python 2.7.8 (default, Oct 20 2014, 15:05:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import osgeo
>>>
</code>```

But into virtualenv (without --no-site-packages):

```<code>user@ubuntu:~$ temp/bin/python
Python 2.7.8 (default, Oct 20 2014, 15:05:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import osgeo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named osgeo
</code>```

What is the reason for this behavior?

答:
Able to solve with this one</p>

```<code>pip install --global-option=build_ext --global-option="-I/usr/include/gdal" GDAL==`gdal-config --version`
</code>```

Title: No module named osgeo.ogr

Body:
I need to import osgeo.ogr module to virtualenv python program.

Global python has this module:

user@ubuntu:~/$ python
Python 2.7.8 (default, Oct 20 2014, 15:05:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import osgeo
>>>

But into virtualenv (without --no-site-packages):

user@ubuntu:~$ temp/bin/python
Python 2.7.8 (default, Oct 20 2014, 15:05:19)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import osgeo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named osgeo

What is the reason for this behavior?

Body:
Able to solve with this one

pip install --global-option=build_ext --global-option="-I/usr/include/gdal" GDAL==`gdal-config --version`


问:
How to define a default parameter of Vector2f ? [SFML]
I have some function func in a class Class:

```<code> void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0)){};
</code>```

And I get a build error:

```<code>error C2572: 'Classs::func': redefinition of default argument: parameter 1
</code>```

I tried many different synataxes but none worked. How can I define a default parameter of this type?

答:
Specify the default parameter in the prototype only. Don't repeat this in the function definition.

```<code>// prototype
void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0));

// definition
void func(int arg1, int arg2, Vector2f vec)
{
    ...
}
</code>```

This advice applies to any default parameter. It's got nothing to do with the type.

Body:
I have some function func in a class Class:

 void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0)){};

And I get a build error:

error C2572: 'Classs::func': redefinition of default argument: parameter 1

I tried many different synataxes but none worked. How can I define a default parameter of this type?

Body:
Specify the default parameter in the prototype only. Don't repeat this in the function definition.

// prototype
void func(int arg1, int arg2, Vector2f vec = Vector2f(0,0));

// definition
void func(int arg1, int arg2, Vector2f vec)
{
    ...
}

This advice applies to any default parameter. It's got nothing to do with the type.


问:
Get the count of distinct userids for last couple of days
Let's say the last 7 days for this table:

```<code>Userid   Download time
Rab01    2020-04-29 03:28
Klm01    2020-04-29 04:01
Klm01    2020-04-30 05:10
Rab01    2020-04-29 12:14
Osa_3    2020-04-25 09:01
</code>```

Following is the required output:

```<code>Count  Download_time
1      2020-04-25
2      2020-04-29
1      2020-04-30
</code>```

答:
You can use date_trunc function for get day only part from datetime and use it for grouping.

The query may be next:

```<code>SELECT
    count(distinct Userid) as Count, -- get unuque users count
    to_char(date_trunc('day', Download_time), 'YYYY-MM-DD') AS Download_Day -- convert time do day
FROM table
WHERE DATE_PART('day', NOW() - Download_time) < 7 -- last 7 days
GROUP BY Download_Day; -- group by day
</code>```

Fiddle

Body:
Let's say the last 7 days for this table:

Userid   Download time
Rab01    2020-04-29 03:28
Klm01    2020-04-29 04:01
Klm01    2020-04-30 05:10
Rab01    2020-04-29 12:14
Osa_3    2020-04-25 09:01

Following is the required output:

Count  Download_time
1      2020-04-25
2      2020-04-29
1      2020-04-30

Body:
You can use date_trunc function for get day only part from datetime and use it for grouping.

The query may be next:

SELECT
    count(distinct Userid) as Count, -- get unuque users count
    to_char(date_trunc('day', Download_time), 'YYYY-MM-DD') AS Download_Day -- convert time do day
FROM table
WHERE DATE_PART('day', NOW() - Download_time) < 7 -- last 7 days
GROUP BY Download_Day; -- group by day

Fiddle


问:
Python Writer Skips first row
I'm new to python and don't know why I get this kind of error.

I have a csv file from which I read some data. I compare the data with another csv file and if I find similarities I want to copy some data from the second file. However here's the problem:

```<code>            with open('WeselVorlageRE5Woche.csv') as woche:
                with open('weselfund.csv','+a',newline='') as fund:

                    readCSV1 = csv.reader(woche, delimiter=';')
                    for row1 in readCSV1:
                        if row[1]==row1[4]: #find starting time
                            if row[3]==row1[1]: # find same train
                                if row[2]=='cancelled': # condition for taking row
                                    zug=row1[6]     #copy trainnumber
                                    print(zug)
                                    for row2 in readCSV1:
                                        if row2[6]==zug: #find all trainnumbers
                                            #write data to csv
                                            writer = csv.writer(fund, delimiter=';')
                                            writer.writerow(row2)
</code>```

In my second for loop it appears as if the first row is skipped. Every time the for loop starts, the first row of data isn't written in the new file.
Dataset i read from
Dataset that is written
Can someone tell me why the first one is always missing?
If I add a dummy-row in the dataset I read from I get exactly what I want written, but I don't want to add all dummies.

答:
A csv reader gets 'used up' if you iterate over it. This is why the second loop doesn't see the first row, because the first loop has already 'used' it. We can show this by making a simple reader over a list of terms:

>>> import csv
>>> test = ["foo", "bar", "baz"]
>>> reader = csv.reader(test)
>>> for row in reader:
...     print(row)
...
['foo']
['bar']
['baz']
>>> for row in reader:
...     print(row)
...
>>>

```

<p>The second time it prints nothing because the iterator has already been exhausted. If your dataset is not too large you can solve this by storing the rows in a list, and thus in memory, instead:</p>

<pre class="lang-py prettyprint-override"><code>data = [row for row in readCSV1]
</code>```

If the document is too big you will need to make a second file reader and feed it to a second csv reader.

The final code becomes:

with open('WeselVorlageRE5Woche.csv') as woche:
    with open('weselfund.csv','+a',newline='') as fund:
        readCSV1 = [row for row in csv.reader(woche, delimiter=';')]
        for row1 in readCSV1:
            if row[1]==row1[4]: #find starting time
                if row[3]==row1[1]: # find same train
                    if row[2]=='cancelled': # condition for taking row
                        zug=row1[6]     #copy trainnumber
                        print(zug)
                        for row2 in readCSV1:
                            if row2[6]==zug: #find all trainnumbers
                                #write data to csv
                                writer = csv.writer(fund, delimiter=';')
                                writer.writerow(row2)
```

<p>with the solution to store it in memory. If you want to use a second reader instead, it becomes</p>

<pre class="lang-py prettyprint-override"><code>with open('WeselVorlageRE5Woche.csv') as woche:
    with open('weselfund.csv','+a',newline='') as fund:
        readCSV1 = [row for row in csv.reader(woche, delimiter=';')]
        for row1 in readCSV1:
            if row[1]==row1[4]: #find starting time
                if row[3]==row1[1]: # find same train
                    if row[2]=='cancelled': # condition for taking row
                        zug=row1[6]     #copy trainnumber
                        print(zug)
                        with open('WeselVorlageRE5Woche.csv') as woche2:
                            readCSV2 = csv.reader(woche2, delimiter=';')
                            for row2 in readCSV2:
                                if row2[6]==zug: #find all trainnumbers
                                    #write data to csv
                                    writer = csv.writer(fund, delimiter=';')
                                    writer.writerow(row2)
</code>```

Title: Python Writer Skips first row

Body:
I'm new to python and don't know why I get this kind of error.

I have a csv file from which I read some data. I compare the data with another csv file and if I find similarities I want to copy some data from the second file. However here's the problem:

            with open('WeselVorlageRE5Woche.csv') as woche:
                with open('weselfund.csv','+a',newline='') as fund:

                    readCSV1 = csv.reader(woche, delimiter=';')
                    for row1 in readCSV1:
                        if row[1]==row1[4]: #find starting time
                            if row[3]==row1[1]: # find same train
                                if row[2]=='cancelled': # condition for taking row
                                    zug=row1[6]     #copy trainnumber
                                    print(zug)
                                    for row2 in readCSV1:
                                        if row2[6]==zug: #find all trainnumbers
                                            #write data to csv
                                            writer = csv.writer(fund, delimiter=';')
                                            writer.writerow(row2)

In my second for loop it appears as if the first row is skipped. Every time the for loop starts, the first row of data isn't written in the new file.
Dataset i read from
Dataset that is written
Can someone tell me why the first one is always missing?
If I add a dummy-row in the dataset I read from I get exactly what I want written, but I don't want to add all dummies.

Body:
A csv reader gets 'used up' if you iterate over it. This is why the second loop doesn't see the first row, because the first loop has already 'used' it. We can show this by making a simple reader over a list of terms:

>>> import csv
>>> test = ["foo", "bar", "baz"]
>>> reader = csv.reader(test)
>>> for row in reader:
...     print(row)
...
['foo']
['bar']
['baz']
>>> for row in reader:
...     print(row)
...
>>>

The second time it prints nothing because the iterator has already been exhausted. If your dataset is not too large you can solve this by storing the rows in a list, and thus in memory, instead:

data = [row for row in readCSV1]

If the document is too big you will need to make a second file reader and feed it to a second csv reader.

The final code becomes:

with open('WeselVorlageRE5Woche.csv') as woche:
    with open('weselfund.csv','+a',newline='') as fund:
        readCSV1 = [row for row in csv.reader(woche, delimiter=';')]
        for row1 in readCSV1:
            if row[1]==row1[4]: #find starting time
                if row[3]==row1[1]: # find same train
                    if row[2]=='cancelled': # condition for taking row
                        zug=row1[6]     #copy trainnumber
                        print(zug)
                        for row2 in readCSV1:
                            if row2[6]==zug: #find all trainnumbers
                                #write data to csv
                                writer = csv.writer(fund, delimiter=';')
                                writer.writerow(row2)

with the solution to store it in memory. If you want to use a second reader instead, it becomes

with open('WeselVorlageRE5Woche.csv') as woche:
    with open('weselfund.csv','+a',newline='') as fund:
        readCSV1 = [row for row in csv.reader(woche, delimiter=';')]
        for row1 in readCSV1:
            if row[1]==row1[4]: #find starting time
                if row[3]==row1[1]: # find same train
                    if row[2]=='cancelled': # condition for taking row
                        zug=row1[6]     #copy trainnumber
                        print(zug)
                        with open('WeselVorlageRE5Woche.csv') as woche2:
                            readCSV2 = csv.reader(woche2, delimiter=';')
                            for row2 in readCSV2:
                                if row2[6]==zug: #find all trainnumbers
                                    #write data to csv
                                    writer = csv.writer(fund, delimiter=';')
                                    writer.writerow(row2)


问:
How can I deploy an Uno Web assembly application
We are not able to find the deployment documentation regarding Uno Web assembly publishing process.</p>

答: To deploy, it's the same as normal web apps: https://github.com/unoplatform/Uno.Wasm.Bootstrap#publishing-the-build-results…. For the package size, if you don't use AOT, a combination of the IL linker and Brotli compression is generally used.</p>


问:
About `std::unique_prt<Base>& pBase= make_unique<Derived>();`
The first piece of code does not compile, whereas the second one does. Why?

The code is almost the same indeed.
I would be grateful to have some help with this question.

The code below does not compile. You could check it on http://cpp.sh/8j53y.

```<code>dynamic_cast
#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base {
public:
    static unique_ptr<Base>& get_instance()
    {
        pBase = make_unique<Derived>();
        return pBase;
    }

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

int main () {

    auto& instance = Base::get_instance();
    return 0;
}
</code>```

The code below does compile.

```<code>#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base {
public:
    static unique_ptr<Base>& get_instance();

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

unique_ptr<Base>& Base::get_instance()
{
     pBase = make_unique<Derived>();
     return pBase;
}

int main () {
    auto& instance =  Base::get_instance();
    return 0;
}
</code>```

答:
When you define Base::get_instance inline, Derived doesn't have a definition yet (only the forward declaration). So, it can't convert std::unique_ptr<Derived> to std::unique_ptr<Base>, because the definition where Derived inherits from Base hasn't been seen yet. For the same reason, std::make_unique<Derived>() would also fail, because Derived doesn't have a definition yet.

This is why you need to define Base::get_instance after the definition of Derived to compile. You can keep it in a header file by marking it inline then defining it out of line:

class Base {
public:
    static unique_ptr<Base>& get_instance();

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

/*
`inline` here so the definition can appear in multiple translation units
(e.g., directly in the header file)
*/
inline unique_ptr<Base>& Base::get_instance()
{
     pBase = make_unique<Derived>();
     return pBase;
}
```

Body:
The first piece of code does not compile, whereas the second one does. Why?

The code is almost the same indeed.
I would be grateful to have some help with this question.

The code below does not compile. You could check it on http://cpp.sh/8j53y.

dynamic_cast
#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base {
public:
    static unique_ptr<Base>& get_instance()
    {
        pBase = make_unique<Derived>();
        return pBase;
    }

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

int main () {

    auto& instance = Base::get_instance();
    return 0;
}

The code below does compile.

#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base {
public:
    static unique_ptr<Base>& get_instance();

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

unique_ptr<Base>& Base::get_instance()
{
     pBase = make_unique<Derived>();
     return pBase;
}

int main () {
    auto& instance =  Base::get_instance();
    return 0;
}


问:
Makefile specific to directory structure
I'm trying to compile my project using a makefile. I'm new to makefiles so forgive my ignorance. The problem I'm running into is that I would like the output command to build all of the .o files but If I run it as such it will not build the .o files and instead will try to compile all .o files in the /obj directory.

How would I compile all .o file rules in the output rule?

```<code>The directory structure for this project is:
recipe_book
|-GFX         (source directory)
|-PageManager (source directory)
|-Pages       (source directory)
|-main        (source directory)
|-obj         (.o files directory)
|-out         (application output)
</code>```

Here is my Makefile:

```<code>#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -w -g

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image

G++ = g++ -std=c++17 $(LINKER_FLAGS) $(COMPILER_FLAGS)

#Source Directories:
GFX := GFX
PAGE_MANAGER := PageManager
PAGES := Pages

#Object Directory:
OBJ := obj

# Complile the objects into the executable
output: main/main.cpp main/main.hpp $(OBJ)/*.o
    $(G++) main/main.cpp $(OBJ)/*.o -o out/recipe_book.out

#make all object files
#'.' turns them into macros?
#GFX
$(OBJ)/%.o: $(GFX)/%.cpp $(GFX)/%.hpp
    $(G++) -I$(GFX) -c $< -o $@

#PageManager
$(OBJ)/%.o: $(PAGE_MANAGER)/%.cpp $(PAGE_MANAGER)/%.hpp
    $(G++) -I$(PAGE_MANAGER) -c $< -o $@

#Pages
$(OBJ)/%.o: $(PAGES)/%.cpp $(PAGES)/%.hpp
    $(G++) -I$(PAGES) -c $< -o $@

clean:
    rm out/*.out obj/*.o
</code>```

答:
Your output target has, as prerequisites, $(OBJ)/*.o.

But, when nothing's been built yet, that wildcard expands to nothing!

You're going to need to list the objects that are required for the final link of the project, e.g.

```<code>output: main/main.cpp main/main.hpp $(OBJ)/GFX.o $(OBJ)/PageManager.o $(OBJ)/Pages.o
</code>```

This will then trigger the creation of those files (via compilation) where needed.

You can streamline it by putting GFX PageManager Pages in a variable, then performing a substitution to prepend $(OBJ)/ to each one and to append .o to each one.

As an aside, I'd probably roll main into this, rather than treating it specially.

Body:
I'm trying to compile my project using a makefile. I'm new to makefiles so forgive my ignorance. The problem I'm running into is that I would like the output command to build all of the .o files but If I run it as such it will not build the .o files and instead will try to compile all .o files in the /obj directory.

How would I compile all .o file rules in the output rule?

The directory structure for this project is:
recipe_book
|-GFX         (source directory)
|-PageManager (source directory)
|-Pages       (source directory)
|-main        (source directory)
|-obj         (.o files directory)
|-out         (application output)

Here is my Makefile:

#COMPILER_FLAGS specifies the additional compilation options we're using
# -w suppresses all warnings
COMPILER_FLAGS = -w -g

#LINKER_FLAGS specifies the libraries we're linking against
LINKER_FLAGS = -lSDL2 -lSDL2_image

G++ = g++ -std=c++17 $(LINKER_FLAGS) $(COMPILER_FLAGS)

#Source Directories:
GFX := GFX
PAGE_MANAGER := PageManager
PAGES := Pages

#Object Directory:
OBJ := obj

# Complile the objects into the executable
output: main/main.cpp main/main.hpp $(OBJ)/*.o
    $(G++) main/main.cpp $(OBJ)/*.o -o out/recipe_book.out

#make all object files
#'.' turns them into macros?
#GFX
$(OBJ)/%.o: $(GFX)/%.cpp $(GFX)/%.hpp
    $(G++) -I$(GFX) -c $< -o $@

#PageManager
$(OBJ)/%.o: $(PAGE_MANAGER)/%.cpp $(PAGE_MANAGER)/%.hpp
    $(G++) -I$(PAGE_MANAGER) -c $< -o $@

#Pages
$(OBJ)/%.o: $(PAGES)/%.cpp $(PAGES)/%.hpp
    $(G++) -I$(PAGES) -c $< -o $@

clean:
    rm out/*.out obj/*.o

Body:
Your output target has, as prerequisites, $(OBJ)/*.o.

But, when nothing's been built yet, that wildcard expands to nothing!

You're going to need to list the objects that are required for the final link of the project, e.g.

output: main/main.cpp main/main.hpp $(OBJ)/GFX.o $(OBJ)/PageManager.o $(OBJ)/Pages.o

This will then trigger the creation of those files (via compilation) where needed.

You can streamline it by putting GFX PageManager Pages in a variable, then performing a substitution to prepend $(OBJ)/ to each one and to append .o to each one.

As an aside, I'd probably roll main into this, rather than treating it specially.


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答:
Pontus Gagge has it right:  Wrap your methods in a class and expose state through a property.

Also, bear in mind the danger with using enums:  you can cast any integer as any enum.  This will compile and run just fine:

```<code>public enum Status
{
    Good,
    Bad,
    Indifferent
};

public class Program
{
    static void Main(string[] args)
    {
        Status s = (Status) 30;
    }
}
</code>```

It's basically unsafe to assume that a variable of an enum type contains one of the possible values; it may include an impossible value.

OwnerDisplayName: Chance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chance

Body:
Pontus Gagge has it right:  Wrap your methods in a class and expose state through a property.

Also, bear in mind the danger with using enums:  you can cast any integer as any enum.  This will compile and run just fine:

public enum Status
{
    Good,
    Bad,
    Indifferent
};

public class Program
{
    static void Main(string[] args)
    {
        Status s = (Status) 30;
    }
}

It's basically unsafe to assume that a variable of an enum type contains one of the possible values; it may include an impossible value.

OwnerDisplayName: Robert Rossney


问:
Function not call when button click
i have create a UIBUtton

```<code>editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];
</code>```

But control not jump to its definition where i check if button give its tag value on click or not.

-

```<code>(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}
</code>```

Can anyone tell me why it not work please.

答:
Try this</p>

```<code>editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
[editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
editButton.hidden = YES;
[editButton setTag:tag];
[backView addSubview:editButton];

- (void)deleteObjectViewImage:(id)sender
{

    UIButton *button = (UIButton *)sender;
    NSLog(@"Button tag is %d",button.tag);
    button.hidden = YES;
}
</code>```

Title: Function not call when button click

Body:
i have create a UIBUtton

editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];

But control not jump to its definition where i check if button give its tag value on click or not.

-

(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}

Can anyone tell me why it not work please.

Body:
Try this

editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
[editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
[editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
editButton.hidden = YES;
[editButton setTag:tag];
[backView addSubview:editButton];

- (void)deleteObjectViewImage:(id)sender
{

    UIButton *button = (UIButton *)sender;
    NSLog(@"Button tag is %d",button.tag);
    button.hidden = YES;
}


问:
Gatsby buildObjectType for array of items
I have a field that contains an array of Strings - in this case it's an array of filenames, but it could be IDs or any identifier. I'd like to use buildObjectType to resolve these Strings to another Node. In other words, resolve an array of Strings to an array of external Nodes.

I have used buildObjectType to resolve a Node from a field containing a single identifier, but haven't been able to get it working when the field is an array of IDs. In the case of a single identifier the resolver is something like:

```<code>context.nodeModel
  .getAllNodes({ type: "ChildYaml" })
  .find(child => child.slug === source.child)
</code>```

Now I need to iterate over an array and resolve each item.

Here's an example of my field in a ParentYaml file

```<code>files:
  - filename1
  - filename2
  - filename3
  - filename4
</code>```

In gatsby-config:

```<code>exports.createSchemaCustomization = ({ actions, schema }) => {
  const { createTypes } = actions

  const typeDefs = [
    schema.buildObjectType({
      name: "ParentYaml",
      fields: {
        files: {
          type: "ChildYaml",
          resolve: (source, args, context, info) => {
            // Iterate over context and resolve each item to a filename
          },
        },
      },
    })
  ]

  createTypes(typeDefs)
}
</code>```

I have tried the following resolve, unsuccessfully. This gets a File Node, but not the ChildYaml.

```<code>resolve: (source, args, context, info) => {
  return source.files.map((fileRef) => {
    return context.nodeModel
      .getAllNodes({ type: "File" })
      .find(file => file.name === fileRef)
  })
},
</code>```

I have also tried a method to resolve the ChildYaml (instead of File) using the slug. This produces a similar result - the resolve returns an array of the desired Nodes, but those Nodes are not available in my page context.

How can I resolve Nodes of an array?

答:
One of the reasons I love Stack Overflow, and the question-asking process - it encourages you to think of the problem in a different way, take a step back and boil the issue down to the basics.

In writing the question and re-reading it later I took a different approach and tried Gatsby's @link directive.

This format replaced the verbose schema.buildObjectType syntax with the following:

```<code>type ParentYaml implements Node {
   files: [ChildYaml] @link(by: "slug")
},
</code>```

which did exactly what I wanted - the files field now resolves each file into it's own ChildYaml Node.

Body:
I have a field that contains an array of Strings - in this case it's an array of filenames, but it could be IDs or any identifier. I'd like to use buildObjectType to resolve these Strings to another Node. In other words, resolve an array of Strings to an array of external Nodes.

I have used buildObjectType to resolve a Node from a field containing a single identifier, but haven't been able to get it working when the field is an array of IDs. In the case of a single identifier the resolver is something like:

context.nodeModel
  .getAllNodes({ type: "ChildYaml" })
  .find(child => child.slug === source.child)

Now I need to iterate over an array and resolve each item.

Here's an example of my field in a ParentYaml file

files:
  - filename1
  - filename2
  - filename3
  - filename4

In gatsby-config:

exports.createSchemaCustomization = ({ actions, schema }) => {
  const { createTypes } = actions

  const typeDefs = [
    schema.buildObjectType({
      name: "ParentYaml",
      fields: {
        files: {
          type: "ChildYaml",
          resolve: (source, args, context, info) => {
            // Iterate over context and resolve each item to a filename
          },
        },
      },
    })
  ]

  createTypes(typeDefs)
}

I have tried the following resolve, unsuccessfully. This gets a File Node, but not the ChildYaml.

resolve: (source, args, context, info) => {
  return source.files.map((fileRef) => {
    return context.nodeModel
      .getAllNodes({ type: "File" })
      .find(file => file.name === fileRef)
  })
},

I have also tried a method to resolve the ChildYaml (instead of File) using the slug. This produces a similar result - the resolve returns an array of the desired Nodes, but those Nodes are not available in my page context.

How can I resolve Nodes of an array?

Body:
One of the reasons I love Stack Overflow, and the question-asking process - it encourages you to think of the problem in a different way, take a step back and boil the issue down to the basics.

In writing the question and re-reading it later I took a different approach and tried Gatsby's @link directive.

This format replaced the verbose schema.buildObjectType syntax with the following:

type ParentYaml implements Node {
   files: [ChildYaml] @link(by: "slug")
},

which did exactly what I wanted - the files field now resolves each file into it's own ChildYaml Node.


问:
Validating request payload in Express.js for Todoist Webhook API
I am trying to integrate the Webhooks API from Todoist. I get the correct header and body information, but fail to validate the X-Todoist-Hmac-SHA256 header. From the Todoist documentation:

To verify each webhook request was indeed sent by Todoist, an X-Todoist-Hmac-SHA256 header is included; it is a SHA256 Hmac generated using your client_secret as the encryption key and the whole request payload as the message to be encrypted. The resulting Hmac would be encoded in a base64 string.

Now this is my code for the webhook route using express.js and the Node.js Crypto library for decrypting:

app.post("/webhooks/todoist", async (req, res) => {

    // this is my stored client secret from Todoist
    const secret = keys.todoistClientSecret

    // Using the Node.js Crypto library
    const hash = crypto.createHmac('sha256', secret)
      .update(req.toString()) // <-- is this the "whole request payload"?
      .digest("base64");

    // These 2 are not equal
    console.log("X-Todoist-Hmac-SHA256:", req.header("X-Todoist-Hmac-SHA256"))
    console.log("Hash:", hash)

    res.status(200).send()
  })```

I already found out that req is of type IncomingMessage. The Crypto library accepts only certain types, if I pass the req object itself, I get the following error:

The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.

What is the correct way to pass the "whole request payload" to the crypto library?

答:
Ok, so after try-and-error-ing some other variants, I found the solution. You have to pass JSON.stringify(req.body) as the message to encrypt. Maybe this helps others.

    const hash = crypto.createHmac('sha256', secret)
      .update(JSON.stringify(req.body)) // <-- this is the needed message to encrypt
      .digest("base64");```
</div>
</div>
</p>

<h1>Import update for special character encoding</h1>

<p>I used <code>app.use(bodyParser.json())</code> in my express setup. This will not work for request bodies that have special characters (like German Umlauts ä, ö, ü). Instead, I will have to set the body parser up like this: </p>

```app.use(bodyParser.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}))
```

<p>Then, in the encryption instead of passing <code>JSON.stringify(req.body)</code> it has to be <code>req.rawBody</code>. So the final code for the crypto library looks like this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    const secret = keys.todoistClientSecret
    const hash = crypto.createHmac('sha256', secret)
      .update(req.rawBody)
      .digest("base64");</code>```

Body:
I am trying to integrate the Webhooks API from Todoist. I get the correct header and body information, but fail to validate the X-Todoist-Hmac-SHA256 header. From the Todoist documentation:

To verify each webhook request was indeed sent by Todoist, an X-Todoist-Hmac-SHA256 header is included; it is a SHA256 Hmac generated using your client_secret as the encryption key and the whole request payload as the message to be encrypted. The resulting Hmac would be encoded in a base64 string.

Now this is my code for the webhook route using express.js and the Node.js Crypto library for decrypting:

app.post("/webhooks/todoist", async (req, res) => {

    // this is my stored client secret from Todoist
    const secret = keys.todoistClientSecret

    // Using the Node.js Crypto library
    const hash = crypto.createHmac('sha256', secret)
      .update(req.toString()) // <-- is this the "whole request payload"?
      .digest("base64");

    // These 2 are not equal
    console.log("X-Todoist-Hmac-SHA256:", req.header("X-Todoist-Hmac-SHA256"))
    console.log("Hash:", hash)

    res.status(200).send()
  })

I already found out that req is of type IncomingMessage. The Crypto library accepts only certain types, if I pass the req object itself, I get the following error:

The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.

What is the correct way to pass the "whole request payload" to the crypto library?

Body:
Ok, so after try-and-error-ing some other variants, I found the solution. You have to pass JSON.stringify(req.body) as the message to encrypt. Maybe this helps others.

    const hash = crypto.createHmac('sha256', secret)
      .update(JSON.stringify(req.body)) // <-- this is the needed message to encrypt
      .digest("base64");

Import update for special character encoding

I used app.use(bodyParser.json()) in my express setup. This will not work for request bodies that have special characters (like German Umlauts ä, ö, ü). Instead, I will have to set the body parser up like this:

app.use(bodyParser.json({
  verify: (req, res, buf) => {
    req.rawBody = buf
  }
}))

Then, in the encryption instead of passing JSON.stringify(req.body) it has to be req.rawBody. So the final code for the crypto library looks like this:

    const secret = keys.todoistClientSecret
    const hash = crypto.createHmac('sha256', secret)
      .update(req.rawBody)
      .digest("base64");


问:
Pandas slicing excluding the end
When slicing a dataframe using loc,

df.loc[start:end]

both start and end are included. Is there an easy way to exclude the end when using loc?

答:
None of the answers addresses the situation where end is not part of the index.
The more general solution is simply comparing the index to start and end, that way you can enforce either of them being inclusive of exclusive.

df[(df.index >= start) & (df.index < end)]
```

<p>For instance:</p>

<pre class="lang-py prettyprint-override"><code>>>> import pandas as pd
>>> import numpy as np

>>> df = pd.DataFrame(
    {
        "x": np.arange(48),
        "y": np.arange(48) * 2,
    },
    index=pd.date_range("2020-01-01 00:00:00", freq="1H", periods=48)
)

>>> start = "2020-01-01 14:00"
>>> end = "2020-01-01 19:30" # this is not in the index

>>> df[(df.index >= start) & (df.index < end)]

                    x   y
2020-01-01 14:00:00 14  28
2020-01-01 15:00:00 15  30
2020-01-01 16:00:00 16  32
2020-01-01 17:00:00 17  34
2020-01-01 18:00:00 18  36
2020-01-01 19:00:00 19  38
</code>```

Title: Pandas slicing excluding the end

Body:
None of the answers addresses the situation where end is not part of the index.
The more general solution is simply comparing the index to start and end, that way you can enforce either of them being inclusive of exclusive.

df[(df.index >= start) & (df.index < end)]

For instance:

>>> import pandas as pd
>>> import numpy as np

>>> df = pd.DataFrame(
    {
        "x": np.arange(48),
        "y": np.arange(48) * 2,
    },
    index=pd.date_range("2020-01-01 00:00:00", freq="1H", periods=48)
)

>>> start = "2020-01-01 14:00"
>>> end = "2020-01-01 19:30" # this is not in the index

>>> df[(df.index >= start) & (df.index < end)]

                    x   y
2020-01-01 14:00:00 14  28
2020-01-01 15:00:00 15  30
2020-01-01 16:00:00 16  32
2020-01-01 17:00:00 17  34
2020-01-01 18:00:00 18  36
2020-01-01 19:00:00 19  38


问:
Empty update channel request with Node js client (GetStream.io)
Trying to update a channel from server-side, but getting error "StreamChat error code 4: UpdateChannel failed with error: \"empty update channel request\"".

Not sure what's wrong since channel.update has only one argument.

That's my code: (simplified)

```<code>const getStreamClient = new StreamChat(api_key, api_key_secret, {
  logger(type, message, data) {
    console.log(message);
    console.log(data);
  }
});

async function updateChannel(id, data) {
  const channels = await getStreamClient.queryChannels({ id }, {}, {});
  const channel = channels[0];
  return channel.update(data);
}

updateChannel("channel-id", { name: "test-name" })
.then(result => {
console.log(result);
})
.catch(err => {
console.error(err);
});
</code>```

Adding logger to StreamChat didn't actually help, can't see any issues there.

答:
This simplified code is fine. There won't be an error.

However, I guess you have an issue in the original code. This error is triggered when

no change body is sent

no members or invites are changed

no moderators are changed

Please ensure you satisfy at least one of these conditions while calling update on a channel.

A side note, you're using id to query channels but it's recommended to use cid because you might modify wrong channel by mistake. For example, messaging:1 or gaming:1 where id is 1 so id isn't unique but cid is.

Body:
Trying to update a channel from server-side, but getting error "StreamChat error code 4: UpdateChannel failed with error: \"empty update channel request\"".

Not sure what's wrong since channel.update has only one argument.

That's my code: (simplified)

const getStreamClient = new StreamChat(api_key, api_key_secret, {
  logger(type, message, data) {
    console.log(message);
    console.log(data);
  }
});

async function updateChannel(id, data) {
  const channels = await getStreamClient.queryChannels({ id }, {}, {});
  const channel = channels[0];
  return channel.update(data);
}

updateChannel("channel-id", { name: "test-name" })
.then(result => {
console.log(result);
})
.catch(err => {
console.error(err);
});

Adding logger to StreamChat didn't actually help, can't see any issues there.


问:
Why does 'typeid(x) == typeid(y)' evaluate to true, where 'x' and 'y' are id-expression of type T and T& respectively?
I am reading the C++11 draft standard and the section on [expr.typeid] mentions the following (emphasis mine):

[...]

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of
  the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid
  expression refers to a std::type_info object representing the cv-unqualified referenced type. If the type of
  the type-id is a class type or a reference to a class type, the class shall be completely-defined.

Further in p5 of the same section, it goes on to give the following example:

```<code>class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2); // yields true
typeid(D)  == typeid(const D); // yields true
typeid(D)  == typeid(d2); // yields true
typeid(D)  == typeid(const D&); // yields true   -- (1)
</code>```

Given the following code sample:

```<code>int main()
{
    int foo = 42;
    int &bar = foo;
    bool comp1 = (typeid(int) == typeid(int&));    // Yields true, same as (1)   -- (2)
    bool comp2 = (typeid(foo) == typeid(bar));     // Yields true, Why?          -- (3)
}
</code>```

My understanding is that [expr.typeid]p4 talks only about the form typeid(type-id) and bar in typeid(bar) is an id-expression and not a type-id. Why does (3) above evaluate to true? Which text in the standard covers this? What have I missed?

答:
The answer is in [expr]

5 If an expression initially has the type “reference to T” ([dcl.ref],
  [dcl.init.ref]), the type is adjusted to T prior to any further
  analysis. The expression designates the object or function denoted by
  the reference, and the expression is an lvalue or an xvalue, depending
  on the expression.

So when we get into [expr.typeid]

3 When typeid is applied to an expression other than a glvalue of a
  polymorphic class type, the result refers to a std::type_info object
  representing the static type of the expression. Lvalue-to-rvalue
  ([conv.lval]), array-to-pointer ([conv.array]), and
  function-to-pointer ([conv.func]) conversions are not applied to the
  expression. If the type of the expression is a class type, the class
  shall be completely-defined. The expression is an unevaluated operand
  (Clause [expr]).

The id-expression in question is already of the referenced type when typeid examines it.

Body:
I am reading the C++11 draft standard and the section on [expr.typeid] mentions the following (emphasis mine):

[...]

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers
  to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer
  (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the
  expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand
  (Clause 5).

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of
  the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid
  expression refers to a std::type_info object representing the cv-unqualified referenced type. If the type of
  the type-id is a class type or a reference to a class type, the class shall be completely-defined.

Further in p5 of the same section, it goes on to give the following example:

class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2); // yields true
typeid(D)  == typeid(const D); // yields true
typeid(D)  == typeid(d2); // yields true
typeid(D)  == typeid(const D&); // yields true   -- (1)

Given the following code sample:

int main()
{
    int foo = 42;
    int &bar = foo;
    bool comp1 = (typeid(int) == typeid(int&));    // Yields true, same as (1)   -- (2)
    bool comp2 = (typeid(foo) == typeid(bar));     // Yields true, Why?          -- (3)
}

My understanding is that [expr.typeid]p4 talks only about the form typeid(type-id) and bar in typeid(bar) is an id-expression and not a type-id. Why does (3) above evaluate to true? Which text in the standard covers this? What have I missed?


问:
Order in Array of K8s entity
I have CRD (Custom Resource Definition) with a field with a type "array". I wonder if in this array the order is preserved , mens , if i apply yaml with:

```<code>myField:
- a
- b
- c
</code>```

And after that I get the entity using kubectl, it is promised to me that I get the order I mentions before and nor

```<code>myField:
- b
- a
- c
</code>```

答:
I don't ask about yaml format, I ask about k8s: if k8s save order in
  its internal storage and cannot change the order

lists/arrays in yaml manifests are like lists in Python which basically are collections of ordered and changeable (mutable) elements. And yes, kubernetes also stores them following this rule.

You can easily check it by performing a simple test. It's not a working example of nginx server as all ports are fictitious, but it illustrates pretty well the idea:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 5
        - containerPort: 4
        - containerPort: 3
        - containerPort: 2
        - containerPort: 1
</code>```

Once you deploy it on your k8s cluster by running kubectl apply -f nginx.yaml you can retrieve it by making a call to kube-api server e.g. by using:

```<code>kubectl get deployment nginx-deployment -o yaml
</code>```

which gives you the following output:

```<code>...
        ports:
        - containerPort: 5
          protocol: TCP
        - containerPort: 4
          protocol: TCP
        - containerPort: 3
          protocol: TCP
        - containerPort: 2
          protocol: TCP
        - containerPort: 1
...
</code>```

As you can see all elements of our list are stored in the same order as they were listed in our yaml manifest. You can try to put those elements in completely different order and you'll see that kubernetes won't sort them in any way. The order of the elements of the list will always be kept.

Title: Order in Array of K8s entity

Body:
I have CRD (Custom Resource Definition) with a field with a type "array". I wonder if in this array the order is preserved , mens , if i apply yaml with:

myField:
- a
- b
- c

And after that I get the entity using kubectl, it is promised to me that I get the order I mentions before and nor

myField:
- b
- a
- c

Body:
I don't ask about yaml format, I ask about k8s: if k8s save order in
  its internal storage and cannot change the order

lists/arrays in yaml manifests are like lists in Python which basically are collections of ordered and changeable (mutable) elements. And yes, kubernetes also stores them following this rule.

You can easily check it by performing a simple test. It's not a working example of nginx server as all ports are fictitious, but it illustrates pretty well the idea:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 5
        - containerPort: 4
        - containerPort: 3
        - containerPort: 2
        - containerPort: 1

Once you deploy it on your k8s cluster by running kubectl apply -f nginx.yaml you can retrieve it by making a call to kube-api server e.g. by using:

kubectl get deployment nginx-deployment -o yaml

which gives you the following output:

...
        ports:
        - containerPort: 5
          protocol: TCP
        - containerPort: 4
          protocol: TCP
        - containerPort: 3
          protocol: TCP
        - containerPort: 2
          protocol: TCP
        - containerPort: 1
...

As you can see all elements of our list are stored in the same order as they were listed in our yaml manifest. You can try to put those elements in completely different order and you'll see that kubernetes won't sort them in any way. The order of the elements of the list will always be kept.


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答:
I would at first parse numbers as integers, put them to the set and compare them: </p>

```<code>  import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class StringsCompare {

    private static String one = "1 2 3 4 5 6";
    private static String two = " 3 2 1 5 6 4 ";

    public static void main(String[] args) {
        StringsCompare sc = new StringsCompare();

        System.out.println(sc.compare(one, two));
    }

    private boolean compare(String one, String two) {

        SortedSet<Integer> setOne = getSet(one);
        SortedSet<Integer> setTwo = getSet(two);

        return setOne.equals(setTwo);
    }

    private SortedSet<Integer> getSet(String str) {
        SortedSet<Integer> result = new TreeSet<Integer>();

        StringTokenizer st = new StringTokenizer(str, " ");

        while (st.hasMoreTokens()) {
            result.add(Integer.valueOf(st.nextToken()));
        }

        return result;
    }
}
</code>```

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";

Body:
I would at first parse numbers as integers, put them to the set and compare them:

  import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class StringsCompare {

    private static String one = "1 2 3 4 5 6";
    private static String two = " 3 2 1 5 6 4 ";

    public static void main(String[] args) {
        StringsCompare sc = new StringsCompare();

        System.out.println(sc.compare(one, two));
    }

    private boolean compare(String one, String two) {

        SortedSet<Integer> setOne = getSet(one);
        SortedSet<Integer> setTwo = getSet(two);

        return setOne.equals(setTwo);
    }

    private SortedSet<Integer> getSet(String str) {
        SortedSet<Integer> result = new TreeSet<Integer>();

        StringTokenizer st = new StringTokenizer(str, " ");

        while (st.hasMoreTokens()) {
            result.add(Integer.valueOf(st.nextToken()));
        }

        return result;
    }
}


问:
How to intertwine Async functions and sync functions in flutter
I am a beginner to flutter and I don't quite understand how to use Async functions in flutter.
For example,

```<code>Future <String> readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  return body;
}
</code>```

So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.

Unfortunately, my build function in main.dart is a synchronous one and when I do:

```<code>child : Text(readData());
</code>```

It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async.
How do I go about waiting to get this string and display it?

答:
Dart Streams - Flutter in Focus

This is very well explained I think should help you

Body:
I am a beginner to flutter and I don't quite understand how to use Async functions in flutter.
For example,

Future <String> readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  return body;
}

So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.

Unfortunately, my build function in main.dart is a synchronous one and when I do:

child : Text(readData());

It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async.
How do I go about waiting to get this string and display it?


问:
Rotate vertices selected using weight map on UVs in Unity3D's Shader Graph around pivot point
TLDR: Can't figure out the correct Shader Graph setup for using UV and vertex displacement to cheaply animate a (unrigged) mesh.

I am trying to rotate a part of the mesh based on the UV coordinates, e.g: fromX 0 toX 0.4, fromY 0 toY 0.6. The mesh is created uv-mapped with this in mind.

I have no problem getting the affected vertices in this area. Problem is that I want to rotate these verts for customizable axis e.g. axis(X:1, Y:0, Z:1) using a weight so that the rotation takes place around a pivoted point. I want the bottom selection to stay connected to the rest of the mesh while the other affected vertices neatly rotate around this point.
The weight can be painted by using split UV channels as seen in the picture:

I multiply the weighted area with a rotation node to rotate it.
And I add that to the negative multiplied position (the rest of the verts, excluding the rotated area) to get the final output displacement.

But the rotated mesh is bent. I need it to be stiff as in the whole part rotated with weight=1 except for the very pivoting vertex.

I can get it as described using a weight=1 based rotation, but the pivot point becomes the center of the mesh, not the desired point.

How can I do this correctly?
Been at it for days, please help :')

答:
Try this:

I've used the UV ranges from your example applied to a sphere of unit size.  The spheres original pivot is in the centre, and its adjusted pivot is shifted 0.5 on the Y axis.

The only variable the shader doesn't know, is the adjusted pivot position; so I pass this through the material.

I've not implemented your weight in the graph, as I just wanted to show you the process.  You can easily plug that in.

The color output is just being used for debug purposes.

The first image is with the default object pivot.
The second image is with the adjusted pivot.
The final image is the graph.  (Note the logic group is driving the vertex rotation based on the UV mask).


问:
How to find all available properties and methods of a gradle plugin in Android Studio?
Is there a way to find all available properties and methods of a Gradle Plugin, or does it purely rely on documentation?

Am I missing a Gradle command or window in Android Studio that shows me all available options? Without it I would practically have to guess...

In this particular case I'm looking for more information on the Firebase Crashlytics Gradle Plugin.

```<code>com.google.firebase:firebase-crashlytics-gradle
</code>```

Edit

To make myself more clear, in the following example taken from Firebase docs how would I find out which methods I can use within the firebaseCrashlytics block.

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.gms.google-services'

android {
    // ...

    buildTypes {
        debug {
            minifyEnabled true
            firebaseCrashlytics {
                // If you don't need crash reporting for your debug build,
                // you can speed up your build by disabling mapping file uploading.
                mappingFileUploadEnabled false
            }
        }

        release {
            minifyEnabled true
            // When minifyEnabled is set to true, Crashlytics automatically
            // uploads mapping files because the plugin detects that obfuscation
            // is enabled. mappingFileUploadEnabled defaults to true if
            // minifyEnabled is true.
        }
    }
}
</code>```

答:
If you run:

```<code>./gradlew tasks
</code>```

It should provide you with a list of different tasks.

Body:
Is there a way to find all available properties and methods of a Gradle Plugin, or does it purely rely on documentation?

Am I missing a Gradle command or window in Android Studio that shows me all available options? Without it I would practically have to guess...

In this particular case I'm looking for more information on the Firebase Crashlytics Gradle Plugin.

com.google.firebase:firebase-crashlytics-gradle

Edit

To make myself more clear, in the following example taken from Firebase docs how would I find out which methods I can use within the firebaseCrashlytics block.

apply plugin: 'com.android.application'
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.gms.google-services'

android {
    // ...

    buildTypes {
        debug {
            minifyEnabled true
            firebaseCrashlytics {
                // If you don't need crash reporting for your debug build,
                // you can speed up your build by disabling mapping file uploading.
                mappingFileUploadEnabled false
            }
        }

        release {
            minifyEnabled true
            // When minifyEnabled is set to true, Crashlytics automatically
            // uploads mapping files because the plugin detects that obfuscation
            // is enabled. mappingFileUploadEnabled defaults to true if
            // minifyEnabled is true.
        }
    }
}

Body:
If you run:

./gradlew tasks

It should provide you with a list of different tasks.