问:
JSON string sending undefined when trying to set custom claim via firebase function
Can anyone see what I am doing wrong here? I am using firebase, I am sending data to my cloud function here

```<code>window.addEventListener("load", function load(event) {

    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            let user = firebase.auth().currentUser;
            let userInfo = db.collection("Users").doc(user.uid);

            userInfo.get().then(function (doc) {
                if (doc.exists) {

                    let userEmail = firebase.auth().currentUser.email
                    var xhttp = new XMLHttpRequest();

                    xhttp.open(
                        "POST",
                        "https://us-central1-******.cloudfunctions.net/addMRole",
                        true
                    );
                    xhttp.setRequestHeader("Content-Type", "application/json");
                    xhttp.send(
                        JSON.stringify({
                            email: userEmail,
                            uID: user.uid
                        })
                    );
                    console.log("should still be working HOPEFULLY HERE YOU ARE")

                }
            });

        }

    });

});

</code>```

and I am sending it to my cloud function here

```<code>exports.addMRole = functions.https.onRequest((req, context) => {

  let email = req.email;
  let uiD = req.uID

  console.log(email)
  console.log(uiD)

  return admin.auth().getUserByEmail(email).then(user => {

    return admin.auth().setCustomUserClaims(uiD, {

      member: true

    });
  }).then(() => {
    return {
      message: `success! ${req.email} is now a member!`
    }
  }).catch(err => {
    console.log(err)
    return err;
  });
});

</code>```

But for some reason it is being sent as undefined to the cloud function for some reason. It does not like how im sending it to it I guess. It looks like its not happy with home im sending it from the first code here

```<code>
xhttp.send(
                        JSON.stringify({
                            email: userEmail,
                            uID: user.uid
                        })
                    );

</code>```

And userEmail / user.uid console log fine before they send, but then in the function when I log here

```<code>console.log(email)
  console.log(uiD)

</code>```

its shows its being sent as undefined in my function logs. So confusing lol. I am basically sending the users email and UID to my cloud function which I want to change their custom claim to member. Its weird because I had it working, then I did something and now cant figure out how to get it working again, no idea where I messed up on this one lol. Thanks for the help <3

答:
This is not right:

```<code>let email = req.email
let uiD = req.uID
</code>```

These will always be undefined, the way you have it written now.  If you want to access the properties of a JSON object that you post to an HTTP function, you should do it like this, as shown in the documentation:

```<code>let email = req.body.email
let uiD = req.body.uID
</code>```

On top of that, your function is also not sending a response to the caller.  As structured right now, it might do its work, but it will always time out after the default 60 seconds.  The way you are just returning the response out of the then callback will not work.  It seems you might be mixing up HTTP type triggers with callable type triggers, which have very different ways of sending the response.  Since you are writing an HTTP type trigger, you should follow the instructions for sending a response in order to terminate the HTTP function correctly.

Body:
Can anyone see what I am doing wrong here? I am using firebase, I am sending data to my cloud function here

window.addEventListener("load", function load(event) {

    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            let user = firebase.auth().currentUser;
            let userInfo = db.collection("Users").doc(user.uid);

            userInfo.get().then(function (doc) {
                if (doc.exists) {

                    let userEmail = firebase.auth().currentUser.email
                    var xhttp = new XMLHttpRequest();

                    xhttp.open(
                        "POST",
                        "https://us-central1-******.cloudfunctions.net/addMRole",
                        true
                    );
                    xhttp.setRequestHeader("Content-Type", "application/json");
                    xhttp.send(
                        JSON.stringify({
                            email: userEmail,
                            uID: user.uid
                        })
                    );
                    console.log("should still be working HOPEFULLY HERE YOU ARE")

                }
            });

        }

    });

});

and I am sending it to my cloud function here

exports.addMRole = functions.https.onRequest((req, context) => {

  let email = req.email;
  let uiD = req.uID

  console.log(email)
  console.log(uiD)

  return admin.auth().getUserByEmail(email).then(user => {

    return admin.auth().setCustomUserClaims(uiD, {

      member: true

    });
  }).then(() => {
    return {
      message: `success! ${req.email} is now a member!`
    }
  }).catch(err => {
    console.log(err)
    return err;
  });
});

But for some reason it is being sent as undefined to the cloud function for some reason. It does not like how im sending it to it I guess. It looks like its not happy with home im sending it from the first code here

xhttp.send(
                        JSON.stringify({
                            email: userEmail,
                            uID: user.uid
                        })
                    );

And userEmail / user.uid console log fine before they send, but then in the function when I log here

console.log(email)
  console.log(uiD)

its shows its being sent as undefined in my function logs. So confusing lol. I am basically sending the users email and UID to my cloud function which I want to change their custom claim to member. Its weird because I had it working, then I did something and now cant figure out how to get it working again, no idea where I messed up on this one lol. Thanks for the help <3

Body:
This is not right:

let email = req.email
let uiD = req.uID

These will always be undefined, the way you have it written now.  If you want to access the properties of a JSON object that you post to an HTTP function, you should do it like this, as shown in the documentation:

let email = req.body.email
let uiD = req.body.uID

On top of that, your function is also not sending a response to the caller.  As structured right now, it might do its work, but it will always time out after the default 60 seconds.  The way you are just returning the response out of the then callback will not work.  It seems you might be mixing up HTTP type triggers with callable type triggers, which have very different ways of sending the response.  Since you are writing an HTTP type trigger, you should follow the instructions for sending a response in order to terminate the HTTP function correctly.


来源: stackexchange

问:
Where do I get the value for `shopOrigin` when using Shopify app bridge?
Throughout the documentation for the new App Bridge, Shopify refers to the shopOrigin value and how it's used to configure the Provider from app-bridge-react but they never specify how to get this value?

The react app is loaded inside of an iframe and the src includes the shopOrigin value as a query string param called shop, but when I try the following code I get the error window is not defined:

```<code>const params = queryString.parse(window.location.search);
const config = {
  apiKey: process.env.SHOPIFY_API_KEY,
  shopOrigin: params.shop,
};
</code>```

1) Why would I be getting window is not defined in javascript code running in a browser?! This makes no sense to me
2) If this value can be read from of the provided libraries such as @shopufy/app-bridge-react please tell me how

答:
Unless you're using a library tailored specifically to Shopify, you have to manually save the shop origin during OAuth authorization.

Hopefully this Shopify tutorial is of some assistance

ContentLicense: CC BY-SA 4.0

Body:
Throughout the documentation for the new App Bridge, Shopify refers to the shopOrigin value and how it's used to configure the Provider from app-bridge-react but they never specify how to get this value?

The react app is loaded inside of an iframe and the src includes the shopOrigin value as a query string param called shop, but when I try the following code I get the error window is not defined:

const params = queryString.parse(window.location.search);
const config = {
  apiKey: process.env.SHOPIFY_API_KEY,
  shopOrigin: params.shop,
};

1) Why would I be getting window is not defined in javascript code running in a browser?! This makes no sense to me
2) If this value can be read from of the provided libraries such as @shopufy/app-bridge-react please tell me how


问:
Programmatically detect SQL Server Edition
I'm using C# with SMO and attempting to detect what edition of SQL Server (e.g., enterprise, standard) I'm connecting to.  I know how to get the version information, but that only tells me what version of SQL Server (e.g., SQL Server 2008 vs SQL Server 2005).

Does anyone know how to get the actual product edition (e.g., enterprise, standard)?

I need this information because some SQL Server features are only enterprise.  Thus, I could just try to call them and catch the exception, but I'd much prefer an upfront detection.

Thanks!

答: It looks like you might be able to do it via SMO and the Server object.  There are properties like Information.Edition which looks like it should do what you want.</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: Dion Brown


问:
Cypress not finding data-test element
Morning/evening everyone. Have a weird issue that, according to the best practices, should just work.
I have the following element on a page which I need to click:

Sign out

I'm doing this in my test:

cy.get('[data-test="sign-out-link"]') .should('be.visible') .click()

But cypress times out saying the element cannot be found...

This gives the same behaviour:
cy.get('a[data-test="sign-out-link"]') .should('be.visible') .click()

Even this just fails, which is kinda weird (it should find that text fairly easily):

cy.contains('Sign out').click()

Anything obvious I'm doing wrong?

答:
Can you please add a small cy.wait() before cypress Sign out test code and see if that is working for you.

```<code>    cy.wait(2000);
    cy.get('[href="/redirect/onejl/sign-out"] > span').contains("Sign out").click();

    cy.wait(2000);
    cy.get('a > span').contains("Sign out").click();

    cy.wait(2000);
    cy.get('[data-test ="sign-out-link"]').should('be.visible').click();
</code>```

Title: Cypress not finding data-test element

Body:
Can you please add a small cy.wait() before cypress Sign out test code and see if that is working for you.

    cy.wait(2000);
    cy.get('[href="/redirect/onejl/sign-out"] > span').contains("Sign out").click();

    cy.wait(2000);
    cy.get('a > span').contains("Sign out").click();

    cy.wait(2000);
    cy.get('[data-test ="sign-out-link"]').should('be.visible').click();


问:
Getting whole JSON input request in JavaCompute
I'm using IIB v10.0.0.18 and I have JSON input message which is received by http input node, and then a JavaCompute node in which I'm trying to get the whole JSON input.
I'm using below code to do this

```<code>MbMessage inMessage = inAssembly.getMessage();
MbElement inRoot = inMessage.getRootElement();
String inputMsg = inRoot.getFirstElementByPath("/JSON/Data/*").getValueAsString();
</code>```

But this is resulting in the first line only of the input message.
I tried also

```<code>String inputMsg = inRoot.getFirstChild().getValueAsString();
</code>```

And

```<code>String inputMsg = inRoot.getLastChild().getValueAsString();
</code>```

