问:
jQuery-mobile and stale data in pages
I'm just starting experimenting with jQuery and trying to apply it to a very simple CRUD app that consists of list, create, edit & show pages.

I've applied the jQuery-mobile markup conventions and everything looks very nice. However, I am confused about the problem of refreshing stale data. I understand that jQuery-mobile overrides links and form submission with AJAX to deliver a 'one-page app'. Again, this is working for me and all my data-role="page" stuff is loading and transitioning correctly.

What I don't understand is that when I modify data, (e.g. submit a form to create a new item then navigate back to the 'list' page) certain pages need to be refreshed from the server to pick up the modified data. What jQuery-mobile does is just re-display the previously loaded page which is now stale. Similarly, every time I re-visit the 'create page' to create another new item the form is still filled in from the previous submit as the page is not actually refreshing.

If this is something I need to script myself, that's fine but I'm curious that there doesn't seem to be any mention of what I would have thought was a common scenario in the jQuery-mobile docs. It feels like I must be missing something obvious. How are other people handling this?

答:
The rel=external technique causes problems elsewhere e.g. you can't deploy a fullscreen ipad app that uses rel=external.

I had exactly the same problem.  I'm tinkering with some patches that were published here

I pasted the following just after my  reference:

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

    $('div').live('pagehide', function(event, ui){
      var page = jQuery(event.target);
        //alert('point 6875654');
      if(page.attr('data-cache') == 'never'){
        //alert('removing jqm history page');
        page.remove();
      };
    });

    </script>
</code>```

I then added the data-cache attribute as follows:

```<code><div class="page" data-role="page" data-cache="never">
</code>```

This seems to have helped a lot, although I still have some related issues around redirects to do with ASP.NET security.

Title: jQuery-mobile and stale data in pages

Body:
The rel=external technique causes problems elsewhere e.g. you can't deploy a fullscreen ipad app that uses rel=external.

I had exactly the same problem.  I'm tinkering with some patches that were published here

I pasted the following just after my <script src="../../Scripts/jquery.mobile-1.0a4.1.min.js" type="text/javascript"></script> reference:

script type="text/javascript">

    $('div').live('pagehide', function(event, ui){
      var page = jQuery(event.target);
        //alert('point 6875654');
      if(page.attr('data-cache') == 'never'){
        //alert('removing jqm history page');
        page.remove();
      };
    });

    </script>

I then added the data-cache attribute as follows:

<div class="page" data-role="page" data-cache="never">

This seems to have helped a lot, although I still have some related issues around redirects to do with ASP.NET security.


来源: stackexchange

问:
Angular2 - Changing property onClick doesn't trigger view update
i'm trying to re-create the TodoMvc app in Angular2.

I'm struggling with filtering the list based off a click event.
Codesandbox here

The flow is as follows:

App renders with this.todoItemFilter = TodoItemFilter.All and *ngFor="let item of todoItems | filter: filterTodoItems"

Clicking All/Active/Completed results in a function call setSelectedFilter(todoItemFilterEnum.All) which updates the filter property this.todoItemFilter = filter; but view is not re-rendered.

I'm pretty sure there are multiple ways to solve this problem i'm actually interesting in as many as possible thank you!

答:
You can set a new reference to todoItems:

```<code>  setSelectedFilter(filter: TodoItemFilter) {
      this.todoItemFilter = filter;
      this.todoItems = [...this.todoItems];
  }
</code>```

This will cause the change detection to detect a 'new' value.

ContentLicense: CC BY-SA 4.0

Body:
You can set a new reference to todoItems:

  setSelectedFilter(filter: TodoItemFilter) {
      this.todoItemFilter = filter;
      this.todoItems = [...this.todoItems];
  }

This will cause the change detection to detect a 'new' value.


问:
Lambda Python - Print Formatting Improvements
I have a lambda

This lambda goes off and reports on anyones access key older than a specific number of days.

import boto3, json, time, datetime, sys

```<code>sns = boto3.client('sns')
usernames = []
mylist = []

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::999999999:role/role",
    RoleSessionName="AssumedRoleSession4"
)
credentials=assumed_role_object['Credentials']
client=boto3.client(
    'iam',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken'],
    )
def lambda_handler(event, context):
    users = client.list_users()
    for key in users['Users']:
        a = str(key['UserName'])
        usernames.append(a)
    for username in usernames:
        try:
            res = client.list_access_keys(UserName=username)
            accesskeydate = res['AccessKeyMetadata'][0]['CreateDate']
            accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
            currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
            accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
            currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
            active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days

            if 90 < active_days:
                a = str(username)
                c = int(int(round(active_days)))

                mylist.append(a)
                mylist.append(c)
        except:
                f = str('')

    print(mylist)
    finallist = ''.join(str(mylist))
    finallist = finallist

    sns_message = (finallist)
    response = sns.publish(
        TopicArn='arn:aws:sns:eu-west-2:111111111:sns',
        Message= sns_message,
        Subject='Access Keys which need rotating',
    )
