问:
javascript enter number of seconds - not less than zero
i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.

how can a make the code logic?

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()">Click</button>
</form></code>```

what should i do? anyone help me?

答:
With JavaScript you can convert your user's input to a Number then check its value with an equality condition.

E.g. you could fill out your sec() function like this:

function sec() {
  const seconds_str = document.getElementById("seconds").value;
  const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions
  let result = "";

  if (seconds_num < 0) {
    result = "Is less than zero :'(";
  } else {
    result = "Is NOT less than zero :)";
  }

  console.log("User input = " + seconds_str);
  console.log("Converted to integer = " + seconds_num);
  console.log(result);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()" type="button">Click</button>
</form></code>```

It would be up to you what you do when you detect a number less than zero. E.g. prevent form submitting, show an error message etc...

Body:
i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.

how can a make the code logic?

function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}

<form>
  Number of seconds:
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()">Click</button>
</form>

what should i do? anyone help me?

Body:
With JavaScript you can convert your user's input to a Number then check its value with an equality condition.

E.g. you could fill out your sec() function like this:

function sec() {
  const seconds_str = document.getElementById("seconds").value;
  const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions
  let result = "";

  if (seconds_num < 0) {
    result = "Is less than zero :'(";
  } else {
    result = "Is NOT less than zero :)";
  }

  console.log("User input = " + seconds_str);
  console.log("Converted to integer = " + seconds_num);
  console.log(result);

}

<form>
  <label for="seconds">Number of seconds:</label>
  <input type="number" id="seconds" name="seconds">
  <button onclick="sec()" type="button">Click</button>
</form>

It would be up to you what you do when you detect a number less than zero. E.g. prevent form submitting, show an error message etc...


来源: stackexchange

问:
Running MySQL Query in Wordpress Causes HTML Markup to Disappear?
We're having an issue adding MySQL queries to our page. It seems that whenever something is run at the top of the page, the rest of the markup and php functions to follow don't show up/aren't run.

Here's a sample query that causes this issue:

```<code>global $wpdb;

$add_query = "CREATE TABLE thetesttable
        (
           id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
           product VARCHAR(50)
        )";

$wpdb->query($add_query) or die(mysql_error());
</code>```

Loading the page once results in a blank page.

The second time, we see Table 'thetesttable' already exists, which means that our queries are getting through.

There are no other errors on the page or anything else detected by Google Chrome.

What could be causing this problem?

Many thanks,

Justian Meyer

答:
After all additional comments, than I suggest adding additional query which is

SHOW TABLES LIKE 'thetesttable';

Run the CREATE TABLE query if no results from above one and skip it if table exist.

ContentLicense: CC BY-SA 3.0

Body:
We're having an issue adding MySQL queries to our page. It seems that whenever something is run at the top of the page, the rest of the markup and php functions to follow don't show up/aren't run.

Here's a sample query that causes this issue:

global $wpdb;

$add_query = "CREATE TABLE thetesttable
        (
           id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
           product VARCHAR(50)
        )";

$wpdb->query($add_query) or die(mysql_error());

Loading the page once results in a blank page.

The second time, we see Table 'thetesttable' already exists, which means that our queries are getting through.

There are no other errors on the page or anything else detected by Google Chrome.

What could be causing this problem?

Many thanks,

Justian Meyer


问:
Persisting the state of d3 treemap on drilling down to child nodes
I am working on the d3 treemap v5 in which I need to persist the state of the treemap in localstorage on each user click. My code is in https://codesandbox.io/s/d3-treemap-wfbtg
When a user clicks the top parent tile it is drilled down to the children tiles. How to persist that in local storage when the user reloads the browser he wants to see the drilled down children tiles. </p>

```<code>class Treegraph extends React.Component {
  createTreeChart = () => {
    const width = 550;
    const height = 500;
    var paddingAllowance = 2;
    const format = d3.format(",d");
    const checkLowVal = d => {
      console.log("ChecklowVal", d);
      if (d.value < 2) {
        return true;
      }
    };
    const name = d =>
      d
        .ancestors()
        .reverse()
        .map(d => d.data.name)
        .join(" / ");
    function tile(node, x0, y0, x1, y1) {
      d3.treemapBinary(node, 0, 0, width, height);
      for (const child of node.children) {
        child.x0 = x0 + (child.x0 / width) * (x1 - x0);
        child.x1 = x0 + (child.x1 / width) * (x1 - x0);
        child.y0 = y0 + (child.y0 / height) * (y1 - y0);
        child.y1 = y0 + (child.y1 / height) * (y1 - y0);
      }
    }
    const treemap = data =>
      d3.treemap().tile(tile)(
        d3
          .hierarchy(data)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value)
      );
    const svg = d3
      .select("#chart")
      .append("svg")
      .attr("viewBox", [0.5, -30.5, width, height + 30])
      .style("font", "16px sans-serif");

    const x = d3.scaleLinear().rangeRound([0, width]);
    const y = d3.scaleLinear().rangeRound([0, height]);

    let group = svg.append("g").call(render, treemap(data));

    function render(group, root) {
      const node = group
        .selectAll("g")
        .data(root.children.concat(root))
        .join("g");

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => (d === root ? zoomout(root) : zoomin(d)));

      var tool = d3
        .select("body")
        .append("div")
        .attr("class", "toolTip");

      d3.select(window.frameElement).style("height", height - 20 + "px");
      d3.select(window.frameElement).style("width", width - 20 + "px");
      node
        .append("rect")
        .attr("id", d => (d.leafUid = "leaf"))
        .attr("fill", d =>
          d === root ? "#fff" : d.children ? "#045c79" : "#045c79"
        )
        .attr("stroke", "#fff")
        .on("mousemove", function(d) {
          tool.style("left", d3.event.pageX + 10 + "px");
          tool.style("top", d3.event.pageY - 20 + "px");
          tool.style("display", "inline-block");
          tool.html(`${d.data.name}<br />(${format(d.data.value)})`);
        })
        .on("click", function(d) {
          tool.style("display", "none");
        })
        .on("mouseout", function(d) {
          tool.style("display", "none");
        });
      node
        .append("foreignObject")
        .attr("class", "foreignObject")
        .attr("width", function(d) {
          return d.dx - paddingAllowance;
        })
        .attr("height", function(d) {
          return d.dy - paddingAllowance;
        })
        .append("xhtml:body")
        .attr("class", "labelbody")
        .append("div")
        .attr("class", "label")
        .text(function(d) {
          return d.name;
        })
        .attr("text-anchor", "middle");
      node
        .append("clipPath")
        .attr("id", d => (d.clipUid = "clip"))
        .append("use")
        .attr("xlink:href", d => d.leafUid.href);

      node
        .append("text")
        .attr("clip-path", d => d.clipUid)
        .attr("font-weight", d => (d === root ? "bold" : null))
        .attr("font-size", d => {
          if (d === root) return "0.8em";
          const width = x(d.x1) - x(d.x0),
            height = y(d.y1) - y(d.y0);
          return Math.max(
            Math.min(
              width / 5,
              height / 2,
              Math.sqrt(width * width + height * height) / 25
            ),
            9
          );
        })
        .attr("text-anchor", d => (d === root ? null : "middle"))
        .attr("transform", d =>
          d === root
            ? null
            : `translate(${(x(d.x1) - x(d.x0)) / 2}, ${(y(d.y1) - y(d.y0)) /
                2})`
        )
        .selectAll("tspan")
        .data(d =>
          d === root
            ? name(d).split(/(?=\/)/g)
            : checkLowVal(d)
            ? d.data.name.split(/(\s+)/).concat(format(d.data.value))
            : d.data.name.split(/(\s+)/).concat(format(d.data.value))
        )
        .join("tspan")
        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) =>
            `${(i === nodes.length - 1) * 0.3 + (i - nodes.length / 2) * 0.9}em`
        )
        .text(d => d);
      node
        .selectAll("text")
        .classed("text-title", d => d === root)
        .classed("text-tile", d => d !== root)
        .filter(d => d === root)
        .selectAll("tspan")
        .attr("y", "1.1em")
        .attr("x", undefined);
      group.call(position, root);
    }
    function position(group, root) {
      group
        .selectAll("g")
        .attr("transform", d =>
          d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
        )
        .select("rect")
        .attr("width", d => (d === root ? width : x(d.x1) - x(d.x0)))
        .attr("height", d => (d === root ? 30 : y(d.y1) - y(d.y0)));
    }

    // When zooming in, draw the new nodes on top, and fade them in.
    function zoomin(d) {
      console.log("The zoomin func", d.data);
      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));
      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .call(position, d.parent)
        )
        .call(t =>
          group1
            .transition(t)
            .attrTween("opacity", () => d3.interpolate(0, 1))
            .call(position, d)
        );
    }

    // When zooming out, draw the old nodes on top, and fade them out.
    function zoomout(d) {
      console.log("The zoomout func", d.parent.data);
      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));
      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .attrTween("opacity", () => d3.interpolate(1, 0))
            .call(position, d)
        )
        .call(t => group1.transition(t).call(position, d.parent));
    }

    return svg.node();
  };
  componentDidMount() {
    this.createTreeChart();
  }
  render() {
    return (
      <React.Fragment>
        <div id="chart" />
      </React.Fragment>
    );
  }
}
</code>```