But both are returning null.
Can anyone please tell me how to get the whole json input as a string in my JavaCompute.
My input JSON looks like this

```<code>{
"id": 1,
"name": "A green door",
"price": 12.50
}
</code>```

and I want this whole message to be retrieved from the JavaCompute node.

Update:
Based on Kimbert's answer, I updated the code to below and it worked:

```<code>MbMessage inMessage = inAssembly.getMessage();
MbElement inRoot = inMessage.getRootElement();
byte[] inRootBytes = inRoot.getLastChild().toBitstream(null, null, null, 0, 1208, 0);
String inRootString = new String(inRootBytes);
</code>```

Now, inRootString has the string value of my input json.

答:
The MbElement class is just a wrapper for a 'syntax element' in the IIB message tree. So MbElement.getValueAsString will return the string value of the syntax element. That might be a string (if the MbElement represents a string field), or null, but it will never be the document fragment from which that element was parsed.

You need to use MbElement.toBitstream. If you use it on an MbElement that points to InputRoot.JSON then you should get the entire input bitstream.

Body:
I'm using IIB v10.0.0.18 and I have JSON input message which is received by http input node, and then a JavaCompute node in which I'm trying to get the whole JSON input.
I'm using below code to do this

MbMessage inMessage = inAssembly.getMessage();
MbElement inRoot = inMessage.getRootElement();
String inputMsg = inRoot.getFirstElementByPath("/JSON/Data/*").getValueAsString();

But this is resulting in the first line only of the input message.
I tried also

String inputMsg = inRoot.getFirstChild().getValueAsString();

And

String inputMsg = inRoot.getLastChild().getValueAsString();

But both are returning null.
Can anyone please tell me how to get the whole json input as a string in my JavaCompute.
My input JSON looks like this

{
"id": 1,
"name": "A green door",
"price": 12.50
}

and I want this whole message to be retrieved from the JavaCompute node.

Update:
Based on Kimbert's answer, I updated the code to below and it worked:

MbMessage inMessage = inAssembly.getMessage();
MbElement inRoot = inMessage.getRootElement();
byte[] inRootBytes = inRoot.getLastChild().toBitstream(null, null, null, 0, 1208, 0);
String inRootString = new String(inRootBytes);

Now, inRootString has the string value of my input json.


问:
PLM regression with log variables returning non-finite values error when there are no null or NA values in the data
I'm using plm package to analyse my panel data, which comprises a set of states for 14 years. In the course of running plm regressions, I've encountered a lot of times the error "model matrix or response contain non-finite values", but i've eventually solved them by deleting observations with null or NA values. However, I'm doing the regression:

mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log (DC) + log(DK) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

summary (mod_3.1_within_log_b)

```

<p>which returns</p>

<pre class="lang-r prettyprint-override"><code>Error in model.matrix.pdata.frame(data, rhs=1, model=model, effect=effect,
model matrix or response contains non-finite values (NA/NaN/inf/-inf)

</code>```

But, as I said, my data contains no more null or NA values. Just to test this, I've run the separate regressions

mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log (DC) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

```

<p>and</p>

<pre class="lang-r prettyprint-override"><code>
mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log(DK) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

summary (mod_3.1_within_log_b)

</code>```

and both worked, indicating that it is when I run with log(DK) and log(DC) together that I receive the error.

Thanks in advance!

答:
As @StupidWolf suggested in the comment, your model matrix may contain contain zero's or possibly negative values (log(-1) returns NaN and log(0) return Inf).

plm does not handle this by removing incomplete observations manually, but we can do this manually by checking the model matrix used (or looking at the original data). Without complete data this is just a suggestion to check for some simple problems in the model matrix.

Note that I've shortened the formula to improve readability.

```<code>mm <- model.matrix(txinad + prod + op + emp + log(RT) +
                    (log(DC) + log(DK)) * Gini, data = dd)
## Check complete.cases
if(any(icc <- !complete.cases(mm))){
    cat('Rows in dd causing trouble:\n')
    print(dd[icc, ])
}
</code>```

This would print any rows in dd, that causes problem in the model.matrix.

Body:
I'm using plm package to analyse my panel data, which comprises a set of states for 14 years. In the course of running plm regressions, I've encountered a lot of times the error "model matrix or response contain non-finite values", but i've eventually solved them by deleting observations with null or NA values. However, I'm doing the regression:

mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log (DC) + log(DK) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

summary (mod_3.1_within_log_b)

which returns