</code>```

This returns

```<code>['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]
</code>```

And with over 100 users with Access Keys older than 90 days, this becomes very difficult to review.  How can i improve my output?

Thanks
Nick

答:
Make real pairs and use pprint (stands for pretty print).

```<code>> import pprint
> mylist = ['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]
> pprint.pprint({username: active_days for username, active_days in zip(mylist[::2], mylist[1::2])})
{'Dav.Jimmy': 469,
 'Dave.Jimmy': 102,
 'David.Jim': 123,
 'David.Jimmy': 480,
 'Jim.Dave': 103,
 'Jimmy.Dave': 179}
</code>```

Of course if you own the code it would be better to define mylist as a dictionnary from the beggining.

Body:
I have a lambda

This lambda goes off and reports on anyones access key older than a specific number of days.

import boto3, json, time, datetime, sys

sns = boto3.client('sns')
usernames = []
mylist = []

sts_client = boto3.client('sts')
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::999999999:role/role",
    RoleSessionName="AssumedRoleSession4"
)
credentials=assumed_role_object['Credentials']
client=boto3.client(
    'iam',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken'],
    )
def lambda_handler(event, context):
    users = client.list_users()
    for key in users['Users']:
        a = str(key['UserName'])
        usernames.append(a)
    for username in usernames:
        try:
            res = client.list_access_keys(UserName=username)
            accesskeydate = res['AccessKeyMetadata'][0]['CreateDate']
            accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
            currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
            accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
            currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())
            active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days

            if 90 < active_days:
                a = str(username)
                c = int(int(round(active_days)))

                mylist.append(a)
                mylist.append(c)
        except:
                f = str('')

    print(mylist)
    finallist = ''.join(str(mylist))
    finallist = finallist

    sns_message = (finallist)
    response = sns.publish(
        TopicArn='arn:aws:sns:eu-west-2:111111111:sns',
        Message= sns_message,
        Subject='Access Keys which need rotating',
    )

This returns

['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]

And with over 100 users with Access Keys older than 90 days, this becomes very difficult to review.  How can i improve my output?

Thanks
Nick

Body:
Make real pairs and use pprint (stands for pretty print).

> import pprint
> mylist = ['David.Jim', 123, 'Dav.Jimmy', 469, 'David.Jimmy', 480, 'Jim.Dave', 103, 'Dave.Jimmy', 102, 'Jimmy.Dave', 179]
> pprint.pprint({username: active_days for username, active_days in zip(mylist[::2], mylist[1::2])})
{'Dav.Jimmy': 469,
 'Dave.Jimmy': 102,
 'David.Jim': 123,
 'David.Jimmy': 480,
 'Jim.Dave': 103,
 'Jimmy.Dave': 179}

Of course if you own the code it would be better to define mylist as a dictionnary from the beggining.


问:
Which mechanism is a better way to extend Dictionary to deal with missing keys and why?
There is a minor annoyance I find myself with a lot - I have a Dictionary<TKey, TValue> that contains values that may or may not be there.

So normal behaviour would be to use the indexer, like this:

```<code>object result = myDictionary["key"];
</code>```

However, if "key" is not in the dictionary this throws a KeyNotFoundException, so you do this instead:

```<code>object val;
if (!myDictionary.TryGetValue("key", out val))
{
    val = ifNotFound;
}
</code>```

Which is fine, except that I can have a load of these in a row - TryGetValue starts to feel awful clunky.

So option 1 is an extension method:

```<code>public static TValue TryGet<TKey, TValue>(
    this Dictionary<TKey, TValue> input,
    TKey key,
    TValue ifNotFound = default(TValue))
{
    TValue val;
    if (input.TryGetValue(key, out val))
    {
        return val;
    }

    return ifNotFound;
}
</code>```

Which lets me do:

```<code>object result = myDictionary.TryGet("key1") ?? ifNotFound;

int i = anotherDictionary.TryGet("key2", -1);
</code>```

Which is simple enough, but an additional extension method with a name similar to existing instance methods potentially adds confusion and reduces maintainability. It's also not consistent with the dictionary's indexer set - that will handle missing keys.

So option 2 is a new implementation of IDictionary<TKey, TValue> with a implicit cast from Dictionary<TKey, TValue> but an indexer that returns default(TValue) instead of throwing a KeyNotFoundException.

That let's me do:

```<code>ForgivingDictionary<string, object> dict = myDictionary;

object val = dict["key"] ?? ifNotFound;

// do stuff to val, then...
dict["key"] = val;
</code>```

So now the get and set values are consistent, but value types are messier and ForgivingDictionary involves a lot more code.

Both methods seem 'messy' - is there a better way to do this already in .Net?

Both methods make compromises that could cause confusion, but is one more obvious/clear than the other? And why?

答:
When naming an extension method intended to replace an existing method, I tend to add to the method name for specificity rather than shortening it:

```<code>GetValueOrDefault(...)
</code>```

As for the ForgivingDictionary, you can constrain TKey so that it can't be a value type. However, if you must deal with value types in it, you're going to return something for a value type and the best option is to return default(TKey) since you can't return null.

Honestly, I'd go with the extension method.

Edit: GetValueOrDefault(), of course, wouldn't add to the dictionary if it didn't find the key. I would just return a default value if it wasn't found, because that's how it's named. If one wanted it to insert as well, a good name would be GetValueOrInsertDefault().

ContentLicense: CC BY-SA 3.0

Body:
There is a minor annoyance I find myself with a lot - I have a Dictionary<TKey, TValue> that contains values that may or may not be there.

So normal behaviour would be to use the indexer, like this:

object result = myDictionary["key"];

However, if "key" is not in the dictionary this throws a KeyNotFoundException, so you do this instead:

object val;
if (!myDictionary.TryGetValue("key", out val))
{
    val = ifNotFound;
}

Which is fine, except that I can have a load of these in a row - TryGetValue starts to feel awful clunky.

So option 1 is an extension method:

public static TValue TryGet<TKey, TValue>(
    this Dictionary<TKey, TValue> input,
    TKey key,
    TValue ifNotFound = default(TValue))
{
    TValue val;
    if (input.TryGetValue(key, out val))
    {
        return val;
    }

    return ifNotFound;
}

Which lets me do:

object result = myDictionary.TryGet("key1") ?? ifNotFound;

int i = anotherDictionary.TryGet("key2", -1);

Which is simple enough, but an additional extension method with a name similar to existing instance methods potentially adds confusion and reduces maintainability. It's also not consistent with the dictionary's indexer set - that will handle missing keys.

So option 2 is a new implementation of IDictionary<TKey, TValue> with a implicit cast from Dictionary<TKey, TValue> but an indexer that returns default(TValue) instead of throwing a KeyNotFoundException.

That let's me do:

ForgivingDictionary<string, object> dict = myDictionary;

object val = dict["key"] ?? ifNotFound;

// do stuff to val, then...
dict["key"] = val;

So now the get and set values are consistent, but value types are messier and ForgivingDictionary involves a lot more code.

Both methods seem 'messy' - is there a better way to do this already in .Net?

Both methods make compromises that could cause confusion, but is one more obvious/clear than the other? And why?

Body:
When naming an extension method intended to replace an existing method, I tend to add to the method name for specificity rather than shortening it:

GetValueOrDefault(...)

As for the ForgivingDictionary, you can constrain TKey so that it can't be a value type. However, if you must deal with value types in it, you're going to return something for a value type and the best option is to return default(TKey) since you can't return null.

Honestly, I'd go with the extension method.

Edit: GetValueOrDefault(), of course, wouldn't add to the dictionary if it didn't find the key. I would just return a default value if it wasn't found, because that's how it's named. If one wanted it to insert as well, a good name would be GetValueOrInsertDefault().


问:
App to run on startup for all users, but needs admin to close
I'm trying to build an application that would run on startup for all users, but non-admin users shouldn't be able to close it. I apologize if this has been answered, but I cannot find the answer even after googling it.</p>

答: The easiest way would probably be to check if the current user is an Administrator in your program's OnClose() event and cancel the event if the result is false. Check here for more details on how to do that: Check if the current user is administrator</p>


问:
unable to create diagonal histogram in seaborn
I'm trying to create a diagonal histogram using pairplot() in seaborn, below is my code:

```<code>import seaborn as sb

colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sb.load_dataset('titanic')
sb.pairplot(ds,hue='embark_town',palette=colors,kind='scatter',diag_kind='hist')
</code>```

But I'm getting the following error:

```<code>TypeError: NumPy boolean subtract, the `-` operator, is deprecated, use the bitwise_xor, the `^` operator, or the logical_xor function instead.
</code>```

Although it creates histogram diagonally but it doesn't create any non entity-relationship plots using the kind parameter. the above code works fine when I use 'kde' in diag_kind parameter.

答:
Okay, I noticed that the problem is happening due to the boolean dtype of the 'adult_male' and 'alone' column, a work-around is to change the dtype of those columns.

```<code>colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sns.load_dataset('titanic')
ds['adult_male'] = ds['adult_male'].astype(str)
ds['alone'] = ds['alone'].astype(str)
sns.pairplot(ds,hue='embark_town',palette=colors,kind='scatter', diag_kind='hist')
</code>```

Output:

Or, change to integer dtype:

```<code>colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sns.load_dataset('titanic')
ds['adult_male'] = ds['adult_male'].astype(int)
ds['alone'] = ds['alone'].astype(int)
sns.pairplot(ds,hue='embark_town',palette=colors,kind='scatter', diag_kind='hist')
</code>```

Output:

Body:
I'm trying to create a diagonal histogram using pairplot() in seaborn, below is my code:

import seaborn as sb

colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sb.load_dataset('titanic')
sb.pairplot(ds,hue='embark_town',palette=colors,kind='scatter',diag_kind='hist')

But I'm getting the following error:

TypeError: NumPy boolean subtract, the `-` operator, is deprecated, use the bitwise_xor, the `^` operator, or the logical_xor function instead.

Although it creates histogram diagonally but it doesn't create any non entity-relationship plots using the kind parameter. the above code works fine when I use 'kde' in diag_kind parameter.

Body:
Okay, I noticed that the problem is happening due to the boolean dtype of the 'adult_male' and 'alone' column, a work-around is to change the dtype of those columns.

colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sns.load_dataset('titanic')
ds['adult_male'] = ds['adult_male'].astype(str)
ds['alone'] = ds['alone'].astype(str)
sns.pairplot(ds,hue='embark_town',palette=colors,kind='scatter', diag_kind='hist')

Output:

Or, change to integer dtype:

colors = ['#c994c7','#dd1c77','#c51b8a','#fa9fb5','#9ebcda','#feb24c']

ds = sns.load_dataset('titanic')
ds['adult_male'] = ds['adult_male'].astype(int)
ds['alone'] = ds['alone'].astype(int)
sns.pairplot(ds,hue='embark_town',palette=colors,kind='scatter', diag_kind='hist')

Output:


问:
Custom CSS being overridden by Bootstrap CSS
I am using Bootstrap 3 and I have a table showing some data. in this table I have applied some JavaScript for conditional formatting, in the event that a condition is met, I set the element's class to "red"

```<code>.red {
background-color:red;
color:white;
}
</code>```

the elements HTML is as follows:

```<code><td class="red">0</td>
</code>```

I now have a conflict on odd rows the text color applies but the background color is overridden by the following  css from bootstrap.

```<code>.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
  background-color: #f9f9f9;
}
</code>```

how can I resolve this conflict and assure that the red class takes presedence?

答:
I had a similar problem, also after using !important the problem stayed.

The problem depends on which browser we are using, in my case it was Chrome.
Normally chrome stores frequently used sites and does not always fully page reload.

The issue was solved only after clearing the chrome history or Ctrl+Shift+R.

Body:
I am using Bootstrap 3 and I have a table showing some data. in this table I have applied some JavaScript for conditional formatting, in the event that a condition is met, I set the element's class to "red"

.red {
background-color:red;
color:white;
}

the elements HTML is as follows:

0

I now have a conflict on odd rows the text color applies but the background color is overridden by the following  css from bootstrap.

.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
  background-color: #f9f9f9;
}

how can I resolve this conflict and assure that the red class takes presedence?


问:
How to move dataframe variable names to first row and add new variable names to multiple dataframes in a list?

library(purrr)
library(tibble)
library(dplyr)
```

<p>Starting list of dataframes</p>

```lst <- list(df1 = data.frame(X.1 = as.character(1:2),
                             heading = letters[1:2]),
            df2 =  data.frame(X.32 = as.character(3:4),
                              another.topic = paste("Line ", 1:2)))

lst
#> $df1
#>   X.1 heading
#> 1   1       a
#> 2   2       b
#>
#> $df2
#>   X.32 another.topic
#> 1    3       Line  1
#> 2    4       Line  2
```

<p>Expected "combined" dataframe, with  new consistent variable names, and old variable names in the first row of each constituent dataframe.</p>

```#>    id   h1            h2
#> 1 df1  X.1       heading
#> 2 df1    1             a
#> 3 df1    2             b
#> 4 df2 X.32 another.topic
#> 5 df2    3       Line  1
#> 6 df2    4       Line  2

```

<p><code>add_row</code> requires "Name-value pairs, passed on to tibble(). Values can be defined only for columns that already exist in .data and unset columns will get an NA value."</p>

<p>Which is what I think I have achieved with this:</p>

```df_nms <-
  map(lst, names) %>%
  map(set_names)

#> $df1
#>       X.1   heading
#>     "X.1" "heading"
#>
#> $df2
#>            X.32   another.topic
#>          "X.32" "another.topic"

```

<p>But I cannot tie up the last bit, using a purrr function to add the names to the head of each dataframe. I've tried numerous variations with <code>map2</code> and <code>pmap</code>  the closest I can get at present (if I treat <code>add_row</code> as a formula , prefixing it with <code>~</code> and remove the <code>.y</code> I get a new first row populated with NAs). I think I'm missing how to pass the name-value pairs to the add_row function.</p>

```map2(lst, df_nms, add_row(.x, .y, .before = 1)) %>%
  map(set_names, c("h1", "h2")) %>%
  map_dfr(bind_rows, .id = "id")
#> Error in add_row(.x, .y, .before = 1): object '.x' not found

```

A pointer to resolve this last step would be most appreciated.

答:
Here's an approach using map, rbindlist from data.table and some base R functions:

```<code>library(purrr)
library(dplyr)
library(data.table)
map(lst, ~ as.data.frame(unname(rbind(colnames(.x),as.matrix(.x))))) %>%
  rbindlist(idcol = "id")
#    id   V1            V2
#1: df1  X.1       heading
#2: df1    1             a
#3: df1    2             b
#4: df2 X.32 another.topic
#5: df2    3       Line  1
#6: df2    4       Line  2
</code>```

Alternatively we could use map_df if we use colnames<-:

```<code>map_df(lst, ~ as.data.frame(rbind(colnames(.x),as.matrix(.x))) %>%
         `colnames<-`(.,paste0("h",seq(1,dim(.)[2]))), .id = "id")
#   id   h1            h2
#1 df1  X.1       heading
#2 df1    1             a
#3 df1    2             b
#4 df2 X.32 another.topic
#5 df2    3       Line  1
#6 df2    4       Line  2
</code>```

Key things here are:

Use as.matrix to get rid of the factor / character incompatibility.

Remove names with unname or set them with colnames<-

Use the idcols = or .id = feature to get the names of the list as a column.

Body:
library(purrr)
library(tibble)
library(dplyr)

Starting list of dataframes

lst <- list(df1 = data.frame(X.1 = as.character(1:2),
                             heading = letters[1:2]),
            df2 =  data.frame(X.32 = as.character(3:4),
                              another.topic = paste("Line ", 1:2)))

lst
#> $df1
#>   X.1 heading
#> 1   1       a
#> 2   2       b
#>
#> $df2
#>   X.32 another.topic
#> 1    3       Line  1
#> 2    4       Line  2

Expected "combined" dataframe, with  new consistent variable names, and old variable names in the first row of each constituent dataframe.

#>    id   h1            h2
#> 1 df1  X.1       heading
#> 2 df1    1             a
#> 3 df1    2             b
#> 4 df2 X.32 another.topic
#> 5 df2    3       Line  1
#> 6 df2    4       Line  2

add_row requires "Name-value pairs, passed on to tibble(). Values can be defined only for columns that already exist in .data and unset columns will get an NA value."

Which is what I think I have achieved with this:

df_nms <-
  map(lst, names) %>%
  map(set_names)

#> $df1
#>       X.1   heading
#>     "X.1" "heading"
#>
#> $df2
#>            X.32   another.topic
#>          "X.32" "another.topic"

But I cannot tie up the last bit, using a purrr function to add the names to the head of each dataframe. I've tried numerous variations with map2 and pmap  the closest I can get at present (if I treat add_row as a formula , prefixing it with ~ and remove the .y I get a new first row populated with NAs). I think I'm missing how to pass the name-value pairs to the add_row function.

map2(lst, df_nms, add_row(.x, .y, .before = 1)) %>%
  map(set_names, c("h1", "h2")) %>%
  map_dfr(bind_rows, .id = "id")
#> Error in add_row(.x, .y, .before = 1): object '.x' not found

A pointer to resolve this last step would be most appreciated.

Body:
Here's an approach using map, rbindlist from data.table and some base R functions:

library(purrr)
library(dplyr)
library(data.table)
map(lst, ~ as.data.frame(unname(rbind(colnames(.x),as.matrix(.x))))) %>%
  rbindlist(idcol = "id")
#    id   V1            V2
#1: df1  X.1       heading
#2: df1    1             a
#3: df1    2             b
#4: df2 X.32 another.topic
#5: df2    3       Line  1
#6: df2    4       Line  2

Alternatively we could use map_df if we use colnames<-:

map_df(lst, ~ as.data.frame(rbind(colnames(.x),as.matrix(.x))) %>%
         `colnames<-`(.,paste0("h",seq(1,dim(.)[2]))), .id = "id")
#   id   h1            h2
#1 df1  X.1       heading
#2 df1    1             a
#3 df1    2             b
#4 df2 X.32 another.topic
#5 df2    3       Line  1
#6 df2    4       Line  2

Key things here are:

Use as.matrix to get rid of the factor / character incompatibility.

Remove names with unname or set them with colnames<-

Use the idcols = or .id = feature to get the names of the list as a column.


问:
How to set the output path of several visual C# projects
I have a solution that contains several c# projects and I would like to be able to set the output path and other properties on all the projects together in a single place. Property Sheets (vsprops) do not seem to be able available for C# projects and the $(SolutionDir) variable is ignored. Are there any other methods to set properties across several C# projects?

Update
By Following the information in the answer by Bas Bossink I was able to set the output path of several projects by creating a common csproj and importing it into the individual project. A few other points:

When building in Visual Studio if changes are made to the common project it is necessary to touch/reload any projects that reference it for the changes to be picked up.

Any properties which are also set in a individual project will override the common properties.

Setting $(SolutionDir) as the output path via the Visual Studio UI does not work as expected because the value is treated as a string literal rather than getting expanded. However, Setting $(SolutionDir) directly into the csproj file with a text editor works as expected.

答:
Unfortunately, these bits of information such as output path are all stored inside the individual *.csproj files. If you want to batch-update a whole bunch of those, you'll have to revert to some kind of a text-updating tool or create a script to touch each of those files.

For things like this (apply changes to a bunch of text files at once) I personally use WildEdit by Helios Software - works like a charm and it's reasonably priced.

But I'm sure there are tons of free alternatives out there, too.

OwnerDisplayName: edobashira

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: edobashira


问:
ScrollView problem in Motorola Milestone
I have multiple listviews, all of them with scrollbars. Everything works great, tested in alot of emulators and a couple of phones... except in Motorola Milestone with 2.1. As i said, i tried it with the emulator in 2.1 and newer (i'm using 1.6 SDK) and i had no problem whatsoever, except when i try it with a physical Milestone. There, the scrollbar doesn't shows and, more important, i can't even scroll on the ListView.

Anyone has a clue on why is this happening?

答:
Turns out it was a 2.x thing. My layout had

```<code><scrollview>
    <listview/>
</scrollview>
</code>```

so my scroll stopped working. The phones i had in that time where all 1.x, the only with a 2.x system was the Milestone and hence the illusion that it was a Milestone problem. Weird thing is, in 2.x emulator it worked fine, so i assumed it wasn't a 2.x problem, i thought that simulator behavor would be consistent with phone behavor.

Body:
Turns out it was a 2.x thing. My layout had

<scrollview>
    <listview/>
</scrollview>

so my scroll stopped working. The phones i had in that time where all 1.x, the only with a 2.x system was the Milestone and hence the illusion that it was a Milestone problem. Weird thing is, in 2.x emulator it worked fine, so i assumed it wasn't a 2.x problem, i thought that simulator behavor would be consistent with phone behavor.


问:
The range library implementation of the copy algorithm
I am building some snippets that should work with both the C++20 Ranges library and the range-v3 library and I noticed some differences in the implementation of the copy algorithm.

The following code using C++20 ranges library (from the Standard Library), compiles with GCC 11 (and prints 1 2 3 4 5).

```<code>#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>

int main()
{
    std::vector<int> arr {1, 2, 3, 4, 5};
    std::ranges::copy(arr, std::ostream_iterator<int>(std::cout, " "));
}
</code>```

Here is a link: https://wandbox.org/permlink/V13bdDoxSYjqDW3m

The same code, using the range-v3 library, fails to compile with VC++ 2019 16.5:

```<code>#include <iostream>
#include <vector>
#include "range/v3/algorithm/copy.hpp"

int main()
{
    std::vector<int> arr {1, 2, 3, 4, 5};
    ranges::copy(arr, std::ostream_iterator<int>(std::cout, " "));
}
</code>```

With the following errors:

```<code>main.cpp(134,9): error C2672: 'operator __surrogate_func': no matching overloaded function found
main.cpp(134,59): error C7602: 'ranges::_copy::copy_fn::operator ()': the associated constraints are not satisfied
range-v3-master\include\range/v3/algorithm/copy.hpp(57): message : see declaration of 'ranges::_copy::copy_fn::operator ()'
main.cpp(134,59): error C2780: 'ranges::detail::in_out_result<I,O> ranges::_copy::copy_fn::operator ()(I,S,O) const': expects 3 arguments - 2 provided
range-v3-master\include\range/v3/algorithm/copy.hpp(45): message : see declaration of 'ranges::_copy::copy_fn::operator ()'
</code>```

There is a unit test in the range-v3 library, which is very similar:

```<code>using namespace ranges;
std::ostringstream sout;
std::vector<int> copy_vec{1,1,1,1,1};
copy(copy_vec, ostream_iterator<>(sout, " "));
CHECK(sout.str() == "1 1 1 1 1 ");
</code>```

If I try is with Compiler Explorer, it does not compile with any compiler (gcc, Clang, VC++). The gcc errors are:

```<code>note:   candidate expects 1 argument, 2 provided
note:   candidate expects 3 arguments, 2 provided
error: no match for call to '(const ranges::copy_fn) (std::vector<int>&, std::ostream_iterator<int>)'
required from here
</code>```

These are basically the same errors that I see in VC++ for my snippet.

Here is a link: https://godbolt.org/z/pEfBb4

I would expect these two would work interchangeably. Why is it no so?

答:
Just to clarify for others looking at the question:

The unit test work because its ranges::ostream_iterator and not std::ostream_iterator that is used in that snippet.

The std::ostream_iterator does not work because it doesn't satisfy the range Iterator concept since it's not default constructible.

Body:
I am building some snippets that should work with both the C++20 Ranges library and the range-v3 library and I noticed some differences in the implementation of the copy algorithm.

The following code using C++20 ranges library (from the Standard Library), compiles with GCC 11 (and prints 1 2 3 4 5).

#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>

int main()
{
    std::vector<int> arr {1, 2, 3, 4, 5};
    std::ranges::copy(arr, std::ostream_iterator<int>(std::cout, " "));
}

Here is a link: https://wandbox.org/permlink/V13bdDoxSYjqDW3m

The same code, using the range-v3 library, fails to compile with VC++ 2019 16.5:

#include <iostream>
#include <vector>
#include "range/v3/algorithm/copy.hpp"

int main()
{
    std::vector<int> arr {1, 2, 3, 4, 5};
    ranges::copy(arr, std::ostream_iterator<int>(std::cout, " "));
}

With the following errors:

main.cpp(134,9): error C2672: 'operator __surrogate_func': no matching overloaded function found
main.cpp(134,59): error C7602: 'ranges::_copy::copy_fn::operator ()': the associated constraints are not satisfied
range-v3-master\include\range/v3/algorithm/copy.hpp(57): message : see declaration of 'ranges::_copy::copy_fn::operator ()'
main.cpp(134,59): error C2780: 'ranges::detail::in_out_result ranges::_copy::copy_fn::operator ()(I,S,O) const': expects 3 arguments - 2 provided
range-v3-master\include\range/v3/algorithm/copy.hpp(45): message : see declaration of 'ranges::_copy::copy_fn::operator ()'

There is a unit test in the range-v3 library, which is very similar:

using namespace ranges;
std::ostringstream sout;
std::vector<int> copy_vec{1,1,1,1,1};
copy(copy_vec, ostream_iterator<>(sout, " "));
CHECK(sout.str() == "1 1 1 1 1 ");

If I try is with Compiler Explorer, it does not compile with any compiler (gcc, Clang, VC++). The gcc errors are:

note:   candidate expects 1 argument, 2 provided
note:   candidate expects 3 arguments, 2 provided
error: no match for call to '(const ranges::copy_fn) (std::vector<int>&, std::ostream_iterator<int>)'
required from here

These are basically the same errors that I see in VC++ for my snippet.

Here is a link: https://godbolt.org/z/pEfBb4

I would expect these two would work interchangeably. Why is it no so?


问:
How to reference System.Windows namespace in .Net Core?
I'm a long time WPF (.Net Framework) developer finally dipping my toes into .Net Core for the first time. I'm currently trying to convert a small v4.7.2 WPF application to .Net Core 3.1. The solution contains a WPF app project and a class library project, with only a handful of classes each, so I decided it would be easier to create a new solution containing a WPF app and class library project (both .Net Core 3.1), then copy the cs and xaml files from the original solution. However I seem to be falling at the first hurdle...

Many of the classes use types from the System.Windows namespace (and System.Windows.Media, System.Windows.Controls, etc). These resolve fine in the WPF app project but not the class library. I've noticed the WPF app project has a reference to the framework "Microsoft.WindowsDesktop.App.Wpf", but the class library project doesn't, which I assume is my problem. However I can't for the life of me figure out how to add this framework into the project. How do I do it?!

I've seen solutions elsewhere of adding <UseWPF>true</UseWPF> to the class lib csproj file, but this has no effect.

答:
As usual, no sooner do I post the question than I find the answer. I also had to change the SDK in the csproj file to:</p>

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
</code>```

Body:
As usual, no sooner do I post the question than I find the answer. I also had to change the SDK in the csproj file to:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">


问:
Can I put all the information for a DocuSign envelope into a Word document without using the DocuSign API?
I would like to mark up an MS Word document with all of the information necessary to upload to DocuSign. Specifically, I want to include all the information required for the DocuSign envelope, and also the places where the signatures need to go. I then want to upload that document, either via the API, or the DocuSign web site, and not have any further need to specify the envelope or the signature locations - I would like my markup to be recognised by DocuSign and acted on without any further interaction. It would, of course, mean that there needs to be some way of conveying to DocuSign what this markup is, or else to conform to some pre-defined DocuSign markup.

I have spoken to DocuSign support and they don't really understand the question, but maybe someone here has tried it, or can give a definitive answer as to whether I am asking for a feature that does or does not exist.

If that feature is not there, then we will build it using the DocuSign API, but if there is a wheel, we don't want to reinvent it.

答:
reading this it sounds like you want your doc to auto-tag this info should help you on your way: https://support.docusign.com/en/guides/AutoPlace-New-DocuSign-Experience

If not, the OOTB function within DocuSign templates you can create the tag (signature) on your word doc and save it in the DocuSign website where you will get the template ID that you can use.


问:
Javascript Object to Array
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

```<code>[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]
</code>```

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

```<code>if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;
</code>```

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

答:
There is a nice JavaScript library called Undersore.js which does all kind of object/array manipulations.

Using it you could do the conversion as easy as this

```<code>_(json).each(function(elem, key){
    json[key] = _(elem).values();
});
</code>```

Title: Javascript Object to Array

Body:
I'm having some problems with converting some JSON and I'm after some help.  This is my problem, I have JSON returned the following:

Example of the JSON recieved (from a CSV file):

[
    {
        "rating": "0",
        "title": "The Killing Kind",
        "author": "John Connolly",
        "type": "Book",
        "asin": "0340771224",
        "tags": "",
        "review": "i still haven't had time to read this one..."
    },
    {
        "rating": "0",
        "title": "The Third Secret",
        "author": "Steve Berry",
        "type": "Book",
        "asin": "0340899263",
        "tags": "",
        "review": "need to find time to read this book"
    },

    cut for brevity

]

Now, this is a one dimensional array of objects, but I have a function that I need to pass this to that will ONLY take a multidimensional array.  There's nothing I can change on this.  I've been looking around the web for conversion and came across this code:

if (! obj.length) { return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;

But my code keeps getting stuck on the "no object length" part.  When I iterate through each object, I get character by character.  Unfortunately, those field names (rating, title, author), etc are not set in stone and I can't access anything using the obj.Field notation.

I'm stuck on this; is there a way to convert those objects into arrays, or do I have to go back to the beginning and dump JSON?

Body:
There is a nice JavaScript library called Undersore.js which does all kind of object/array manipulations.

Using it you could do the conversion as easy as this

_(json).each(function(elem, key){
    json[key] = _(elem).values();
});


问:
How to get current CoreData item in onDelete
There two entities Parent and Child, which is one to many relationship. One Parent and many Child.

I use EditMode to delete Child data like:

```<code>@ObservedObject private var db = CoreDataDB<Child>(predicate: "parent")

var body: some View {

    VStack {
        Form {

            Section(header: Text("Title")) {
                ForEach(db.loadDB(relatedTo: parent)) { child in

                    if self.editMode == .active {
                        ChildListCell(name: child.name, order: child.order)
                    } else {
                        ...
                    }
                }
                .onDelete { indices in
                  // how to know which child is by indices here ???
                  let thisChild = child // <-- this is wrong!!!

                  self.db.deleting(at: indices)
                }
            }
        }
    }
}
</code>```

The deleting method is defined in another Class like:

```<code>public func deleting(at indexset: IndexSet) {

    CoreData.executeBlockAndCommit {

        for index in indexset {
            CoreData.stack.context.delete(self.fetchedObjects[index])
        }
    }
}
</code>```

And I also want to update other Attribute of Parent and Child Entities when onDelete occurs. But I have to locate the current Child item which is deleted. How to make it?

Thanks for any help.

答:
Here is possible approach... (assuming your .loadDB returns array, but in general similar will work with any random access collection)

Tested with Xcode 11.4 (using regular array of items)

```<code>var body: some View {
    VStack {
        Form {
            Section(header: Text("Title")) {
                // separate to standalone function...
                self.sectionContent(with: db.loadDB(relatedTo: parent))
            }
        }
    }
}

// ... to have access to shown container
private func sectionContent(with children: [Child]) -> some View {
    // now we have access to children container in internal closures
    ForEach(children) { child in

        if self.editMode == .active {
            ChildListCell(name: child.name, order: child.order)
        } else {
            ...
        }
    }
    .onDelete { indices in

        // children, indices, and child by index are all valid here
        if let first = indices.first {
            let thisChild = children[first]       // << here !!
            // do something here
        }

        self.db.deleting(at: indices)
    }
}
</code>```

Body:
There two entities Parent and Child, which is one to many relationship. One Parent and many Child.

I use EditMode to delete Child data like:

@ObservedObject private var db = CoreDataDB<Child>(predicate: "parent")

var body: some View {

    VStack {
        Form {

            Section(header: Text("Title")) {
                ForEach(db.loadDB(relatedTo: parent)) { child in

                    if self.editMode == .active {
                        ChildListCell(name: child.name, order: child.order)
                    } else {
                        ...
                    }
                }
                .onDelete { indices in
                  // how to know which child is by indices here ???
                  let thisChild = child // <-- this is wrong!!!

                  self.db.deleting(at: indices)
                }
            }
        }
    }
}

The deleting method is defined in another Class like:

public func deleting(at indexset: IndexSet) {

    CoreData.executeBlockAndCommit {

        for index in indexset {
            CoreData.stack.context.delete(self.fetchedObjects[index])
        }
    }
}

And I also want to update other Attribute of Parent and Child Entities when onDelete occurs. But I have to locate the current Child item which is deleted. How to make it?

Thanks for any help.

Body:
Here is possible approach... (assuming your .loadDB returns array, but in general similar will work with any random access collection)

Tested with Xcode 11.4 (using regular array of items)

var body: some View {
    VStack {
        Form {
            Section(header: Text("Title")) {
                // separate to standalone function...
                self.sectionContent(with: db.loadDB(relatedTo: parent))
            }
        }
    }
}

// ... to have access to shown container
private func sectionContent(with children: [Child]) -> some View {
    // now we have access to children container in internal closures
    ForEach(children) { child in

        if self.editMode == .active {
            ChildListCell(name: child.name, order: child.order)
        } else {
            ...
        }
    }
    .onDelete { indices in

        // children, indices, and child by index are all valid here
        if let first = indices.first {
            let thisChild = children[first]       // << here !!
            // do something here
        }

        self.db.deleting(at: indices)
    }
}


问:
Find correct regex
I'm trying to find the correct regex for this case:

???-1.1.0-???

I need prefix and suffix between version, ? can be everything (letter, number or nothing)

What I have :

```<code>static check(version: string) {
    return /-(\d+)\.(\d+)\.(\d+)-$/.test(version);
}
</code>```

THanks for your help :)

答:
Wouldn't "???-1-" still be the "prefix", there is no way to tell by a simple regex, you will need to capture everything between number, dot, number, etc... until you meet another dash.

Breakdown

There are three groups: the prefix (optional), version, and suffix (also optional).

([a-z][a-z-]*\-)?

Starts with a letter, followed by zero or more letters and dashes, ending with a dash

([0-9][0-9.]*)

Starts with a number, followed by zero or more numbers and dot-literals

(\-[a-z][a-z-]*)?

Starts with a dash, followed by a letter and zero or more letters and dashes

Unit tests

const VERSION_PATTERN = /([a-z][a-z-]*\-)?([0-9][0-9.]*)(\-[a-z][a-z-]*)?/i;

const isVersionValid = (version) =>  VERSION_PATTERN.test(version);

const testCases = [
  { version: 'toto-1-1.0-toto', valid : true  },
  { version: 'toto-1-1.0'     , valid : true  },
  { version: '1-1.0-toto'     , valid : true  },
  { version: '1-1.0'          , valid : true  },
  { version: 'toto'           , valid : false },
];

mocha.setup("bdd");
chai.should();

testCases.forEach(testCase => {
  describe("Validity test", function() {
      it(`"${testCase.version}" is ${testCase.valid ? 'valid' : 'invalid'}`, () => {
          isVersionValid(testCase.version).should.equal(testCase.valid);
      });
  });
});

mocha.run();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.2.0/chai.js"></script>

<div id="mocha"></div></code>```

Title: Find correct regex

Body:
I'm trying to find the correct regex for this case:

???-1.1.0-???

I need prefix and suffix between version, ? can be everything (letter, number or nothing)

What I have :

static check(version: string) {
    return /-(\d+)\.(\d+)\.(\d+)-$/.test(version);
}

THanks for your help :)

Body:
Wouldn't "???-1-" still be the "prefix", there is no way to tell by a simple regex, you will need to capture everything between number, dot, number, etc... until you meet another dash.

Breakdown

There are three groups: the prefix (optional), version, and suffix (also optional).

([a-z][a-z-]*\-)?

Starts with a letter, followed by zero or more letters and dashes, ending with a dash

([0-9][0-9.]*)

Starts with a number, followed by zero or more numbers and dot-literals

(\-[a-z][a-z-]*)?

Starts with a dash, followed by a letter and zero or more letters and dashes

Unit tests

const VERSION_PATTERN = /([a-z][a-z-]*\-)?([0-9][0-9.]*)(\-[a-z][a-z-]*)?/i;

const isVersionValid = (version) =>  VERSION_PATTERN.test(version);

const testCases = [
  { version: 'toto-1-1.0-toto', valid : true  },
  { version: 'toto-1-1.0'     , valid : true  },
  { version: '1-1.0-toto'     , valid : true  },
  { version: '1-1.0'          , valid : true  },
  { version: 'toto'           , valid : false },
];

mocha.setup("bdd");
chai.should();

testCases.forEach(testCase => {
  describe("Validity test", function() {
      it(`"${testCase.version}" is ${testCase.valid ? 'valid' : 'invalid'}`, () => {
          isVersionValid(testCase.version).should.equal(testCase.valid);
      });
  });
});

mocha.run();

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.2.5/mocha.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.2.0/chai.js"></script>

<div id="mocha"></div>


问:
What services let me query big data and let me provide a non-simple query code
I would like to create huge data sets (25 ints a row, 30 rows per second, multiply that by 60).
On the other hand, I want to query it for rows that match a certain condition (e.g. rows that not more than 5 ints of the 25 are out of a certain range).

And I want it all in real time, i.e. inserting and querying continuously.

Does someone know how to do it, preferably using a cloud service (Amazon? Google?)

Thanks

答: Try one-tick, though its designed for market pricing data, I think it can be adapted to other forms of high frequency data. You can then build filtering/aggregation rules that can help you analyze the data</p>


问:
Filter the dataframe according to a list of dates
I have the following dataframe for weather stations (short dataframe):

```<code>      import pandas as pd
      import numpy as np

      df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                                 'Qtd_Instrumentation': [18, 5, 25, 10],
                                  'Year_Construction': [2015, 2008, 2016, 2020]})
</code>```

I would like to generate a new dataframe. This would need to be filtered by the year the station was built. I tried to create a list containing the objective years and build the df_ as follows:

```<code>      list_years = [2015, 2016, 2017, 2018, 2019, 2020]
      df_Filter =  df_Station[df_Station['Year_Construction'] == list_years]
</code>```

However, this code has the error: ValueError: Lengths must match to compare

I would like the output (df_Filter) to be:

```<code>            print(df_Filter)

            Hemisphere  Qtd_Instrumentation Year_Construction
               North            18              2015
               North            25              2016
               South            10              2020
</code>```

Thank you.

答:
```<code>import pandas as pd

df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                           'Qtd_Instrumentation': [18, 5, 25, 10],
                           'Year_Construction': [2015, 2008, 2016, 2020]})

list_years = [2015, 2016, 2017, 2018, 2019, 2020]
df_Filter = df_Station[df_Station['Year_Construction'].isin(list_years)]

print(df_Filter)
</code>```

Output

```<code>  Hemisphere  Qtd_Instrumentation  Year_Construction
0      North                   18               2015
2      North                   25               2016
3      South                   10               2020
</code>```

Body:
I have the following dataframe for weather stations (short dataframe):

      import pandas as pd
      import numpy as np

      df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                                 'Qtd_Instrumentation': [18, 5, 25, 10],
                                  'Year_Construction': [2015, 2008, 2016, 2020]})