答:
Here is a quick idea, store the name as ID on local storage. Hopefully name is unique, otherwise make sure you have an unique ID for each node.

https://codesandbox.io/s/d3-treemap-4ehbf?file=/src/treegraph.js

first load localstorage for lastSelection with last selected node name

  componentDidMount() {
    const lastSelection = localStorage.getItem("lastSelection");
    console.log("lastSelection:", lastSelection);
    this.createTreeChart(lastSelection);
  }
```

<ul>
<li>add a parameter to you <code>createTreeChart</code> so when it loads and there is a lastaSelection you have to reload that state</li>
</ul>

<pre class="lang-js prettyprint-override"><code>  createTreeChart = (lastSelection = null) => {
</code>```

decouple your treemap in a variable, filter the lastSelection node and zoomin into it. this step could be improved, not sure if the refreshing zoomin is interesting.

    const tree = treemap(data);
    let group = svg.append("g").call(render, tree);
    if (lastSelection !== null) {
      const lastNode = tree
        .descendants()
        .find(e => e.data.name === lastSelection);
      zoomin(lastNode);
    }
```

<ul>
<li>finally update localStorage on node click.</li>
</ul>

<pre class="lang-js prettyprint-override"><code>      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => {
          if (d === root) {
           localStorage.setItem("lastSelection", null);
            zoomout(root);
          } else {
           localStorage.setItem("lastSelection", d.data.name);
            zoomin(d);
          }
        });
</code>```

This could be improved, but it's a starting point.

ContentLicense: CC BY-SA 4.0

Body:
I am working on the d3 treemap v5 in which I need to persist the state of the treemap in localstorage on each user click. My code is in https://codesandbox.io/s/d3-treemap-wfbtg
When a user clicks the top parent tile it is drilled down to the children tiles. How to persist that in local storage when the user reloads the browser he wants to see the drilled down children tiles.

class Treegraph extends React.Component {
  createTreeChart = () => {
    const width = 550;
    const height = 500;
    var paddingAllowance = 2;
    const format = d3.format(",d");
    const checkLowVal = d => {
      console.log("ChecklowVal", d);
      if (d.value < 2) {
        return true;
      }
    };
    const name = d =>
      d
        .ancestors()
        .reverse()
        .map(d => d.data.name)
        .join(" / ");
    function tile(node, x0, y0, x1, y1) {
      d3.treemapBinary(node, 0, 0, width, height);
      for (const child of node.children) {
        child.x0 = x0 + (child.x0 / width) * (x1 - x0);
        child.x1 = x0 + (child.x1 / width) * (x1 - x0);
        child.y0 = y0 + (child.y0 / height) * (y1 - y0);
        child.y1 = y0 + (child.y1 / height) * (y1 - y0);
      }
    }
    const treemap = data =>
      d3.treemap().tile(tile)(
        d3
          .hierarchy(data)
          .sum(d => d.value)
          .sort((a, b) => b.value - a.value)
      );
    const svg = d3
      .select("#chart")
      .append("svg")
      .attr("viewBox", [0.5, -30.5, width, height + 30])
      .style("font", "16px sans-serif");

    const x = d3.scaleLinear().rangeRound([0, width]);
    const y = d3.scaleLinear().rangeRound([0, height]);

    let group = svg.append("g").call(render, treemap(data));

    function render(group, root) {
      const node = group
        .selectAll("g")
        .data(root.children.concat(root))
        .join("g");

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => (d === root ? zoomout(root) : zoomin(d)));

      var tool = d3
        .select("body")
        .append("div")
        .attr("class", "toolTip");

      d3.select(window.frameElement).style("height", height - 20 + "px");
      d3.select(window.frameElement).style("width", width - 20 + "px");
      node
        .append("rect")
        .attr("id", d => (d.leafUid = "leaf"))
        .attr("fill", d =>
          d === root ? "#fff" : d.children ? "#045c79" : "#045c79"
        )
        .attr("stroke", "#fff")
        .on("mousemove", function(d) {
          tool.style("left", d3.event.pageX + 10 + "px");
          tool.style("top", d3.event.pageY - 20 + "px");
          tool.style("display", "inline-block");
          tool.html(`${d.data.name}<br />(${format(d.data.value)})`);
        })
        .on("click", function(d) {
          tool.style("display", "none");
        })
        .on("mouseout", function(d) {
          tool.style("display", "none");
        });
      node
        .append("foreignObject")
        .attr("class", "foreignObject")
        .attr("width", function(d) {
          return d.dx - paddingAllowance;
        })
        .attr("height", function(d) {
          return d.dy - paddingAllowance;
        })
        .append("xhtml:body")
        .attr("class", "labelbody")
        .append("div")
        .attr("class", "label")
        .text(function(d) {
          return d.name;
        })
        .attr("text-anchor", "middle");
      node
        .append("clipPath")
        .attr("id", d => (d.clipUid = "clip"))
        .append("use")
        .attr("xlink:href", d => d.leafUid.href);

      node
        .append("text")
        .attr("clip-path", d => d.clipUid)
        .attr("font-weight", d => (d === root ? "bold" : null))
        .attr("font-size", d => {
          if (d === root) return "0.8em";
          const width = x(d.x1) - x(d.x0),
            height = y(d.y1) - y(d.y0);
          return Math.max(
            Math.min(
              width / 5,
              height / 2,
              Math.sqrt(width * width + height * height) / 25
            ),
            9
          );
        })
        .attr("text-anchor", d => (d === root ? null : "middle"))
        .attr("transform", d =>
          d === root
            ? null
            : `translate(${(x(d.x1) - x(d.x0)) / 2}, ${(y(d.y1) - y(d.y0)) /
                2})`
        )
        .selectAll("tspan")
        .data(d =>
          d === root
            ? name(d).split(/(?=\/)/g)
            : checkLowVal(d)
            ? d.data.name.split(/(\s+)/).concat(format(d.data.value))
            : d.data.name.split(/(\s+)/).concat(format(d.data.value))
        )
        .join("tspan")
        .attr("x", 3)
        .attr(
          "y",
          (d, i, nodes) =>
            `${(i === nodes.length - 1) * 0.3 + (i - nodes.length / 2) * 0.9}em`
        )
        .text(d => d);
      node
        .selectAll("text")
        .classed("text-title", d => d === root)
        .classed("text-tile", d => d !== root)
        .filter(d => d === root)
        .selectAll("tspan")
        .attr("y", "1.1em")
        .attr("x", undefined);
      group.call(position, root);
    }
    function position(group, root) {
      group
        .selectAll("g")
        .attr("transform", d =>
          d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
        )
        .select("rect")
        .attr("width", d => (d === root ? width : x(d.x1) - x(d.x0)))
        .attr("height", d => (d === root ? 30 : y(d.y1) - y(d.y0)));
    }