Error in model.matrix.pdata.frame(data, rhs=1, model=model, effect=effect,
model matrix or response contains non-finite values (NA/NaN/inf/-inf)

But, as I said, my data contains no more null or NA values. Just to test this, I've run the separate regressions

mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log (DC) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

and

mod_3.1_within_log_b <- plm(log(PIB) ~ txinad + prod + op + emp + log(RT) + log(DK) + Gini + I(log(DC)*Gini) + I(log(DK)*Gini), data = dd, effect = 'individual')

summary (mod_3.1_within_log_b)

and both worked, indicating that it is when I run with log(DK) and log(DC) together that I receive the error.

Thanks in advance!

Body:
As @StupidWolf suggested in the comment, your model matrix may contain contain zero's or possibly negative values (log(-1) returns NaN and log(0) return Inf).

plm does not handle this by removing incomplete observations manually, but we can do this manually by checking the model matrix used (or looking at the original data). Without complete data this is just a suggestion to check for some simple problems in the model matrix.

Note that I've shortened the formula to improve readability.

mm <- model.matrix(txinad + prod + op + emp + log(RT) +
                    (log(DC) + log(DK)) * Gini, data = dd)
## Check complete.cases
if(any(icc <- !complete.cases(mm))){
    cat('Rows in dd causing trouble:\n')
    print(dd[icc, ])
}

This would print any rows in dd, that causes problem in the model.matrix.


问:
how to create a line in d3?
I have managed to create a line chart in d3 but now need to overlay a couple of horizontal lines and vertical lines.  Here is what the chart looks like:

Here is the code:

```<code> <!DOCTYPE html>
    <meta charset="utf-8">
    <style>

    body {
      font: 14px sans-serif;
    }

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      stroke-width: 1.5px;
      shape-rendering: crispEdges;
    }

    .line {
      fill: none;
      stroke: steelblue;
      stroke-width: 3.5px;
    }

    .dot {
      stroke: blue;
    }

    .grid .tick {
        stroke: lightgrey;
        opacity: 0.7;
    }
    </style>
    <body>
    <script src="https://d3js.org/d3.v3.js"></script>
    <script>
          var tests = <?php echo $tests; ?>;
          console.log("tests=" +JSON.stringify(tests));
          var events = <?php echo $events; ?>;
          console.log("events=" +JSON.stringify(events));

    var margin = {top: 50, right: 20, bottom: 60, left: 90},
        width = 900 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .ticks(d3.time.years,1)
        //makes the xAxis ticks a little longer than the xMinorAxis ticks
        .tickSize(10)
        .orient("bottom");

    var xMinorAxis = d3.svg.axis()
        .scale(x)
        .ticks(d3.time.months,1)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.total_km); });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // function for the y grid lines
    function make_y_axis() {
      return d3.svg.axis()
          .scale(y)
          .orient("left")
          .ticks(5) //somehow this makes the y-axis grid draw every other line, rather than every line
    }

    var data = [];
    function DataPoint(x,y) {
        this.date_time = x;
        this.total_km = y;
    }

    var lowerLimit;
    var upperLimit;
    function loadData() {
        for (i=1; i < tests.length; i++) {
            var test = tests[i];
            console.log("x="+test[0]+", y="+test[1]);
            data.push(new DataPoint(test[0],test[1]));
            lowerLimit = test[2];
            upperLimit = test[3];
        }
    }
    loadData();
    console.log("data1="+JSON.stringify(data));

    function processData(data) {
        data.forEach(function(d) {
            console.log("d.date_time="+d.date_time +", d.total_km="+d.total_km);
            d.date = new Date(d.date_time);
            console.log("d.date=" +d.date);
        });

        //using imported data to define extent of x and y domains
        x.domain(d3.extent(data, function(d) { return d.date; }));
        y.domain(d3.extent(data, function(d) { return d.total_km; }));

        // Draw the y Grid lines
        svg.append("g")
            .attr("class", "grid")
            .call(make_y_axis()
                .tickSize(-width, 0, 0) //causes the line to be drawn the full width of the chart
                .tickFormat("")
            )

        //draw the data line
        svg.append("path")
            .datum(data)
            .attr("class", "line")
            .attr("d", line);

        //draw the upper limit
        var minDate = new Date(data[0].date_time);
        console.log("minDate="+minDate +", x(minDate)="+x(minDate));
        var maxDate = new Date(data[data.length-1].date_time);
        console.log("maxDate="+maxDate +", x(maxDate)="+x(maxDate));
        svg.append("line")
            .attr("class", "x")
            .style("stroke", "red")
            .style("stroke-dasharray", "3,3")
            .style("opacity", 0)
            .attr("x1", x(minDate))
            .attr("y1", y(upperLimit))
            .attr("x2", x(maxDate))
            .attr("y2", y(upperLimit));

    //creating a group(g) and will append a circle and 2 lines inside each group
    var g = svg.selectAll()
            .data(data).enter().append("g");

       //The markers on the line
         g.append("circle")
             //circle radius is increased
            .attr("r", 4.5)
            .attr("cx", function(d) { return x(d.date); })
            .attr("cy", function(d) { return y(d.total_km); });

    svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis)
          .selectAll(".tick text")
          .call(wrap, 35);

    svg.append("g")
        .attr("class","xMinorAxis")
        .attr("transform", "translate(0," + height + ")")
        .style({ 'stroke': 'Black', 'fill': 'none', 'stroke-width': '1px'})
        .call(xMinorAxis)
        .selectAll("text").remove();

    svg.append("text")      // text label for the x-axis
            .attr("x", width / 2 )
            .attr("y",  height + margin.bottom)
            .style("text-anchor", "middle")
            .text("Date");

    svg.append("text")      // text label for the y-axis
            .attr("y",30 - margin.left)
            .attr("x",50 - (height / 2))
            .attr("transform", "rotate(-90)")
            .style("text-anchor", "end")
            .style("font-size", "16px")
            .text("Tryglycerides (mg/dL)");

    svg.append("text")      // text label for chart Title
            .attr("x", width / 2 )
            .attr("y", 0 - (margin.top/2))
            .style("text-anchor", "middle")
            .style("font-size", "16px")
            .style("text-decoration", "underline")
            .text("Tryglyceride Levels");

    svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
  };
  processData(data);
</script>
</code>```

I want to create horizontal line at 149 for the upper limit where you want the triglyceride levels to be below.  I try to create that line in the "draw the upper limit" section.  But no line is drawn.

答:
Well I'm not real happy with this solution, but it works.  Could not figure out why the svg.append("line") command failed to display a line, so I used the svg.append("path") command instead.  I added the following code:

```<code>var data2 = [];
data2.push(new DataPoint(data[0].date_time,149));
data2.push(new DataPoint(data[data.length-1].date_time,149));
svg.append("path")
    .datum(data2)
    .attr("d", line)
    .style("stroke", "red")
    .style("stroke-dasharray", "3,3")
</code>```

Then I modified the DataPoint code to this:

```<code>function DataPoint(x,y) {
    this.date_time = x;
    this.date = new Date(x);
    this.total_km = y;
}
</code>```

Now the chart has a red dashed line representing the tryglyceride upper limit:

Title: how to create a line in d3?

Body:
I have managed to create a line chart in d3 but now need to overlay a couple of horizontal lines and vertical lines.  Here is what the chart looks like:

Here is the code:

 <!DOCTYPE html>
    <meta charset="utf-8">

I want to create horizontal line at 149 for the upper limit where you want the triglyceride levels to be below.  I try to create that line in the "draw the upper limit" section.  But no line is drawn.

Body:
Well I'm not real happy with this solution, but it works.  Could not figure out why the svg.append("line") command failed to display a line, so I used the svg.append("path") command instead.  I added the following code:

var data2 = [];
data2.push(new DataPoint(data[0].date_time,149));
data2.push(new DataPoint(data[data.length-1].date_time,149));
svg.append("path")
    .datum(data2)
    .attr("d", line)
    .style("stroke", "red")
    .style("stroke-dasharray", "3,3")

Then I modified the DataPoint code to this:

function DataPoint(x,y) {
    this.date_time = x;
    this.date = new Date(x);
    this.total_km = y;
}

Now the chart has a red dashed line representing the tryglyceride upper limit:


问:
String interpolation in YAML
In Perl I can do something like the following:

```<code>my $home = "/home";
my $alice = "$home/alice";
</code>```

Can I do something like the following in YAML:

```<code>Home: /home
Alice: $Home/alice
</code>```

So "Alice" is effectively /home/alice in the end?

答:
With Yglu, you can write your example this way:

```<code>Home: /home
Alice: !? .Home + '/alice'
</code>```

or

```<code>Home: /home
Alice: !? ('{0}/alice').format($_.Home)
</code>```

Disclaimer: I am the author of Yglu.

ContentLicense: CC BY-SA 3.0

Title: String interpolation in YAML

Body:
In Perl I can do something like the following:

my $home = "/home";
my $alice = "$home/alice";

Can I do something like the following in YAML:

Home: /home
Alice: $Home/alice

So "Alice" is effectively /home/alice in the end?

Body:
With Yglu, you can write your example this way:

Home: /home
Alice: !? .Home + '/alice'

or

Home: /home
Alice: !? ('{0}/alice').format($_.Home)

Disclaimer: I am the author of Yglu.


问:
Blazor binding value to "input date" in one-way
Since Blazor doesn't support stopping event propagation I need one-way binding for an input element with type="date" and with an onchange event handler.

Something like this:

```<code><input type="date" value="@_endDate" format-value="yyyy-MM-dd" onchange="@EndDate_change"/>
</code>```

But this doesn't work. The page contains datePicker but without any value.

"_endDate" is of type DateTime.

If I use Two-way binding then everything working fine.

```<code><input type="date" bind="@_endDate" format-value="yyyy-MM-dd"/>
</code>```

Any idea why the first "input" doesn't work? Is there any mistake or is this a bug in blazor?
For plain text one-way binding with onchange event works without problems.

Edit1:
_endDate contains the current date and is set as DateTime.Now

```<code>protected void EndDate_change(UIChangeEventArgs endDateEvent)
{
    _endDate = Convert.ToDateTime(endDateEvent.Value);
    StateHasChanged();
}
</code>```

答:
Try using @bind-Value instead of just @bind, it works for me</p>

```<code>        <div class="col-4 border border-primary border-0 text-left">
            <InputDate id="expenseedate" class="form-control form-control-sm col-4" format-value="yyyy-MM-dd" @bind-Value="@_endDate" @oninput="@ResetError" placeholder="Enter Expense end Date"></InputDate>
        </div>
</code>```

Body:
Since Blazor doesn't support stopping event propagation I need one-way binding for an input element with type="date" and with an onchange event handler.

Something like this:

<input type="date" value="@_endDate" format-value="yyyy-MM-dd" onchange="@EndDate_change"/>

But this doesn't work. The page contains datePicker but without any value.

"_endDate" is of type DateTime.

If I use Two-way binding then everything working fine.

<input type="date" bind="@_endDate" format-value="yyyy-MM-dd"/>

Any idea why the first "input" doesn't work? Is there any mistake or is this a bug in blazor?
For plain text one-way binding with onchange event works without problems.

Edit1:
_endDate contains the current date and is set as DateTime.Now

protected void EndDate_change(UIChangeEventArgs endDateEvent)
{
    _endDate = Convert.ToDateTime(endDateEvent.Value);
    StateHasChanged();
}

Body:
Try using @bind-Value instead of just @bind, it works for me

        <div class="col-4 border border-primary border-0 text-left">
            <InputDate id="expenseedate" class="form-control form-control-sm col-4" format-value="yyyy-MM-dd" @bind-Value="@_endDate" @oninput="@ResetError" placeholder="Enter Expense end Date"></InputDate>
        </div>


问:
Get git commit list between tags from remote
If there any way I can retrieve all commits between tags from remote master? So far what I did is checkout to master branch and update the repo then fire the following command.</p>

```<code>git checkout master
git pull
git log tag1..tag2 --pretty=format:'* %h %an: %s (%cr)' -- .
</code>```

答:
I[s] there any way I can retrieve all commits between tags from remote master?

It is not clear to me what you mean by retrieve, nor, for that matter, what you mean by between.  But in general, in most cases, you can just run git fetch and use the tag names in your repository.  Your repository will contain copies of the tag names in their repository.  If necessary, you can run git fetch --tags; see below.

Long

Remember that in general, a Git repository contains all commits: one clone is as good as another.1  If some clone has some new commits that you don't yet have, you simply run git fetch to have your Git call up their Git and have their Git give to you the commits that you did not have; and now you have all of their commits.  (They probably have most of yours, but if you have some they did not have, you still have those and they still don't.)

What branch names, tag names, remote-tracking names, and any other names do in a repository is let you pick out any one particular commit.  That is, every commit has a unique name, which is its big ugly hash ID, such as c7a62075917b3340f908093f63f1161c44ed1475.  These names are terrible for humans so we mostly don't use them.  Instead, we have Git remember some specific commit(s) for us, under some sort of human-readable name like master—a branch name—or v2.1, a tag name.  Multiple human-readable names can refer to the same Git hash name.

The key differences between a branch name like master and a tag name like v2.1 are:

Branch names should move over time, so that we can have more commits.  In fact, they're so mobile that they move automatically: when you git checkout some branch name, then make a new commit, the branch name automatically identfiies the new commit you just made.  The new commit itself links back, in Git's usual backwards fashion, to the previous branch-tip commit.

Tag names, by contrast, should never move.  If tag xyz names commit c7a62075917b3340f908093f63f1161c44ed1475 today, it should name that same commit tomorrow.  It should have named that same commit yesterday, too, if the tag name existed yesterday.  Some software actually depends on this.2

Branch names are private, not shared.  When you clone a repository, your clone renames all their branch names to become your remote-tracking names.  That is, their master becomes your origin/master.3  Of course you're allowed to create your own branch names, and then keep them in sync, but you have to then keep them in sync: Git does not do that automatically.4

Tag names, by contrast, are meant to be shared across all clones.  When you clone a repository that has tags v1.0 through v1.7, for instance, you get your own tag names v1.0 through v1.7, but they're literally exactly the same as the original repository's v1.0 through v1.7.  When you run git fetch and pick up new commits, if one of those is tagged v1.8, you get a new v1.8.5

Because of these rules, it's usually unnecessary to do anything special.  If you git clone <url> you get their commits and their tags, and every subsequent git fetch origin gets you any new commits they created, along with any new tags they made for the new commits.  If they go back and add new tag names for old commits, though, you may occasionally need to run git fetch --tags, as noted in footnote 5.

The issue with talking about commits between some particular chosen commits is that commits form a Directed Acyclic Graph or DAG, not just a simple linear chain.  If we have a linear chain like this:

```<code>... <-F <-G <-H ...
</code>```

then the notion of between is clearer: the commits between F and H, including both edges, are F, G, and H, though in the other order since Git works backwards.  If we have two tag names, pointing at commits F and H respectively:

```<code>...--F--G--H--...
     ^     ^
     |     |
  tag:v1 tag:v2
</code>```

then the Git notation v1..v2 (note two dots here) selects commits H and G.  The reason F is excluded is that v1..v2 really means v2 ^v1, i.e., select all commits starting at H and working backwards: H, G, F, and everything before F too; but then select commits starting at F and working backwards, and throw those out of the list.  So from H, G, F, and before, we remove the F-and-before part, leaving just H and G.

To avoid excluding commit F, we just need to start the excluding with whatever commit(s) come before F.  That way we get H and G and F, and toss out whatever is earlier (obviously commit E ).

But we can make commit chains that branch (and later maybe merge):

```<code>         tag:v1.4
             |
             v
          I--J--...
         /
...--G--H
         \
          K--L--...
             ^
             |
         tag:v1.3
</code>```

Which commits are between v1.4 and v1.3?  Git has an answer; it's up to you to decide whether that answer makes sense for your use-case.  (Git's answer is that v1.3..v1.4 selects commits J and I, but not L nor K nor H, nor anything before H).

1Shallow clones are a big exception to this rule, but we can assume your clone is not shallow since you did not mention that.

2For instance, the Go module system assumes Git tag names never move from one Git commit to another.  This allows it to cache the tag-to-hash-ID mapping.

3Note that the kind of clone that the "fork" button achieves on most hosting providers is an exception here: it copies their fork's branch names to your fork's branch names.  But after that, the two are independent.

4This ignores what Git calls a mirror clone, but again, that's OK: we are presumably not talking about mirror clones here.

5This is all under your control: git fetch --tags gets all tags, git fetch --no-tags gets no tags, and the default is a sort of weird mixture where you get the tags that go with the commits you're getting, but not any other tags.  A later git fetch --tags will create new tags, if they created new tags for old commits.  You can also run git fetch with various other options to force tag creation and/or update and/or pruning.

Body:
If there any way I can retrieve all commits between tags from remote master? So far what I did is checkout to master branch and update the repo then fire the following command.

git checkout master
git pull
git log tag1..tag2 --pretty=format:'* %h %an: %s (%cr)' -- .

Body:
I[s] there any way I can retrieve all commits between tags from remote master?

It is not clear to me what you mean by retrieve, nor, for that matter, what you mean by between.  But in general, in most cases, you can just run git fetch and use the tag names in your repository.  Your repository will contain copies of the tag names in their repository.  If necessary, you can run git fetch --tags; see below.

Long

Remember that in general, a Git repository contains all commits: one clone is as good as another.1  If some clone has some new commits that you don't yet have, you simply run git fetch to have your Git call up their Git and have their Git give to you the commits that you did not have; and now you have all of their commits.  (They probably have most of yours, but if you have some they did not have, you still have those and they still don't.)

What branch names, tag names, remote-tracking names, and any other names do in a repository is let you pick out any one particular commit.  That is, every commit has a unique name, which is its big ugly hash ID, such as c7a62075917b3340f908093f63f1161c44ed1475.  These names are terrible for humans so we mostly don't use them.  Instead, we have Git remember some specific commit(s) for us, under some sort of human-readable name like master—a branch name—or v2.1, a tag name.  Multiple human-readable names can refer to the same Git hash name.

The key differences between a branch name like master and a tag name like v2.1 are:

Branch names should move over time, so that we can have more commits.  In fact, they're so mobile that they move automatically: when you git checkout some branch name, then make a new commit, the branch name automatically identfiies the new commit you just made.  The new commit itself links back, in Git's usual backwards fashion, to the previous branch-tip commit.

Tag names, by contrast, should never move.  If tag xyz names commit c7a62075917b3340f908093f63f1161c44ed1475 today, it should name that same commit tomorrow.  It should have named that same commit yesterday, too, if the tag name existed yesterday.  Some software actually depends on this.2

Branch names are private, not shared.  When you clone a repository, your clone renames all their branch names to become your remote-tracking names.  That is, their master becomes your origin/master.3  Of course you're allowed to create your own branch names, and then keep them in sync, but you have to then keep them in sync: Git does not do that automatically.4

Tag names, by contrast, are meant to be shared across all clones.  When you clone a repository that has tags v1.0 through v1.7, for instance, you get your own tag names v1.0 through v1.7, but they're literally exactly the same as the original repository's v1.0 through v1.7.  When you run git fetch and pick up new commits, if one of those is tagged v1.8, you get a new v1.8.5

Because of these rules, it's usually unnecessary to do anything special.  If you git clone <url> you get their commits and their tags, and every subsequent git fetch origin gets you any new commits they created, along with any new tags they made for the new commits.  If they go back and add new tag names for old commits, though, you may occasionally need to run git fetch --tags, as noted in footnote 5.

The issue with talking about commits between some particular chosen commits is that commits form a Directed Acyclic Graph or DAG, not just a simple linear chain.  If we have a linear chain like this:

... <-F <-G <-H ...

then the notion of between is clearer: the commits between F and H, including both edges, are F, G, and H, though in the other order since Git works backwards.  If we have two tag names, pointing at commits F and H respectively:

...--F--G--H--...
     ^     ^
     |     |
  tag:v1 tag:v2

then the Git notation v1..v2 (note two dots here) selects commits H and G.  The reason F is excluded is that v1..v2 really means v2 ^v1, i.e., select all commits starting at H and working backwards: H, G, F, and everything before F too; but then select commits starting at F and working backwards, and throw those out of the list.  So from H, G, F, and before, we remove the F-and-before part, leaving just H and G.

To avoid excluding commit F, we just need to start the excluding with whatever commit(s) come before F.  That way we get H and G and F, and toss out whatever is earlier (obviously commit E ).

But we can make commit chains that branch (and later maybe merge):

         tag:v1.4
             |
             v
          I--J--...
         /
...--G--H
         \
          K--L--...
             ^
             |
         tag:v1.3

Which commits are between v1.4 and v1.3?  Git has an answer; it's up to you to decide whether that answer makes sense for your use-case.  (Git's answer is that v1.3..v1.4 selects commits J and I, but not L nor K nor H, nor anything before H).

1Shallow clones are a big exception to this rule, but we can assume your clone is not shallow since you did not mention that.

2For instance, the Go module system assumes Git tag names never move from one Git commit to another.  This allows it to cache the tag-to-hash-ID mapping.

3Note that the kind of clone that the "fork" button achieves on most hosting providers is an exception here: it copies their fork's branch names to your fork's branch names.  But after that, the two are independent.

4This ignores what Git calls a mirror clone, but again, that's OK: we are presumably not talking about mirror clones here.

5This is all under your control: git fetch --tags gets all tags, git fetch --no-tags gets no tags, and the default is a sort of weird mixture where you get the tags that go with the commits you're getting, but not any other tags.  A later git fetch --tags will create new tags, if they created new tags for old commits.  You can also run git fetch with various other options to force tag creation and/or update and/or pruning.


问:
How can I execute a print statement after a menu loops and then returns back to the main menu?
In the printMenuItems method, the program should loop while the user selects items to add into a shopping cart. While the user is in the items menu, the program should display "your current total is: $" at the bottom until the user chooses to go back to the main menu. Once back at the main menu, it should display "Your total due is: $" at the bottom of the program. I currently have the "Your total due is: $" statement executing before the the program goes back to the main menu, which puts the "Your total due is" statement above the main menu when the user goes back. I'm trying to figure out how to put that statement below the main menu</p>

```<code>import java.util.Scanner;
public class Homework1 {

    static double userTotal = 0;
    static double userCredit = 100;
    static double [] menuPrices = {19.99, 29.49, 15.79, 24.99, 24.99};
    static Scanner myScanner = new Scanner(System.in);

    public static int printMainMenu() {
        System.out.println("Please select a menu item from the list below: \n" +
                "1 - View item menu \n" +
                "2 - Pay total due \n" +
                "3 - Add $5 in credit \n" +
                "4 - Clear order");

        int userChoice = myScanner.nextInt();
        if (userChoice > 0 && userChoice < 5) {
            return userChoice;
        }
        else {
            System.out.println("Please enter a valid option!");
            printMainMenu();
        }
        return 0;
    }

    public static double printMenuItems(double userTotal) {
        System.out.println("What would you like to add to your order? \n" +
                "(1) Toaster: $19.99 \n" +
                "(2) Coffee maker: $24.49 \n" +
                "(3) Waffle maker: $15.79 \n" +
                "(4) Blender: $24.99 \n" +
                "(5) Kettle: $24.99 \n" +
                "(6) Go to the main menu");
        System.out.println("Your current total is: $" + userTotal);
        int menuSelections = myScanner.nextInt();

        if (menuSelections == 1) {
            System.out.println("You have added a Toaster to your order.");
            userTotal += menuPrices[0];
        }
        else if (menuSelections == 2) {
            System.out.println("You have added a Coffee maker to your order.");
            userTotal += menuPrices[1];
        }
        else if (menuSelections == 3) {
            System.out.println("You have added a Waffle maker to your order.");
            userTotal += menuPrices[2];
        }
        else if (menuSelections == 4) {
            System.out.println("You have added a Blender to your order.");
            userTotal += menuPrices[3];
        }
        else if (menuSelections == 5) {
            System.out.println("You have added a Kettle to your order.");
            userTotal += menuPrices[4];
        }
        else if (menuSelections == 6) {
            System.out.println("Your total due is: $" + userTotal);
            return userTotal;
        }
        else {
            System.out.println("Invalid item number please try again");
        }
        return printMenuItems(userTotal);

    }

    public static boolean payTotalDue(double userTotal) {
        double preTaxTotal = userTotal;
        if (preTaxTotal > 50) {
            preTaxTotal -= (preTaxTotal * 0.2);
            preTaxTotal += (preTaxTotal * 0.085);

            if (preTaxTotal <= userCredit) {
                System.out.println("Thank you! You saved: $" + (userTotal + (userTotal * 0.085) - preTaxTotal) +
                        " Your change is: $" + (userCredit - preTaxTotal));
                System.out.println("Your items will be on their way soon!");

            }
            else {
                System.out.println("Insufficient funds!");
                System.exit(0);
            }

        }
        else {
            preTaxTotal += (preTaxTotal * 0.085);
            System.out.println("Thank you! Your change is: $" + (userCredit - preTaxTotal));
            System.out.println("Your items will be on their way soon!");
        }
        return true;
    }

    public static void main(String[] args) {

        while (true) {
            int mainMenuSelection = printMainMenu();
            if (mainMenuSelection == 1) {
                userTotal = printMenuItems(userTotal);

            }
            else if (mainMenuSelection == 2) {
                if (payTotalDue(userTotal)) {
                    userTotal = 0;
                    break;
                }
            }
            else if (mainMenuSelection == 3) {
                userCredit += 5;
                System.out.println("Credit available: $" + userCredit);
            }
            else if (mainMenuSelection == 4) {
                System.out.println("Current order balance has been cleared. Current due: $0.00");
                userTotal = 0;
            }
        }
    }
}
</code>```