I would like to generate a new dataframe. This would need to be filtered by the year the station was built. I tried to create a list containing the objective years and build the df_ as follows:

      list_years = [2015, 2016, 2017, 2018, 2019, 2020]
      df_Filter =  df_Station[df_Station['Year_Construction'] == list_years]

However, this code has the error: ValueError: Lengths must match to compare

I would like the output (df_Filter) to be:

            print(df_Filter)

            Hemisphere  Qtd_Instrumentation Year_Construction
               North            18              2015
               North            25              2016
               South            10              2020

Thank you.

Body:
import pandas as pd

df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                           'Qtd_Instrumentation': [18, 5, 25, 10],
                           'Year_Construction': [2015, 2008, 2016, 2020]})

list_years = [2015, 2016, 2017, 2018, 2019, 2020]
df_Filter = df_Station[df_Station['Year_Construction'].isin(list_years)]

print(df_Filter)

Output

  Hemisphere  Qtd_Instrumentation  Year_Construction
0      North                   18               2015
2      North                   25               2016
3      South                   10               2020


问:
How to convert a targeting code in python to kotlin?
I am developing an image segmentation application that will use watersheds. For that, I found a code that I will need to use in python. However, I'm having a hard time converting to kotlin, as the Mat Mat () doesn't have the zero_likes function, just the zero function. I am using opencv 3.31. How do I do this check in kotlin:

```<code>marked[marked == 1] = 0
marked[marked > 1] = 255
</code>```

Code python:

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

# Load the image
img = cv2.imread("/path/to/image.png", 3)

# Create a blank image of zeros (same dimension as img)
# It should be grayscale (1 color channel)
marker = np.zeros_like(img[:,:,0]).astype(np.int32)

# This step is manual. The goal is to find the points
# which create the result we want. I suggest using a
# tool to get the pixel coordinates.

# Dictate the background and set the markers to 1
marker[204][95] = 1
marker[240][137] = 1
marker[245][444] = 1
marker[260][427] = 1
marker[257][378] = 1
marker[217][466] = 1

# Dictate the area of interest
# I used different values for each part of the car (for visibility)
marker[235][370] = 255    # car body
marker[135][294] = 64     # rooftop
marker[190][454] = 64     # rear light
marker[167][458] = 64     # rear wing
marker[205][103] = 128    # front bumper

# rear bumper
marker[225][456] = 128
marker[224][461] = 128
marker[216][461] = 128

# front wheel
marker[225][189] = 192
marker[240][147] = 192

# rear wheel
marker[258][409] = 192
marker[257][391] = 192
marker[254][421] = 192

# Now we have set the markers, we use the watershed
# algorithm to generate a marked image
marked = cv2.watershed(img, marker)