    // When zooming in, draw the new nodes on top, and fade them in.
    function zoomin(d) {
      console.log("The zoomin func", d.data);
      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.append("g").call(render, d));
      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .call(position, d.parent)
        )
        .call(t =>
          group1
            .transition(t)
            .attrTween("opacity", () => d3.interpolate(0, 1))
            .call(position, d)
        );
    }

    // When zooming out, draw the old nodes on top, and fade them out.
    function zoomout(d) {
      console.log("The zoomout func", d.parent.data);
      x.domain([d.parent.x0, d.parent.x1]);
      y.domain([d.parent.y0, d.parent.y1]);
      const group0 = group.attr("pointer-events", "none");
      const group1 = (group = svg.insert("g", "*").call(render, d.parent));
      svg
        .transition()
        .duration(750)
        .call(t =>
          group0
            .transition(t)
            .remove()
            .attrTween("opacity", () => d3.interpolate(1, 0))
            .call(position, d)
        )
        .call(t => group1.transition(t).call(position, d.parent));
    }

    return svg.node();
  };
  componentDidMount() {
    this.createTreeChart();
  }
  render() {
    return (
      <React.Fragment>

      </React.Fragment>
    );
  }
}

Body:
Here is a quick idea, store the name as ID on local storage. Hopefully name is unique, otherwise make sure you have an unique ID for each node.

https://codesandbox.io/s/d3-treemap-4ehbf?file=/src/treegraph.js

first load localstorage for lastSelection with last selected node name

  componentDidMount() {
    const lastSelection = localStorage.getItem("lastSelection");
    console.log("lastSelection:", lastSelection);
    this.createTreeChart(lastSelection);
  }