答:
Simply under the bloc

```<code> public static int printMainMenu() {
    System.out.println("Please select a menu item from the list below: \n" +
            "1 - View item menu \n" +
            "2 - Pay total due \n" +
            "3 - Add $5 in credit \n" +
            "4 - Clear order");
</code>```

add

```<code>if ( userTotal > 0 ) {
            System.out.println("Your total due is: $" + userTotal);
        }
</code>```

and remove from printing from bloc

```<code> else if (menuSelections == 6) {
        System.out.println("Your total due is: $" + userTotal);
        return userTotal;
    }
</code>```

Also it would be nicer/simpler to use java switch instead of many if else

```<code> switch (myScanner.nextInt()) {
            case 1:
                System.out.println("You have added a Toaster to your order.");
                userTotal += menuPrices[0];
                break;
            case 2:
                System.out.println("You have added a Coffee to your order.");
                userTotal += menuPrices[0];
                break;
            case 3: (continue with same..)
            default:
                System.out.println("Invalid item number please try again");
        }
</code>```

as per question how do I run code printout once you can use this simple snippet

```<code>static boolean doOnce = true; //put this somewhere to be executed once , like begin of your program
...
if ( doOnce ) {
        System.out.println("Your total due is: $" + userTotal);
        doOnce = false;
}
</code>```

Body:
In the printMenuItems method, the program should loop while the user selects items to add into a shopping cart. While the user is in the items menu, the program should display "your current total is: $" at the bottom until the user chooses to go back to the main menu. Once back at the main menu, it should display "Your total due is: $" at the bottom of the program. I currently have the "Your total due is: $" statement executing before the the program goes back to the main menu, which puts the "Your total due is" statement above the main menu when the user goes back. I'm trying to figure out how to put that statement below the main menu

import java.util.Scanner;
public class Homework1 {

    static double userTotal = 0;
    static double userCredit = 100;
    static double [] menuPrices = {19.99, 29.49, 15.79, 24.99, 24.99};
    static Scanner myScanner = new Scanner(System.in);

    public static int printMainMenu() {
        System.out.println("Please select a menu item from the list below: \n" +
                "1 - View item menu \n" +
                "2 - Pay total due \n" +
                "3 - Add $5 in credit \n" +
                "4 - Clear order");

        int userChoice = myScanner.nextInt();
        if (userChoice > 0 && userChoice < 5) {
            return userChoice;
        }
        else {
            System.out.println("Please enter a valid option!");
            printMainMenu();
        }
        return 0;
    }

    public static double printMenuItems(double userTotal) {
        System.out.println("What would you like to add to your order? \n" +
                "(1) Toaster: $19.99 \n" +
                "(2) Coffee maker: $24.49 \n" +
                "(3) Waffle maker: $15.79 \n" +
                "(4) Blender: $24.99 \n" +
                "(5) Kettle: $24.99 \n" +
                "(6) Go to the main menu");
        System.out.println("Your current total is: $" + userTotal);
        int menuSelections = myScanner.nextInt();

        if (menuSelections == 1) {
            System.out.println("You have added a Toaster to your order.");
            userTotal += menuPrices[0];
        }
        else if (menuSelections == 2) {
            System.out.println("You have added a Coffee maker to your order.");
            userTotal += menuPrices[1];
        }
        else if (menuSelections == 3) {
            System.out.println("You have added a Waffle maker to your order.");
            userTotal += menuPrices[2];
        }
        else if (menuSelections == 4) {
            System.out.println("You have added a Blender to your order.");
            userTotal += menuPrices[3];
        }
        else if (menuSelections == 5) {
            System.out.println("You have added a Kettle to your order.");
            userTotal += menuPrices[4];
        }
        else if (menuSelections == 6) {
            System.out.println("Your total due is: $" + userTotal);
            return userTotal;
        }
        else {
            System.out.println("Invalid item number please try again");
        }
        return printMenuItems(userTotal);

    }

    public static boolean payTotalDue(double userTotal) {
        double preTaxTotal = userTotal;
        if (preTaxTotal > 50) {
            preTaxTotal -= (preTaxTotal * 0.2);
            preTaxTotal += (preTaxTotal * 0.085);

            if (preTaxTotal <= userCredit) {
                System.out.println("Thank you! You saved: $" + (userTotal + (userTotal * 0.085) - preTaxTotal) +
                        " Your change is: $" + (userCredit - preTaxTotal));
                System.out.println("Your items will be on their way soon!");

            }
            else {
                System.out.println("Insufficient funds!");
                System.exit(0);
            }

        }
        else {
            preTaxTotal += (preTaxTotal * 0.085);
            System.out.println("Thank you! Your change is: $" + (userCredit - preTaxTotal));
            System.out.println("Your items will be on their way soon!");
        }
        return true;
    }

    public static void main(String[] args) {

        while (true) {
            int mainMenuSelection = printMainMenu();
            if (mainMenuSelection == 1) {
                userTotal = printMenuItems(userTotal);

            }
            else if (mainMenuSelection == 2) {
                if (payTotalDue(userTotal)) {
                    userTotal = 0;
                    break;
                }
            }
            else if (mainMenuSelection == 3) {
                userCredit += 5;
                System.out.println("Credit available: $" + userCredit);
            }
            else if (mainMenuSelection == 4) {
                System.out.println("Current order balance has been cleared. Current due: $0.00");
                userTotal = 0;
            }
        }
    }
}