# Plot this one. If it does what we want, proceed;
# otherwise edit your markers and repeat
plt.imshow(marked, cmap='gray')
plt.show()

# Make the background black, and what we want to keep white
marked[marked == 1] = 0
marked[marked > 1] = 255

# Use a kernel to dilate the image, to not lose any detail on the outline
# I used a kernel of 3x3 pixels
kernel = np.ones((3,3),np.uint8)
dilation = cv2.dilate(marked.astype(np.float32), kernel, iterations = 1)

# Plot again to check whether the dilation is according to our needs
# If not, repeat by using a smaller/bigger kernel, or more/less iterations
plt.imshow(dilation, cmap='gray')
plt.show()

# Now apply the mask we created on the initial image
final_img = cv2.bitwise_and(img, img, mask=dilation.astype(np.uint8))

# cv2.imread reads the image as BGR, but matplotlib uses RGB
# BGR to RGB so we can plot the image with accurate colors
b, g, r = cv2.split(final_img)
final_img = cv2.merge([r, g, b])

# Plot the final result
plt.imshow(final_img)
plt.show()
</code>```

code kotlin:

```<code> // Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)

    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
        for(y in my_canvas.pointsToDrawY.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(y).toInt(),
                255.0
            )
        }
    }
    //Now we have set the markers, we use the watershed
    //algorithm to generate a marked image
    Imgproc.watershed(srcOriginal, markers)
    val marker_tempo = Mat()
    markers.convertTo(marker_tempo, CvType.CV_8U)
    // Plot this one. If it does what we want, proceed;
    // otherwise edit your markers and repeat
    //Create Bitmap
    val bmpOut = Bitmap.createBitmap(srcOriginal.cols(), srcOriginal.rows(), Bitmap.Config.RGB_565)
    Utils.matToBitmap(marker_tempo, bmpOut)
    val mPath = Environment.getExternalStorageDirectory().toString() + "/gray.png"
    Imgcodecs.imwrite(mPath,marker_tempo)
    //Make the background black, and what we want to keep white

    //Use a kernel to dilate the image, to not lose any detail on the outline
    //I used a kernel of 3x3 pixels
    val kernel = Mat(3, 3, CvType.CV_8U)
    val dilatation = Imgproc.dilate(marker_tempo, marker_tempo, kernel)
    val mPath1 = Environment.getExternalStorageDirectory().toString() + "/dilation.png"
    Imgcodecs.imwrite(mPath1,marker_tempo)
    //Now apply the mask we created on the initial image
    val final_image = Core.bitwise_and(srcOriginal, srcOriginal, dilatation)
    //cv2.imread reads the image as BGR, but matplotlib uses RGB
    //BGR to RGB so we can plot the image with accurate colors