add a parameter to you createTreeChart so when it loads and there is a lastaSelection you have to reload that state

  createTreeChart = (lastSelection = null) => {

decouple your treemap in a variable, filter the lastSelection node and zoomin into it. this step could be improved, not sure if the refreshing zoomin is interesting.

    const tree = treemap(data);
    let group = svg.append("g").call(render, tree);
    if (lastSelection !== null) {
      const lastNode = tree
        .descendants()
        .find(e => e.data.name === lastSelection);
      zoomin(lastNode);
    }

finally update localStorage on node click.

      node
        .filter(d => (d === root ? d.parent : d.children))
        .attr("cursor", "pointer")
        .on("click", d => {
          if (d === root) {
           localStorage.setItem("lastSelection", null);
            zoomout(root);
          } else {
           localStorage.setItem("lastSelection", d.data.name);
            zoomin(d);
          }
        });

This could be improved, but it's a starting point.


问:
facing problem in andriod studio 3.2 can't run emulator my computer specs are 2gm ram and can not even build app
Unable to detect adb version, exit value: 0xc0000135. ADB depends on the Windows Universal C Runtime, which is usually installed by default via Windows Update. You may need to manually fetch and install the runtime package here: https://support.microsoft.com/en-ca/help/2999226/update-for-universal-c-runtime-in-windows</p>

答: Chech android studio pc requirements my friend . Your PC specs is very low</p>


问:
Get the title of a Pull Request from command line
I'm writing a continuous integration step that checks the titles of our pull requests for proper tags and formatting before allowing them to be merged.

To do this, I need to echo the title of the Pull Request when given the PR number. Is there a way to do this simply in command line?

答:
With Github's new official CLI (command line interface):

```<code>gh pr view 3 --repo OWNER/REPO | head -n 1
</code>```

where:

3 is the PR number

gh pr view [options] displays the title (first line), body, and other information about the PR

head -n 1 only keeps the first line of the gh pr view output in order to only get the title

See additional details and options and installation instructions.

Body:
With Github's new official CLI (command line interface):

gh pr view 3 --repo OWNER/REPO | head -n 1

where:

3 is the PR number

gh pr view [options] displays the title (first line), body, and other information about the PR

head -n 1 only keeps the first line of the gh pr view output in order to only get the title

See additional details and options and installation instructions.


问:
Batch Script to rename computer and join to domain on a single click
I have 200 domain computers and i need to change the host name and rejoin to domain on a click.

First operation

Powershell.exe "-ExecutionPolicy Bypass Add-Computer -DomainName <Domain Name> -ComputerName <Old_ComputerName> -NewName <New_ComputerName> -$credential = New-Object System.Management.Automation.PSCredential($username = "<Domain\User ID>", ($password = <Password> | ConvertTo-SecureString -asPlainText -Force))"
```

<ol start="2">
<li>Second operation</li>
</ol>

<pre class="lang-bat prettyprint-override"><code>net user Administrator <Password>
</code>```

Restart computer

But, While executing the above script in cmd with elevated privileges. I am getting the below error.

At line:1 char:206
+ ... ement.Automation.PSCredential($username = Domain\User ID, ($passw ...
+                                                                 ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument
```

We are looking for a single line command to do the above operation.

答:
This command syntax is not correct.

Do this is a script and run the script (deliver to users as an exe using the PS2EXE tool), thus no need for a batch file.

```<code># Begin Script
$AddComputerSplat = @{
    DomainName   = <Domain Name>
    ComputerName = <Old_ComputerName>
    NewName      = '<New_ComputerName>'
    $credential  = New-Object System.Management.Automation.PSCredential($username = 'Domain\UserID',
    ($password   = 'Password' | ConvertTo-SecureString -asPlainText -Force))
}
Add-Computer @AddComputerSplat
</code>```

Get-LocalUser

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localuser?view=powershell-5.1

New-LocalUser

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/new-localuser?view=powershell-5.1

Get-LocalGroupMember

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localgroupmember?view=powershell-5.1

Add-LocalGroupMember

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/add-localgroupmember?view=powershell-5.1

```<code># End Script
</code>```

Or if you just want to use cmd.exe and call the consoelhost, then this approach should work for you.

```<code>$Command = 'Add-Computer -DomainName <Domain Name> -ComputerName <Old_ComputerName> -NewName <New_ComputerName> -$credential = New-Object System.Management.Automation.PSCredential($username = "<Domain\User ID>", ($password = <Password> | ConvertTo-SecureString -asPlainText -Force))"'
powershell -ArgumentList '-NoExit', 'NoProfile', '-ExecutionPolicy Bypass', "-Command  &{ $ConsoleCommand }"
</code>```

Body:
I have 200 domain computers and i need to change the host name and rejoin to domain on a click.

First operation

Powershell.exe "-ExecutionPolicy Bypass Add-Computer -DomainName <Domain Name> -ComputerName <Old_ComputerName> -NewName <New_ComputerName> -$credential = New-Object System.Management.Automation.PSCredential($username = "<Domain\User ID>", ($password = <Password> | ConvertTo-SecureString -asPlainText -Force))"

Second operation

net user Administrator <Password>

Restart computer

But, While executing the above script in cmd with elevated privileges. I am getting the below error.

At line:1 char:206
+ ... ement.Automation.PSCredential($username = Domain\User ID, ($passw ...
+                                                                 ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument

We are looking for a single line command to do the above operation.

Body:
This command syntax is not correct.

Do this is a script and run the script (deliver to users as an exe using the PS2EXE tool), thus no need for a batch file.

# Begin Script
$AddComputerSplat = @{
    DomainName   = <Domain Name>
    ComputerName = <Old_ComputerName>
    NewName      = '<New_ComputerName>'
    $credential  = New-Object System.Management.Automation.PSCredential($username = 'Domain\UserID',
    ($password   = 'Password' | ConvertTo-SecureString -asPlainText -Force))
}
Add-Computer @AddComputerSplat

Get-LocalUser

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localuser?view=powershell-5.1

New-LocalUser

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/new-localuser?view=powershell-5.1

Get-LocalGroupMember

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/get-localgroupmember?view=powershell-5.1

Add-LocalGroupMember

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/add-localgroupmember?view=powershell-5.1

# End Script

Or if you just want to use cmd.exe and call the consoelhost, then this approach should work for you.

$Command = 'Add-Computer -DomainName <Domain Name> -ComputerName <Old_ComputerName> -NewName <New_ComputerName> -$credential = New-Object System.Management.Automation.PSCredential($username = "<Domain\User ID>", ($password = <Password> | ConvertTo-SecureString -asPlainText -Force))"'
powershell -ArgumentList '-NoExit', 'NoProfile', '-ExecutionPolicy Bypass', "-Command  &{ $ConsoleCommand }"


问:
upgrading kubernetes from 1.17.5 to 1.17.6 fails
i'm attempting to conduct a k8s upgrade with a multi-master setup (with keepalived and haproxy):

```<code>kubeadm upgrade apply v1.17.6
</code>```

from v1.17.5. however, i encounter the following error:

```<code>[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
[upgrade/config] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[preflight] Running pre-flight checks.
[upgrade] Making sure the cluster is healthy:
[upgrade/version] You have chosen to change the cluster version to "v1.17.6"
[upgrade/versions] Cluster version: v1.17.5
[upgrade/versions] kubeadm version: v1.17.6
[upgrade/confirm] Are you sure you want to proceed with the upgrade? [y/N]: y
[upgrade/prepull] Will prepull images for components [kube-apiserver kube-controller-manager kube-scheduler etcd]
[upgrade/prepull] Prepulling image for component etcd.
[upgrade/prepull] Prepulling image for component kube-apiserver.
[upgrade/prepull] Prepulling image for component kube-controller-manager.
[upgrade/prepull] Prepulling image for component kube-scheduler.
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-scheduler
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-apiserver
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-etcd
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-controller-manager
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-scheduler
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-apiserver
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-etcd
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-controller-manager
[upgrade/prepull] Prepulled image for component etcd.
[upgrade/prepull] Prepulled image for component kube-scheduler.
[upgrade/prepull] Prepulled image for component kube-apiserver.
[upgrade/prepull] Prepulled image for component kube-controller-manager.
[upgrade/prepull] Successfully prepulled the images for all the control plane components
[upgrade/apply] Upgrading your Static Pod-hosted control plane to version "v1.17.6"...
Static pod: kube-apiserver-k8s-master02 hash: bb5f938cbb69a4e3c96fbcc0f2e49e19
Static pod: kube-controller-manager-k8s-master02 hash: a036029e87d630db24866f0abb3f8853
Static pod: kube-scheduler-k8s-master02 hash: b95be9ddff954501b1709fd9f2e0a160
[upgrade/etcd] Upgrading to TLS for etcd
[upgrade/etcd] Non fatal issue encountered during upgrade: the desired etcd version for this Kubernetes version "v1.17.6" is "3.4.3-0", but the current etcd version is "3.4.3". Won't downgrade etcd, instead just continue
[upgrade/staticpods] Writing new Static Pod manifests to "/etc/kubernetes/tmp/kubeadm-upgraded-manifests962117447"
W0528 22:04:28.039648   13824 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[upgrade/staticpods] Preparing for "kube-apiserver" upgrade
[upgrade/staticpods] Renewing apiserver certificate
[upgrade/staticpods] Renewing apiserver-kubelet-client certificate
[upgrade/staticpods] Renewing front-proxy-client certificate
[upgrade/staticpods] Renewing apiserver-etcd-client certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/kube-apiserver.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2020-05-28-22-04-25/kube-apiserver.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
Static pod: kube-apiserver-k8s-master02 hash: bb5f938cbb69a4e3c96fbcc0f2e49e19
Static pod: kube-apiserver-k8s-master02 hash: 485fbbf3f31c5f40e0e22cc118531d44
[apiclient] Found 3 Pods for label selector component=kube-apiserver
[upgrade/apply] FATAL: couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced: timed out waiting for the condition
To see the stack trace of this error execute with --v=5 or higher
</code>```

running with verbosity shows:

```<code>timed out waiting for the condition
couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.rollbackOldManifests
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:515
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.upgradeComponent
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:255
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.StaticPodControlPlane
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:472
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.PerformStaticPodUpgrade
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:606
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.PerformControlPlaneUpgrade
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:224
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.runApply
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:164
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.NewCmdApply.func1
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:79
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:826
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).ExecuteC
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:914
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).Execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:864
k8s.io/kubernetes/cmd/kubeadm/app.Run
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/kubeadm.go:50
main.main
    _output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/kubeadm.go:25
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1357
[upgrade/apply] FATAL
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.runApply
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:165
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.NewCmdApply.func1
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:79
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:826
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).ExecuteC
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:914
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).Execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:864
k8s.io/kubernetes/cmd/kubeadm/app.Run
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/kubeadm.go:50
main.main
    _output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/kubeadm.go:25
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1357
</code>```

can anyone point me in the right direction?

答:
Referring from the docs you need to drain the control plane node first and then run kubeadm upgrade.</p>

```<code>kubectl drain <cp-node-name> --ignore-daemonsets
</code>```

Body:
i'm attempting to conduct a k8s upgrade with a multi-master setup (with keepalived and haproxy):

kubeadm upgrade apply v1.17.6

from v1.17.5. however, i encounter the following error:

[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
[upgrade/config] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -oyaml'
[preflight] Running pre-flight checks.
[upgrade] Making sure the cluster is healthy:
[upgrade/version] You have chosen to change the cluster version to "v1.17.6"
[upgrade/versions] Cluster version: v1.17.5
[upgrade/versions] kubeadm version: v1.17.6
[upgrade/confirm] Are you sure you want to proceed with the upgrade? [y/N]: y
[upgrade/prepull] Will prepull images for components [kube-apiserver kube-controller-manager kube-scheduler etcd]
[upgrade/prepull] Prepulling image for component etcd.
[upgrade/prepull] Prepulling image for component kube-apiserver.
[upgrade/prepull] Prepulling image for component kube-controller-manager.
[upgrade/prepull] Prepulling image for component kube-scheduler.
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-scheduler
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-apiserver
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-etcd
[apiclient] Found 0 Pods for label selector k8s-app=upgrade-prepull-kube-controller-manager
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-scheduler
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-apiserver
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-etcd
[apiclient] Found 3 Pods for label selector k8s-app=upgrade-prepull-kube-controller-manager
[upgrade/prepull] Prepulled image for component etcd.
[upgrade/prepull] Prepulled image for component kube-scheduler.
[upgrade/prepull] Prepulled image for component kube-apiserver.
[upgrade/prepull] Prepulled image for component kube-controller-manager.
[upgrade/prepull] Successfully prepulled the images for all the control plane components
[upgrade/apply] Upgrading your Static Pod-hosted control plane to version "v1.17.6"...
Static pod: kube-apiserver-k8s-master02 hash: bb5f938cbb69a4e3c96fbcc0f2e49e19
Static pod: kube-controller-manager-k8s-master02 hash: a036029e87d630db24866f0abb3f8853
Static pod: kube-scheduler-k8s-master02 hash: b95be9ddff954501b1709fd9f2e0a160
[upgrade/etcd] Upgrading to TLS for etcd
[upgrade/etcd] Non fatal issue encountered during upgrade: the desired etcd version for this Kubernetes version "v1.17.6" is "3.4.3-0", but the current etcd version is "3.4.3". Won't downgrade etcd, instead just continue
[upgrade/staticpods] Writing new Static Pod manifests to "/etc/kubernetes/tmp/kubeadm-upgraded-manifests962117447"
W0528 22:04:28.039648   13824 manifests.go:214] the default kube-apiserver authorization-mode is "Node,RBAC"; using "Node,RBAC"
[upgrade/staticpods] Preparing for "kube-apiserver" upgrade
[upgrade/staticpods] Renewing apiserver certificate
[upgrade/staticpods] Renewing apiserver-kubelet-client certificate
[upgrade/staticpods] Renewing front-proxy-client certificate
[upgrade/staticpods] Renewing apiserver-etcd-client certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/kube-apiserver.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2020-05-28-22-04-25/kube-apiserver.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
Static pod: kube-apiserver-k8s-master02 hash: bb5f938cbb69a4e3c96fbcc0f2e49e19
Static pod: kube-apiserver-k8s-master02 hash: 485fbbf3f31c5f40e0e22cc118531d44
[apiclient] Found 3 Pods for label selector component=kube-apiserver
[upgrade/apply] FATAL: couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced: timed out waiting for the condition
To see the stack trace of this error execute with --v=5 or higher

running with verbosity shows:

timed out waiting for the condition
couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.rollbackOldManifests
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:515
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.upgradeComponent
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:255
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.StaticPodControlPlane
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:472
k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade.PerformStaticPodUpgrade
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/phases/upgrade/staticpods.go:606
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.PerformControlPlaneUpgrade
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:224
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.runApply
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:164
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.NewCmdApply.func1
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:79
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:826
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).ExecuteC
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:914
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).Execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:864
k8s.io/kubernetes/cmd/kubeadm/app.Run
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/kubeadm.go:50
main.main
    _output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/kubeadm.go:25
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1357
[upgrade/apply] FATAL
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.runApply
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:165
k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade.NewCmdApply.func1
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/cmd/upgrade/apply.go:79
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:826
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).ExecuteC
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:914
k8s.io/kubernetes/vendor/github.com/spf13/cobra.(*Command).Execute
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/vendor/github.com/spf13/cobra/command.go:864
k8s.io/kubernetes/cmd/kubeadm/app.Run
    /workspace/anago-v1.17.6-beta.0.42+fd4285294a6370/src/k8s.io/kubernetes/_output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/app/kubeadm.go:50
main.main
    _output/dockerized/go/src/k8s.io/kubernetes/cmd/kubeadm/kubeadm.go:25
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1357

can anyone point me in the right direction?

Body:
Referring from the docs you need to drain the control plane node first and then run kubeadm upgrade.

kubectl drain <cp-node-name> --ignore-daemonsets


问:
How to use a single variable which can have multiple data types in C++
How can a variable have 2 data types? If "month" is a variable and it should be take from input with std::cin. What should I do so that the user can enter a string like "January" or enter an integer like 1?</p>

答:
The declaration will conflict. You can't declare two different data types with a single identifier. For example, std::string month and int month will throw an error. Look at the following:

```<code>#include <iostream>