Body:
Simply under the bloc

 public static int printMainMenu() {
    System.out.println("Please select a menu item from the list below: \n" +
            "1 - View item menu \n" +
            "2 - Pay total due \n" +
            "3 - Add $5 in credit \n" +
            "4 - Clear order");

add

if ( userTotal > 0 ) {
            System.out.println("Your total due is: $" + userTotal);
        }

and remove from printing from bloc

 else if (menuSelections == 6) {
        System.out.println("Your total due is: $" + userTotal);
        return userTotal;
    }

Also it would be nicer/simpler to use java switch instead of many if else

 switch (myScanner.nextInt()) {
            case 1:
                System.out.println("You have added a Toaster to your order.");
                userTotal += menuPrices[0];
                break;
            case 2:
                System.out.println("You have added a Coffee to your order.");
                userTotal += menuPrices[0];
                break;
            case 3: (continue with same..)
            default:
                System.out.println("Invalid item number please try again");
        }

as per question how do I run code printout once you can use this simple snippet

static boolean doOnce = true; //put this somewhere to be executed once , like begin of your program
...
if ( doOnce ) {
        System.out.println("Your total due is: $" + userTotal);
        doOnce = false;
}


问:
How do I resolve the "ValueError: not enough values to unpack" in this sklearn code?
Setting up a basic pipeline for Titanic Kaggle data, but am getting the error: ValueError: not enough values to unpack (expected 3, got 2).

While there are a handful of SO posts on this error, they don't quite line up, or provide solid method for diagnosing this problem, let alone a solution.  The error's traceback is vague, unfortunately. I've commented out most lines and rerun the code to see if I could narrow down which

Here's a sample of the data:

```<code>PassengerId Pclass  Sex     Age     SibSp   Parch   Fare    Embarked    Title
892           3     male    34.5      0       0     7.8292      Q       Mr
893           3     female  47.0      1       0     7.0000      S       Mrs
894           2     male    62.0      0       0     9.6875      Q       Mr
895           3     male    27.0      0       0     8.6625      S       Mr
896           3     female  22.0      1       1     12.2875     S       Mrs
</code>```

Here's the pipeline code I'm working with:

```<code>from sklearn.pipeline import Pipeline

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

#Create a column transformer to impute missing values and one-hot encode specific columns
col_transform = ColumnTransformer(transformers=[
                                                ('one_hot', OneHotEncoder(categories='auto', sparse=False), ['Sex', 'Embarked', 'Title']),
                                                ('imputer', SimpleImputer(strategy='median'))],
                                  remainder='passthrough')

#Create a pipeline for the column transformer and logistic regressor
pipe = Pipeline(steps=[('encoding', col_transform),
                       ('logistic_reg', LogisticRegression(max_iter=10000, tol=0.1))])
param_grid = {
#     'logistic_reg__class_weight':[None, 'balanced'],
#     'logistic_reg__solver':['lbfgs', 'liblinear', 'newton-cg']
}

clf = GridSearchCV(pipe, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1)

best_clf=clf.fit(X_train, y_train)
</code>```

Question:  Any ideas why I'm getting the error mentioned above?

EDIT:  Here's the full error

```<code>_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 418, in _process_worker
    r = call_item()
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 272, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 567, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 516, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 352, in fit
    Xt, fit_params = self._fit(X, y, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 317, in _fit
    **fit_params_steps[name])
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 716, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py", line 472, in fit_transform
    self._validate_transformers()
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py", line 265, in _validate_transformers
    names, transformers, _ = zip(*self.transformers)
ValueError: not enough values to unpack (expected 3, got 2)
"""

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-17-6a051cf930ab> in <module>
     25 clf = GridSearchCV(pipe, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1) #5 fold cross-validation; n_jobs=use all processors
     26
---> 27 best_clf=clf.fit(X_train, y_train)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    686                 return results
    687
--> 688             self._run_search(evaluate_candidates)
    689
    690         # For multi-metric evaluation, store the best_index_, best_params_ and

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates)
   1147     def _run_search(self, evaluate_candidates):
   1148         """Search all candidates in param_grid"""
-> 1149         evaluate_candidates(ParameterGrid(self.param_grid))
   1150
   1151

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params)
    665                                for parameters, (train, test)
    666                                in product(candidate_params,
--> 667                                           cv.split(X, y, groups)))
    668
    669                 if len(out) < 1:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
    932
    933             with self._backend.retrieval_context():
--> 934                 self.retrieve()
    935             # Make sure that we get a last message telling us we are done
    936             elapsed_time = time.time() - self._start_time

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in retrieve(self)
    831             try:
    832                 if getattr(self._backend, 'supports_timeout', False):
--> 833                     self._output.extend(job.get(timeout=self.timeout))
    834                 else:
    835                     self._output.extend(job.get())

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in wrap_future_result(future, timeout)
    519         AsyncResults.get from multiprocessing."""
    520         try:
--> 521             return future.result(timeout=timeout)
    522         except LokyTimeoutError:
    523             raise TimeoutError()

~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    433                 raise CancelledError()
    434             elif self._state == FINISHED:
--> 435                 return self.__get_result()
    436             else:
    437                 raise TimeoutError()

~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

ValueError: not enough values to unpack (expected 3, got 2)
</code>```

Edit 2:

```<code>col_transform = ColumnTransformer(transformers=[
                                                ('imputer', SimpleImputer(missing_values=np.nan, strategy='median')),
                                                ('one_hot', OneHotEncoder(categories='auto', sparse=False))],
                                  remainder='passthrough')
</code>```

答:
For those that have run across the same problem, here's what I've figured out:  The syntax of the transformers inside the ColumnTransformer is critical. They must be numbers, and for the OneHotEncoder, it must apparently be in the slice(x, y,...z) format, with the arguments being integer column numbers (I tried to add it as a list and tuple, and neither worked).  Sergey Bushmanov had the first bit right (that my imputer wasn't functioning because I didn't specify the column correctly, but there'd been no indication as to how the OneHotEncoder issue should be resolved, so I'm marking this answer as correct.

```<code>ct = ColumnTransformer(
                       [("imputer", SimpleImputer(missing_values=np.nan, strategy='median'), [2]),
                        ("one_hot", OneHotEncoder(categories='auto', sparse=False), slice(1, 6, 7))])
</code>```

Body:
Setting up a basic pipeline for Titanic Kaggle data, but am getting the error: ValueError: not enough values to unpack (expected 3, got 2).

While there are a handful of SO posts on this error, they don't quite line up, or provide solid method for diagnosing this problem, let alone a solution.  The error's traceback is vague, unfortunately. I've commented out most lines and rerun the code to see if I could narrow down which

Here's a sample of the data:

PassengerId Pclass  Sex     Age     SibSp   Parch   Fare    Embarked    Title
892           3     male    34.5      0       0     7.8292      Q       Mr
893           3     female  47.0      1       0     7.0000      S       Mrs
894           2     male    62.0      0       0     9.6875      Q       Mr
895           3     male    27.0      0       0     8.6625      S       Mr
896           3     female  22.0      1       1     12.2875     S       Mrs

Here's the pipeline code I'm working with:

from sklearn.pipeline import Pipeline

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

#Create a column transformer to impute missing values and one-hot encode specific columns
col_transform = ColumnTransformer(transformers=[
                                                ('one_hot', OneHotEncoder(categories='auto', sparse=False), ['Sex', 'Embarked', 'Title']),
                                                ('imputer', SimpleImputer(strategy='median'))],
                                  remainder='passthrough')

#Create a pipeline for the column transformer and logistic regressor
pipe = Pipeline(steps=[('encoding', col_transform),
                       ('logistic_reg', LogisticRegression(max_iter=10000, tol=0.1))])
param_grid = {
#     'logistic_reg__class_weight':[None, 'balanced'],
#     'logistic_reg__solver':['lbfgs', 'liblinear', 'newton-cg']
}

clf = GridSearchCV(pipe, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1)

best_clf=clf.fit(X_train, y_train)

Question:  Any ideas why I'm getting the error mentioned above?

EDIT:  Here's the full error

_RemoteTraceback                          Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 418, in _process_worker
    r = call_item()
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\externals\loky\process_executor.py", line 272, in __call__
    return self.fn(*self.args, **self.kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py", line 567, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 516, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 352, in fit
    Xt, fit_params = self._fit(X, y, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 317, in _fit
    **fit_params_steps[name])
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\memory.py", line 355, in __call__
    return self.func(*args, **kwargs)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\pipeline.py", line 716, in _fit_transform_one
    res = transformer.fit_transform(X, y, **fit_params)
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py", line 472, in fit_transform
    self._validate_transformers()
  File "C:\Users\Lofgran\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py", line 265, in _validate_transformers
    names, transformers, _ = zip(*self.transformers)
ValueError: not enough values to unpack (expected 3, got 2)
"""

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-17-6a051cf930ab> in <module>
     25 clf = GridSearchCV(pipe, param_grid=param_grid, cv=5, verbose=True, n_jobs=-1) #5 fold cross-validation; n_jobs=use all processors
     26
---> 27 best_clf=clf.fit(X_train, y_train)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    686                 return results
    687
--> 688             self._run_search(evaluate_candidates)
    689
    690         # For multi-metric evaluation, store the best_index_, best_params_ and

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in _run_search(self, evaluate_candidates)
   1147     def _run_search(self, evaluate_candidates):
   1148         """Search all candidates in param_grid"""
-> 1149         evaluate_candidates(ParameterGrid(self.param_grid))
   1150
   1151

~\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\model_selection\_search.py in evaluate_candidates(candidate_params)
    665                                for parameters, (train, test)
    666                                in product(candidate_params,
--> 667                                           cv.split(X, y, groups)))
    668
    669                 if len(out) < 1:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in __call__(self, iterable)
    932
    933             with self._backend.retrieval_context():
--> 934                 self.retrieve()
    935             # Make sure that we get a last message telling us we are done
    936             elapsed_time = time.time() - self._start_time

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\parallel.py in retrieve(self)
    831             try:
    832                 if getattr(self._backend, 'supports_timeout', False):
--> 833                     self._output.extend(job.get(timeout=self.timeout))
    834                 else:
    835                     self._output.extend(job.get())

~\AppData\Local\Continuum\anaconda3\lib\site-packages\joblib\_parallel_backends.py in wrap_future_result(future, timeout)
    519         AsyncResults.get from multiprocessing."""
    520         try:
--> 521             return future.result(timeout=timeout)
    522         except LokyTimeoutError:
    523             raise TimeoutError()

~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    433                 raise CancelledError()
    434             elif self._state == FINISHED:
--> 435                 return self.__get_result()
    436             else:
    437                 raise TimeoutError()

~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    382     def __get_result(self):
    383         if self._exception:
--> 384             raise self._exception
    385         else:
    386             return self._result

ValueError: not enough values to unpack (expected 3, got 2)

Edit 2:

col_transform = ColumnTransformer(transformers=[
                                                ('imputer', SimpleImputer(missing_values=np.nan, strategy='median')),
                                                ('one_hot', OneHotEncoder(categories='auto', sparse=False))],
                                  remainder='passthrough')

Body:
For those that have run across the same problem, here's what I've figured out:  The syntax of the transformers inside the ColumnTransformer is critical. They must be numbers, and for the OneHotEncoder, it must apparently be in the slice(x, y,...z) format, with the arguments being integer column numbers (I tried to add it as a list and tuple, and neither worked).  Sergey Bushmanov had the first bit right (that my imputer wasn't functioning because I didn't specify the column correctly, but there'd been no indication as to how the OneHotEncoder issue should be resolved, so I'm marking this answer as correct.

ct = ColumnTransformer(
                       [("imputer", SimpleImputer(missing_values=np.nan, strategy='median'), [2]),
                        ("one_hot", OneHotEncoder(categories='auto', sparse=False), slice(1, 6, 7))])


问:
Able to use Spinnaker without a Cloud provider?
My team is working on improving our CI/CD pipeline, and have started looking into Spinnaker. We don't yet have a cloud platform, but would like to try and setup a POC in a local environment. Is this possible? I have seen plenty of articles about setting up the local environment, but it still seems like we have to choose a cloud provider.

Does anyone have experience with this, or is it not possible?

NOTE: In the future we plan to have a cloud provider, but due to time constraints around having infrastructure provisioned it would be in our best interest to start out locally and add the cloud later.

答:
Yes is possible. I run spinnaker Open source from a K3S cluster in a local ubuntu server. There is a project by Armory called Minnaker that automates this. I highly recommend you try it out for PoC and even some Prod deployments. It works fine and it doesnt add all the complexities of installations.

Minnaker Project on GitHub


问:
Can you call React's useState and useCallback multiple times in a single functional component? If so, how does it work?
I couldn't find any mention of this yet in the official React docs or on the blagosphere.

I think you can and usually should do something like this when you have more than one state variable:

```<code>function MyComponent() {
  const [foo, setFoo] = useState(0);
  const [bar, setBar] = useState(1);

  return (
    <div>
      <div onClick={() => setFoo(foo+1)}>{foo}</div>
      <div onClick={() => setBar(bar+1)}>{bar}</div>
    </div>
  );
}
</code>```

Is this allowed and encouraged, as opposed to calling useState a single time with an all-encompassing object called state which has fields foo and bar? If it is allowed and encouraged, how does useState know whenever it's called whether it's referring to the already stored foo or the already stored bar?

I also have basically the same question about useCallback. I've wondered, if I call useCallback twice in the same component to create two different callbacks, how does useCallback know that I meant to reference a function defined before vs create a new one, and if referencing an already used function it needs to return the memoized version of, how does it know which of the two? Especially if both callbacks have the same list of dependencies?

答:
It's fine to use multiple useState in your render function.

One important requirement is that their number and order should always be the same.

References:

https://reactjs.org/docs/hooks-rules.html#explanation

Body:
I couldn't find any mention of this yet in the official React docs or on the blagosphere.

I think you can and usually should do something like this when you have more than one state variable:

function MyComponent() {
  const [foo, setFoo] = useState(0);
  const [bar, setBar] = useState(1);

  return (

 setFoo(foo+1)}>{foo}

 setBar(bar+1)}>{bar}

  );
}

Is this allowed and encouraged, as opposed to calling useState a single time with an all-encompassing object called state which has fields foo and bar? If it is allowed and encouraged, how does useState know whenever it's called whether it's referring to the already stored foo or the already stored bar?

I also have basically the same question about useCallback. I've wondered, if I call useCallback twice in the same component to create two different callbacks, how does useCallback know that I meant to reference a function defined before vs create a new one, and if referencing an already used function it needs to return the memoized version of, how does it know which of the two? Especially if both callbacks have the same list of dependencies?


问:
Handel on volume slider not showing up?
I have a volume slider, I am using jquery. And although it works, the 'ball' or 'handle' is not showing up.

How can I make the handled show up?

I have imported for jquery:

```<code><script src="jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
</code>```

Here is all the code: js code to handle the changes in volume, as well as its html and css.

$("#volume").slider({
   min: 0,
   max: 100,
   value: 0,
  range: "min",
   slide: function(event, ui) {
     setVolume(ui.value / 100);
   }
 });

 function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.audioUtilitiesDiv {
  width: 20%;
  display: inline-block;
  background-color: lightblue;
}

#player {
 width: 350px;
 height: 50px;
 position: relative;
 margin: 0 auto;
 top: 80px;

 i {
  position: absolute;
  margin-top: -6px;
  color: #666;
 }

 i.fa-volume-down {
  margin-left: -8px;
 }

 i.fa-volume-up {
  margin-right: -8px;
  right: 0;
 }
}

#volume {
 position: absolute;
 left: 24px;
 margin: 0 auto;
 height: 5px;
 width: 300px;
 background: #555;
 border-radius: 15px;

 .ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: green;
  border: none;
  border-radius: 10px;
   outline: none;
 }

 .ui-slider-handle {
  width: 20px;
   height: 20px;
  border-radius: 20px;
   background: #FFF;
   position: absolute;
   margin-left: -8px;
   margin-top: -8px;
   cursor: pointer;
   outline: none;
 }
}</code>```

```