</code>```

In pointsToDrawX and pointsToDrawY I'm saving all the x, y coordinates of the user's touch event on the screen. It is from these coordinates that I will pass to the watershed algorithm to perform the segmentation and remove the background from the image. Can someone help me convert this code?

答:
```<code>//Load the image
srcOriginal = Imgcodecs.imread(currentPhotoPath)

//Create a blank image of zeros (same dimension as img)
//It should be grayscale (1 color channel)
markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

//This step is manual. The goal is to find the points
//which create the result we want. I suggest using a
//tool to get the pixel coordinates.
//Dictate the background and set the markers to 1
for (value in 0..my_canvas.pointsToDrawY.size - 1) {
        markers.put(
            my_canvas.pointsToDrawX[value].toInt(),
            my_canvas.pointsToDrawY[value].toInt(),
            1.0
       )
}
//Dictate the area of interest
//I used different values for each part of the car (for visibility)
for (value in 0..my_canvas.pointsToDrawYStepTwo.size - 1) {
        markers.put(
            my_canvas.pointsToDrawXStepTwo[value].toInt(),
            my_canvas.pointsToDrawYStepTwo[value].toInt(),
            255.0
        )
}

//Now we have set the markers, we use the watershed
//algorithm to generate a marked image
watershed(srcOriginal, markers)
//Plot this one. If it does what we want, proceed;
//otherwise edit your markers and repeat
val mPath1 = Environment.getExternalStorageDirectory().toString() + "/watershed.png"
    Imgcodecs.imwrite(mPath1,markers)
//Make the background black, and what we want to keep white
for (x in 0 until srcOriginal.rows()-1) {
        for (y in 0 until srcOriginal.cols()-1) {
            if(markers.get(x,y).get(0).equals(1.0)){
                markers.put(
                    x,
                    y,
                    0.0
                )
            }
            if((markers[x, y].get(0) == 255.0)){
                markers.put(
                    x,
                    y,
                    255.0
                )
            }
        }
    }

//Use a kernel to dilate the image, to not lose any detail on the outline
//I used a kernel of 3x3 pixels
val marker_tempo = Mat()
val dilatation = Mat()
markers.convertTo(marker_tempo, CvType.CV_8U)
val kernel = Mat(3, 3, CvType.CV_8U)
Imgproc.dilate(marker_tempo, dilatation, kernel)
//Plot again to check whether the dilation is according to our needs
//If not, repeat by using a smaller/bigger kernel, or more/less iterations
val mPath2 = Environment.getExternalStorageDirectory().toString() + "/dilatation.png"
Imgcodecs.imwrite(mPath2,dilatation)
//Now apply the mask we created on the initial image
val final = Mat()
Core.bitwise_and(srcOriginal, srcOriginal, final, dilatation)
//Plot the final result
val mPath = Environment.getExternalStorageDirectory().toString() + "/final.png"
Imgcodecs.imwrite(mPath,final)
</code>```

Body:
I am developing an image segmentation application that will use watersheds. For that, I found a code that I will need to use in python. However, I'm having a hard time converting to kotlin, as the Mat Mat () doesn't have the zero_likes function, just the zero function. I am using opencv 3.31. How do I do this check in kotlin:

marked[marked == 1] = 0
marked[marked > 1] = 255

Code python:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = cv2.imread("/path/to/image.png", 3)

# Create a blank image of zeros (same dimension as img)
# It should be grayscale (1 color channel)
marker = np.zeros_like(img[:,:,0]).astype(np.int32)

# This step is manual. The goal is to find the points
# which create the result we want. I suggest using a
# tool to get the pixel coordinates.

# Dictate the background and set the markers to 1
marker[204][95] = 1
marker[240][137] = 1
marker[245][444] = 1
marker[260][427] = 1
marker[257][378] = 1
marker[217][466] = 1

# Dictate the area of interest
# I used different values for each part of the car (for visibility)
marker[235][370] = 255    # car body
marker[135][294] = 64     # rooftop
marker[190][454] = 64     # rear light
marker[167][458] = 64     # rear wing
marker[205][103] = 128    # front bumper

# rear bumper
marker[225][456] = 128
marker[224][461] = 128
marker[216][461] = 128

# front wheel
marker[225][189] = 192
marker[240][147] = 192

# rear wheel
marker[258][409] = 192
marker[257][391] = 192
marker[254][421] = 192

# Now we have set the markers, we use the watershed
# algorithm to generate a marked image
marked = cv2.watershed(img, marker)

# Plot this one. If it does what we want, proceed;
# otherwise edit your markers and repeat
plt.imshow(marked, cmap='gray')
plt.show()

# Make the background black, and what we want to keep white
marked[marked == 1] = 0
marked[marked > 1] = 255

# Use a kernel to dilate the image, to not lose any detail on the outline
# I used a kernel of 3x3 pixels
kernel = np.ones((3,3),np.uint8)
dilation = cv2.dilate(marked.astype(np.float32), kernel, iterations = 1)

# Plot again to check whether the dilation is according to our needs
# If not, repeat by using a smaller/bigger kernel, or more/less iterations
plt.imshow(dilation, cmap='gray')
plt.show()

# Now apply the mask we created on the initial image
final_img = cv2.bitwise_and(img, img, mask=dilation.astype(np.uint8))

# cv2.imread reads the image as BGR, but matplotlib uses RGB
# BGR to RGB so we can plot the image with accurate colors
b, g, r = cv2.split(final_img)
final_img = cv2.merge([r, g, b])

# Plot the final result
plt.imshow(final_img)
plt.show()

code kotlin:

 // Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)

    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32S)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
        for(y in my_canvas.pointsToDrawY.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(y).toInt(),
                255.0
            )
        }
    }
    //Now we have set the markers, we use the watershed
    //algorithm to generate a marked image
    Imgproc.watershed(srcOriginal, markers)
    val marker_tempo = Mat()
    markers.convertTo(marker_tempo, CvType.CV_8U)
    // Plot this one. If it does what we want, proceed;
    // otherwise edit your markers and repeat
    //Create Bitmap
    val bmpOut = Bitmap.createBitmap(srcOriginal.cols(), srcOriginal.rows(), Bitmap.Config.RGB_565)
    Utils.matToBitmap(marker_tempo, bmpOut)
    val mPath = Environment.getExternalStorageDirectory().toString() + "/gray.png"
    Imgcodecs.imwrite(mPath,marker_tempo)
    //Make the background black, and what we want to keep white

    //Use a kernel to dilate the image, to not lose any detail on the outline
    //I used a kernel of 3x3 pixels
    val kernel = Mat(3, 3, CvType.CV_8U)
    val dilatation = Imgproc.dilate(marker_tempo, marker_tempo, kernel)
    val mPath1 = Environment.getExternalStorageDirectory().toString() + "/dilation.png"
    Imgcodecs.imwrite(mPath1,marker_tempo)
    //Now apply the mask we created on the initial image
    val final_image = Core.bitwise_and(srcOriginal, srcOriginal, dilatation)
    //cv2.imread reads the image as BGR, but matplotlib uses RGB
    //BGR to RGB so we can plot the image with accurate colors

In pointsToDrawX and pointsToDrawY I'm saving all the x, y coordinates of the user's touch event on the screen. It is from these coordinates that I will pass to the watershed algorithm to perform the segmentation and remove the background from the image. Can someone help me convert this code?


问:
how to get a request in node repl
I've started to build a typescript library (intended to be used on the server side) and right now I'm trying to use the node repl to play around with my code and see what happens in certain situations... I've built and required the file, but now I'm having a problem: I have a function that takes a http Request (type Request from express.js), and I'd like to try and run it in the repl providing it with a copy of a request that I previously made from my browser. Is this feasible?
I thought maybe I could do it by either:

doing regex magic on the request exported as cURL or

sending the request to node, but then how am I going to receive it while in the repl?

答:
I'm not sure I understand your use-case, but you can try something like this:

In some temp folder type:

npm install "request-promise"
```