int main(void) {
    int month = 2;
    std::string month = "January"; // confliction
}
</code>```

You'll get something:

```<code>error: conflicting declaration 'std::string month'
    5 |     std::string month = "January";
      |                 ^~~~~
vectors.cpp:4:9: note: previous declaration as 'int month'
    4 |     int month = 2;
      |         ^~~~~
</code>```

You can overload functions, but not variables.

Body:
The declaration will conflict. You can't declare two different data types with a single identifier. For example, std::string month and int month will throw an error. Look at the following:

#include <iostream>

int main(void) {
    int month = 2;
    std::string month = "January"; // confliction
}

You'll get something:

error: conflicting declaration 'std::string month'
    5 |     std::string month = "January";
      |                 ^~~~~
vectors.cpp:4:9: note: previous declaration as 'int month'
    4 |     int month = 2;
      |         ^~~~~

You can overload functions, but not variables.


问:
How do you encode an apostrophe so that it's searchable in mysql?
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

```<code>mov_title = '$search_keywords'
</code>```

it all works, but this method will not yield any results for partial searches, so I have to use this

```<code>mov_title LIKE '%$search_keywords%'
</code>```

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

```<code>$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));
</code>```

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

答: Use mysql_real_escape_string(), and do not use htmlspecialchars().  The latter is not for database escaping, it's for HTML production.

LastEditorDisplayName: Jonathan Leffler

ContentLicense: CC BY-SA 2.5

Body:
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

mov_title = '$search_keywords'

it all works, but this method will not yield any results for partial searches, so I have to use this

mov_title LIKE '%$search_keywords%'

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

OwnerDisplayName: chaos


问:
Converting from dip to px
I currently have this running with the stack output below as it is throwing up an error.</p>

```<code>    Resources r = getResources();
    float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());

> Uncaught handler: thread main exiting due to uncaught exception
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.pne/com.test.pne.one}: android.content.res.Resources$NotFoundException: String resource ID #0xe
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.access$2100(ActivityThread.java:116)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4203)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xe
at android.content.res.Resources.getText(Resources.java:205)
at android.widget.TextView.setText(TextView.java:2809)
at com.quiz.max.Quiz.onCreate(Quiz.java:87)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
... 11 more
</code>```

答:
I don't even really see what your question is, but the error seems as though it's caused by a String resource that isn't being found (Maybe try Fixing Android project properties?)

```<code>Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xe at
</code>```

Maybe if you explain more what you want, I can try to help more.

Title: Converting from dip to px

Body:
I currently have this running with the stack output below as it is throwing up an error.

    Resources r = getResources();
    float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());

> Uncaught handler: thread main exiting due to uncaught exception
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.pne/com.test.pne.one}: android.content.res.Resources$NotFoundException: String resource ID #0xe
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.access$2100(ActivityThread.java:116)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4203)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xe
at android.content.res.Resources.getText(Resources.java:205)
at android.widget.TextView.setText(TextView.java:2809)
at com.quiz.max.Quiz.onCreate(Quiz.java:87)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
... 11 more

Body:
I don't even really see what your question is, but the error seems as though it's caused by a String resource that isn't being found (Maybe try Fixing Android project properties?)

Caused by: android.content.res.Resources$NotFoundException: String resource ID #0xe at

Maybe if you explain more what you want, I can try to help more.


问:
Add elements of a list together python
I have this list

```<code>r1 = 2
r2 = 4
r3 = 5
r4 = 9
lst = [r1, r2, r3, r4]
</code>```

I want to create a new list which looks like this:

```<code>new_lst = [r1, r1+r2, r1+r2+r3, r1+r2+r3+r4]
</code>```

Except in the new_lst r1 is named "x1", r1+r2 named "x2 etc.

I'm currently doing this using:

```<code>new_lst = []
new_lst.append(sum(lst[0:1]))
new_lst.append(sum(lst[0:2]))
new_lst.append(sum(lst[0:3]))
new_lst.append(sum(lst[0:4]))
</code>```

And then refer to this list by saying if "n" is between 0 and x1, x1 and x1+x2 etc; print y. i.e.

```<code> if n >=0 and n <= new_lst[0]:
      print(y)
 elif n >=new_lst[0] and n <= new_lst[1]:
      print(z)
</code>```

答:
As best as I can understand your question, I believe the following does what you describe.  It creates x1 through x4 via simple list assignment:

```<code>r1 = 2
r2 = 4
r3 = 5
r4 = 9

array = [r1, r2, r3, r4]

x1, x2, x3, x4 = [sum(array[0:n + 1]) for n in range(len(array))]

if 0 <= n <= x1:
    print(y)
elif x1 <= n <= x2:
    print(z)