Thanks for any help I receive, please let me know if you need any more info.

答:
You need to include the proper jQuery, jQuery UI, and CSS libraries to allow Slider to work properly. I also found a number of CSS Syntax errors. Consider the following.

$(function() {
  var audioElement = $("<audio>");

  function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
  }

  $("#volume").slider({
    min: 0,
    max: 1,
    value: 0,
    step: 0.1,
    range: "min",
    slide: function(event, ui) {
      setVolume(ui.value);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.audioUtilitiesDiv {
  display: inline-block;
  background-color: lightblue;
}

#player {
  width: 350px;
  height: 50px;
  position: relative;
  margin: 0 auto;
  top: 80px;
}

i {
  position: absolute;
  margin-top: -6px;
  color: #666;
}

i.fa-volume-down {
  margin-left: -8px;
}

i.fa-volume-up {
  margin-right: -8px;
  right: 0;
}

#volume {
  position: absolute;
  left: 24px;
  margin: 0 auto;
  height: 5px;
  width: 300px;
  background: #555;
  border-radius: 15px;
}

.ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: green;
  border: none;
  border-radius: 10px;
  outline: none;
}

.ui-slider-handle {
  width: 20px;
  height: 20px;
  border-radius: 20px;
  background: #FFF;
  position: absolute;
  margin-left: -8px;
  margin-top: -8px;
  cursor: pointer;
  outline: none;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

```

Title: Handel on volume slider not showing up?

Body:
I have a volume slider, I am using jquery. And although it works, the 'ball' or 'handle' is not showing up.

How can I make the handled show up?

I have imported for jquery:

Here is all the code: js code to handle the changes in volume, as well as its html and css.

$("#volume").slider({
   min: 0,
   max: 100,
   value: 0,
  range: "min",
   slide: function(event, ui) {
     setVolume(ui.value / 100);
   }
 });

 function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
 }

.audioUtilitiesDiv {
  width: 20%;
  display: inline-block;
  background-color: lightblue;
}

#player {
 width: 350px;
 height: 50px;
 position: relative;
 margin: 0 auto;
 top: 80px;

 i {
  position: absolute;
  margin-top: -6px;
  color: #666;
 }

 i.fa-volume-down {
  margin-left: -8px;
 }

 i.fa-volume-up {
  margin-right: -8px;
  right: 0;
 }
}

#volume {
 position: absolute;
 left: 24px;
 margin: 0 auto;
 height: 5px;
 width: 300px;
 background: #555;
 border-radius: 15px;

 .ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: green;
  border: none;
  border-radius: 10px;
   outline: none;
 }

 .ui-slider-handle {
  width: 20px;
   height: 20px;
  border-radius: 20px;
   background: #FFF;
   position: absolute;
   margin-left: -8px;
   margin-top: -8px;
   cursor: pointer;
   outline: none;
 }
}

Thanks for any help I receive, please let me know if you need any more info.

Body:
You need to include the proper jQuery, jQuery UI, and CSS libraries to allow Slider to work properly. I also found a number of CSS Syntax errors. Consider the following.

$(function() {
  var audioElement = $("<audio>");

  function setVolume(myVolume) {
    if (audioElement != undefined) {
      audioElement.volume = myVolume;
    }
  }

  $("#volume").slider({
    min: 0,
    max: 1,
    value: 0,
    step: 0.1,
    range: "min",
    slide: function(event, ui) {
      setVolume(ui.value);
    }
  });
});

.audioUtilitiesDiv {
  display: inline-block;
  background-color: lightblue;
}

#player {
  width: 350px;
  height: 50px;
  position: relative;
  margin: 0 auto;
  top: 80px;
}

i {
  position: absolute;
  margin-top: -6px;
  color: #666;
}

i.fa-volume-down {
  margin-left: -8px;
}

i.fa-volume-up {
  margin-right: -8px;
  right: 0;
}

#volume {
  position: absolute;
  left: 24px;
  margin: 0 auto;
  height: 5px;
  width: 300px;
  background: #555;
  border-radius: 15px;
}

.ui-slider-range-min {
  height: 5px;
  width: 300px;
  position: absolute;
  background: green;
  border: none;
  border-radius: 10px;
  outline: none;
}

.ui-slider-handle {
  width: 20px;
  height: 20px;
  border-radius: 20px;
  background: #FFF;
  position: absolute;
  margin-left: -8px;
  margin-top: -8px;
  cursor: pointer;
  outline: none;
}

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="audioUtilitiesDiv">
  <div id="player">
    <i class="fa fa-volume-down"></i>
    <div id="volume"></div>
    <i class="fa fa-volume-up"></i>
  </div>
</div>


问:
In pandas, how to convert a numeric type to category type to use with seaborn hue
I am stuck on what seems like an easy problem trying to color the different groups on a scatterplot I am creating. I have the following example dataframe and graph:

```<code>test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
# test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)
</code>```

which creates this graph:

However, instead of a continuous scale, I'd like a categorical scale for each of the 3 categories [2, 3, 4]. After I uncomment the line of code test_df['D'] = ..., to change this column to a category column-type for category-coloring in the seaborn plot, I receive the following error from the seaborn plot: TypeError: data type not understood

Does anybody know the correct way to convert this numeric column to a factor / categorical column to use for coloring?

Thanks!

答:
I copy/pasted your code, added libraries for import and removed the comment as I thought it looked good. I get a plot with 'categorical' colouring for value [2,3,4] without changing any of your code.

Try updating your seaborn module using: pip install --upgrade seaborn

Here is a list of working libraries used with your code.

```<code>matplotlib==3.1.2
numpy==1.18.1
seaborn==0.10.0
pandas==0.25.3
</code>```

... which executed below code.

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

test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)
plt.show()
```

Body:
I am stuck on what seems like an easy problem trying to color the different groups on a scatterplot I am creating. I have the following example dataframe and graph:

test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
# test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)

which creates this graph:

However, instead of a continuous scale, I'd like a categorical scale for each of the 3 categories [2, 3, 4]. After I uncomment the line of code test_df['D'] = ..., to change this column to a category column-type for category-coloring in the seaborn plot, I receive the following error from the seaborn plot: TypeError: data type not understood

Does anybody know the correct way to convert this numeric column to a factor / categorical column to use for coloring?

Thanks!

Body:
I copy/pasted your code, added libraries for import and removed the comment as I thought it looked good. I get a plot with 'categorical' colouring for value [2,3,4] without changing any of your code.

Try updating your seaborn module using: pip install --upgrade seaborn

Here is a list of working libraries used with your code.

matplotlib==3.1.2
numpy==1.18.1
seaborn==0.10.0
pandas==0.25.3

... which executed below code.

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

test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)
plt.show()


问:
set_facts with dict as argument of a loop
I'd like to obtain the list of bridged interfaces grouped by master like this:

```<code>brv100:
 - vnet0
 - eth0
brv101:
  - vnet1
  - eth1
</code>```

I want to use native json output from the shell commands.
The only thing I managed to do is to get a predefined number of interfaces like this:

```<code>- hosts: localhost
  gather_facts: no

  tasks:
    - shell:
        cmd: ip -details -pretty -json link show type bridge
      register: list_bridges

    - set_fact:
        bridges: "{{ list_bridges.stdout }}"

    - debug:
        msg: "{{ bridges | map(attribute='ifname') | list}}"

    - name: get json
      shell:
        cmd: ip -details -pretty -json link show master "{{ifname}}"
      with_items: "{{bridges | map(attribute='ifname') | list}}"
      loop_control:
        loop_var: ifname
      register: list_interfaces

    - set_fact:
        interfaces: "{{ list_interfaces.results | map(attribute='stdout') | list }}"

    - set_fact:
        toto: "{{interfaces.1}} + {{interfaces.2}}"
    - debug:
        msg: "{{toto | map(attribute='ifname')|list}}"
</code>```

Now if I want to do the same with a loop :

```<code>    - set_fact:
    toto: " {{item|default([])}}+ {{ item |default([])}}.{{idx}} "
  loop: "{{interfaces}}"
  loop_control:
   label: "{{item}}"
   index_var: idx
   - debug: var=toto
</code>```

The result doesn't seem to be a list of list, but a list of strings and I can't extract the 'ifname' values with a simple debug

```<code>    - debug:
        msg: "{{toto | map(attribute='ifname')|list}}"
</code>```

What am I supposed to do so as to get benefit of the json native output and get simple list of bridged interfaces (like brctl show was used to do)?

答:
The lists of bridged interfaces grouped by the master are available in ansible_facts. The task below sets the dictionary of the bridges and bridged interfaces

```<code>- set_fact:
    bridges: "{{ dict(ansible_facts|
                 dict2items|
                 json_query('[?value.type == `bridge`].[key, value.interfaces]')) }}"
</code>```

Q: "Manage to get the same result manipulating JSON data."

A: The output of the ip -json ... command is JSON formated string which must be converted to JSON dictionary in Ansible by the from_yaml filter (JSON is a subset of YAML). For example, the tasks below give the same result

```<code>  vars:

    my_debug: false

  tasks:

    - name: Get bridges names
      command: "ip -details -json link show type bridge"
      register: list_bridges
    - set_fact:
        bridges: "{{ list_bridges.stdout|
                     from_yaml|
                     map(attribute='ifname')|
                     list }}"
    - debug:
        var: bridges
      when: my_debug

    - name: Get bridges interfaces
      command: "ip -details -json link show master {{ item }}"
      loop: "{{ bridges }}"
      register: list_interfaces
    - set_fact:
        bridges_interfaces: "{{ list_interfaces.results|
                                json_query('[].stdout')|
                                map('from_yaml')|
                                list }}"

    - debug:
        msg: "{{ msg.split('\n') }}"
      vars:
        msg: "{{ item|to_nice_yaml }}"
      loop: "{{ bridges_interfaces }}"
      loop_control:
        label: "{{ item|json_query('[].ifname') }}"
      when: my_debug

    - name: Set dictionary of bridges
      set_fact:
        bridges_dict: "{{ bridges_dict|
                          default({})|
                          combine({item.0: item.1|json_query('[].ifname')}) }}"
      loop: "{{ bridges|zip(bridges_interfaces)|list }}"
      loop_control:
        label: "{{ item.1|json_query('[].ifname') }}"
    - debug:
        var: bridges_dict
</code>```

Template to write the bridges to a file

```<code>{% for k,v in bridges_dict.items() %}
{{ k }}:
{% if v is iterable %}
{% for i in v %}
  - {{ i }}
{% endfor %}
{% endif %}
{% endfor %}
</code>```

```<code>    - name: Write the bridges to file
      template:
        src: bridges.txt.j2
        dest: bridges.txt
</code>```

The file bridges.txt will be created in the remote host running the task.

Body:
I'd like to obtain the list of bridged interfaces grouped by master like this:

brv100:
 - vnet0
 - eth0
brv101:
  - vnet1
  - eth1

I want to use native json output from the shell commands.
The only thing I managed to do is to get a predefined number of interfaces like this:

- hosts: localhost
  gather_facts: no

  tasks:
    - shell:
        cmd: ip -details -pretty -json link show type bridge
      register: list_bridges

    - set_fact:
        bridges: "{{ list_bridges.stdout }}"

    - debug:
        msg: "{{ bridges | map(attribute='ifname') | list}}"

    - name: get json
      shell:
        cmd: ip -details -pretty -json link show master "{{ifname}}"
      with_items: "{{bridges | map(attribute='ifname') | list}}"
      loop_control:
        loop_var: ifname
      register: list_interfaces

    - set_fact:
        interfaces: "{{ list_interfaces.results | map(attribute='stdout') | list }}"

    - set_fact:
        toto: "{{interfaces.1}} + {{interfaces.2}}"
    - debug:
        msg: "{{toto | map(attribute='ifname')|list}}"

Now if I want to do the same with a loop :

    - set_fact:
    toto: " {{item|default([])}}+ {{ item |default([])}}.{{idx}} "
  loop: "{{interfaces}}"
  loop_control:
   label: "{{item}}"
   index_var: idx
   - debug: var=toto

The result doesn't seem to be a list of list, but a list of strings and I can't extract the 'ifname' values with a simple debug

    - debug:
        msg: "{{toto | map(attribute='ifname')|list}}"

What am I supposed to do so as to get benefit of the json native output and get simple list of bridged interfaces (like brctl show was used to do)?

Body:
The lists of bridged interfaces grouped by the master are available in ansible_facts. The task below sets the dictionary of the bridges and bridged interfaces

- set_fact:
    bridges: "{{ dict(ansible_facts|
                 dict2items|
                 json_query('[?value.type == `bridge`].[key, value.interfaces]')) }}"