<p>Then from the same temp folder, enter the REPL and type:</p>

<pre class="lang-js prettyprint-override"><code>(async () => {const response = await require("request-promise").get("https://cnn.com"); console.log(response)})()
</code>```

This example is for get, but it can be easily changed to other HTTP methods.

Title: how to get a request in node repl

Body:
I'm not sure I understand your use-case, but you can try something like this:

In some temp folder type:

npm install "request-promise"

Then from the same temp folder, enter the REPL and type:

(async () => {const response = await require("request-promise").get("https://cnn.com"); console.log(response)})()

This example is for get, but it can be easily changed to other HTTP methods.


问:
Thread synchronization problem
I use Qt and C++. I have a list of threads (Qlist<QtThread>).

I try to synchronize them. All threads calculate some values. And I want to take them.

Have you any ideas? thank a lot

答: You can use the finished() signal of a thread to execute a slot when your thread finishes executing.</p>

Title: Thread synchronization problem


问:
How do I efficiently compute the gyration tensor in numpy?
The gyration tensor of a set of N points in 3d space is defined as

assuming the condition

.

How do I compute this in numpy without using an explicit for loop? I know that I can just do something like

```<code>import numpy as np

def calculate_gyration_tensor(points):
    '''
    Calculates the gyration tensor of a set of points.
    '''
    COM = centre_of_mass(points)
    gyration_tensor = np.zeros((3, 3))
    for p in points:
        gyration_tensor += np.outer(p-COM, p-COM)
    return gyration_tensor / len(points)
</code>```

but this quickly becomes inefficient for large N, because of the for loop. Is there a better way to do it?

答:
You can do with np.einsum like this:

```<code>def gyration(points):
    '''
    Calculate the gyrason tensor
    points : numpy array of shape N x 3
    '''

    center = points.mean(0)

    # normalized points
    normed_points = points - center[None,:]

    return np.einsum('im,in->mn', normed_points,normed_points)/len(points)

# test
points = np.arange(36).reshape(12,3)

gyration(points)
</code>```

Output:

```<code>array([[107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25]])
</code>```

Body:
The gyration tensor of a set of N points in 3d space is defined as

assuming the condition

.

How do I compute this in numpy without using an explicit for loop? I know that I can just do something like

import numpy as np

def calculate_gyration_tensor(points):
    '''
    Calculates the gyration tensor of a set of points.
    '''
    COM = centre_of_mass(points)
    gyration_tensor = np.zeros((3, 3))
    for p in points:
        gyration_tensor += np.outer(p-COM, p-COM)
    return gyration_tensor / len(points)

but this quickly becomes inefficient for large N, because of the for loop. Is there a better way to do it?

Body:
You can do with np.einsum like this:

def gyration(points):
    '''
    Calculate the gyrason tensor
    points : numpy array of shape N x 3
    '''

    center = points.mean(0)

    # normalized points
    normed_points = points - center[None,:]

    return np.einsum('im,in->mn', normed_points,normed_points)/len(points)

# test
points = np.arange(36).reshape(12,3)

gyration(points)

Output:

array([[107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25]])


问:
iOS App rejected after processing. UIWebView issue?
I am trying to update my app and I am at the test phase.
For that purpose I have a beta test app Target of my App on the App connect and I use Testflight.
That test app is only being used to test the app before submission on different env than the live apps.

But after uploading a build yesterday I got this email:

```<code>Dear Developer,

We identified one or more issues with a recent delivery for your app, *. Please correct the following issues, then upload again.

ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com/documentation/uikit/uiwebview).
</code>```

The build goes into processing and then disappears.

I checked my plist file.

I checked my app icon

Is the UIWebView the reason for rejection ?

Apple assumes that the app is not yet live so it can't be used with UIWebViews?

答:
Go to your project directory and run grep -r UIWebView . command. You will get all the UIWebView references in your project including third party PODs/SDK/Libraries.

Replace UIWebView with WKWebView in your code and if any of your third party library internally using UIWebView, ask their support team to provide an update with WKWebView and replace in your code with updated third party library.

You are done! All the best!

Body:
I am trying to update my app and I am at the test phase.
For that purpose I have a beta test app Target of my App on the App connect and I use Testflight.
That test app is only being used to test the app before submission on different env than the live apps.

But after uploading a build yesterday I got this email:

Dear Developer,

We identified one or more issues with a recent delivery for your app, *. Please correct the following issues, then upload again.

ITMS-90809: Deprecated API Usage - New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security and reliability. Learn more (https://developer.apple.com/documentation/uikit/uiwebview).

The build goes into processing and then disappears.

I checked my plist file.

I checked my app icon

Is the UIWebView the reason for rejection ?

Apple assumes that the app is not yet live so it can't be used with UIWebViews?


问:
Can I declare a delegate in an Object's New() constructor? Or with initialization parameters?
I'm trying to declare a delegate inline with my data in C# and that doesn't seem to compile. I'm hoping someone can help me (re)structure either my thoughts or my code.

My goal is to create different player types in an online game.  Each player type has a strategy they employ. This strategy is employed by calling an inline async function that might call a HTTP REST resource as part of the IQueryable evaluation.

Question:

What is a maintainable way to configure the code required within the EvaluateTurn() delegate for each of the AIPlayer types?

More player types will be added, and the IQueryable to be a deferred execution Linq Query against CosmosDB, AzureTable, SQL, in-memory array etc.

```<code>public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }

    public delegate int EvaluateTurn(IQueryable<GameplayRound> playHistory);
}

public List<AIPlayer> CreateDefaultPersonas()
{
    var ret = new List<AIPlayer>();

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "CopyCat" ,
        Description = "Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. Meow",
    });

    ret.Add(new AIPlayer() {
        PlayerPersonaName = "Grudger" ,
         Description = "Listen, pardner. I'll start cooperatin', and keep cooperatin', but if y'all ever cheat me, I'LL CHEAT YOU BACK 'TIL THE END OF TARNATION."
    });

    ret.Add(new AIPlayer() {
        PlayerPersonaName = "AlwaysCheat",
        Description = "the strong shall eat the weak"
    });

   ret.Add(new AIPlayer() {
       PlayerPersonaName = "AlwaysCooperate",
       Description = "Let's be best friends! <3"
   });

   ret.Add(new AIPlayer() {
       PlayerPersonaName = "Detective",
       Description = "First: I analyze you. I start: Cooperate, Cheat, Cooperate, Cooperate. If you cheat back, I'll act like Copycat. If you never cheat back, I'll act like Always Cheat, to exploit you. Elementary, my dear Watson."
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "CopyKitten",
        Description = "Hello! I'm like Copycat, except I Cheat back only after you Cheat me twice in a row. After all, the first one could be a mistake! Purrrrr",
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "Simpleton",
        Description = "hi i try start cooperate. if you cooperate back, i do same thing as last move, even if it mistake. if you cheat back, i do opposite thing as last move, even if it mistake.",
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "Random",
        Description = "Monkey robot! Ninja pizza tacos! lol i'm so random (Just plays Cheat or Cooperate randomly with a 50 / 50 chance)",
    });
   return ret;
}
</code>```

答:
A delegate is a type, you need to declare a property of that type:

```<code>public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }
    public EvaluateTurn Evaluation { get; set; }

    public delegate int EvaluateTurn(IQueryable<GameplayRound> playHistory);
}
</code>```

Then:

```<code>new AIPlayer()
{
    PlayerPersonaName = "CopyCat" ,
    Description = "Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. Meow",
    Evaluation = playHistory => 1
};
</code>```

Or you could just use Func for brevity:

```<code>public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }
    public Func<IQueryable<GameplayRound>, int> Evaluation { get; set; }
}
</code>```

Body:
I'm trying to declare a delegate inline with my data in C# and that doesn't seem to compile. I'm hoping someone can help me (re)structure either my thoughts or my code.

My goal is to create different player types in an online game.  Each player type has a strategy they employ. This strategy is employed by calling an inline async function that might call a HTTP REST resource as part of the IQueryable evaluation.

Question:

What is a maintainable way to configure the code required within the EvaluateTurn() delegate for each of the AIPlayer types?

More player types will be added, and the IQueryable to be a deferred execution Linq Query against CosmosDB, AzureTable, SQL, in-memory array etc.

public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }

    public delegate int EvaluateTurn(IQueryable<GameplayRound> playHistory);
}

public List<AIPlayer> CreateDefaultPersonas()
{
    var ret = new List<AIPlayer>();

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "CopyCat" ,
        Description = "Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. Meow",
    });

    ret.Add(new AIPlayer() {
        PlayerPersonaName = "Grudger" ,
         Description = "Listen, pardner. I'll start cooperatin', and keep cooperatin', but if y'all ever cheat me, I'LL CHEAT YOU BACK 'TIL THE END OF TARNATION."
    });

    ret.Add(new AIPlayer() {
        PlayerPersonaName = "AlwaysCheat",
        Description = "the strong shall eat the weak"
    });

   ret.Add(new AIPlayer() {
       PlayerPersonaName = "AlwaysCooperate",
       Description = "Let's be best friends! <3"
   });

   ret.Add(new AIPlayer() {
       PlayerPersonaName = "Detective",
       Description = "First: I analyze you. I start: Cooperate, Cheat, Cooperate, Cooperate. If you cheat back, I'll act like Copycat. If you never cheat back, I'll act like Always Cheat, to exploit you. Elementary, my dear Watson."
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "CopyKitten",
        Description = "Hello! I'm like Copycat, except I Cheat back only after you Cheat me twice in a row. After all, the first one could be a mistake! Purrrrr",
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "Simpleton",
        Description = "hi i try start cooperate. if you cooperate back, i do same thing as last move, even if it mistake. if you cheat back, i do opposite thing as last move, even if it mistake.",
    });

    ret.Add(new AIPlayer()
    {
        PlayerPersonaName = "Random",
        Description = "Monkey robot! Ninja pizza tacos! lol i'm so random (Just plays Cheat or Cooperate randomly with a 50 / 50 chance)",
    });
   return ret;
}

Body:
A delegate is a type, you need to declare a property of that type:

public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }
    public EvaluateTurn Evaluation { get; set; }

    public delegate int EvaluateTurn(IQueryable<GameplayRound> playHistory);
}

Then:

new AIPlayer()
{
    PlayerPersonaName = "CopyCat" ,
    Description = "Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. Meow",
    Evaluation = playHistory => 1
};

Or you could just use Func for brevity:

public class AIPlayer
{
    public string PlayerPersonaName { get; set; }
    public string Description { get; set; }
    public Func<IQueryable<GameplayRound>, int> Evaluation { get; set; }
}


问:
Difference between list() and [ ] in Python 3
Is there any difference between list() and [] while initializing a list in Python 3?

答:
The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.

```<code>sample_touple = ('a', 'C', 'J', 13)
list1 = list(sample_touple)
print ("List values ", list1)