</code>```

The fact that you need to do this at all suggests to me you've gone down a wrong path somewhere.  Perhaps you're using individual variables where a dict would serve you better.

Title: Add elements of a list together python

Body:
I have this list

r1 = 2
r2 = 4
r3 = 5
r4 = 9
lst = [r1, r2, r3, r4]

I want to create a new list which looks like this:

new_lst = [r1, r1+r2, r1+r2+r3, r1+r2+r3+r4]

Except in the new_lst r1 is named "x1", r1+r2 named "x2 etc.

I'm currently doing this using:

new_lst = []
new_lst.append(sum(lst[0:1]))
new_lst.append(sum(lst[0:2]))
new_lst.append(sum(lst[0:3]))
new_lst.append(sum(lst[0:4]))

And then refer to this list by saying if "n" is between 0 and x1, x1 and x1+x2 etc; print y. i.e.

 if n >=0 and n <= new_lst[0]:
      print(y)
 elif n >=new_lst[0] and n <= new_lst[1]:
      print(z)

Body:
As best as I can understand your question, I believe the following does what you describe.  It creates x1 through x4 via simple list assignment:

r1 = 2
r2 = 4
r3 = 5
r4 = 9

array = [r1, r2, r3, r4]

x1, x2, x3, x4 = [sum(array[0:n + 1]) for n in range(len(array))]

if 0 <= n <= x1:
    print(y)
elif x1 <= n <= x2:
    print(z)

The fact that you need to do this at all suggests to me you've gone down a wrong path somewhere.  Perhaps you're using individual variables where a dict would serve you better.


问:
Can I specify Node.js command line options in AWS Lambda?
I'm using AWS SAM and running against Node 10.x.

Would love to pass in the flags for experimental modules and top level await.

Thanks!

答:
You can add Node.js command line options to lambda by setting the NODE_OPTIONS environment variable.

https://nodejs.org/api/cli.html#cli_node_options_options


问:
error: RPC failed; curl transfer closed with outstanding read data remaining
I'm facing this error when I try to clone a repository from GitLab (GitLab 6.6.2 4ef8369):

```<code>remote: Counting objects: 66352, done.
remote: Compressing objects: 100% (10417/10417), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
</code>```

The clone is then aborted. How can I avoid this?

答:
you need to turn off the compression:

```<code>git config --global core.compression 0
</code>```

then you need to use shallow clone

```<code>git clone --depth=1 <url>
</code>```

then most important step is to cd into your cloned project

```<code>cd <shallow cloned project dir>
</code>```

now deopen the clone,step by step

```<code>git fetch --depth=N, with increasing N
</code>```

eg.

```<code>git fetch --depth=4
</code>```

then,

```<code>git fetch --depth=100
</code>```

then,

```<code>git fetch --depth=500
</code>```

you can choose how many steps you want by replacing this N,

and finally download all of the remaining revisions using,

```<code>git fetch --unshallow
</code>```

upvote if it helps you :)

Body:
I'm facing this error when I try to clone a repository from GitLab (GitLab 6.6.2 4ef8369):

remote: Counting objects: 66352, done.
remote: Compressing objects: 100% (10417/10417), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

The clone is then aborted. How can I avoid this?

Body:
you need to turn off the compression:

git config --global core.compression 0

then you need to use shallow clone

git clone --depth=1 <url>

then most important step is to cd into your cloned project

cd <shallow cloned project dir>

now deopen the clone,step by step

git fetch --depth=N, with increasing N

eg.

git fetch --depth=4

then,

git fetch --depth=100

then,

git fetch --depth=500

you can choose how many steps you want by replacing this N,

and finally download all of the remaining revisions using,

git fetch --unshallow

upvote if it helps you :)


问:
Python - Iterating Through Multiple Dictionarys and Their Keys
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1
```

Any tips or hints would be greatly appreciated. Thanks!

答:
To iterate through any dictionary is pretty straightforward. Say we have the following dictionary:

d = {
    "a": 1,
    "z": 26
}
```

<p>and we wanted to print out the keys with their values.</p>

<pre class="lang-py prettyprint-override"><code>for key in d: # note, key represents "a" and "z"
    print(key, d[key])
</code>```

However, for the purposes of what you're trying to accomplish, dictionaries might not be necessary at all, like @ggorlen commented.

A quick rendition I came up with to do the same thing

query = "enter a lottery number or 'quit' to quit: "
entries = input(query)
numbers = []
while entries != "quit":
    numbers.append(entries)
    entries = input(query)

winning_numbers = "123456"

for i in range(len(numbers)):
    if numbers[i] == winning_numbers:
        print(f"ticket {i} is a winner!")
```

I'm not sure why you're checking every tickets' number 1 and 2 against the total winning numbers because that's not how normal lotteries work, which is why my version looks a bit different, but of course you could make that change easily if it was what you wanted.

Body:
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1

Any tips or hints would be greatly appreciated. Thanks!

Body:
To iterate through any dictionary is pretty straightforward. Say we have the following dictionary:

d = {
    "a": 1,
    "z": 26
}

and we wanted to print out the keys with their values.

for key in d: # note, key represents "a" and "z"
    print(key, d[key])

However, for the purposes of what you're trying to accomplish, dictionaries might not be necessary at all, like @ggorlen commented.

A quick rendition I came up with to do the same thing

query = "enter a lottery number or 'quit' to quit: "
entries = input(query)
numbers = []
while entries != "quit":
    numbers.append(entries)
    entries = input(query)

winning_numbers = "123456"

for i in range(len(numbers)):
    if numbers[i] == winning_numbers:
        print(f"ticket {i} is a winner!")

I'm not sure why you're checking every tickets' number 1 and 2 against the total winning numbers because that's not how normal lotteries work, which is why my version looks a bit different, but of course you could make that change easily if it was what you wanted.


问:
Unable to consume artifact deployed in a private Bit-bucket repository
I am using wagon-git version 0.2.5 to deploy and consume the artifact from my private bitbucket. Following the same steps as given in the documentation http://synergian.github.io/wagon-git/bitbucket.html.

Error:

Could not resolve dependencies for project com.xxx:yyy:jar:1.0.0: The following artifacts could not be resolved: com.aaa:bbb:jar:3.0: Could not find artifact com.aaa:bbb:jar:3.0 in xxx_repo (https://api.bitbucket.org/2.0/repositories/company/xxx_repo/raw/releases)

Research:

From my research, I found many suggested the problem in repository URL so I changed to
https://bitbucket.org/company/xxx_repo/raw/releases/  from this URL I am able to access the repo but the compilation fails with an error saying zip END header not found

Compilation failure:
[ERROR] Error reading /home/msuser1/.m2/repository/com/aaa/bbb/3.0/bbb-3.0.jar; zip END header not found

And too many warning saying checksum validation failed.

[WARNING] Could not validate integrity of download from https://bitbucket.org/company/xxx_repo/raw/artifacts/com/aaa/bbb/3.0/bbb-3.0.jar: Checksum validation failed, expected <!doctype but is 2f947caee42a20633fb9c412ew53591f64b8c4481

Solution:

What is the exact URL for consuming the artifact from a private bitbucket?

Can anyone provide complete working steps to deploy and consume artifact from private bitbucket using wagon-git?

答:
We have to add username, password, and HTTP Basic Auth in Maven settings.xml to fetch and pull from bitbucket/Github private repository.</p>

```<code>  <servers>
    <server>
      <id>your-repo-id</id>
      <username>yourgithubusername</username>
      <password>yourgithubpassword</password>
    </server>
    <configuration>
     <httpHeaders>
       <property>
        <name>Authorization</name>
        <value>BASIC-AUTH HEADER VALUE</value>
       </property>
     </httpHeaders>
    </configuration>
  </servers>
</settings>```
</code>```

Body:
We have to add username, password, and HTTP Basic Auth in Maven settings.xml to fetch and pull from bitbucket/Github private repository.

  <servers>
    <server>
      <id>your-repo-id</id>
      <username>yourgithubusername</username>
      <password>yourgithubpassword</password>
    </server>
    <configuration>
     <httpHeaders>
       <property>
        <name>Authorization</name>
        <value>BASIC-AUTH HEADER VALUE</value>
       </property>
     </httpHeaders>
    </configuration>
  </servers>
</settings>```


问:
Can's use curly braces for it blocks in rspec?
```<code>it 'returns true for correct password' do
   expect(user.is_password?('password')).to eq(true)
end
</code>```

I have this code for my rspec, but when i replace it with

it 'returns true for correct password' { expect ...}

it complains

```<code>syntax error, unexpected '{', expecting `end'
  ...ns true for correct password' {expect(user.is_password?('pas..
</code>```

shouldn't curly braces equivalent to do...end ?

答:
Since do and end are keywords which are not used in any other context except for blocks, the Ruby interpreter doesn't have trouble understanding it. But curly braces are used in at least two different contexts, firstly acting as block delimiters, and secondly acting as delimiters for Hash, which means you have to help the Ruby interpreter a little bit here when using the curly braces to let it know what context you want to use the curly braces in.

In your case, if you use the method syntax with parentheses, i.e. it() instead of it, this should tell the interpreter that the curly braces after the parentheses are meant to be interpreted as delimiters for a block.

Use this...

it('returns true for correct password') { expect ... }
```

<p>instead of this.</p>

<pre class="lang-rb prettyprint-override"><code>it 'returns true for correct password' { expect ... }
</code>```

Body:
it 'returns true for correct password' do
   expect(user.is_password?('password')).to eq(true)
end

I have this code for my rspec, but when i replace it with

it 'returns true for correct password' { expect ...}

it complains

