问:
How to identify Redis keys from Redis-cli monitor command?
Possibly related to - Redis command to get all available keys?

I have a Redis server storing SixPack data (https://github.com/sixpack/sixpack - a framework to enable A/B testing). I can monitor the Redis server and see the following sample entries when I run monitor command:

```<code>$ redis-cli monitor|grep 'TEST'
</code>```

I can see that there are several keys being used/set. I am attaching a sample below:

```<code>1581720438.878978 [15 127.0.0.1:39722] "GETBIT" "sixpack:e:-28591_:excluded" "2307"
1581720439.623866 [15 127.0.0.1:39722] "LRANGE" "sixpack:e:-28003_:alternatives" "0" "-1"
1581720439.624209 [15 127.0.0.1:39722] "HGET" "sixpack:e:-28003_" "traffic_fraction"
1581720439.624557 [15 127.0.0.1:39722] "GET" "sixpack:e:-28003_:winner"
1581720439.624822 [15 127.0.0.1:39722] "HEXISTS" "sixpack:e:-28003_" "archived"
1581720439.625110 [15 127.0.0.1:39722] "EVALSHA" "bcbf3b3ac336a33c2cd7ad0e1fca28db7b49fdee" "1" "sixpack:e:-28003_Recapture:users" "ac945bf7-285e-4f69-83fd-1336e084a318"
</code>```

However, when I try to access the keys by running $ redis-cli KEYS '*' command, I only get an empty list (empty list or set).

Updated: I checked that this is not a cluster setup. I also check the DBSIZE command. It returns 0.

How can I derive the keys from the MONITOR output? Is there a way to get all the keys in a Redis CLI?

答:
Based on the hint from @AlisterBulman, I ran the INFO command like this.

```<code> $ redis-cli INFO | grep keys
</code>```

From the output I can see that the DB number '15' has the keys.

```<code>db15:keys=300869,expires=0,avg_ttl=0
</code>```

Then I ran this command to get the keys.

```<code>$ redis-cli -n 15 KEYS '*'
</code>```

Body:
Possibly related to - Redis command to get all available keys?

I have a Redis server storing SixPack data (https://github.com/sixpack/sixpack - a framework to enable A/B testing). I can monitor the Redis server and see the following sample entries when I run monitor command:

$ redis-cli monitor|grep 'TEST'

I can see that there are several keys being used/set. I am attaching a sample below:

1581720438.878978 [15 127.0.0.1:39722] "GETBIT" "sixpack:e:-28591_:excluded" "2307"
1581720439.623866 [15 127.0.0.1:39722] "LRANGE" "sixpack:e:-28003_:alternatives" "0" "-1"
1581720439.624209 [15 127.0.0.1:39722] "HGET" "sixpack:e:-28003_" "traffic_fraction"
1581720439.624557 [15 127.0.0.1:39722] "GET" "sixpack:e:-28003_:winner"
1581720439.624822 [15 127.0.0.1:39722] "HEXISTS" "sixpack:e:-28003_" "archived"
1581720439.625110 [15 127.0.0.1:39722] "EVALSHA" "bcbf3b3ac336a33c2cd7ad0e1fca28db7b49fdee" "1" "sixpack:e:-28003_Recapture:users" "ac945bf7-285e-4f69-83fd-1336e084a318"

However, when I try to access the keys by running $ redis-cli KEYS '*' command, I only get an empty list (empty list or set).

Updated: I checked that this is not a cluster setup. I also check the DBSIZE command. It returns 0.

How can I derive the keys from the MONITOR output? Is there a way to get all the keys in a Redis CLI?

Body:
Based on the hint from @AlisterBulman, I ran the INFO command like this.

 $ redis-cli INFO | grep keys

From the output I can see that the DB number '15' has the keys.

db15:keys=300869,expires=0,avg_ttl=0

Then I ran this command to get the keys.

$ redis-cli -n 15 KEYS '*'


来源: stackexchange

问:
Twilio Autopilot - How can I receive images from Whatsapp?
I'm building a chatbot with Twilio Autopilot and I want to get the images that I send to the bot, how can I get it? How can I get locations as well?

Thanks a lot.

答:
Autopilot Troublehooting

Unable to receive picture messages

Autopilot is currently unable to receive messages with pictures or other media types supported by Twilio on any messaging channel and will throw error with code 11200.

I haven't tried WhatsApp location data but there is a blog on the functionality that may help?

New Rich Features Support Deeper Customer Engagement on WhatsApp

ContentLicense: CC BY-SA 4.0


问:
C++ getline for text file
Pretty simple really, I hope. I have opened a text file, and I want it to read the first line with getline. I want it to take all the integers in that line, separated by commas, and add them together to be stored in a variable. However, I'm not quite sure how to set this up with delimiters.</p>

```<code>#include <fstream>
#include <iostream>

int main(){
        std::fstream codeBreaker;
        int x,y,z;
        codeBreaker.open("input.txt");
        void decipher();
        void encode();
        std::cout << "Have a nice day!" << std::endl;
        return 0;
}

void decipher(){

}

void encode(){

}
</code>```

答:
You've already outlined the first step: read in the first line with std::getline. One point you've missed though is that almost anytime you read data you want to check whether the read succeeded.

```<code>std::string line;
if (std::getline(infile, line))
    // we got some data
else
    // the read failed
</code>```

From there, you need to parse that line into individual numbers. One way to do that is with a stringstream.

```<code>std::stringstream buffer(line);
</code>```

Since your numbers are separated by commas, you'll then need to read (but otherwise ignore) the comma, and then the next number. Continue until you reach the end of the line, which you'll typically find out by checking whether reading the number succeeded or not.

```<code>int number;
while (buffer >> number) {
    char ch;
    buffer.get(ch);
    if (ch != ',')
        // unexpected input ?
    // do something with the number we just read here
}
</code>```

Title: C++ getline for text file

Body:
Pretty simple really, I hope. I have opened a text file, and I want it to read the first line with getline. I want it to take all the integers in that line, separated by commas, and add them together to be stored in a variable. However, I'm not quite sure how to set this up with delimiters.

#include <fstream>
#include <iostream>

int main(){
        std::fstream codeBreaker;
        int x,y,z;
        codeBreaker.open("input.txt");
        void decipher();
        void encode();
        std::cout << "Have a nice day!" << std::endl;
        return 0;
}

void decipher(){

}

void encode(){

}

Body:
You've already outlined the first step: read in the first line with std::getline. One point you've missed though is that almost anytime you read data you want to check whether the read succeeded.

std::string line;
if (std::getline(infile, line))
    // we got some data
else
    // the read failed

From there, you need to parse that line into individual numbers. One way to do that is with a stringstream.

std::stringstream buffer(line);

Since your numbers are separated by commas, you'll then need to read (but otherwise ignore) the comma, and then the next number. Continue until you reach the end of the line, which you'll typically find out by checking whether reading the number succeeded or not.

int number;
while (buffer >> number) {
    char ch;
    buffer.get(ch);
    if (ch != ',')
        // unexpected input ?
    // do something with the number we just read here
}


问:
Restricting use of special characters using python
I have very basic knowledge of Python 3.x but what I needed to do was to look through a text file and ensure a file is not being written using restricted characters.

So far I have this:

```<code>import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')

#Compare text to allowed characters
if re.search('^[A-Za-z0-9' '\,\%\[\]\=_-]*$', data):
    print("All good")
else:
    print ("Error!")
</code>```

I am not able to remove all the whitespace from the text file and that is what I think is causing this the file to go into error. Is there a way I can remove all whitespace from the data string or have re.search accept whitespace.

Thank you for your help.

答:
I found the solution: using \s matches whitespace character.</p>
```<code>import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')
if not re.search('^[A-Za-z0-9' '\s\,\.\&\%\[\]\=_-]*$', data):
    print ("Error!")
</code>```

Body:
I have very basic knowledge of Python 3.x but what I needed to do was to look through a text file and ensure a file is not being written using restricted characters.

So far I have this:

import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')

#Compare text to allowed characters
if re.search('^[A-Za-z0-9' '\,\%\[\]\=_-]*$', data):
    print("All good")
else:
    print ("Error!")

I am not able to remove all the whitespace from the text file and that is what I think is causing this the file to go into error. Is there a way I can remove all whitespace from the data string or have re.search accept whitespace.

Thank you for your help.

Body:
I found the solution: using \s matches whitespace character.

import re

#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
    data = file.read().replace('\n'' ', '').replace(' ','')
if not re.search('^[A-Za-z0-9' '\s\,\.\&\%\[\]\=_-]*$', data):
    print ("Error!")


问:
Is there a way to copy BLOB records between databases in Oracle 10g?
We have a production table that has millions of rows in it and contains a BLOB field, I would like to copy a smaller selection of these records into our development database without getting a DBA involved if possible.  I tried the following COPY command but received a CPY-0012: Datatype cannot be copied

```<code>COPY FROM user/password@prod_db TO user/password@dev_db -
INSERT TABLE_A (COL1, COL2, COL3, BLOB_COL) USING -
SELECT COL1, COL2, COL3, BLOB_COL -
FROM TABLE_A WHERE COL1='KEY'
</code>```

Is there a way to copy records with a BLOB field between databases via SQL?

答:
Unfortunately you cannot copy BLOB values using the COPY command.

An alternative is to set up a DB link on the source database, and execute a SQL INSERT statement:

```<code>CREATE DATABASE LINK link_to_prod CONNECT TO prod_user IDENTIFIED BY prod_password USING 'prod_db';

INSERT INTO TABLE_A@link_to_prod (COL1, COL2, COL3, BLOB_COL) SELECT COL1, COL2, COL3, BLOB_COL FROM TABLE_A
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have a production table that has millions of rows in it and contains a BLOB field, I would like to copy a smaller selection of these records into our development database without getting a DBA involved if possible.  I tried the following COPY command but received a CPY-0012: Datatype cannot be copied

COPY FROM user/password@prod_db TO user/password@dev_db -
INSERT TABLE_A (COL1, COL2, COL3, BLOB_COL) USING -
SELECT COL1, COL2, COL3, BLOB_COL -
FROM TABLE_A WHERE COL1='KEY'

Is there a way to copy records with a BLOB field between databases via SQL?

Body:
Unfortunately you cannot copy BLOB values using the COPY command.

An alternative is to set up a DB link on the source database, and execute a SQL INSERT statement:

CREATE DATABASE LINK link_to_prod CONNECT TO prod_user IDENTIFIED BY prod_password USING 'prod_db';

INSERT INTO TABLE_A@link_to_prod (COL1, COL2, COL3, BLOB_COL) SELECT COL1, COL2, COL3, BLOB_COL FROM TABLE_A


问:
Google timeline chart make first column clickable
I am using google timeline chart. Is that possible to make the first column clickable by making it as an html?

I try to make the column(User Name) to allow html, so that when I try add the row, I can make it as a link like this Google

```<code>dataTable.addColumn({type: 'string', id: 'User Name', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'User Id'});
dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});
</code>```

But this doesn't seem to work, it is rendered as a plain text.

答:
there aren't any click events provided by the chart,

but we can add regular events using javascript / jquery.

we just need to wait for the chart's 'ready' event before assigning the event listener.

```<code>google.visualization.events.addListener(chart, 'ready', function () {
  $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
});
</code>```

here, we use the <text> element filter [text-anchor="end"]

to only assign the event to the row labels, and not the x-axis labels.

see following working snippet,

which uses a cell property to store the url,

to be retrieved when clicked.

google.charts.load('current', {
  packages: ['timeline']
}).then(function () {
  var container = document.getElementById('timeline');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn({type: 'string', id: 'User Name'});
  dataTable.addColumn({type: 'string', id: 'User Id'});
  dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
  dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
  dataTable.addColumn({type: 'date', id: 'Start'});
  dataTable.addColumn({type: 'date', id: 'End'});
  dataTable.addRows([
    [{v: 'User A', p: {url: 'https://www.google.com'}}, '1', null, 'cyan', new Date(2020, 0, 1), new Date(2020, 0, 31)],
    [{v: 'User B', p: {url: 'https://www.yahoo.com'}}, '2', null, 'magenta', new Date(2020, 1, 1), new Date(2020, 1, 14)],
    [{v: 'User C', p: {url: 'https://www.bing.com'}}, '3', null, 'lime', new Date(2020, 2, 1), new Date(2020, 2, 10)]
  ]);

  google.visualization.events.addListener(chart, 'ready', function () {
    $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
  });

  chart.draw(dataTable);

  function onLabelClick(sender) {
    var label = $(sender.target).text();
    var rowIndex = dataTable.getFilteredRows([{
      column: 0,
      value: label
    }])[0];
    var url = dataTable.getProperty(rowIndex, 0, 'url');
    console.log(label, url);
    // window.open(url, '_blank');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline" style="height: 180px;"></div></code>```