string_value="sampletest"
list2 = list(string_value)
print ("List string values : ", list2)
</code>```

Output :

```<code>List values  ['a', 'C', 'J', 13]
List string values :  ['s', 'a', 'm', 'p', 'l', 'e', 't', 'e', 's', 't']
</code>```

Where [] to direct declare as list

```<code>sample = [1,2,3]

</code>```

Body:
The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.

sample_touple = ('a', 'C', 'J', 13)
list1 = list(sample_touple)
print ("List values ", list1)

string_value="sampletest"
list2 = list(string_value)
print ("List string values : ", list2)

Output :

List values  ['a', 'C', 'J', 13]
List string values :  ['s', 'a', 'm', 'p', 'l', 'e', 't', 'e', 's', 't']

Where [] to direct declare as list

sample = [1,2,3]


问:
Am i violating any NF RULE on my database design?
Good day!

I am a newbie on creating database... I need to create a db for my recruitment web application.

My database schema is as follows:

NOTE: I included the applicant_id on other tables... e.g. exam, interview, exam type.

Am i violating any normalization rule? If i do, what do you recommend to improve my design? Thank you

答:
You don't seem to be violating any normalization rules upon first glance.  It's not clear from your schema design, however, that the applicant_id is a referencing the applicant table.  Make sure you declare it as a foreign key that references the applicant table when actually implementing the scehma.

Not to make any assumptions on your data, but can the result of a screening be stored in 4 characters?


答:
Functionally they produce the same result, different internal Python implementation:</p>

```<code>import dis

def brackets():
    return []

def list_builtin():
    return list()
</code>```

```<code>print(dis.dis(brackets))
  5           0 BUILD_LIST               0
              2 RETURN_VALUE
</code>```

```<code>print(dis.dis(list_builtin))
 9           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE
</code>```

Title: Difference between list() and [ ] in Python 3

Body: Is there any difference between list() and [] while initializing a list in Python 3?

Body:
Functionally they produce the same result, different internal Python implementation:

import dis

def brackets():
    return []

def list_builtin():
    return list()

print(dis.dis(brackets))
  5           0 BUILD_LIST               0
              2 RETURN_VALUE

print(dis.dis(list_builtin))
 9           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE


答:
they are close to equivalent; the constructor variant does a function lookup and a function call; the literal does not - disassembling the python bytecode shows:

```<code>from dis import dis

def list_constructor():
    return list()

def list_literal():
    return []

print("constructor:")
dis(list_constructor)

print()

print("literal:")
dis(list_literal)
</code>```

this outputs:

```<code>constructor:
  5           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

literal:
  8           0 BUILD_LIST               0
              2 RETURN_VALUE
</code>```

as for the timing: the benchmark given in this answer may be misleading for some  (probably rare) cases. compare e.g. with this:

```<code>$ python3 -m timeit 'list(range(7))'
1000000 loops, best of 5: 224 nsec per loop
$ python3 -m timeit '[i for i in range(7)]'
1000000 loops, best of 5: 352 nsec per loop
</code>```

it seems that constructing a list from a generator is faster using list than a list-comprehension. i assume this is because the for loop in the list-comprehension is a python loop whereas the same loop is run in the C implementation in the python interpreter in the list version.

also note that list can be reassigned to something else (e.g. list = int now list() will just return the integer 0) - but you can not tinker with [].

and while it may be obvious... for completeness: the two versions have a different interface: list accepts exactls on iterable as argument. it will iterate over it and put the elements into the new list; the literal version does not (except for explicit list-comprehensions):

```<code>print([0, 1, 2])  # [0, 1, 2]
# print(list(0, 1,2))  # TypeError: list expected at most 1 argument, got 3

tpl = (0, 1, 2)
print([tpl])           # [(0, 1, 2)]
print(list(tpl))       # [0, 1, 2]

print([range(3)])      # [range(0, 3)]
print(list(range(3)))  # [0, 1, 2]

# list-comprehension
print([i for i in range(3)])      # [0, 1, 2]
print(list(i for i in range(3)))  # [0, 1, 2]  simpler: list(range(3))
</code>```

Body:
they are close to equivalent; the constructor variant does a function lookup and a function call; the literal does not - disassembling the python bytecode shows:

from dis import dis

def list_constructor():
    return list()

def list_literal():
    return []

print("constructor:")
dis(list_constructor)

print()

print("literal:")
dis(list_literal)

this outputs:

constructor:
  5           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

literal:
  8           0 BUILD_LIST               0
              2 RETURN_VALUE

as for the timing: the benchmark given in this answer may be misleading for some  (probably rare) cases. compare e.g. with this:

$ python3 -m timeit 'list(range(7))'
1000000 loops, best of 5: 224 nsec per loop
$ python3 -m timeit '[i for i in range(7)]'
1000000 loops, best of 5: 352 nsec per loop

it seems that constructing a list from a generator is faster using list than a list-comprehension. i assume this is because the for loop in the list-comprehension is a python loop whereas the same loop is run in the C implementation in the python interpreter in the list version.

also note that list can be reassigned to something else (e.g. list = int now list() will just return the integer 0) - but you can not tinker with [].

and while it may be obvious... for completeness: the two versions have a different interface: list accepts exactls on iterable as argument. it will iterate over it and put the elements into the new list; the literal version does not (except for explicit list-comprehensions):

print([0, 1, 2])  # [0, 1, 2]
# print(list(0, 1,2))  # TypeError: list expected at most 1 argument, got 3

tpl = (0, 1, 2)
print([tpl])           # [(0, 1, 2)]
print(list(tpl))       # [0, 1, 2]

print([range(3)])      # [range(0, 3)]
print(list(range(3)))  # [0, 1, 2]

# list-comprehension
print([i for i in range(3)])      # [0, 1, 2]
print(list(i for i in range(3)))  # [0, 1, 2]  simpler: list(range(3))


问:
Python and using data from Google Sheets
I'm wondering what's the best way to analyse data being pulled from Google Sheets. I've successfully managed to connect to a specific sheet and return all data using:

```<code>scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

sheet = client.open('KB Swings').sheet1

total_swings = sheet.get_all_records()
print(total_swings)

</code>```

But I want to do a basic sum of data in a specific column.

答:
The best way to analyze tabular data in python is pandas:
Here is a short introduction.</p>

Body:
I'm wondering what's the best way to analyse data being pulled from Google Sheets. I've successfully managed to connect to a specific sheet and return all data using:

scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

sheet = client.open('KB Swings').sheet1

total_swings = sheet.get_all_records()
print(total_swings)

But I want to do a basic sum of data in a specific column.


答:
Since list() is a function that returns a list object and [] is the list object itself, the second form is faster since it doesn't involve the function call:

```<code>> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop

> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop
</code>```

So if you really want to find a difference, there's that. In practical terms they're the same, however.

Body:
Since list() is a function that returns a list object and [] is the list object itself, the second form is faster since it doesn't involve the function call:

> python3 -m timeit 'list()'
10000000 loops, best of 3: 0.0853 usec per loop

> python3 -m timeit '[]'
10000000 loops, best of 3: 0.0219 usec per loop

So if you really want to find a difference, there's that. In practical terms they're the same, however.