syntax error, unexpected '{', expecting `end'
  ...ns true for correct password' {expect(user.is_password?('pas..

shouldn't curly braces equivalent to do...end ?

Body:
Since do and end are keywords which are not used in any other context except for blocks, the Ruby interpreter doesn't have trouble understanding it. But curly braces are used in at least two different contexts, firstly acting as block delimiters, and secondly acting as delimiters for Hash, which means you have to help the Ruby interpreter a little bit here when using the curly braces to let it know what context you want to use the curly braces in.

In your case, if you use the method syntax with parentheses, i.e. it() instead of it, this should tell the interpreter that the curly braces after the parentheses are meant to be interpreted as delimiters for a block.

Use this...

it('returns true for correct password') { expect ... }

instead of this.

it 'returns true for correct password' { expect ... }


问:
How to invite people to private GitHub repo through command line interface?
Usually one must click link "Invite teams or people" after accessing "https://github.com///settings/access" in a web browser.
But, I wish to do this through a command line interface, because I must invite
many persons. Is it possible?

答:
You could use the GitHub API in order to add a collaborator

```<code>PUT /repos/:owner/:repo/collaborators/:username
</code>```

See for instance here:

```<code>curl -H "Authorization: token YOUR_TOKEN" "https://api.github.com/repos/YOUR_USER_NAME/YOUR_REPO/collaborators/COLLABORATOR_USER_NAME" -X PUT -d '{"permission":"admin"}'
</code>```

With permission level being one of:

pull - can pull, but not push to or administer this repository.

push - can pull and push, but not administer this repository.

admin - can pull, push and administer this repository.

maintain - Recommended for project managers who need to manage the repository without access to sensitive or destructive actions.

triage - Recommended for contributors who need to proactively manage issues and pull requests without write access.

(default is "push")

Update Sept. 2020, considering GitHub CLI gh is now 1.0, it could be a good feature to add (a kind of gh repo invite)

In the meantime, you can use gh pi to make a similar API call, automatically authenticated, with -f to add POST fields.

```<code>gh api repos/YOUR_USER_NAME/YOUR_REPO/collaborators/COLLABORATOR_USER_NAME" -f '{"permission":"admin"}'
</code>```

Body:
You could use the GitHub API in order to add a collaborator

PUT /repos/:owner/:repo/collaborators/:username

See for instance here:

curl -H "Authorization: token YOUR_TOKEN" "https://api.github.com/repos/YOUR_USER_NAME/YOUR_REPO/collaborators/COLLABORATOR_USER_NAME" -X PUT -d '{"permission":"admin"}'

With permission level being one of:

pull - can pull, but not push to or administer this repository.

push - can pull and push, but not administer this repository.

admin - can pull, push and administer this repository.

maintain - Recommended for project managers who need to manage the repository without access to sensitive or destructive actions.

triage - Recommended for contributors who need to proactively manage issues and pull requests without write access.

(default is "push")

Update Sept. 2020, considering GitHub CLI gh is now 1.0, it could be a good feature to add (a kind of gh repo invite)

In the meantime, you can use gh pi to make a similar API call, automatically authenticated, with -f to add POST fields.

gh api repos/YOUR_USER_NAME/YOUR_REPO/collaborators/COLLABORATOR_USER_NAME" -f '{"permission":"admin"}'


问:
How to pass Object from Birt Report to HTML dynamic text(Layout)
I'm new with BIRT in eclipse. I need to pass Object from BIRT side to HTML dynamic text(in Layout)

onFetch of dataSet

```<code>json = {Name: row["Name"],
        Lastname: row["Lastname"],
        Date: row["Date"]};
</code>```

beforeClose of Dataset

```<code>reportContext.setPersistentGlobalVariable("json", json);
</code>```

and by dynamic Text in Layout

```<code>var str = <value-of>reportContext.getPersistentGlobalVariable("json")</value-of>;
</code>```

i have error Uncaught SyntaxError: Unexpected identifier

```<code>var str = [object Object];
</code>```

Can someone point me in the right direction? Any idea how can i pass object between Birt Report and JavaScript(HTML)?
Thanks in advance!

答:
You can pass an object from dataset to Dynamic Text by following steps.

Step-1 : Create a report level variable.

Step-2 : Inside "Fetch" method just create a object. [As you have created json object]

```<code>vars["user"]={
    Name: row["Name"],
    Lastname: row["LastName"],
    Date: row["Date"]
 };
</code>```

Step-3 : on Close/beforeClose method assign the object to variable [As you have done]

Step-4 : Create a HTML Dynamic text on your report

Step-5 : Access the attributes as below-

```<code>vars["user"].Lastname
</code>```

I have created a sample report. You can refer here:-

https://drive.google.com/file/d/1dlh4qmamGur7voaNnlgamFTOIpAMk3_f/view?usp=sharing

Body:
I'm new with BIRT in eclipse. I need to pass Object from BIRT side to HTML dynamic text(in Layout)

onFetch of dataSet

json = {Name: row["Name"],
        Lastname: row["Lastname"],
        Date: row["Date"]};

beforeClose of Dataset

reportContext.setPersistentGlobalVariable("json", json);

and by dynamic Text in Layout

var str = <value-of>reportContext.getPersistentGlobalVariable("json")</value-of>;

i have error Uncaught SyntaxError: Unexpected identifier

var str = [object Object];

Can someone point me in the right direction? Any idea how can i pass object between Birt Report and JavaScript(HTML)?
Thanks in advance!

Body:
You can pass an object from dataset to Dynamic Text by following steps.

Step-1 : Create a report level variable.

Step-2 : Inside "Fetch" method just create a object. [As you have created json object]

vars["user"]={
    Name: row["Name"],
    Lastname: row["LastName"],
    Date: row["Date"]
 };

Step-3 : on Close/beforeClose method assign the object to variable [As you have done]

Step-4 : Create a HTML Dynamic text on your report

Step-5 : Access the attributes as below-

vars["user"].Lastname

I have created a sample report. You can refer here:-

https://drive.google.com/file/d/1dlh4qmamGur7voaNnlgamFTOIpAMk3_f/view?usp=sharing


问:
How to add active class to link on click
I have below code and i want make the clicked link active. I tried different approaches but did not work.</p>

```<code> <div id="collapse1" class="panel-collapse collapse">
    <ul class="list-group">
      <a><li class="list-group-item active" style="background-color: #394263;color: white">A</li></a>
      <a><li class="list-group-item" style="background-color: #394263;color: white">B</li></a>
        <a><li class="list-group-item" style="background-color: #394263;color: white">C</li></a>
    </ul>
  </div>
</code>```

答:
So First mistake here is:

its not a ideal approach to have a direct anchor in UL, You should use anchor inside LI.
and then add class on clicked item and remove from all others
Check this example

$(document).ready(function(){
  $('.list-group-item').click(function(){
    $('.list-group-item').removeClass('active');
    $(this).addClass('active');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.list-group-item.active a {
  color: red;
}</code>```

A

B

C