Body:
I am using google timeline chart. Is that possible to make the first column clickable by making it as an html?

I try to make the column(User Name) to allow html, so that when I try add the row, I can make it as a link like this Google

dataTable.addColumn({type: 'string', id: 'User Name', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'User Id'});
dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});

But this doesn't seem to work, it is rendered as a plain text.

Body:
there aren't any click events provided by the chart,

but we can add regular events using javascript / jquery.

we just need to wait for the chart's 'ready' event before assigning the event listener.

google.visualization.events.addListener(chart, 'ready', function () {
  $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
});

here, we use the <text> element filter [text-anchor="end"]

to only assign the event to the row labels, and not the x-axis labels.

see following working snippet,

which uses a cell property to store the url,

to be retrieved when clicked.

google.charts.load('current', {
  packages: ['timeline']
}).then(function () {
  var container = document.getElementById('timeline');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn({type: 'string', id: 'User Name'});
  dataTable.addColumn({type: 'string', id: 'User Id'});
  dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
  dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
  dataTable.addColumn({type: 'date', id: 'Start'});
  dataTable.addColumn({type: 'date', id: 'End'});
  dataTable.addRows([
    [{v: 'User A', p: {url: 'https://www.google.com'}}, '1', null, 'cyan', new Date(2020, 0, 1), new Date(2020, 0, 31)],
    [{v: 'User B', p: {url: 'https://www.yahoo.com'}}, '2', null, 'magenta', new Date(2020, 1, 1), new Date(2020, 1, 14)],
    [{v: 'User C', p: {url: 'https://www.bing.com'}}, '3', null, 'lime', new Date(2020, 2, 1), new Date(2020, 2, 10)]
  ]);

  google.visualization.events.addListener(chart, 'ready', function () {
    $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
  });

  chart.draw(dataTable);

  function onLabelClick(sender) {
    var label = $(sender.target).text();
    var rowIndex = dataTable.getFilteredRows([{
      column: 0,
      value: label
    }])[0];
    var url = dataTable.getProperty(rowIndex, 0, 'url');
    console.log(label, url);
    // window.open(url, '_blank');
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline" style="height: 180px;"></div>


问:
Can a Worker Service be called and/or used inside an existing ASPNET.Core web project?
I've been reading and learing about the new Worker Service features provided in .Net Core 3.0. I have been using this link from Microsoft: Background tasks with hosted services in ASP.NET Core

What I don't understand is this, can these worker service concepts be introduced into an existing ASPNET Web Project, like a Razor Pages site? Or must you create a new project and then deploy that project as a service using whatever mechanism the host OS proivdes for that?

答:
Yes, you can host any number of hosted services (IHostedService) within ASP.NET Core applications. With version 3, ASP.NET Core uses the generic host (Host.CreateDefaultBuilder) which is the framework that is hosting these hosted services when the application starts. In fact, the ASP.NET Core web application is an IHostedService itself.

To add additional hosted services to your ASP.NET Core application, just register additional hosted services with your service collection, e.g. within the Startup’s ConfigureServices:

```<code>services.AddHostedService<MyHostedService>();
</code>```

That service will then launch together with the ASP.NET Core web server when the application runs.

The Worker SDK that is mentioned in the documentation is actually a subset of the Web SDK that you are using with ASP.NET Core application. Microsoft.NET.Sdk.Worker is basically Microsoft.NET.Sdk.Web without the web-specific stuff like Razor compilation and wwwroot folder stuff. It basically sets up automatic file globbing e.g. for the appsettings.json and does some other useful things that the core Microsoft.NET.Sdk does not have.

Ultimately this means, that when you are using the Web SDK, then you already have everything the Worker SDK offers. So you do not need to specify the Worker SDK just to host additional background services.

Body:
Yes, you can host any number of hosted services (IHostedService) within ASP.NET Core applications. With version 3, ASP.NET Core uses the generic host (Host.CreateDefaultBuilder) which is the framework that is hosting these hosted services when the application starts. In fact, the ASP.NET Core web application is an IHostedService itself.

To add additional hosted services to your ASP.NET Core application, just register additional hosted services with your service collection, e.g. within the Startup’s ConfigureServices:

services.AddHostedService<MyHostedService>();

That service will then launch together with the ASP.NET Core web server when the application runs.

The Worker SDK that is mentioned in the documentation is actually a subset of the Web SDK that you are using with ASP.NET Core application. Microsoft.NET.Sdk.Worker is basically Microsoft.NET.Sdk.Web without the web-specific stuff like Razor compilation and wwwroot folder stuff. It basically sets up automatic file globbing e.g. for the appsettings.json and does some other useful things that the core Microsoft.NET.Sdk does not have.

Ultimately this means, that when you are using the Web SDK, then you already have everything the Worker SDK offers. So you do not need to specify the Worker SDK just to host additional background services.


问:
PHP Variables made with foreach
I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.

For example if i have

```<code>$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
</code>```

I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:

```<code>$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
</code>```

NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.

Is this possible?

答: You can actually use the built-in function called extract</p>

Title: PHP Variables made with foreach

Body:
I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.

For example if i have

$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];

I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:

$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';

NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.

Is this possible?


问:
MongoDB aggregation - how to get a percentage value by rate
I'm trying to get information on row base all data collection

my data :

```<code>{
    _id : 1,
    age : 21,
    salary : 2500
},
{
    _id : 2,
    age : 42,
    salary : 4300
},
{
    _id : 3,
    age : 32,
    salary : 3100
},
{
    _id : 4,
    age : 18,
    salary : 7000
},
{
    _id : 5,
    age : 25,
    salary : 5600
},
{
    _id : 6,
    age : 28,
    salary : 5200
}
,
{
    _id : 7,
    age : 38,
    salary : 5000
},
{
    _id : 8,
    age : 28,
    salary : 5200
}
</code>```

I want to divide the values into four options.

First option is 25 percent.

Second option values between 25 and 50 percent.

Third option between 50 and 75 percent and

last option between 75 and 100 percent.

So when I want to pull out an object it will show me the values relative to the other values.

for example :

```<code>{
    _id : 4,
    age : 'less than 25 percent',
    salary : 'more than 75 percent'
}
</code>```

答:
Take a look if this meets your requirements.

Explanation

Mongodb aggregation offers more analytical operations to compute data. With $facet operation we can compute several aggregations in one.

We calculate min / max values for salary and age. Then we calculate percentage for each salary and age with this formula

```<code> x  − min
---------- x 100
max − min
</code>```

With $switch we define 4 options: less than 25, less than 50, less than 75 and more han 75

```<code>db.collection.aggregate([
  {
    $facet: {
      extremes: [
        {
          $group: {
            _id: null,
            maxAge: {
              $max: "$age"
            },
            minAge: {
              $min: "$age"
            },
            maxSalary: {
              $max: "$salary"
            },
            minSalary: {
              $min: "$salary"
            }
          }
        }
      ],
      root: [
        {
          $match: {}
        }
      ]
    }
  },
  {
    $set: {
      extremes: {
        $arrayElemAt: [
          "$extremes",
          0
        ]
      }
    }
  },
  {
    $unwind: "$root"
  },
  {
    $addFields: {
      root: {
        agePercent: {
          $toInt: {
            $multiply: [
              {
                $divide: [
                  {
                    $subtract: [
                      "$root.age",
                      "$extremes.minAge"
                    ]
                  },
                  {
                    $subtract: [
                      "$extremes.maxAge",
                      "$extremes.minAge"
                    ]
                  }
                ]
              },
              100
            ]
          }
        },
        salaryPercent: {
          $toInt: {
            $multiply: [
              {
                $divide: [
                  {
                    $subtract: [
                      "$root.salary",
                      "$extremes.minSalary"
                    ]
                  },
                  {
                    $subtract: [
                      "$extremes.maxSalary",
                      "$extremes.minSalary"
                    ]
                  }
                ]
              },
              100
            ]
          }
        }
      }
    }
  },
  {
    $replaceWith: "$root"
  },
  {
    $project: {
      age: {
        $switch: {
          branches: [
            {
              case: {$lt: ["$agePercent",25]},
              then: "less than 25 percent"
            },
            {
              case: {$lt: ["$agePercent",50]},
              then: "less than 50 percent"
            },
            {
              case: {$lt: ["$agePercent",75]},
              then: "less than 75 percent"
            },
            {
              case: {$gte: ["$agePercent",75]},
              then: "more than 75 percent"
            }
          ],
          default: "Unknown"
        }
      },
      salary: {
        $switch: {
          branches: [
            {
              case: {$lt: ["$salaryPercent",25]},
              then: "less than 25 percent"
            },
            {
              case: {$lt: ["$salaryPercent",50]},
              then: "less than 50 percent"
            },
            {
              case: {$lt: ["$salaryPercent",75]},
              then: "less than 75 percent"
            },
            {
              case: {$gte: ["$salaryPercent",75]},
              then: "more than 75 percent"
            }
          ],
          default: "Unknown"
        }
      }
    }
  }
])
</code>```

MongoPlayground

Body:
I'm trying to get information on row base all data collection

my data :

{
    _id : 1,
    age : 21,
    salary : 2500
},
{
    _id : 2,
    age : 42,
    salary : 4300
},
{
    _id : 3,
    age : 32,
    salary : 3100
},
{
    _id : 4,
    age : 18,
    salary : 7000
},
{
    _id : 5,
    age : 25,
    salary : 5600
},
{
    _id : 6,
    age : 28,
    salary : 5200
}
,
{
    _id : 7,
    age : 38,
    salary : 5000
},
{
    _id : 8,
    age : 28,
    salary : 5200
}

I want to divide the values into four options.

First option is 25 percent.

Second option values between 25 and 50 percent.

Third option between 50 and 75 percent and

last option between 75 and 100 percent.

So when I want to pull out an object it will show me the values relative to the other values.

for example :

{
    _id : 4,
    age : 'less than 25 percent',
    salary : 'more than 75 percent'
}

Body:
Take a look if this meets your requirements.

Explanation

Mongodb aggregation offers more analytical operations to compute data. With $facet operation we can compute several aggregations in one.

We calculate min / max values for salary and age. Then we calculate percentage for each salary and age with this formula

 x  − min
---------- x 100
max − min

With $switch we define 4 options: less than 25, less than 50, less than 75 and more han 75

db.collection.aggregate([
  {
    $facet: {
      extremes: [
        {
          $group: {
            _id: null,
            maxAge: {
              $max: "$age"
            },
            minAge: {
              $min: "$age"
            },
            maxSalary: {
              $max: "$salary"
            },
            minSalary: {
              $min: "$salary"
            }
          }
        }
      ],
      root: [
        {
          $match: {}
        }
      ]
    }
  },
  {
    $set: {
      extremes: {
        $arrayElemAt: [
          "$extremes",
          0
        ]
      }
    }
  },
  {
    $unwind: "$root"
  },
  {
    $addFields: {
      root: {
        agePercent: {
          $toInt: {
            $multiply: [
              {
                $divide: [
                  {
                    $subtract: [
                      "$root.age",
                      "$extremes.minAge"
                    ]
                  },
                  {
                    $subtract: [
                      "$extremes.maxAge",
                      "$extremes.minAge"
                    ]
                  }
                ]
              },
              100
            ]
          }
        },
        salaryPercent: {
          $toInt: {
            $multiply: [
              {
                $divide: [
                  {
                    $subtract: [
                      "$root.salary",
                      "$extremes.minSalary"
                    ]
                  },
                  {
                    $subtract: [
                      "$extremes.maxSalary",
                      "$extremes.minSalary"
                    ]
                  }
                ]
              },
              100
            ]
          }
        }
      }
    }
  },
  {
    $replaceWith: "$root"
  },
  {
    $project: {
      age: {
        $switch: {
          branches: [
            {
              case: {$lt: ["$agePercent",25]},
              then: "less than 25 percent"
            },
            {
              case: {$lt: ["$agePercent",50]},
              then: "less than 50 percent"
            },
            {
              case: {$lt: ["$agePercent",75]},
              then: "less than 75 percent"
            },
            {
              case: {$gte: ["$agePercent",75]},
              then: "more than 75 percent"
            }
          ],
          default: "Unknown"
        }
      },
      salary: {
        $switch: {
          branches: [
            {
              case: {$lt: ["$salaryPercent",25]},
              then: "less than 25 percent"
            },
            {
              case: {$lt: ["$salaryPercent",50]},
              then: "less than 50 percent"
            },
            {
              case: {$lt: ["$salaryPercent",75]},
              then: "less than 75 percent"
            },
            {
              case: {$gte: ["$salaryPercent",75]},
              then: "more than 75 percent"
            }
          ],
          default: "Unknown"
        }
      }
    }
  }
])

MongoPlayground


问:
Fatal error: Uncaught ArgumentCountError: Too few arguments
How can I fix this problem?
Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_config(), 1 passed in
my code is :</p>

```<code>$site_name = get_config('site_name');
// Get site configuration

function get_config($conn, $setting_name) {

$setting_query = mysqli_query($conn, "SELECT value FROM settings WHERE setting = '" .mysqli_real_escape_string($conn, "$setting_name"). "'");

return mysqli_result($setting_query, 0);

}
</code>```

答: The function takes 2 arguments: $conn and $setting_name. You're only passing 1, that I assume is $setting_name, it's missing $conn argument.

Body:
How can I fix this problem?
Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_config(), 1 passed in
my code is :

$site_name = get_config('site_name');
// Get site configuration

function get_config($conn, $setting_name) {

$setting_query = mysqli_query($conn, "SELECT value FROM settings WHERE setting = '" .mysqli_real_escape_string($conn, "$setting_name"). "'");

return mysqli_result($setting_query, 0);

}


问:
Why is my dynamically-generated oval becoming a square?
Thought i had everything looking ok.

https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="doit()" value="Do it"></code>```

Any ideas?

答:
You have to have your width twice the size of height for a better result (horizontal one).

Then, the oval shape is created with the CSS border-radius property. So to apply that in JavaScript you have to use it as,

newdiv.style.borderRadius = "50%";

You can try the same thing as width/height

Try the code snippet below. Adjust the values and get your own oval shape.

function doit() {
 drawOval("90", "100", "100", "50");
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.borderRadius = "50%";
   newdiv.style.left  = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="doit()" value="Do it"></code>```

Body:
Thought i had everything looking ok.

https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html

function doit() {
 drawOval(100, 150, 90, 90);
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.left = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }

<input type="button" onClick="doit()" value="Do it">

Any ideas?

Body:
You have to have your width twice the size of height for a better result (horizontal one).

Then, the oval shape is created with the CSS border-radius property. So to apply that in JavaScript you have to use it as,

newdiv.style.borderRadius = "50%";

You can try the same thing as width/height

Try the code snippet below. Adjust the values and get your own oval shape.

function doit() {
 drawOval("90", "100", "100", "50");
 myOval = document.getElementById("newdiv");
}

function drawOval(left, top, width, height) {
 if (document.createElement) {
   newdiv=document.createElement("div");
   newdiv.style.position="absolute";
   newdiv.style.borderRadius = "50%";
   newdiv.style.left  = left+"px";
   newdiv.style.top  = top+"px";
   newdiv.style.width = width+"px";
   newdiv.style.height = height+"px";
   newdiv.style.backgroundColor = 'red';
   newdiv.style.visibility = 'visible';
   newdiv.id = 'newdiv';
   document.body.appendChild(newdiv);
   }
 }

<input type="button" onClick="doit()" value="Do it">


问:
passport.js throws Error: Can't set headers after they are sent
I have read other solutions, but those aren't working for me.

[1] This talks about using else, which I have already used.

[2] One other talks about using return with done which seems illogical because the docs don't mention using return

I have a page that I need to load regardless of whether a user is logged in or not. If the user is not logged in, I have to show a Login Button, otherwise a logout button.

This is the route where the error occurs:

```<code>app.get('/', (req, res, next) => {
    if(req.query.code || req.cookie) { //either first time authenticating or already a user
        passport.authenticate('google')(req, res, next)
    }
    res.render('index', { user: req.user });
})
</code>```

This is the route I hit when user hits login:

```<code>app.get('/google', passport.authenticate('google', {
    scope: ['profile', 'email']
}));
</code>```

This is my passport strategy setup:

```<code>passport.use(
    new GoogleStrategy({
        callbackURL: `${process.env.address}`,
        clientID: `${process.env.GOOGLE_SSO_CLIENT_ID}`,
        clientSecret: `${process.env.GOOGLE_SSO_CLIENT_SECRET}`,

    }, (accessToken, refreshToken, profile, done) => {

        if(accessToken) {
            User.findOne({email: profile.email}).then((currentUser) => {

                if(currentUser){ // already exists
                    console.log('user is: ', currentUser);
                    done(null, currentUser)
                    // do something
                } else { // if not, create user in our db
                    new User({
                        email: profile.email,
                        joinDate: Date.now(),
                        username: 'random'
                    }).save().then((newUser) => {
                        console.log('created new user: ', newUser);
                        done(null, newUser)
                        // do something
                    });
                }
            });
        } else {
            done(null, null)
        }
    })
)
</code>```

The problem might be that I am trying to hit the URL where

答:
I assume that this would work you job?</p>

```<code>app.get('/', (req, res, next) => {
    if(req.query.code || req.cookie) {
        passport.authenticate('google', function(req, res, next) {
           res.render('index', { user: req.user });
        });
    } else {
        res.render('index');
    }
})
</code>```

Body:
I have read other solutions, but those aren't working for me.

[1] This talks about using else, which I have already used.

[2] One other talks about using return with done which seems illogical because the docs don't mention using return

I have a page that I need to load regardless of whether a user is logged in or not. If the user is not logged in, I have to show a Login Button, otherwise a logout button.

This is the route where the error occurs:

app.get('/', (req, res, next) => {
    if(req.query.code || req.cookie) { //either first time authenticating or already a user
        passport.authenticate('google')(req, res, next)
    }
    res.render('index', { user: req.user });
})

This is the route I hit when user hits login:

app.get('/google', passport.authenticate('google', {
    scope: ['profile', 'email']
}));

This is my passport strategy setup:

passport.use(
    new GoogleStrategy({
        callbackURL: `${process.env.address}`,
        clientID: `${process.env.GOOGLE_SSO_CLIENT_ID}`,
        clientSecret: `${process.env.GOOGLE_SSO_CLIENT_SECRET}`,

    }, (accessToken, refreshToken, profile, done) => {

        if(accessToken) {
            User.findOne({email: profile.email}).then((currentUser) => {

                if(currentUser){ // already exists
                    console.log('user is: ', currentUser);
                    done(null, currentUser)
                    // do something
                } else { // if not, create user in our db
                    new User({
                        email: profile.email,
                        joinDate: Date.now(),
                        username: 'random'
                    }).save().then((newUser) => {
                        console.log('created new user: ', newUser);
                        done(null, newUser)
                        // do something
                    });
                }
            });
        } else {
            done(null, null)
        }
    })
)

The problem might be that I am trying to hit the URL where

Body:
I assume that this would work you job?

app.get('/', (req, res, next) => {
    if(req.query.code || req.cookie) {
        passport.authenticate('google', function(req, res, next) {
           res.render('index', { user: req.user });
        });
    } else {
        res.render('index');
    }
})


问:
EF Core - Pulling Data From Two Identical Tables
TLDR: I have a two tables with identical definitions, and I need to pull from one table or the other depending on some switch.

For example, assume a table with a bunch of "generic" FooItem and a table with "Fancy" FooItem... and the only difference between the two tables is the names, SIMPLE_FOO and FANCY_FOO

Depending on a boolean value, like GetFancy == true, I should read from FANCY_FOO, otherwise, SIMPLE_FOO.

This gets a complicated in the DbContext.  I can't have more than one DbSet<FooItem> in my context, and I can't dynamically "inject" the table name in the ModelBuilder.Entity<FooItem>(e => e.ToView("pickOne"))  ... and I don't want to duplicate an entire dbContext just to have a different table name in there.

I'm sure the solution is simple, but I'm just not seeing it.  Any assistance is appreciated.

EDIT:  I cannot change the database.  It's a dumb way to do it, but that's the way they did it and I have to live with it.

答:
Just have two entities in your solution, one for each table.  They can inherit from a base class since they are identical.  Create your base class "BaseFooItem" that has all of the fields in both tables.  Then create an entity class for each of the variants (Simple and Fancy) and annotate each to match the necessary table name; e.g.:

```<code>[Table("SIMPLE_FOO")]
public class SimpleFooItem: BaseFooItem {
}
</code>```

If you don't want to use data annotations, you can set the table name with the FluentAPI too.  Then create a DbSet for each entity:

```<code>    public DbSet<SimpleFooItem> SimpleFooItems { get; set; }
    public DbSet<FancyFooItem> FancyFooItems { get; set; }
</code>```

Then do your conditional where ever to switch between each DbSet, for example:

```<code>if (GetFancy) {
   return dbContext.FancyFooItems.SingleOrDefault(a => a.Id == id);
} else {
   return dbContext.SimpleFooItems.SingleOrDefault(a => a.Id == id);
}
</code>```

Hopefully I am understanding your needs correctly.

Body:
Just have two entities in your solution, one for each table.  They can inherit from a base class since they are identical.  Create your base class "BaseFooItem" that has all of the fields in both tables.  Then create an entity class for each of the variants (Simple and Fancy) and annotate each to match the necessary table name; e.g.:

[Table("SIMPLE_FOO")]
public class SimpleFooItem: BaseFooItem {
}

If you don't want to use data annotations, you can set the table name with the FluentAPI too.  Then create a DbSet for each entity:

    public DbSet<SimpleFooItem> SimpleFooItems { get; set; }
    public DbSet<FancyFooItem> FancyFooItems { get; set; }

Then do your conditional where ever to switch between each DbSet, for example:

if (GetFancy) {
   return dbContext.FancyFooItems.SingleOrDefault(a => a.Id == id);
} else {
   return dbContext.SimpleFooItems.SingleOrDefault(a => a.Id == id);
}

Hopefully I am understanding your needs correctly.


问:
What is the difference between ContainerVisual.Offset and Visual.VisualOffset?
If you look at the documentation for DrawingVisuals, you'll find two very similar-looking properties: Offset (inherited from ContainerVisual) and VisualOffset (from Visual). The descriptions of the properties are extremely similar and there is no further explanation on the docs. What is the difference between them? When should I be using which?

答:
Pick your favorite, as they are effectively the same

Here is the source code,

Given

```<code>public class DrawingVisual : ContainerVisual
</code>```

ContainerVisual implements Offset as such

```<code>public Vector Offset
{
    get
    {
        return base.VisualOffset;
    }
    set
    {
         base.VisualOffset = value;
    }
}
</code>```

Body:
Pick your favorite, as they are effectively the same

Here is the source code,

Given

public class DrawingVisual : ContainerVisual

ContainerVisual implements Offset as such

public Vector Offset
{
    get
    {
        return base.VisualOffset;
    }
    set
    {
         base.VisualOffset = value;
    }
}


答:
You don't need a loop, you want extract:

```<code>extract($_POST); // But use caution, see below
</code>```

Cautions and best practices

As noted in the comments this forces all parameters in the $_POST array into the current symbol space.

In global space

```<code><?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>
</code>```

The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.

Inside a function

```<code>function myFunc() {
    // (Mostly) empty symbol space! (excluding super globals)
    extract($_POST);
}
</code>```

Inside a function, as the first line, no harm done.

Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well.  However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.

With options

You can also use extract with extract_type options that do not overwrite.

The best option to use, in my opinion, is simply to prefix all variables from extract:

```<code>// $_GET = test=1&name=Joe

extract($_GET, EXTR_PREFIX_ALL, "request_get");

echo $request_get_test; // 1
echo $request_get_name; // Joe
</code>```

That way you don't have the overwrite problem, but you also know you got everything from the array.

Alternate - looping w/ conditional

If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:

```<code>foreach ($_POST as $key => $value) {
    if (isset($$key)) continue;

    $$key = $value;
}
</code>```

(The example condition I've used is an overwrite prevention.)

Title: PHP Variables made with foreach

Body:
You don't need a loop, you want extract:

extract($_POST); // But use caution, see below

Cautions and best practices

As noted in the comments this forces all parameters in the $_POST array into the current symbol space.

In global space

<?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>

The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.

Inside a function

function myFunc() {
    // (Mostly) empty symbol space! (excluding super globals)
    extract($_POST);
}

Inside a function, as the first line, no harm done.

Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well.  However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.

With options

You can also use extract with extract_type options that do not overwrite.

The best option to use, in my opinion, is simply to prefix all variables from extract:

// $_GET = test=1&name=Joe

extract($_GET, EXTR_PREFIX_ALL, "request_get");

echo $request_get_test; // 1
echo $request_get_name; // Joe

That way you don't have the overwrite problem, but you also know you got everything from the array.

Alternate - looping w/ conditional

If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:

foreach ($_POST as $key => $value) {
    if (isset($$key)) continue;

    $$key = $value;
}

(The example condition I've used is an overwrite prevention.)


问:
How to speed up DataFrame setting?
Now I have a  list of records whose format is (index,column,value), and a DataFrame which is filled with 0. For every record in list, I should do something like df.loc[index,column]+=value. This is a sample:

```<code>import pandas as pd
df = pd.DataFrame(index=list('abcd'),columns=list('abcd'),dtype=int)
df = df.fillna(0)
records = [('a','b',3),('a','b',5),('c','a',6)]
for index,column,value in records:
    df.loc[index,column] += value
</code>```

And the expected output will be:

```<code>   a  b  c  d
a  0  8  0  0
b  0  0  0  0
c  6  0  0  0
d  0  0  0  0
</code>```

However it runs too slowly since the records list is TOO big, and I wonder are there any methods to speed it up?

Update: It doesn't matter to use int index and column names instead of str, that is, the data structure also can be a numpy.array instead of a DataFrame. Therefore, the input records can be format like this:

```<code>records = [(0,1,3),(0,1,5),(3,1,6)]
</code>```

And the expected output, of course, can be a numpy.array looks like:

```<code>[[0. 8. 0. 0.]
 [0. 0. 0. 0.]
 [6. 0. 0. 0.]
 [0. 0. 0. 0.]]
</code>```

答:
As it turns out, you can indeed use a NumPy array instead of a Pandas DataFrame. This particular solution takes advantage of numpy.ufunc.at.

import numpy as np

arr = np.zeros((4, 4), dtype=int)

print(arr, end='\n\n')

idx_records = [(0, 1, 3), (0, 1, 5), (2, 0, 6)]

dim_1_idx, dim_2_ix, vals = zip(*idx_records)

print(dim_1_idx)
print(dim_2_ix)
print(vals, end='\n\n')

np.add.at(arr, (dim_1_idx, dim_2_ix), vals)

print(arr)
```

<p>Ouput:</p>

<pre class="lang-none prettyprint-override"><code>[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

(0, 0, 2)
(1, 1, 0)
(3, 5, 6)

[[0 8 0 0]
 [0 0 0 0]
 [6 0 0 0]
 [0 0 0 0]]
</code>```

Benchmarks by C.K. show this solution taking ~7.20 seconds, versus ~10.55 seconds for the Pandas method, on 10 million rows.

Title: How to speed up DataFrame setting?

Body:
Now I have a  list of records whose format is (index,column,value), and a DataFrame which is filled with 0. For every record in list, I should do something like df.loc[index,column]+=value. This is a sample:

import pandas as pd
df = pd.DataFrame(index=list('abcd'),columns=list('abcd'),dtype=int)
df = df.fillna(0)
records = [('a','b',3),('a','b',5),('c','a',6)]
for index,column,value in records:
    df.loc[index,column] += value

And the expected output will be:

   a  b  c  d
a  0  8  0  0
b  0  0  0  0
c  6  0  0  0
d  0  0  0  0

However it runs too slowly since the records list is TOO big, and I wonder are there any methods to speed it up?

Update: It doesn't matter to use int index and column names instead of str, that is, the data structure also can be a numpy.array instead of a DataFrame. Therefore, the input records can be format like this:

records = [(0,1,3),(0,1,5),(3,1,6)]

And the expected output, of course, can be a numpy.array looks like:

[[0. 8. 0. 0.]
 [0. 0. 0. 0.]
 [6. 0. 0. 0.]
 [0. 0. 0. 0.]]

Body:
As it turns out, you can indeed use a NumPy array instead of a Pandas DataFrame. This particular solution takes advantage of numpy.ufunc.at.

import numpy as np

arr = np.zeros((4, 4), dtype=int)

print(arr, end='\n\n')

idx_records = [(0, 1, 3), (0, 1, 5), (2, 0, 6)]

dim_1_idx, dim_2_ix, vals = zip(*idx_records)

print(dim_1_idx)
print(dim_2_ix)
print(vals, end='\n\n')

np.add.at(arr, (dim_1_idx, dim_2_ix), vals)

print(arr)

Ouput:

[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

(0, 0, 2)
(1, 1, 0)
(3, 5, 6)

[[0 8 0 0]
 [0 0 0 0]
 [6 0 0 0]
 [0 0 0 0]]

Benchmarks by C.K. show this solution taking ~7.20 seconds, versus ~10.55 seconds for the Pandas method, on 10 million rows.


问:
How can I filter all rows that have something1 followed by xyz and to store them in a separate pandas dataframe
I have a data frame looking like below.

INPUT

```<code>col1
</code>```

0   something1

1   xyz

2   something1

3   abc

4   something1

5   xyz

6   something1

7   xyz

OUTPUT

```<code>col1
</code>```

0   something1

4   something1

6   something1

答:
Create a  new subset of your df filtering the value you want on col1

```<code>df_output = df[df['col1']== 'something1']
</code>```

or if you want just a df with values grouped ie sorted then

```<code>data = {'col':["something1"
, "something2"
, "something1"
, "something3"
, "something1"
, "something2"
, "something1"
,"something2"]}

df = pd.DataFrame(data)

df.sort_values(by='col')

col
0   something1
2   something1
4   something1
6   something1
1   something2
5   something2
7   something2
</code>```

Body:
I have a data frame looking like below.

INPUT

col1

0   something1

1   xyz

2   something1

3   abc

4   something1

5   xyz

6   something1

7   xyz

OUTPUT

col1

0   something1

4   something1

6   something1

Body:
Create a  new subset of your df filtering the value you want on col1

df_output = df[df['col1']== 'something1']

or if you want just a df with values grouped ie sorted then

data = {'col':["something1"
, "something2"
, "something1"
, "something3"
, "something1"
, "something2"
, "something1"
,"something2"]}

df = pd.DataFrame(data)

df.sort_values(by='col')

col
0   something1
2   something1
4   something1
6   something1
1   something2
5   something2
7   something2


问:
scikit-learn error: The least populated class in y has only 1 member
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

```<code>In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.
</code>```

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.

答:
Try this way, It worked for me which also mentioned here:</p>

```<code>x_train, x_test, y_train, y_test = train_test_split(data_x,data_y,test_size=0.33, random_state=42) .
</code>```

Body:
I'm trying to split my dataset into a training and a test set by using the train_test_split function from scikit-learn, but I'm getting this error:

In [1]: y.iloc[:,0].value_counts()
Out[1]:
M2    38
M1    35
M4    29
M5    15
M0    15
M3    15

In [2]: xtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=1/3, random_state=85, stratify=y)
Out[2]:
Traceback (most recent call last):
  File "run_ok.py", line 48, in <module>
    xtrain,xtest,ytrain,ytest = train_test_split(X,y,test_size=1/3,random_state=85,stratify=y)
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1700, in train_test_split
    train, test = next(cv.split(X=arrays[0], y=stratify))
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 953, in split
    for train, test in self._iter_indices(X, y, groups):
  File "/home/aurora/.pyenv/versions/3.6.0/lib/python3.6/site-packages/sklearn/model_selection/_split.py", line 1259, in _iter_indices
    raise ValueError("The least populated class in y has only 1"
ValueError: The least populated class in y has only 1 member, which is too few. The minimum number of groups for any class cannot be less than 2.

However, all classes have at least 15 samples. Why am I getting this error?

X is a pandas DataFrame which represents the data points, y is a pandas DataFrame with one column that contains the target variable.

I cannot post the original data because it's proprietary, but it is fairly reproducible by creating a random pandas DataFrame (X) with 1k rows x 500 columns, and a random pandas DataFrame (y) with the same number of rows (1k) of X, and, for each row the target variable (a categorical label).
The y pandas DataFrame should have different categorical labels (e.g. 'class1', 'class2'...) and each labels should have at least 15 occurrences.

Body:
Try this way, It worked for me which also mentioned here:

x_train, x_test, y_train, y_test = train_test_split(data_x,data_y,test_size=0.33, random_state=42) .


问:
Sagemaker with tensorflow 2 not saving model
I am working with Keras and I am trying to train a model using Sagemaker. I have the following issue:
When I train my model using TensorFlow 1.12 everything works fine:

```<code>estimator = TensorFlow(entry_point='entrypoint-2.py',
                            base_job_name='mlearning-test',
                         role=role,
                         train_instance_count=1,
                         input_mode='Pipe',
                         train_instance_type='ml.p2.xlarge',
                         framework_version='1.12.0')
</code>```

My model is trained and the model is saved in S3. Not problems.

However, if I changed the framework version to be 2.0.0

```<code>estimator = TensorFlow(entry_point='entrypoint-2.py',
                                base_job_name='mlearning-test',
                             role=role,
                             train_instance_count=1,
                             input_mode='Pipe',
                             train_instance_type='ml.p2.xlarge',
                             framework_version='2.0.0')
</code>```

I get the following error:

```<code>2020-02-12 13:54:36,601 sagemaker_tensorflow_container.training WARNING  No model artifact is saved under path /opt/ml/model. Your training job will not save any model files to S3.
For details of how to construct your training script see:
https://sagemaker.readthedocs.io/en/stable/using_tf.html#adapting-your-local-tensorflow-script
</code>```

The training job is marked as successful but there is nothing in the S3 bucket and indeed there was not training.

As an alternative, I tried putting the py_version='py3' but this keeps happening. is there a major difference that I am not aware of when using TF2 on sagemaker?

I don't think the entry point is needed since it works fine with version 1.12 but in case you are curious or can spot something here it is:

```<code>import tensorflow as tf
from sagemaker_tensorflow import PipeModeDataset
#from tensorflow.contrib.data import map_and_batch

INPUT_TENSOR_NAME = 'inputs_input'
BATCH_SIZE = 64
NUM_CLASSES = 5
BUFFER_SIZE = 50
PREFETCH_SIZE = 1
LENGHT = 512
SEED = 26
EPOCHS = 1
WIDTH = 512

def keras_model_fn(hyperparameters):
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(WIDTH, 'relu', input_shape=(None, WIDTH), name = 'inputs'),
        #tf.keras.layers.InputLayer(input_shape=(None, WIDTH), name=INPUT_TENSOR_NAME),
        tf.keras.layers.Dense(256, 'relu'),
        tf.keras.layers.Dense(128, 'relu'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')
    ])

    opt = tf.keras.optimizers.RMSprop()

    model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=["accuracy"])
    return model

def serving_input_fn(hyperparameters):
    # Notice that the input placeholder has the same input shape as the Keras model input
    tensor = tf.placeholder(tf.float32, shape=[None, WIDTH])

    # The inputs key INPUT_TENSOR_NAME matches the Keras InputLayer name
    inputs = {INPUT_TENSOR_NAME: tensor}
    return tf.estimator.export.ServingInputReceiver(inputs, inputs)

def train_input_fn(training_dir, params):
    """Returns input function that would feed the model during training"""
    return _input_fn('train')

def eval_input_fn(training_dir, params):
    """Returns input function that would feed the model during evaluation"""
    return _input_fn('eval')

def _input_fn(channel):
    """Returns a Dataset for reading from a SageMaker PipeMode channel."""
    print("DATA "+channel)
    features={
        'question': tf.FixedLenFeature([WIDTH], tf.float32),
        'label': tf.FixedLenFeature([1], tf.int64)
    }

    def parse(record):
        parsed = tf.parse_single_example(record, features)
        #print("-------->"+str(tf.cast(parsed['question'], tf.float32))
        return {
            INPUT_TENSOR_NAME: tf.cast(parsed['question'], tf.float32)
        }, parsed['label']

    ds = PipeModeDataset(channel)
    if EPOCHS > 1:
        ds = ds.repeat(EPOCHS)
    ds = ds.prefetch(PREFETCH_SIZE)
    #ds = ds.apply(map_and_batch(parse, batch_size=BATCH_SIZE,
    #                            num_parallel_batches=BUFFER_SIZE))
    ds = ds.map(parse, num_parallel_calls=NUM_PARALLEL_BATCHES)
    ds = ds.batch(BATCH_SIZE)

    return ds
</code>```

答:
you're correct, there has been a major, beneficial change last year in the SageMaker TensorFlow experience named the Script Mode formalism. As you can see in the SDK Documentation:

"Warning.
We have added a new format of your TensorFlow training script with TensorFlow version 1.11. This new way gives the user script more flexibility. This new format is called Script Mode, as opposed to Legacy Mode, which is what we support with TensorFlow 1.11 and older versions. In addition we are adding Python 3 support with Script Mode. The last supported version of Legacy Mode will be TensorFlow 1.12. Script Mode is available with TensorFlow version 1.11 and newer. Make sure you refer to the correct version of this README when you prepare your script. You can find the Legacy Mode README here."

with TensorFlow 2, you need to follow that Script Mode formalism and save your model in the opt/ml/model path, otherwise nothing will be sent to S3. Script Mode is quite straightforward to implement and gives better flexibility and portability, and this spec is shared with SageMaker Sklearn container, SageMaker Pytorch container and SageMaker MXNet container so definitely worth adopting

Body:
I am working with Keras and I am trying to train a model using Sagemaker. I have the following issue:
When I train my model using TensorFlow 1.12 everything works fine:

estimator = TensorFlow(entry_point='entrypoint-2.py',
                            base_job_name='mlearning-test',
                         role=role,
                         train_instance_count=1,
                         input_mode='Pipe',
                         train_instance_type='ml.p2.xlarge',
                         framework_version='1.12.0')

My model is trained and the model is saved in S3. Not problems.

However, if I changed the framework version to be 2.0.0

estimator = TensorFlow(entry_point='entrypoint-2.py',
                                base_job_name='mlearning-test',
                             role=role,
                             train_instance_count=1,
                             input_mode='Pipe',
                             train_instance_type='ml.p2.xlarge',
                             framework_version='2.0.0')

I get the following error:

2020-02-12 13:54:36,601 sagemaker_tensorflow_container.training WARNING  No model artifact is saved under path /opt/ml/model. Your training job will not save any model files to S3.
For details of how to construct your training script see:
https://sagemaker.readthedocs.io/en/stable/using_tf.html#adapting-your-local-tensorflow-script

The training job is marked as successful but there is nothing in the S3 bucket and indeed there was not training.

As an alternative, I tried putting the py_version='py3' but this keeps happening. is there a major difference that I am not aware of when using TF2 on sagemaker?

I don't think the entry point is needed since it works fine with version 1.12 but in case you are curious or can spot something here it is:

import tensorflow as tf
from sagemaker_tensorflow import PipeModeDataset
#from tensorflow.contrib.data import map_and_batch

INPUT_TENSOR_NAME = 'inputs_input'
BATCH_SIZE = 64
NUM_CLASSES = 5
BUFFER_SIZE = 50
PREFETCH_SIZE = 1
LENGHT = 512
SEED = 26
EPOCHS = 1
WIDTH = 512

def keras_model_fn(hyperparameters):
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(WIDTH, 'relu', input_shape=(None, WIDTH), name = 'inputs'),
        #tf.keras.layers.InputLayer(input_shape=(None, WIDTH), name=INPUT_TENSOR_NAME),
        tf.keras.layers.Dense(256, 'relu'),
        tf.keras.layers.Dense(128, 'relu'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')
    ])

    opt = tf.keras.optimizers.RMSprop()

    model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=["accuracy"])
    return model

def serving_input_fn(hyperparameters):
    # Notice that the input placeholder has the same input shape as the Keras model input
    tensor = tf.placeholder(tf.float32, shape=[None, WIDTH])

    # The inputs key INPUT_TENSOR_NAME matches the Keras InputLayer name
    inputs = {INPUT_TENSOR_NAME: tensor}
    return tf.estimator.export.ServingInputReceiver(inputs, inputs)

def train_input_fn(training_dir, params):
    """Returns input function that would feed the model during training"""
    return _input_fn('train')

def eval_input_fn(training_dir, params):
    """Returns input function that would feed the model during evaluation"""
    return _input_fn('eval')

def _input_fn(channel):
    """Returns a Dataset for reading from a SageMaker PipeMode channel."""
    print("DATA "+channel)
    features={
        'question': tf.FixedLenFeature([WIDTH], tf.float32),
        'label': tf.FixedLenFeature([1], tf.int64)
    }

    def parse(record):
        parsed = tf.parse_single_example(record, features)
        #print("-------->"+str(tf.cast(parsed['question'], tf.float32))
        return {
            INPUT_TENSOR_NAME: tf.cast(parsed['question'], tf.float32)
        }, parsed['label']

    ds = PipeModeDataset(channel)
    if EPOCHS > 1:
        ds = ds.repeat(EPOCHS)
    ds = ds.prefetch(PREFETCH_SIZE)
    #ds = ds.apply(map_and_batch(parse, batch_size=BATCH_SIZE,
    #                            num_parallel_batches=BUFFER_SIZE))
    ds = ds.map(parse, num_parallel_calls=NUM_PARALLEL_BATCHES)
    ds = ds.batch(BATCH_SIZE)

    return ds


问:
EF Core 3.1 Migration Tool is failing because of a dependency on .NET Core 2.0
I have a project that uses EF Core 3.1. The startup project is an Azure Function that is running using V3 and framework 3.1. The rest of the projects are class libraries that are .NET Standard 2.0 projects.

I am trying to generate a migration script for EF Core 3.1 and I am getting the following error from Azure DevOps

```<code>Starting: Run EF Core Migrations
==============================================================================
Task         : Command line
Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
Version      : 2.163.0
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
==============================================================================
Generating script.
Script contents:
dotnet ef migrations script --startup-project C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj --output C:\vstsagent\A6\_work\2\a/16138/Migrations/SqlScript.sql --context $dbContext --idempotent --verbose --framework netcoreapp3.1
========================== Starting Command Output ===========================
"C:\Windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "C:\vstsagent\A6\_work\_temp\3930c14d-f779-4939-9748-dd2ab8c6baa0.cmd""
Using project 'C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj'.
Using startup project 'C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj'.
Writing 'C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\obj\MyProject.Function.WebApi.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp\tmp74C6.tmp /verbosity:quiet /nologo C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj
Writing 'C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\obj\MyProject.Function.WebApi.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp\tmp77C5.tmp;TargetFramework=netcoreapp3.1 /verbosity:quiet /nologo C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj
Build started...

Build succeeded.
dotnet exec --depsfile C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.deps.json --additionalprobingpath C:\Windows\ServiceProfiles\NetworkService\.nuget\packages C:\Windows\ServiceProfiles\NetworkService\.dotnet\tools\.store\dotnet-ef\3.1.1\dotnet-ef\3.1.1\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --output C:\vstsagent\A6\_work\2\a/16138/Migrations/covImsSqlScript.sql --context $dbContext --idempotent --assembly C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.dll --startup-assembly C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.dll --project-dir C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\ --language C# --working-dir C:\vstsagent\A6\_work\2\s --verbose --root-namespace MyProject.Function.WebApi
It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '2.0.0' was not found.
  - The following frameworks were found:
      3.1.0 at [C:\vstsagent\A6\_work\_tool\dotnet\shared\Microsoft.NETCore.App]
      3.1.1 at [C:\vstsagent\A6\_work\_tool\dotnet\shared\Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.

The specified framework can be found at:
  - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0&arch=x64&rid=win81-x64
##[error]Cmd.exe exited with code '-2147450730'.
Finishing: Run EF Core Migrations
</code>```

When I look into the folder of the tool that gets installed when you execute dotnet.exe tool install dotnet-ef -g I can see that there is a directory that is still referencing the framework 2.0, which is present on the command that dotnet ef migrations script run.

```<code>C:\Windows\ServiceProfiles\NetworkService\.dotnet\tools\.store\dotnet-ef\3.1.1\dotnet-ef\3.1.1\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll
</code>```

The only thing I can think of is that EF Core 3.1 needs .NET Core 2.0 to also be installed on the build server for it to work. However, that does not feel right.

Has anyone experienced something similar and did you manage to find a solution other than installing .NET Core 2.0?

答:
I think I found what was the issue. I was missing the --project parameter. However, once I put it I was getting the following error:

```<code>Error:
  An assembly specified in the application dependencies manifest (MyProject.Function.WebApi.deps.json) was not found:
    package: 'MyProject.Common', version: '1.0.0'
    path: 'MyProject.Common.dll'
</code>```

It looks like the EF Core Migration Tool does not like a startup project that is an Azure Function Project. Since the migration project is .NET Standard what I did was to create a console project that does nothing (just a Program.CS with a Console.Writelne("")) and make it reference the project that contained the migrations and use it as my Startup Project. By doing that migrations are working fine.

Body:
I have a project that uses EF Core 3.1. The startup project is an Azure Function that is running using V3 and framework 3.1. The rest of the projects are class libraries that are .NET Standard 2.0 projects.

I am trying to generate a migration script for EF Core 3.1 and I am getting the following error from Azure DevOps

Starting: Run EF Core Migrations
==============================================================================
Task         : Command line
Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
Version      : 2.163.0
Author       : Microsoft Corporation
Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
==============================================================================
Generating script.
Script contents:
dotnet ef migrations script --startup-project C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj --output C:\vstsagent\A6\_work\2\a/16138/Migrations/SqlScript.sql --context $dbContext --idempotent --verbose --framework netcoreapp3.1
========================== Starting Command Output ===========================
"C:\Windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "C:\vstsagent\A6\_work\_temp\3930c14d-f779-4939-9748-dd2ab8c6baa0.cmd""
Using project 'C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj'.
Using startup project 'C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj'.
Writing 'C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\obj\MyProject.Function.WebApi.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp\tmp74C6.tmp /verbosity:quiet /nologo C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj
Writing 'C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\obj\MyProject.Function.WebApi.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp\tmp77C5.tmp;TargetFramework=netcoreapp3.1 /verbosity:quiet /nologo C:\vstsagent\A6\_work\2\s/MyProject/MyProject.Function.WebApi/MyProject.Function.WebApi.csproj
Build started...

Build succeeded.
dotnet exec --depsfile C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.deps.json --additionalprobingpath C:\Windows\ServiceProfiles\NetworkService\.nuget\packages C:\Windows\ServiceProfiles\NetworkService\.dotnet\tools\.store\dotnet-ef\3.1.1\dotnet-ef\3.1.1\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --output C:\vstsagent\A6\_work\2\a/16138/Migrations/covImsSqlScript.sql --context $dbContext --idempotent --assembly C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.dll --startup-assembly C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\bin\Debug\netcoreapp3.1\MyProject.Function.WebApi.dll --project-dir C:\vstsagent\A6\_work\2\s\MyProject\MyProject.Function.WebApi\ --language C# --working-dir C:\vstsagent\A6\_work\2\s --verbose --root-namespace MyProject.Function.WebApi
It was not possible to find any compatible framework version
The framework 'Microsoft.NETCore.App', version '2.0.0' was not found.
  - The following frameworks were found:
      3.1.0 at [C:\vstsagent\A6\_work\_tool\dotnet\shared\Microsoft.NETCore.App]
      3.1.1 at [C:\vstsagent\A6\_work\_tool\dotnet\shared\Microsoft.NETCore.App]

You can resolve the problem by installing the specified framework and/or SDK.

The specified framework can be found at:
  - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=2.0.0&arch=x64&rid=win81-x64
##[error]Cmd.exe exited with code '-2147450730'.
Finishing: Run EF Core Migrations

When I look into the folder of the tool that gets installed when you execute dotnet.exe tool install dotnet-ef -g I can see that there is a directory that is still referencing the framework 2.0, which is present on the command that dotnet ef migrations script run.

C:\Windows\ServiceProfiles\NetworkService\.dotnet\tools\.store\dotnet-ef\3.1.1\dotnet-ef\3.1.1\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll

The only thing I can think of is that EF Core 3.1 needs .NET Core 2.0 to also be installed on the build server for it to work. However, that does not feel right.

Has anyone experienced something similar and did you manage to find a solution other than installing .NET Core 2.0?

Body:
I think I found what was the issue. I was missing the --project parameter. However, once I put it I was getting the following error:

Error:
  An assembly specified in the application dependencies manifest (MyProject.Function.WebApi.deps.json) was not found:
    package: 'MyProject.Common', version: '1.0.0'
    path: 'MyProject.Common.dll'

It looks like the EF Core Migration Tool does not like a startup project that is an Azure Function Project. Since the migration project is .NET Standard what I did was to create a console project that does nothing (just a Program.CS with a Console.Writelne("")) and make it reference the project that contained the migrations and use it as my Startup Project. By doing that migrations are working fine.


问:
Changing mm/dd/yyyy and m/dd/yyyy to yyyy
I have a data set with the dates written as follows:

5/18/12
12/20/10
2/17/08

etc

Is there a way to transform these into yyyy format? I'm struggling because they didn't include 0s in front of the months, so each date is a different number of characters long.

答:
Using the lubridate package you need to convert the string to dates and then you can just pull out the year with the aptly named year function

```<code>library(lubridate)
dates <- c("5/18/12", "12/20/10", "2/17/08")
dates <- as_date(dates,format = "%m/%d/%y", tz = "UTC" )
year(dates)
</code>```

which gives:

[1] 2012 2010 2008

Body:
Using the lubridate package you need to convert the string to dates and then you can just pull out the year with the aptly named year function

library(lubridate)
dates <- c("5/18/12", "12/20/10", "2/17/08")
dates <- as_date(dates,format = "%m/%d/%y", tz = "UTC" )
year(dates)

which gives:

[1] 2012 2010 2008