Q: "Manage to get the same result manipulating JSON data."

A: The output of the ip -json ... command is JSON formated string which must be converted to JSON dictionary in Ansible by the from_yaml filter (JSON is a subset of YAML). For example, the tasks below give the same result

  vars:

    my_debug: false

  tasks:

    - name: Get bridges names
      command: "ip -details -json link show type bridge"
      register: list_bridges
    - set_fact:
        bridges: "{{ list_bridges.stdout|
                     from_yaml|
                     map(attribute='ifname')|
                     list }}"
    - debug:
        var: bridges
      when: my_debug

    - name: Get bridges interfaces
      command: "ip -details -json link show master {{ item }}"
      loop: "{{ bridges }}"
      register: list_interfaces
    - set_fact:
        bridges_interfaces: "{{ list_interfaces.results|
                                json_query('[].stdout')|
                                map('from_yaml')|
                                list }}"

    - debug:
        msg: "{{ msg.split('\n') }}"
      vars:
        msg: "{{ item|to_nice_yaml }}"
      loop: "{{ bridges_interfaces }}"
      loop_control:
        label: "{{ item|json_query('[].ifname') }}"
      when: my_debug

    - name: Set dictionary of bridges
      set_fact:
        bridges_dict: "{{ bridges_dict|
                          default({})|
                          combine({item.0: item.1|json_query('[].ifname')}) }}"
      loop: "{{ bridges|zip(bridges_interfaces)|list }}"
      loop_control:
        label: "{{ item.1|json_query('[].ifname') }}"
    - debug:
        var: bridges_dict

Template to write the bridges to a file

{% for k,v in bridges_dict.items() %}
{{ k }}:
{% if v is iterable %}
{% for i in v %}
  - {{ i }}
{% endfor %}
{% endif %}
{% endfor %}

    - name: Write the bridges to file
      template:
        src: bridges.txt.j2
        dest: bridges.txt

The file bridges.txt will be created in the remote host running the task.


问:
AWS CLI: Copy certain number of files from each bucket to local
I'm trying to download the first (just to give an example) 10 files from every bucket.
I'm new to this, I've read aws cli's documentation but couldn't find anything about this.</p>

答:
There is no single command that can do this.

However, you could combine several AWS CLI commands together.

For example, these commands will LIST the first 10 objects:

for bucket in $(aws s3api list-buckets --query Buckets[].[Name] --output text);
do
  echo Bucket: $bucket;
  aws s3api list-objects --query Contents[0:10].[Key] --bucket $bucket --output text;
done;
```

First, it obtains a list of buckets then, for each bucket, lists the names of the first 10 files.

You could modify if by adding another for that will call aws s3 cp with the filename to download the objects.

You should also consider what you'd like to do about clashing filenames (for example, if a file with the same name appears in the first 10 files of more than one bucket).

Body:
There is no single command that can do this.

However, you could combine several AWS CLI commands together.

For example, these commands will LIST the first 10 objects:

for bucket in $(aws s3api list-buckets --query Buckets[].[Name] --output text);
do
  echo Bucket: $bucket;
  aws s3api list-objects --query Contents[0:10].[Key] --bucket $bucket --output text;
done;

First, it obtains a list of buckets then, for each bucket, lists the names of the first 10 files.

You could modify if by adding another for that will call aws s3 cp with the filename to download the objects.

You should also consider what you'd like to do about clashing filenames (for example, if a file with the same name appears in the first 10 files of more than one bucket).