```

Body:
I have below code and i want make the clicked link active. I tried different approaches but did not work.

A

B

C

Body:
So First mistake here is:

its not a ideal approach to have a direct anchor in UL, You should use anchor inside LI.
and then add class on clicked item and remove from all others
Check this example

$(document).ready(function(){
  $('.list-group-item').click(function(){
    $('.list-group-item').removeClass('active');
    $(this).addClass('active');
  });
});

.list-group-item.active a {
  color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="collapse1" class="panel-collapse collapse">
    <ul class="list-group">
      <li class="list-group-item active" style="background-color: #394263;color: white"><a>A</a></li>
      <li class="list-group-item" style="background-color: #394263;color: white"><a>B</a></li>
        <li class="list-group-item" style="background-color: #394263;color: white"><a>C</a></li>
    </ul>
  </div>


问:
How can I remove a certain pattern from a string?
I have this string like "682_2, 682_3, 682_4". (682 is a random number)

How can i get this string "2, 3, 4" using regex and ruby?

答:
you can use scan which returns an array containing the matches:

```<code>string_code.scan(/(?<=_)\d/)
</code>```

(?<=_) tells to find a pattern that has a given pattern (_ in this case) before itself but wont capture that, it captures only \d. if it can have more than 1 digit like 682_13,682_33 then \d+ is necessary.

Body:
you can use scan which returns an array containing the matches:

string_code.scan(/(?<=_)\d/)

(?<=_) tells to find a pattern that has a given pattern (_ in this case) before itself but wont capture that, it captures only \d. if it can have more than 1 digit like 682_13,682_33 then \d+ is necessary.


问:
Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

```<code>2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more
</code>```

The application starter class is this:

```<code>@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}
</code>```

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

```<code>@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}
</code>```

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?

答:
I am using gradle, met seem issue when I have a commandLineRunner consumes kafka topics and a health check endpoint for receiving incoming hooks. I spent 12 hours to figure out, finally found that I used mybatis-spring-boot-starter with spring-boot-starter-web, and they have some conflicts. Latter I directly introduced mybatis-spring, mybatis and spring-jdbc rather than the mybatis-spring-boot-starter, and the program worked well.

hope this helps

Body:
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more

The application starter class is this:

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?


问:
rails and sql where IS NOT NULL not working properly with join. Rails 2.3.5 and Ruby 1.8.7 - mysql 5
I have 3 tables & models:
brands
brand_data_records
and
brand_data_records_brands - the join table

In rails i want all brand_data_records for a given date range for a given brand where a given attribute is not null in the db.

So I have:

```<code>BrandDataRecord.find(:all, :select => column_match, :joins => :brands, :conditions => ["brand_data_records_brands.brand_id = ? and date_retrieved >= ? AND date_retrieved <= ? and ? IS NOT NULL",brand.id,start_date,end_date,column_match])
</code>```

This generates this sql:

```<code>  SELECT sentiment FROM `brand_data_records` INNER JOIN `brand_data_records_brands` ON `brand_data_records_brands`.brand_data_record_id = `brand_data_records`.id INNER JOIN `brands` ON `brands`.id = `brand_data_records_brands`.brand_id WHERE (brand_data_records_brands.brand_id = 330516084 and date_retrieved >= '2011-05-02' AND date_retrieved <= '2011-06-01' and 'sentiment' IS NOT NULL)
</code>```

Which generally works, but it gives back a bunch of extra records that have a null value. I think its something to do with the joins, if I remove them with sql only it works fine, but im not sure how to fix in rails (or even in sql for that fact)

答:
You probably mean to reference the column:

```<code> `sentiment` IS NOT NULL
</code>```

What you're doing inadvertently is asserting that the string 'sentiment' is not null, which of course it will never be. Passing in :sentiment or 'sentiment'.to_sym' in your conditions should fix this as symbols get escaped with backquotes on conversion.

Body:
I have 3 tables & models:
brands
brand_data_records
and
brand_data_records_brands - the join table

In rails i want all brand_data_records for a given date range for a given brand where a given attribute is not null in the db.

So I have:

BrandDataRecord.find(:all, :select => column_match, :joins => :brands, :conditions => ["brand_data_records_brands.brand_id = ? and date_retrieved >= ? AND date_retrieved <= ? and ? IS NOT NULL",brand.id,start_date,end_date,column_match])

This generates this sql:

  SELECT sentiment FROM `brand_data_records` INNER JOIN `brand_data_records_brands` ON `brand_data_records_brands`.brand_data_record_id = `brand_data_records`.id INNER JOIN `brands` ON `brands`.id = `brand_data_records_brands`.brand_id WHERE (brand_data_records_brands.brand_id = 330516084 and date_retrieved >= '2011-05-02' AND date_retrieved <= '2011-06-01' and 'sentiment' IS NOT NULL)

Which generally works, but it gives back a bunch of extra records that have a null value. I think its something to do with the joins, if I remove them with sql only it works fine, but im not sure how to fix in rails (or even in sql for that fact)

Body:
You probably mean to reference the column:

 `sentiment` IS NOT NULL

What you're doing inadvertently is asserting that the string 'sentiment' is not null, which of course it will never be. Passing in :sentiment or 'sentiment'.to_sym' in your conditions should fix this as symbols get escaped with backquotes on conversion.


问:
Nested Run Keywords Statement In Robot Framework
I have to execute a nested run keyword Statement and I am following below code in a function:

```<code>${value}=  Run keyword And Return Status   Dictionary Should Contain Key  ${details}  edit
    Run Keyword If   '${value}'=='True'
    ...  Run Keywords
        ...    Run Keyword If  '&{details}[edit]'=='Block1'  Log  Block1 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block2'  Log  Block2 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block3'  Log  Block3 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block4'
                    ...  Run Keywords
                            ...  Log  Block4 1 Call
                                ...    AND  Log  Block4 2 Call
                                ...    AND  Log  Block4 3 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block5'
                     ...  Run Keywords
                            ...  Log  Block5 1 Call
                                ...    AND  Log  Block5 2 Call
                                ...    AND  Log  Block5 3 Call
</code>```

When I am passing the value as Block2, It returns:

```<code>Block2 Call
Block4 2 Call
Block4 3 Call

Also, it does not return correct response with values 'Block4' and 'Block5'
I have tried this with ELSE If Statements also, but still this does not work.

Does Run Keyword does not support the Nested Statements?  Or Is there any other which by which this can be accomplished?
</code>```

答:
Solved this by putting all the conditions in  a separate method:</p>

```<code>${value}=  Run keyword And Return Status   Dictionary Should Contain Key  ${details}  edit
    Run Keyword If   '${value}'=='True'  Run_Conditions  &{details}

Run_Conditions
     [Arguments]  &{details}
     Run Keyword If  '&{details}[edit]'=='Block1'  Log  Block1 Call
     Run Keyword If  '&{details}[edit]'=='Block2'  Log  Block2 Call
     Run Keyword If  '&{details}[edit]'=='Block3'  Log  Block3 Call
     Run Keyword If  '&{details}[edit]'=='Block4'
     ...  Run Keywords
           ...  Log  Block4 1 Call
           ...    AND  Log  Block4 2 Call
           ...    AND  Log  Block4 3 Call
     Run Keyword If  '&{details}[edit]'=='Block5'
     ...  Run Keywords
          ...  Log  Block5 1 Call
          ...    AND  Log  Block5 2 Call
          ...    AND  Log  Block5 3 Call

</code>```

Body:
I have to execute a nested run keyword Statement and I am following below code in a function:

${value}=  Run keyword And Return Status   Dictionary Should Contain Key  ${details}  edit
    Run Keyword If   '${value}'=='True'
    ...  Run Keywords
        ...    Run Keyword If  '&{details}[edit]'=='Block1'  Log  Block1 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block2'  Log  Block2 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block3'  Log  Block3 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block4'
                    ...  Run Keywords
                            ...  Log  Block4 1 Call
                                ...    AND  Log  Block4 2 Call
                                ...    AND  Log  Block4 3 Call
        ...    AND  Run Keyword If  '&{details}[edit]'=='Block5'
                     ...  Run Keywords
                            ...  Log  Block5 1 Call
                                ...    AND  Log  Block5 2 Call
                                ...    AND  Log  Block5 3 Call

When I am passing the value as Block2, It returns:

Block2 Call
Block4 2 Call
Block4 3 Call

Also, it does not return correct response with values 'Block4' and 'Block5'
I have tried this with ELSE If Statements also, but still this does not work.

Does Run Keyword does not support the Nested Statements?  Or Is there any other which by which this can be accomplished?

Body:
Solved this by putting all the conditions in  a separate method:

${value}=  Run keyword And Return Status   Dictionary Should Contain Key  ${details}  edit
    Run Keyword If   '${value}'=='True'  Run_Conditions  &{details}

Run_Conditions
     [Arguments]  &{details}
     Run Keyword If  '&{details}[edit]'=='Block1'  Log  Block1 Call
     Run Keyword If  '&{details}[edit]'=='Block2'  Log  Block2 Call
     Run Keyword If  '&{details}[edit]'=='Block3'  Log  Block3 Call
     Run Keyword If  '&{details}[edit]'=='Block4'
     ...  Run Keywords
           ...  Log  Block4 1 Call
           ...    AND  Log  Block4 2 Call
           ...    AND  Log  Block4 3 Call
     Run Keyword If  '&{details}[edit]'=='Block5'
     ...  Run Keywords
          ...  Log  Block5 1 Call
          ...    AND  Log  Block5 2 Call
          ...    AND  Log  Block5 3 Call