问:
How to display two graph generated from separate code from “observablehq” on one browser window
I am new in d3.js.I downloaded two code generating graphs from site “observablehq”. Here are links to codes.

1- zoomable-area-chart

2-focus-context

I want to display both graphs in the same browser window. For this, I placed the files in the same directory. Here is html code of zoomable-area-chart

```<code><!DOCTYPE html>
<meta charset="utf-8">
<title>Zoomable Area Chart</title>
<link rel="stylesheet" type="text/css" href="./inspector.css">
<body>
<script type="module">

import define from "./index.js";
import {Runtime, Library, Inspector} from "./runtime.js";

const runtime = new Runtime();
const main = runtime.module(define, Inspector.into(document.body));

</script>
</code>```

Here is html code of focus-context

```<code><!DOCTYPE html>
<meta charset="utf-8">
<title>Focus + Context</title>
<link rel="stylesheet" type="text/css" href="inspector1.css">
<body>
<script type="module">

import define from "./index1.js";
import {Runtime, Library, Inspector} from "./runtime1.js";

const runtime = new Runtime();
const main = runtime.module(define, Inspector.into(document.body));

</script>
</code>```

I placed "Focus + Context" "script" in html file of "Zoomable Area Chart" like this

```<code>    <!DOCTYPE html>
    <meta charset="utf-8">
    <title>Zoomable Area Chart</title>
    <link rel="stylesheet" type="text/css" href="./inspector.css">
    <body>
    <script type="module">

    import define from "./index.js";
    import {Runtime, Library, Inspector} from "./runtime.js";

    const runtime = new Runtime();
    const main = runtime.module(define, Inspector.into(document.body));

    </script>
    <script type="module">

        import define from "./index1.js";
        import {Runtime, Library, Inspector} from "./runtime1.js";

        const runtime = new Runtime();
        const main = runtime.module(define, Inspector.into(document.body));

    </script>
</code>```

then I ran that html file using "webstorm" into browser. It is not displaying both graphs into the same browser window. It is displaying errors for the first graph and displaying the second graph

Here is js file for "Zoomable Area Chart"

```<code>// https://observablehq.com/@d3/zoomable-area-chart@212
export default function define(runtime, observer) {
  const main = runtime.module();
  const fileAttachments = new Map([["flights.csv",new URL("./files/1171cb24da0255c434c1ff554b4964c39c1253aa9349f2d356a25351acd3579367f92b24366ae5b6c208c9336811489c0a176cbc0cc62e31feff51e294a178fe",import.meta.url)]]);
  main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
  main.variable(observer()).define(["md"], function(md){return(
md`# Zoomable Area Chart

This zoomable time series area chart shows the number of flights per day. The effect of the September 11, 2001 attacks on air travel is evident.`
)});
  main.variable(observer("chart")).define("chart", ["d3","margin","width","height","DOM","area","data","x","xAxis","yAxis","y"], function(d3,margin,width,height,DOM,area,data,x,xAxis,yAxis,y)
{
  const zoom = d3.zoom()
      .scaleExtent([1, 32])
      .extent([[margin.left, 0], [width - margin.right, height]])
      .translateExtent([[margin.left, -Infinity], [width - margin.right, Infinity]])
      .on("zoom", zoomed);

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height]);

  const clip = DOM.uid("clip");

  svg.append("clipPath")
      .attr("id", clip.id)
    .append("rect")
      .attr("x", margin.left)
      .attr("y", margin.top)
      .attr("width", width - margin.left - margin.right)
      .attr("height", height - margin.top - margin.bottom);

  const path = svg.append("path")
      .attr("clip-path", clip)
      .attr("fill", "steelblue")
      .attr("d", area(data, x));

  const gx = svg.append("g")
      .call(xAxis, x);

  svg.append("g")
      .call(yAxis, y);

  svg.call(zoom)
    .transition()
      .duration(750)
      .call(zoom.scaleTo, 4, [x(Date.UTC(2001, 8, 1)), 0]);

  function zoomed() {
    const xz = d3.event.transform.rescaleX(x);
    path.attr("d", area(data, xz));
    gx.call(xAxis, xz);
  }

  return svg.node();
}
);
  main.variable(observer("height")).define("height", function(){return(
500
)});
  main.variable(observer("margin")).define("margin", function(){return(
{top: 20, right: 20, bottom: 30, left: 30}
)});
  main.variable(observer("x")).define("x", ["d3","data","margin","width"], function(d3,data,margin,width){return(
d3.scaleUtc()
    .domain(d3.extent(data, d => d.date))
    .range([margin.left, width - margin.right])
)});
  main.variable(observer("y")).define("y", ["d3","data","height","margin"], function(d3,data,height,margin){return(
d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)]).nice()
    .range([height - margin.bottom, margin.top])
)});
  main.variable(observer("xAxis")).define("xAxis", ["height","margin","d3","width"], function(height,margin,d3,width){return(
(g, x) => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
)});
  main.variable(observer("yAxis")).define("yAxis", ["margin","d3","data"], function(margin,d3,data){return(
(g, y) => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
)});
  main.variable(observer("area")).define("area", ["d3","y"], function(d3,y){return(
(data, x) => d3.area()
    .curve(d3.curveStepAfter)
    .x(d => x(d.date))
    .y0(y(0))
    .y1(d => y(d.value))
  (data)
)});
  main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
Object.assign(d3.csvParse(await FileAttachment("flights.csv").text(), d3.autoType), {y: "Flights"})
)});
  main.variable(observer("d3")).define("d3", ["require"], function(require){return(
require("d3@5")
)});
  return main;
}
</code>```

Here is js file for "Focus + Context"

```<code>// https://observablehq.com/@d3/focus-context@320
export default function define(runtime, observer) {
  const main = runtime.module();
  const fileAttachments = new Map([["aapl.csv",new URL("./files/de259092d525c13bd10926eaf7add45b15f2771a8b39bc541a5bba1e0206add4880eb1d876be8df469328a85243b7d813a91feb8cc4966de582dc02e5f8609b7",import.meta.url)]]);
  main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
  main.variable(observer()).define(["md"], function(md){return(
md`# Focus + Context

This [area chart](/@d3/area-chart) uses brushing to specify a focused area. Drag the gray region to pan, or brush to zoom. Compare to a [zoomable chart](/@d3/zoomable-area-chart). Data: [Yahoo Finance](https://finance.yahoo.com/lookup)`
)});
  main.variable(observer("chart")).define("chart", ["d3","width","height","DOM","margin","data","xAxis","yAxis","area"], function(d3,width,height,DOM,margin,data,xAxis,yAxis,area)
{
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height])
      .style("display", "block");

  const clipId = DOM.uid("clip");

  svg.append("clipPath")
      .attr("id", clipId.id)
    .append("rect")
      .attr("x", margin.left)
      .attr("y", 0)
      .attr("height", height)
      .attr("width", width - margin.left - margin.right);

  const gx = svg.append("g");

  const gy = svg.append("g");

  const path = svg.append("path")
      .datum(data)
      .attr("clip-path", clipId)
      .attr("fill", "steelblue");

  return Object.assign(svg.node(), {
    update(focusX, focusY) {
      gx.call(xAxis, focusX, height);
      gy.call(yAxis, focusY, data.y);
      path.attr("d", area(focusX, focusY));
    }
  });
}
);
  main.variable(observer("viewof focus")).define("viewof focus", ["d3","width","focusHeight","margin","x","xAxis","data","area","y"], function(d3,width,focusHeight,margin,x,xAxis,data,area,y)
{
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, focusHeight])
      .style("display", "block");

  const brush = d3.brushX()
      .extent([[margin.left, 0.5], [width - margin.right, focusHeight - margin.bottom + 0.5]])
      .on("brush", brushed)
      .on("end", brushended);

  const defaultSelection = [x(d3.utcYear.offset(x.domain()[1], -1)), x.range()[1]];

  svg.append("g")
      .call(xAxis, x, focusHeight);

  svg.append("path")
      .datum(data)
      .attr("fill", "steelblue")
      .attr("d", area(x, y.copy().range([focusHeight - margin.bottom, 4])));

  const gb = svg.append("g")
      .call(brush)
      .call(brush.move, defaultSelection);

  function brushed() {
    if (d3.event.selection) {
      svg.property("value", d3.event.selection.map(x.invert, x).map(d3.utcDay.round));
      svg.dispatch("input");
    }
  }

  function brushended() {
    if (!d3.event.selection) {
      gb.call(brush.move, defaultSelection);
    }
  }

  return svg.node();
}
);
  main.variable(observer("focus")).define("focus", ["Generators", "viewof focus"], (G, _) => G.input(_));
  main.variable(observer()).define(["focus","d3","data","chart","x","y"], function(focus,d3,data,chart,x,y)
{
  const [minX, maxX] = focus;
  const maxY = d3.max(data, d => minX <= d.date && d.date <= maxX ? d.value : NaN);
  chart.update(x.copy().domain(focus), y.copy().domain([0, maxY]));
}
);
  main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
Object.assign(d3.csvParse(await FileAttachment("aapl.csv").text(), d3.autoType).map(({date, close}) => ({date, value: close})), {y: "↑ Close $"})
)});
  main.variable(observer("area")).define("area", ["d3"], function(d3){return(
(x, y) => d3.area()
    .defined(d => !isNaN(d.value))
    .x(d => x(d.date))
    .y0(y(0))
    .y1(d => y(d.value))
)});
  main.variable(observer("x")).define("x", ["d3","data","margin","width"], function(d3,data,margin,width){return(
d3.scaleUtc()
    .domain(d3.extent(data, d => d.date))
    .range([margin.left, width - margin.right])
)});
  main.variable(observer("y")).define("y", ["d3","data","height","margin"], function(d3,data,height,margin){return(
d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)])
    .range([height - margin.bottom, margin.top])
)});
  main.variable(observer("xAxis")).define("xAxis", ["margin","d3","width"], function(margin,d3,width){return(
(g, x, height) => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
)});
  main.variable(observer("yAxis")).define("yAxis", ["margin","d3"], function(margin,d3){return(
(g, y, title) => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y))
    .call(g => g.select(".domain").remove())
    .call(g => g.selectAll(".title").data([title]).join("text")
        .attr("class", "title")
        .attr("x", -margin.left)
        .attr("y", 10)
        .attr("fill", "currentColor")
        .attr("text-anchor", "start")
        .text(title))
)});
  main.variable(observer("margin")).define("margin", function(){return(
{top: 20, right: 20, bottom: 30, left: 40}
)});
  main.variable(observer("height")).define("height", function(){return(
440
)});
  main.variable(observer("focusHeight")).define("focusHeight", function(){return(
100
)});
  main.variable(observer("d3")).define("d3", ["require"], function(require){return(
require("d3@5")
)});
  return main;
}
</code>```

How I can display both graphs in the same browser window correctly. You can download the complete project from this link

答:
iframe is the tag which you can use for call other html pages into your web page</p>

```<code><iframe src="index1.html" height="700px"  width="100%" style=" border:none;"></iframe>
</code>```

Body:
I am new in d3.js.I downloaded two code generating graphs from site “observablehq”. Here are links to codes.

1- zoomable-area-chart

2-focus-context

I want to display both graphs in the same browser window. For this, I placed the files in the same directory. Here is html code of zoomable-area-chart

<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoomable Area Chart</title>
<link rel="stylesheet" type="text/css" href="./inspector.css">

Here is html code of focus-context

<!DOCTYPE html>
<meta charset="utf-8">
<title>Focus + Context</title>
<link rel="stylesheet" type="text/css" href="inspector1.css">

I placed "Focus + Context" "script" in html file of "Zoomable Area Chart" like this

    <!DOCTYPE html>
    <meta charset="utf-8">
    <title>Zoomable Area Chart</title>
    <link rel="stylesheet" type="text/css" href="./inspector.css">

then I ran that html file using "webstorm" into browser. It is not displaying both graphs into the same browser window. It is displaying errors for the first graph and displaying the second graph

Here is js file for "Zoomable Area Chart"

// https://observablehq.com/@d3/zoomable-area-chart@212
export default function define(runtime, observer) {
  const main = runtime.module();
  const fileAttachments = new Map([["flights.csv",new URL("./files/1171cb24da0255c434c1ff554b4964c39c1253aa9349f2d356a25351acd3579367f92b24366ae5b6c208c9336811489c0a176cbc0cc62e31feff51e294a178fe",import.meta.url)]]);
  main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
  main.variable(observer()).define(["md"], function(md){return(
md`# Zoomable Area Chart

This zoomable time series area chart shows the number of flights per day. The effect of the September 11, 2001 attacks on air travel is evident.`
)});
  main.variable(observer("chart")).define("chart", ["d3","margin","width","height","DOM","area","data","x","xAxis","yAxis","y"], function(d3,margin,width,height,DOM,area,data,x,xAxis,yAxis,y)
{
  const zoom = d3.zoom()
      .scaleExtent([1, 32])
      .extent([[margin.left, 0], [width - margin.right, height]])
      .translateExtent([[margin.left, -Infinity], [width - margin.right, Infinity]])
      .on("zoom", zoomed);

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height]);

  const clip = DOM.uid("clip");

  svg.append("clipPath")
      .attr("id", clip.id)
    .append("rect")
      .attr("x", margin.left)
      .attr("y", margin.top)
      .attr("width", width - margin.left - margin.right)
      .attr("height", height - margin.top - margin.bottom);

  const path = svg.append("path")
      .attr("clip-path", clip)
      .attr("fill", "steelblue")
      .attr("d", area(data, x));

  const gx = svg.append("g")
      .call(xAxis, x);

  svg.append("g")
      .call(yAxis, y);

  svg.call(zoom)
    .transition()
      .duration(750)
      .call(zoom.scaleTo, 4, [x(Date.UTC(2001, 8, 1)), 0]);

  function zoomed() {
    const xz = d3.event.transform.rescaleX(x);
    path.attr("d", area(data, xz));
    gx.call(xAxis, xz);
  }

  return svg.node();
}
);
  main.variable(observer("height")).define("height", function(){return(
500
)});
  main.variable(observer("margin")).define("margin", function(){return(
{top: 20, right: 20, bottom: 30, left: 30}
)});
  main.variable(observer("x")).define("x", ["d3","data","margin","width"], function(d3,data,margin,width){return(
d3.scaleUtc()
    .domain(d3.extent(data, d => d.date))
    .range([margin.left, width - margin.right])
)});
  main.variable(observer("y")).define("y", ["d3","data","height","margin"], function(d3,data,height,margin){return(
d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)]).nice()
    .range([height - margin.bottom, margin.top])
)});
  main.variable(observer("xAxis")).define("xAxis", ["height","margin","d3","width"], function(height,margin,d3,width){return(
(g, x) => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
)});
  main.variable(observer("yAxis")).define("yAxis", ["margin","d3","data"], function(margin,d3,data){return(
(g, y) => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y).ticks(null, "s"))
    .call(g => g.select(".domain").remove())
    .call(g => g.select(".tick:last-of-type text").clone()
        .attr("x", 3)
        .attr("text-anchor", "start")
        .attr("font-weight", "bold")
        .text(data.y))
)});
  main.variable(observer("area")).define("area", ["d3","y"], function(d3,y){return(
(data, x) => d3.area()
    .curve(d3.curveStepAfter)
    .x(d => x(d.date))
    .y0(y(0))
    .y1(d => y(d.value))
  (data)
)});
  main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
Object.assign(d3.csvParse(await FileAttachment("flights.csv").text(), d3.autoType), {y: "Flights"})
)});
  main.variable(observer("d3")).define("d3", ["require"], function(require){return(
require("d3@5")
)});
  return main;
}

Here is js file for "Focus + Context"

// https://observablehq.com/@d3/focus-context@320
export default function define(runtime, observer) {
  const main = runtime.module();
  const fileAttachments = new Map([["aapl.csv",new URL("./files/de259092d525c13bd10926eaf7add45b15f2771a8b39bc541a5bba1e0206add4880eb1d876be8df469328a85243b7d813a91feb8cc4966de582dc02e5f8609b7",import.meta.url)]]);
  main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
  main.variable(observer()).define(["md"], function(md){return(
md`# Focus + Context

This [area chart](/@d3/area-chart) uses brushing to specify a focused area. Drag the gray region to pan, or brush to zoom. Compare to a [zoomable chart](/@d3/zoomable-area-chart). Data: [Yahoo Finance](https://finance.yahoo.com/lookup)`
)});
  main.variable(observer("chart")).define("chart", ["d3","width","height","DOM","margin","data","xAxis","yAxis","area"], function(d3,width,height,DOM,margin,data,xAxis,yAxis,area)
{
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height])
      .style("display", "block");

  const clipId = DOM.uid("clip");

  svg.append("clipPath")
      .attr("id", clipId.id)
    .append("rect")
      .attr("x", margin.left)
      .attr("y", 0)
      .attr("height", height)
      .attr("width", width - margin.left - margin.right);

  const gx = svg.append("g");

  const gy = svg.append("g");

  const path = svg.append("path")
      .datum(data)
      .attr("clip-path", clipId)
      .attr("fill", "steelblue");

  return Object.assign(svg.node(), {
    update(focusX, focusY) {
      gx.call(xAxis, focusX, height);
      gy.call(yAxis, focusY, data.y);
      path.attr("d", area(focusX, focusY));
    }
  });
}
);
  main.variable(observer("viewof focus")).define("viewof focus", ["d3","width","focusHeight","margin","x","xAxis","data","area","y"], function(d3,width,focusHeight,margin,x,xAxis,data,area,y)
{
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, focusHeight])
      .style("display", "block");

  const brush = d3.brushX()
      .extent([[margin.left, 0.5], [width - margin.right, focusHeight - margin.bottom + 0.5]])
      .on("brush", brushed)
      .on("end", brushended);

  const defaultSelection = [x(d3.utcYear.offset(x.domain()[1], -1)), x.range()[1]];

  svg.append("g")
      .call(xAxis, x, focusHeight);

  svg.append("path")
      .datum(data)
      .attr("fill", "steelblue")
      .attr("d", area(x, y.copy().range([focusHeight - margin.bottom, 4])));

  const gb = svg.append("g")
      .call(brush)
      .call(brush.move, defaultSelection);

  function brushed() {
    if (d3.event.selection) {
      svg.property("value", d3.event.selection.map(x.invert, x).map(d3.utcDay.round));
      svg.dispatch("input");
    }
  }

  function brushended() {
    if (!d3.event.selection) {
      gb.call(brush.move, defaultSelection);
    }
  }

  return svg.node();
}
);
  main.variable(observer("focus")).define("focus", ["Generators", "viewof focus"], (G, _) => G.input(_));
  main.variable(observer()).define(["focus","d3","data","chart","x","y"], function(focus,d3,data,chart,x,y)
{
  const [minX, maxX] = focus;
  const maxY = d3.max(data, d => minX <= d.date && d.date <= maxX ? d.value : NaN);
  chart.update(x.copy().domain(focus), y.copy().domain([0, maxY]));
}
);
  main.variable(observer("data")).define("data", ["d3","FileAttachment"], async function(d3,FileAttachment){return(
Object.assign(d3.csvParse(await FileAttachment("aapl.csv").text(), d3.autoType).map(({date, close}) => ({date, value: close})), {y: "↑ Close $"})
)});
  main.variable(observer("area")).define("area", ["d3"], function(d3){return(
(x, y) => d3.area()
    .defined(d => !isNaN(d.value))
    .x(d => x(d.date))
    .y0(y(0))
    .y1(d => y(d.value))
)});
  main.variable(observer("x")).define("x", ["d3","data","margin","width"], function(d3,data,margin,width){return(
d3.scaleUtc()
    .domain(d3.extent(data, d => d.date))
    .range([margin.left, width - margin.right])
)});
  main.variable(observer("y")).define("y", ["d3","data","height","margin"], function(d3,data,height,margin){return(
d3.scaleLinear()
    .domain([0, d3.max(data, d => d.value)])
    .range([height - margin.bottom, margin.top])
)});
  main.variable(observer("xAxis")).define("xAxis", ["margin","d3","width"], function(margin,d3,width){return(
(g, x, height) => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
)});
  main.variable(observer("yAxis")).define("yAxis", ["margin","d3"], function(margin,d3){return(
(g, y, title) => g
    .attr("transform", `translate(${margin.left},0)`)
    .call(d3.axisLeft(y))
    .call(g => g.select(".domain").remove())
    .call(g => g.selectAll(".title").data([title]).join("text")
        .attr("class", "title")
        .attr("x", -margin.left)
        .attr("y", 10)
        .attr("fill", "currentColor")
        .attr("text-anchor", "start")
        .text(title))
)});
  main.variable(observer("margin")).define("margin", function(){return(
{top: 20, right: 20, bottom: 30, left: 40}
)});
  main.variable(observer("height")).define("height", function(){return(
440
)});
  main.variable(observer("focusHeight")).define("focusHeight", function(){return(
100
)});
  main.variable(observer("d3")).define("d3", ["require"], function(require){return(
require("d3@5")
)});
  return main;
}

How I can display both graphs in the same browser window correctly. You can download the complete project from this link

Body:
iframe is the tag which you can use for call other html pages into your web page

<iframe src="index1.html" height="700px"  width="100%" style=" border:none;"></iframe>


来源: stackexchange

问:
Error when instantiating a class for the second time
I'm new to python and PyQt and was developing my first app using it, and I've been stuck in a problem when trying to instantiate a class I made again. I've got the following error:

```<code>Traceback (most recent call last):
  File "ConfiguradorAnx.py", line 16, in <lambda>
     self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct))
TypeError: 'InfoProduct' object is not callable
Aborted
</code>```

The code goes like this:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets, uic
import sys

class StartWindow(QtWidgets.QMainWindow):   #This function should inherit the class
                                            #used to make the ui file
    def __init__(self):
        super(StartWindow,self).__init__()   #Calling the QMainWindow constructor
        uic.loadUi('Janela_inicial.ui',self)

        #defining quit button from generated ui
        self.QuitButton = self.findChild(QtWidgets.QPushButton, 'QuitButton')
        self.QuitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)

        #defining product info button
        self.ProductInfo = self.findChild(QtWidgets.QPushButton, 'ProductInformation')
        self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct))
        self.show() #Show the start window

    def newWindow(self, _class):
        self.newWindow = _class()
        del self.newWindow

class InfoProduct(QtWidgets.QMainWindow):
    def __init__(self):
        super(InfoProduct,self).__init__()
        uic.loadUi('informacao_prod.ui',self)
        self.QuitButton = self.findChild(QtWidgets.QPushButton, 'pushButton')
        self.QuitButton.clicked.connect(lambda: self.destroy())
        self.show()

def main():
    app = QtWidgets.QApplication(sys.argv)  #Creates a instance of Qt application
    InitialWindow = StartWindow()
    app.exec_() #Start application

if __name__ == '__main__':
    main()
</code>```

The first time I click on self.ProductInfo button it works and the InfoProduct window opens, but when I close the window and click on the same button again, I've got the error. I can't figure out what is it that I'm missing, I hope you guys could help!

Cheers!

答:
You're overwriting the newWindow function in its execution:

```<code>def newWindow(self, _class):
    self.newWindow = _class()
</code>```

By doing this, the result is that the next time you click the button, the lambda will try to call self.newWindow(InfoProduct), but at that point self.newWindow is an instance of InfoProduct, which obviously is not callable.

The solution is simple (and very important) use different names for the function and the variable that points to the instance:

```<code>        self.ProductInfo.clicked.connect(lambda: self.createNewWindow(InfoProduct))

    def createNewWindow(self, _class):
        self.newWindow = _class()
</code>```

Two small side notes:

There's no need to use findChild, as loadUi already creates python instance attributes for widgets: you already can access self.QuitButton, etc.

Avoid using capitalized names for variables and attributes. Read more about this and other code styling suggestions on the Style Guide for Python Code (aka, PEP-8).

ContentLicense: CC BY-SA 4.0

Body:
I'm new to python and PyQt and was developing my first app using it, and I've been stuck in a problem when trying to instantiate a class I made again. I've got the following error:

Traceback (most recent call last):
  File "ConfiguradorAnx.py", line 16, in <lambda>
     self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct))
TypeError: 'InfoProduct' object is not callable
Aborted

The code goes like this:

from PyQt5 import QtCore, QtGui, QtWidgets, uic
import sys

class StartWindow(QtWidgets.QMainWindow):   #This function should inherit the class
                                            #used to make the ui file
    def __init__(self):
        super(StartWindow,self).__init__()   #Calling the QMainWindow constructor
        uic.loadUi('Janela_inicial.ui',self)

        #defining quit button from generated ui
        self.QuitButton = self.findChild(QtWidgets.QPushButton, 'QuitButton')
        self.QuitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)

        #defining product info button
        self.ProductInfo = self.findChild(QtWidgets.QPushButton, 'ProductInformation')
        self.ProductInfo.clicked.connect(lambda: self.newWindow(InfoProduct))
        self.show() #Show the start window

    def newWindow(self, _class):
        self.newWindow = _class()
        del self.newWindow

class InfoProduct(QtWidgets.QMainWindow):
    def __init__(self):
        super(InfoProduct,self).__init__()
        uic.loadUi('informacao_prod.ui',self)
        self.QuitButton = self.findChild(QtWidgets.QPushButton, 'pushButton')
        self.QuitButton.clicked.connect(lambda: self.destroy())
        self.show()

def main():
    app = QtWidgets.QApplication(sys.argv)  #Creates a instance of Qt application
    InitialWindow = StartWindow()
    app.exec_() #Start application

if __name__ == '__main__':
    main()

The first time I click on self.ProductInfo button it works and the InfoProduct window opens, but when I close the window and click on the same button again, I've got the error. I can't figure out what is it that I'm missing, I hope you guys could help!

Cheers!

Body:
You're overwriting the newWindow function in its execution:

def newWindow(self, _class):
    self.newWindow = _class()

By doing this, the result is that the next time you click the button, the lambda will try to call self.newWindow(InfoProduct), but at that point self.newWindow is an instance of InfoProduct, which obviously is not callable.

The solution is simple (and very important) use different names for the function and the variable that points to the instance:

        self.ProductInfo.clicked.connect(lambda: self.createNewWindow(InfoProduct))

    def createNewWindow(self, _class):
        self.newWindow = _class()

Two small side notes:

There's no need to use findChild, as loadUi already creates python instance attributes for widgets: you already can access self.QuitButton, etc.

Avoid using capitalized names for variables and attributes. Read more about this and other code styling suggestions on the Style Guide for Python Code (aka, PEP-8).


问:
How to remove dist files in Angular 6?
I want to deploy my angular project i generated dist file in my src folder like this

```<code>ng build
</code>```

Before deploying I decided to add some functionality to my page :

Question
Is it posible to update dist files by doing like this?

```<code>ng serve update /dist dir
</code>```

if false I want to delete the dist file and create another one so that it can be update with all folders, this is what I wanna do

```<code>ng serve remove /dist dir
</code>```

Is this the right way of removing dist files ?

答:
Since you are using package.json AND to be operating system safe I recommend rimraf. It's not only about Windows vs Linux. Also about Linux Distribution vs Linux Distribution, changing access rights, etc. You are safe with this extra layer of abstraction.

Install:

```<code>npm install rimraf
</code>```

In your scripts section of package.json add it as first command and append what ever you want to do after the &&:

```<code>"scripts": {
    "ng": "rimraf /dist && ng build"
}
</code>```

Invoke the build/serve:

```<code>npm run ng
</code>```

ng is what you defined as your script execution identifier.

Title: How to remove dist files in Angular 6?

Body:
I want to deploy my angular project i generated dist file in my src folder like this

ng build

Before deploying I decided to add some functionality to my page :

Question
Is it posible to update dist files by doing like this?

ng serve update /dist dir

if false I want to delete the dist file and create another one so that it can be update with all folders, this is what I wanna do

ng serve remove /dist dir

Is this the right way of removing dist files ?

Body:
Since you are using package.json AND to be operating system safe I recommend rimraf. It's not only about Windows vs Linux. Also about Linux Distribution vs Linux Distribution, changing access rights, etc. You are safe with this extra layer of abstraction.

Install:

npm install rimraf

In your scripts section of package.json add it as first command and append what ever you want to do after the &&:

"scripts": {
    "ng": "rimraf /dist && ng build"
}

Invoke the build/serve:

npm run ng

ng is what you defined as your script execution identifier.


问:
Problem with last card flipping over in memory game
I created a memory card game and I am having an issue that the last card is not flipping over before the alert is coming up that they have finished the game. I have been stuck on thios for a while now and I have inserted my js code below. I'm pretty new to all of this so any help would be great.

```<code>const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    alert("Congratulations you got all " + noOfMatches + " matches");
    stopGame();
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1000);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }
</code>```

If anyone has any questions please let me know.

答:
We can introduce a delay to the alert, by setTimeout so alert will play after the card has been flipped, I have changed the function, countMatches as:

```<code>function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    setTimeout(function(){
      alert("Congratulations you got all "     + noOfMatches + " matches");
    stopGame();
    },1000);
  }
}
</code>```

Final Change:

```<code>const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    setTimeout(function(){
      alert("Congratulations you got all "     + noOfMatches + " matches");
    stopGame();
    },1000);
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1300);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }
</code>```

Problem 2:

Cards's getting disabled, at the end of matching all cards, you have removed click event listeners for cards after matching hence we must add them in start game.

Paste this part from our starting code ( main.js body ) :

```<code>badges.forEach((card) =>
card.addEventListener("click", flipCard));
</code>```

Into startGame() as :

```<code>function startGame() {
    badges.forEach((card) =>                            card.addEventListener("click", flipCard));
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }
</code>```

Body:
I created a memory card game and I am having an issue that the last card is not flipping over before the alert is coming up that they have finished the game. I have been stuck on thios for a while now and I have inserted my js code below. I'm pretty new to all of this so any help would be great.

const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    alert("Congratulations you got all " + noOfMatches + " matches");
    stopGame();
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1000);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }

If anyone has any questions please let me know.

Body:
We can introduce a delay to the alert, by setTimeout so alert will play after the card has been flipped, I have changed the function, countMatches as:

function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    setTimeout(function(){
      alert("Congratulations you got all "     + noOfMatches + " matches");
    stopGame();
    },1000);
  }
}

Final Change:

const badges = document.querySelectorAll(".badge-card");

//Declaring the variables
let hasFlippedCard = false;
let isBoardLocked = true;
let cardOne, cardTwo;
let noOfMatches = 0;

//Funtion to randomise the cards
(function randomiseCards() {
  badges.forEach((card) => {
    let ramdomPos = Math.floor(Math.random() * 16);
    card.style.order = ramdomPos;
  });
})();

badges.forEach((card) => card.addEventListener("click", flipCard));

//Funtion to flip the cards
function flipCard() {
  if (isBoardLocked) return;
  if (this === cardOne) return;

  this.classList.add("flip");

  if (!hasFlippedCard) {
    hasFlippedCard = true;
    cardOne = this;
    return;
  }
  cardTwo = this;
  isBoardLocked = true;
  checkForMatch();
}

//Funtion to check for matches
function checkForMatch() {
  let isMatch = cardOne.dataset.framework === cardTwo.dataset.framework;

  if (isMatch) {
    countMatches();
    disableCards();

  } else {
    unflipCards();
  }
}

//Funtion to count matches of cards
function countMatches() {
  noOfMatches = noOfMatches + 1;
  if (foundAllMatches()) {
    setTimeout(function(){
      alert("Congratulations you got all "     + noOfMatches + " matches");
    stopGame();
    },1000);
  }
}

//Funtion to check if user has found all matches
function foundAllMatches() {
  if (noOfMatches == badges.length / 2) {
    return true;
  } else {
    return false;
  }
}

//Funtion to disbale the cards
function disableCards() {
  cardOne.removeEventListener("click", flipCard);
  cardTwo.removeEventListener("click", flipCard);

  resetBoard();
}

//Funtion to unflip the cards
function unflipCards() {
  setTimeout(() => {
    cardOne.classList.remove("flip");
    cardTwo.classList.remove("flip");

    //time to flip card back over
    resetBoard();
  }, 900);
}

//Funtion to reset the board
function resetBoard() {
  hasFlippedCard = false;
  isBoardLocked = false;
  cardOne = null;
  cardTwo = null;
}

//Funtion to unflip cards at end of game
function unflipAllcards() {
  $(".flip").removeClass('flip');
}

//Timer and start game button
  let timeContainer = $('#timer-value');
  let startButton2 = $('#start-game')
  let timer = 0;
  let maxTime = 60;
  let timeout = null;

  function count() {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        $(timeContainer).text(timer)
        count();
      } else {
        alert("Time's up! You got " + noOfMatches + " matches");
        startButton2.show()
        stopGame();
      }
    }, 1300);
  }

  //Start game button
  function startGame() {
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }

  //Funtion for stopping the game
  function stopGame() {
    if (timeout) {
      clearTimeout(timeout);
      startButton2.show()
    }
    timer = 0;
    $(timeContainer).text(timer)
    isBoardLocked = true;
    unflipAllcards();
  }

Problem 2:

Cards's getting disabled, at the end of matching all cards, you have removed click event listeners for cards after matching hence we must add them in start game.

Paste this part from our starting code ( main.js body ) :

badges.forEach((card) =>
card.addEventListener("click", flipCard));

Into startGame() as :

function startGame() {
    badges.forEach((card) =>                            card.addEventListener("click", flipCard));
    if (timeout) {
      clearTimeout(timeout);
    }
    timer = 0;
    $(timeContainer).text(timer)
    startButton2.hide()
    count();
    isBoardLocked = false;
  }


问:
More efficient way to reuse vector as array in winsock?
I'm currently using vectors as c-style arrays to send and recieve data through Winsock.

I have a std::vector and I'm using that as my 'byte array'.

The problem is, I'm using two vectors, one for each send, and one for each recv, but what I'm doing seems to be fairly inefficient.

Example:

```<code>std::string EndBody("\r\n.\r\n");
std::fill(m_SendBuffer.begin(),m_SendBuffer.end(),0);
std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
SendData();
</code>```

SendData just calls send the appropriate amount of times and ensures everything works as it should.

Anyway. Unless I zero out the vector before each use I get errors with stuff overlapping. Is there a more efficient way for me to do what I'm doing? Because it seems that zeroing out the entire buffer on each call is horribly inefficient.

Thanks.

答:
Wouldn't calling clear mean the vector gets a new size of 0? If the OP is using the vector as a large chunk of memory then they'd have to then call resize after clear to ensure the appropriate space is available for calls to send and recv.

Calling clear then resize on the vector would be around the same as just filling it with zeros would it not?

vector::clear

vector::resize

fill

OwnerDisplayName: Amja

ContentLicense: CC BY-SA 2.5

Body:
I'm currently using vectors as c-style arrays to send and recieve data through Winsock.

I have a std::vector and I'm using that as my 'byte array'.

The problem is, I'm using two vectors, one for each send, and one for each recv, but what I'm doing seems to be fairly inefficient.

Example:

std::string EndBody("\r\n.\r\n");
std::fill(m_SendBuffer.begin(),m_SendBuffer.end(),0);
std::copy(EndBody.begin(),EndBody.end(),m_SendBuffer.begin());
SendData();

SendData just calls send the appropriate amount of times and ensures everything works as it should.

Anyway. Unless I zero out the vector before each use I get errors with stuff overlapping. Is there a more efficient way for me to do what I'm doing? Because it seems that zeroing out the entire buffer on each call is horribly inefficient.

Thanks.

OwnerDisplayName: Cypherjb


问:
problem with adding UIActivityIndicator to the view !
I am trying to add a UIActivityIndicator to my custom view (programmatically). I am using the following code. But I dont see anything on the screen. Any idea why ?

Thanks.

```<code>UIActivityIndicatorView *activityIndicator=[[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(75, 395, 200, 200)] autorelease];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.center=self.view.center;
[self.view addSubview:activityIndicator];
</code>```

答:
UIActivityIndicator has its hidesWhenStopped property equal to YES by default - that is it is hidden if you do not start animating it. So to make it appear on the screen try one of the following (whichever is more suitable for you):

set hidesWhenStopped property to NO

start animating it (using -startAnimating method)

comment "activityIndicator.center=self.view.center;"

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add a UIActivityIndicator to my custom view (programmatically). I am using the following code. But I dont see anything on the screen. Any idea why ?

Thanks.

UIActivityIndicatorView *activityIndicator=[[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(75, 395, 200, 200)] autorelease];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.center=self.view.center;
[self.view addSubview:activityIndicator];


问:
Redux changing value of deep nested array
I have an initial state like so:

```<code>const initState = {
    posts: data
}
</code>```

now posts is something like :

```<code>[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": []
  },

//some more here
]

</code>```

So what I want to do is, when dispatch is fired I want to add new comments to that specific comments array. This is how I do it:

```<code> if (action.type === "ADD_COMMENT") {
        let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
        let index = state.posts.indexOf(findPost);
        console.log(findPost);

        return {
            ...state,
            posts: [...state.posts,
            state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
        }
    }

</code>```

Even though my app works completely fine I have a problem with the redux state. Because everytime action is happened it adds new comments in to that specific array along with a new array in to state.

So in case of firing new action I do get something like this:

```<code>[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": ["comment here"]
  },
[
  {
    "comments": ["comment here"]
  },

//some more here
]

]
</code>```

In each click it creates a new entry in to my state which I don't want at all. How can I make it possible that it only adds the comments in to that specific array but not as separate entry?

答:
You push the new comment in the "posts" array instead of the post's object.

You can try with a map

```<code>if (action.type === "ADD_COMMENT") {

 const posts = state.posts.map(post => {
       if( post.slug === action.payload.comment.postSlug){
          post.comments.unshift(action.payload.comment);
       }
       return post
    });

    return {...state, posts}
}
</code>```

EDIT : With this solution you mutate the state, wich is not recommended
To avoid this simply copy your posts in a new variable

```<code>let posts = [...state.posts]
</code>```

And then do your map.

Body:
I have an initial state like so:

const initState = {
    posts: data
}

now posts is something like :

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": []
  },

//some more here
]

So what I want to do is, when dispatch is fired I want to add new comments to that specific comments array. This is how I do it:

 if (action.type === "ADD_COMMENT") {
        let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
        let index = state.posts.indexOf(findPost);
        console.log(findPost);

        return {
            ...state,
            posts: [...state.posts,
            state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
        }
    }

Even though my app works completely fine I have a problem with the redux state. Because everytime action is happened it adds new comments in to that specific array along with a new array in to state.

So in case of firing new action I do get something like this:

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": ["comment here"]
  },
[
  {
    "comments": ["comment here"]
  },

//some more here
]

]

In each click it creates a new entry in to my state which I don't want at all. How can I make it possible that it only adds the comments in to that specific array but not as separate entry?

Body:
You push the new comment in the "posts" array instead of the post's object.

You can try with a map

if (action.type === "ADD_COMMENT") {

 const posts = state.posts.map(post => {
       if( post.slug === action.payload.comment.postSlug){
          post.comments.unshift(action.payload.comment);
       }
       return post
    });

    return {...state, posts}
}

EDIT : With this solution you mutate the state, wich is not recommended
To avoid this simply copy your posts in a new variable

let posts = [...state.posts]

And then do your map.


问:
Does usn increases if a bind happens in Active Directory?
Usingg ldp.exe utility, I have connected to LDAP using an admin account of the windows box..
View ==>Tree for CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com   gives:

```<code>distinguishedName: CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com;
userPrincipalName: testing@adb.fed.xyz.com;
uSNChanged: 34251;
uSNCreated: 34246;
</code>```

Then I do a bind

```<code>res = ldap_bind_s(ld, NULL, &NtAuthIdentity, NEGOTIATE (1158)); // v.3
    {NtAuthIdentity: User='testing'; Pwd=<unavailable>; domain = 'adb'}
Authenticated as: 'ADB\testing'.
</code>```

Then again checked usn. Its increased

```<code>distinguishedName: CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com;
userPrincipalName: testing@adb.fed.xyz.com;
uSNChanged: 34252;
uSNCreated: 34246;
</code>```

Then I repeated the above steps i.e. again performed the bind.but this time when I tried getting the uSNChanged  number , i saw that its NOT incremented...

Does binding a user for the fist time only increases the usn number? How usn number change is handled in case of bind.

Can someone please explain this?

答:
The USN will change on the account that you use to authenticate.

The USN only changes when the account is modified. When you authenticate, the lastLogon attribute gets updated, and therefore the account has changed, so the USN is updated.

Credentials are often cached automatically, so doing the same thing a second time will use the same access token from the first attempt and will not count as a second login. So the lastLogon will not be updated and the USN will not change.

The USN will not change on the account you are binding to. So if you bind to an account that is not the same as the account you are using to authenticate, you will see that the USN does not change.

Body:
Usingg ldp.exe utility, I have connected to LDAP using an admin account of the windows box..
View ==>Tree for CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com   gives:

distinguishedName: CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com;
userPrincipalName: testing@adb.fed.xyz.com;
uSNChanged: 34251;
uSNCreated: 34246;

Then I do a bind

res = ldap_bind_s(ld, NULL, &NtAuthIdentity, NEGOTIATE (1158)); // v.3
    {NtAuthIdentity: User='testing'; Pwd=<unavailable>; domain = 'adb'}
Authenticated as: 'ADB\testing'.

Then again checked usn. Its increased

distinguishedName: CN=testing test,OU=AutomationQA_OU_2,DC=adb,DC=fed,DC=xyz,DC=com;
userPrincipalName: testing@adb.fed.xyz.com;
uSNChanged: 34252;
uSNCreated: 34246;

Then I repeated the above steps i.e. again performed the bind.but this time when I tried getting the uSNChanged  number , i saw that its NOT incremented...

Does binding a user for the fist time only increases the usn number? How usn number change is handled in case of bind.

Can someone please explain this?


问:
`vsync` property in TabController constructor
According to this: sample code

I created my own implementation of TabController:

```<code>void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: choices.length);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        bottomNavigationBar: new Material(
          color: Colors.blue,
          child: new TabBar(
            controller: _tabController,
            isScrollable: false,
            tabs: choices.map((Choice choice) {
              return new Tab(
                text: null,
                icon: new Icon(choice.icon),
              );
            }).toList(),
          ),
        ),
        appBar: new AppBar(
          title: const Text('Swap'),
        ),
        body: new TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return new Padding(
              padding: const EdgeInsets.all(16.0),
              child: new ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}
</code>```

In line: _tabController = new TabController(vsync: this, length: choices.length); I got error this message:

error: The argument type '_MyAppState' can't be assigned to the parameter type 'TickerProvider'. (argument_type_not_assignable at [swap] lib/main.dart:24)

What is wrong with my code?

答:
Add any of these SingleTickerProviderStateMixin/ TickerProviderStateMixin  mixins at the end of the statement like below:

Eg:

class _ListingViewState extends State with SingleTickerProviderStateMixin { }

Body:
According to this: sample code

I created my own implementation of TabController:

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: choices.length);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        bottomNavigationBar: new Material(
          color: Colors.blue,
          child: new TabBar(
            controller: _tabController,
            isScrollable: false,
            tabs: choices.map((Choice choice) {
              return new Tab(
                text: null,
                icon: new Icon(choice.icon),
              );
            }).toList(),
          ),
        ),
        appBar: new AppBar(
          title: const Text('Swap'),
        ),
        body: new TabBarView(
          controller: _tabController,
          children: choices.map((Choice choice) {
            return new Padding(
              padding: const EdgeInsets.all(16.0),
              child: new ChoiceCard(choice: choice),
            );
          }).toList(),
        ),
      ),
    );
  }
}

In line: _tabController = new TabController(vsync: this, length: choices.length); I got error this message:

error: The argument type '_MyAppState' can't be assigned to the parameter type 'TickerProvider'. (argument_type_not_assignable at [swap] lib/main.dart:24)

What is wrong with my code?


问:
If dict().fromkeys() all point to the same object, what purpose does the default value argument serve?
The dict method {}.fromkeys() takes an iterable of strings, which will be transformed into dictionary keys. The default value will default to None. For instance:

```<code>d = {}.fromkeys(['loss', 'val_loss'])
</code>```

```<code>{'loss': None, 'val_loss': None}
</code>```

An optional, second argument is the default value that all these values will take:

```<code>d = {}.fromkeys(['loss', 'val_loss'], [])
</code>```

```<code>{'loss': [], 'val_loss': []}
</code>```

I understand that you can initialize an empty dict like this. Where it gets more complicated is that the default values point to the same object.

```<code>[id(val) for val in d.values()]
</code>```

```<code>[140711273848032, 140711273848032]
</code>```

If you would append one list, it would append all the values of this dict. Therefore, you need to re-assign the values to a new object in order to treat the dict values as separate objects:

```<code>d['loss'] = list([0.2, 0.4])
</code>```

If you don't do that, you will change all dict values at the same time.

My question: what purpose is the optional default value intended to serve?

As I see it, you will need to reassign this default value anyway, unless you want to manipulate the same object with different dict keys. I can't think of an honest reason to have many dict keys for one object.

答:
This can work ( dictionary comprehension)</p>

```<code>keys = {'A', 'B', 'C'}
int_lst = [9]
a_dict = { key : list(int_lst) for key in keys }
print(a_dict)
a_dict['B'].append(12)
print(a_dict)
</code>```

Body:
The dict method {}.fromkeys() takes an iterable of strings, which will be transformed into dictionary keys. The default value will default to None. For instance:

d = {}.fromkeys(['loss', 'val_loss'])

{'loss': None, 'val_loss': None}

An optional, second argument is the default value that all these values will take:

d = {}.fromkeys(['loss', 'val_loss'], [])

{'loss': [], 'val_loss': []}

I understand that you can initialize an empty dict like this. Where it gets more complicated is that the default values point to the same object.

[id(val) for val in d.values()]

[140711273848032, 140711273848032]

If you would append one list, it would append all the values of this dict. Therefore, you need to re-assign the values to a new object in order to treat the dict values as separate objects:

d['loss'] = list([0.2, 0.4])

If you don't do that, you will change all dict values at the same time.

My question: what purpose is the optional default value intended to serve?

As I see it, you will need to reassign this default value anyway, unless you want to manipulate the same object with different dict keys. I can't think of an honest reason to have many dict keys for one object.

Body:
This can work ( dictionary comprehension)

keys = {'A', 'B', 'C'}
int_lst = [9]
a_dict = { key : list(int_lst) for key in keys }
print(a_dict)
a_dict['B'].append(12)
print(a_dict)


问:
When trying to subscribe the user to push notifications, my service worker requires a refresh to become active
When trying to subscribe the user to push notifications, my service worker requires a refresh to become active. If i then refresh the page, I can continue the process of subscribing the user, which implies to me that the service worker has not finished registering. I have tried adding await etc to my code and it still requires the refresh.

```<code>async function send() {
    // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    });
    console.log("Service Worker Registered...");

    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    // Store info
    await fetch("/subscribe", {
        method: "POST",
        body: JSON.stringify(subscription),
        headers: {
            "content-type": "application/json"
        }
    });
    console.log("Subscribed...");
}
</code>```

The above is where I am at currently. The first visit to the page logs an error. Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. After a refresh the notifications prompt on chrome appears and I can finish the process.

答:
I did this and it worked. I don't think it is 100% correct but it ended up working for me.</p>

```<code>    // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    }).then(
    function (register) {
        var serviceWorker;
        if (register.installing) {
            serviceWorker = register.installing;
            // console.log('Service worker installing');
        } else if (register.waiting) {
            serviceWorker = register.waiting;
            // console.log('Service worker installed & waiting');
        } else if (register.active) {
            serviceWorker = register.active;
            // console.log('Service worker active');
        }

        if (serviceWorker) {
            console.log("sw current state", serviceWorker.state);
            if (serviceWorker.state == "activated") {
                //If push subscription wasnt done yet have to do here
                console.log("sw already activated - Do watever needed here");
            }
            serviceWorker.addEventListener("statechange", function(e) {
                console.log("sw statechange : ", e.target.state);
                if (e.target.state == "activated") {
                    // use pushManger for subscribing here.
                    console.log("Just now activated. now we can subscribe for push notification")
                    subscribeForPushNotification(register);
                }
            });
        }
    }
);
}
async function subscribeForPushNotification(){
 // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    });
    console.log("Service Worker Registered...");

    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    // Store
    await fetch("/subscribe", {
        method: "POST",
        body: JSON.stringify(subscription),
        headers: {
            "content-type": "application/json"
        }
    });
    console.log("Push Sent...");
}```
</code>```

Body:
When trying to subscribe the user to push notifications, my service worker requires a refresh to become active. If i then refresh the page, I can continue the process of subscribing the user, which implies to me that the service worker has not finished registering. I have tried adding await etc to my code and it still requires the refresh.

async function send() {
    // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    });
    console.log("Service Worker Registered...");

    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    // Store info
    await fetch("/subscribe", {
        method: "POST",
        body: JSON.stringify(subscription),
        headers: {
            "content-type": "application/json"
        }
    });
    console.log("Subscribed...");
}

The above is where I am at currently. The first visit to the page logs an error. Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. After a refresh the notifications prompt on chrome appears and I can finish the process.

Body:
I did this and it worked. I don't think it is 100% correct but it ended up working for me.

    // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    }).then(
    function (register) {
        var serviceWorker;
        if (register.installing) {
            serviceWorker = register.installing;
            // console.log('Service worker installing');
        } else if (register.waiting) {
            serviceWorker = register.waiting;
            // console.log('Service worker installed & waiting');
        } else if (register.active) {
            serviceWorker = register.active;
            // console.log('Service worker active');
        }

        if (serviceWorker) {
            console.log("sw current state", serviceWorker.state);
            if (serviceWorker.state == "activated") {
                //If push subscription wasnt done yet have to do here
                console.log("sw already activated - Do watever needed here");
            }
            serviceWorker.addEventListener("statechange", function(e) {
                console.log("sw statechange : ", e.target.state);
                if (e.target.state == "activated") {
                    // use pushManger for subscribing here.
                    console.log("Just now activated. now we can subscribe for push notification")
                    subscribeForPushNotification(register);
                }
            });
        }
    }
);
}
async function subscribeForPushNotification(){
 // Register Service Worker
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("worker.js", {
        scope: "/portal/"
    });
    console.log("Service Worker Registered...");

    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    // Store
    await fetch("/subscribe", {
        method: "POST",
        body: JSON.stringify(subscription),
        headers: {
            "content-type": "application/json"
        }
    });
    console.log("Push Sent...");
}```


问:
BigQuery query result having variable number of columns?
I have a table in this form:

```<code>TIME  TYPE COUNT
00:01 DOG  4
00:04 CAT  5
00:07 DOG  2
00:30 BIRD 1
01:04 DOG  2
01:30 BIRD 3
01:40 DOG  1
02:01 BIRD 4
</code>```

I do a query like this that joins the sum of COUNT of each TYPE based on hour:

```<code>select HOUR(`TIME`), `TYPE`, sum(`COUNT`)
from `table`
where `TYPE` = 'DOG'
group by HOUR(`TIME`)
FULL JOIN
...(same query but... where `TYPE` = 'CAT')
ON hour...
FULL JOIN
...(same query again, but where `TYPE` = 'BIRD')
etc.
</code>```

The purpose being to get a result like this:

```<code>HOUR DOG CAT BIRD
00   6   5   1
01   5   0   3
02   0   0   4
</code>```

My question is: How can you do this without joins?
I want a query to work for any distinct TYPE values that happen to the be in the table and are not known upfront, so the table would grow in columns foreach distinct TYPE.

Is this something that could be done with BigQuery script?

答:
Use sum(case . . ):

```<code>select extract(hour from time),
       sum(case when type = 'dog' then count else 0 end) as dog,
       sum(case when type = 'cat' then count else 0 end) as cat,
       sum(case when type = 'bird' then count else 0 end) as bird
from t
group by extract(hour from time);
</code>```

For this version, you need to explicitly list each value.  If you want a dynamic SQL, you need to construct the query as a string and then run it.

Body:
I have a table in this form:

TIME  TYPE COUNT
00:01 DOG  4
00:04 CAT  5
00:07 DOG  2
00:30 BIRD 1
01:04 DOG  2
01:30 BIRD 3
01:40 DOG  1
02:01 BIRD 4

I do a query like this that joins the sum of COUNT of each TYPE based on hour:

select HOUR(`TIME`), `TYPE`, sum(`COUNT`)
from `table`
where `TYPE` = 'DOG'
group by HOUR(`TIME`)
FULL JOIN
...(same query but... where `TYPE` = 'CAT')
ON hour...
FULL JOIN
...(same query again, but where `TYPE` = 'BIRD')
etc.

The purpose being to get a result like this:

HOUR DOG CAT BIRD
00   6   5   1
01   5   0   3
02   0   0   4

My question is: How can you do this without joins?
I want a query to work for any distinct TYPE values that happen to the be in the table and are not known upfront, so the table would grow in columns foreach distinct TYPE.

Is this something that could be done with BigQuery script?

Body:
Use sum(case . . ):

select extract(hour from time),
       sum(case when type = 'dog' then count else 0 end) as dog,
       sum(case when type = 'cat' then count else 0 end) as cat,
       sum(case when type = 'bird' then count else 0 end) as bird
from t
group by extract(hour from time);

For this version, you need to explicitly list each value.  If you want a dynamic SQL, you need to construct the query as a string and then run it.


问:
Redux dispatching actions in a specific order
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

```<code>export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}
</code>```

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

```<code>IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......
</code>```

Whereas the 2nd IS_DONE action is supposed to be carried out the last

答:
Take a look at redux-saga it will help you write a generator function that will help you to make those asynchronous flows easy to read, write, and test.

here is an example :

function* fetchUser(action) {
   try {
      //you can call your here your actions that you want to dispatch
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}
function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}
```

Body:
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......

Whereas the 2nd IS_DONE action is supposed to be carried out the last


问:
Understand how inheritance works in java
I'm learning oop, and I need to understand how inheritance actually works.

Let's say I have server call, with response that contain list of Movies, And another server call that I get the movie credits by movie id.

so my classes will look like this:

Class Movies :

```<code>public class Movies {
    private Movie[] movies;

   public Movies( Movie[] movies) {
        this.movies = movies;
    }
}
</code>```

Class Movie:

```<code>public class Movie extends Movies {
    private String title;
    private int id;
    private int voteCount;

    public Movie(String title, int id, int voteCount) {
        super();//the problem
        this.title = title;
        this.id = id;
        this.voteCount = voteCount;
    } }
</code>```

Class Credits:

```<code>public class Credits extends Movie {
     private int id; //movieId
       private Cast[] casts;

        public Credits(int id, Cast[] casts) {
            super();//the problem
            this.id = id;
            this.casts = casts;
        }
</code>```

As you can see Credits extends Movie that extends from Movies.

The problem is for example Credits inherit from Movie, because Credits is part of a Movie, but when I extends Movie inside Credits and need to pass arguments to super() inside my constrcutor I don't really know what to do.

How can I get access to this arguments? why do I need to pass voteCount for example in my Credits` class to super constructor?

答:
You're using inheritance the wrong way. You have to understand what inheritance means. In programming, inheritance means specialization. It is not some arbitrary way to be able to access other parts of the program.

Which is to say: a subclass is a specialized version of its superclass.

Especially the "is a" is important. When you write:

```<code>public class Movie extends Movies
</code>```

what you're really expressing is: "a Movie object is a (special kind of) Movies object", and

```<code>public class Credits extends Movie
</code>```

"a Credits object is a (special kind of) Movie object".

You can already see that this doesn't make sense - a Movie is not a collection of Movie objects, and Credits are not some kind of Movie.

Theoretical explanation: Liskov substitution principle.

Body:
I'm learning oop, and I need to understand how inheritance actually works.

Let's say I have server call, with response that contain list of Movies, And another server call that I get the movie credits by movie id.

so my classes will look like this:

Class Movies :

public class Movies {
    private Movie[] movies;

   public Movies( Movie[] movies) {
        this.movies = movies;
    }
}

Class Movie:

public class Movie extends Movies {
    private String title;
    private int id;
    private int voteCount;

    public Movie(String title, int id, int voteCount) {
        super();//the problem
        this.title = title;
        this.id = id;
        this.voteCount = voteCount;
    } }

Class Credits:

public class Credits extends Movie {
     private int id; //movieId
       private Cast[] casts;

        public Credits(int id, Cast[] casts) {
            super();//the problem
            this.id = id;
            this.casts = casts;
        }

As you can see Credits extends Movie that extends from Movies.

The problem is for example Credits inherit from Movie, because Credits is part of a Movie, but when I extends Movie inside Credits and need to pass arguments to super() inside my constrcutor I don't really know what to do.

How can I get access to this arguments? why do I need to pass voteCount for example in my Credits` class to super constructor?

Body:
You're using inheritance the wrong way. You have to understand what inheritance means. In programming, inheritance means specialization. It is not some arbitrary way to be able to access other parts of the program.

Which is to say: a subclass is a specialized version of its superclass.

Especially the "is a" is important. When you write:

public class Movie extends Movies

what you're really expressing is: "a Movie object is a (special kind of) Movies object", and

public class Credits extends Movie

"a Credits object is a (special kind of) Movie object".

You can already see that this doesn't make sense - a Movie is not a collection of Movie objects, and Credits are not some kind of Movie.

Theoretical explanation: Liskov substitution principle.


问:
Logging custom metrics using AWS Cloudwatch Agent and Python
We send up custom metrics to AWS using Python (see existing code below) and separately use the AWS CloudWatch Agent to send up metrics for our EC2 machine. However, we'd like to stop sending the custom metrics through a boto client and instead send them up using the AWS CloudWatch agent.

I've found details on how to send up custom metrics from StatsD and collectd, but it's unclear how to send up your own custom metrics. I'm guessing we'll have to export our metrics in a similar data format to one of these, but it's unclear how to do that. In summary, we need to:

Export the metric in Python to a log file in the right format

Update the AWS CloudWatch Agent to read from those log files and upload the metric

Does anyone have an example that covers that?

Existing Code

```<code>import boto3
cloudwatch = boto3.client(
    service_name="cloudwatch",
    region_name=env["AWS_DEPLOYED_REGION"],
    api_version="2010-08-01",
)
cloudwatch.put_metric_data(
    Namespace="myNameSpace",
    MetricData=[
        {
            "MetricName": "someName",
            "Dimensions": [
                {"Name": "Stage", "Value": "..."},
                {"Name": "Purpose", "Value": "..."},
            ],
            "Values": values,
            "StorageResolution": 60,
            "Unit": "someUnit",
        },
    ],
)
</code>```

答:
CloudWatch Agent supports StatsD or CollectD for collecting custom metrics. There is no support for using the AWS CloudWatch SDK and pointing it to the CW Agent.

To use StatsD or CollectD, you just follow the documentation for that specific tool. Then CloudWatch provide an adapter for both that interface to the CloudWatch Agent as I linked above. This is generally useful for people who already use StatsD or CollectD for custom and application metrics however its clearly painful in your case as you will have to onboard to either or in order to achieve you desired effect.

Body:
We send up custom metrics to AWS using Python (see existing code below) and separately use the AWS CloudWatch Agent to send up metrics for our EC2 machine. However, we'd like to stop sending the custom metrics through a boto client and instead send them up using the AWS CloudWatch agent.

I've found details on how to send up custom metrics from StatsD and collectd, but it's unclear how to send up your own custom metrics. I'm guessing we'll have to export our metrics in a similar data format to one of these, but it's unclear how to do that. In summary, we need to:

Export the metric in Python to a log file in the right format

Update the AWS CloudWatch Agent to read from those log files and upload the metric

Does anyone have an example that covers that?

Existing Code

import boto3
cloudwatch = boto3.client(
    service_name="cloudwatch",
    region_name=env["AWS_DEPLOYED_REGION"],
    api_version="2010-08-01",
)
cloudwatch.put_metric_data(
    Namespace="myNameSpace",
    MetricData=[
        {
            "MetricName": "someName",
            "Dimensions": [
                {"Name": "Stage", "Value": "..."},
                {"Name": "Purpose", "Value": "..."},
            ],
            "Values": values,
            "StorageResolution": 60,
            "Unit": "someUnit",
        },
    ],
)


问:
deploying a database and application with ClickOnce
I am new to ClickOnce. I created a WinForms application using C# and SQL Server Express. Currently my database is located in the mssql data folder. My connection string is located in an app.config file.

```<code><add name="default"  providerName="System.Data.SqlClient"
  connectionString="Server=localhost\SQLEXPRESS;Database=DBase;Trusted_Connection=True;" />
</code>```

How do I include my database file for it to deploy with the application?

To which folder will the database be deployed and will my connection string (above) be still working?

答:
You have a couple of options.  First, if this is a simple database I recommend that you forego using SQL Express and use SQL Server Compact.  A Compact SQL database is a file that can be bundled with your application installation.  Below is a link guiding you through the creation process of a SQL Compact database.

http://technet.microsoft.com/en-us/library/ms173009.aspx

The following link discusses setting up the necessary dependencies and prerequisites for SQL Server Compact. (Note, you will need to scroll to the section entitled Private File–Based Deployment.)

http://msdn.microsoft.com/en-us/library/aa983326(v=VS.100).aspx

If you have a complex database, or one that may grow larger than the 3GB limit that is set for SQL Compact databases, the only alternative is to set SQL Server Express as a prerequisite to your application and once it is installed create a routine within your application that checks to see if your database exists in SQL Express and, if not, launches a database creation and updating routine.

In my case, I have a heavy, data-driven application that was written before SQL Compact was out and had to function in environments that were often disconnected from our servers.  I had to use SQL Express so that we had to develop a mechanism to check for database updates when the server was available.  If there are updates, encrypted script files are downloaded and executed, sequentially against the child database.  After the database container is updated, a follow-up routine is called to check and synchronize the data.

--EDIT--

I wanted to quickly respond that, yes, you can bundle and attach a SQL Server database programatically to a local instance of SQL Server.  There are many barriers to this and if you have a user base that uses multiple versions of Windows, PC architectures and multiple different security scenarios, you will probably have trouble consistently attaching your database to the user's SQL Server.  Yes, it can be done.  However, I'd recommend avoiding that scenario at all possibly costs.

Body:
I am new to ClickOnce. I created a WinForms application using C# and SQL Server Express. Currently my database is located in the mssql data folder. My connection string is located in an app.config file.

<add name="default"  providerName="System.Data.SqlClient"
  connectionString="Server=localhost\SQLEXPRESS;Database=DBase;Trusted_Connection=True;" />

How do I include my database file for it to deploy with the application?

To which folder will the database be deployed and will my connection string (above) be still working?


问:
RecipientListRouter order of execution
I have successfully used RecipientListRouter in my program where based on the value I am sending it to multiple channels.

I would like to know -
1. Will this maintain the order of execution, say in the below case we receive an event that will be processed by both channelChkn and channelDeboard. So, first the event will be processed by channelChkn and then channelDeboard

Is it executed in different thread or in the same sender's thread

```<code>        RecipientListRouter router = new RecipientListRouter();
        router.setIgnoreSendFailures(true);
        router.setApplySequence(true);
        router.addRecipient("channelChkn","headers.get('eventSubType').contains('CHKN')");
        router.addRecipient("channelBkd","headers.get('eventSubType').contains('BKD')");
        router.addRecipient("channelBrd","headers.get('eventSubType').contains('BRD')");
        router.addRecipient("channelDeboard","headers.get('isDeBoarded') == true");
        router.setDefaultOutputChannelName(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME);
        LOGGER.info("********************* RecipientListRouter *********************"+router.getRecipients());
        return router;

</code>```

答: Yes, they will be executed in order, on the calling thread, as long as all of the recipient target channels are synchronous (no queue channels, no executor channels, no publish-subscribe channels configured with an executor).</p>

Title: RecipientListRouter order of execution

Body:
I have successfully used RecipientListRouter in my program where based on the value I am sending it to multiple channels.

I would like to know -
1. Will this maintain the order of execution, say in the below case we receive an event that will be processed by both channelChkn and channelDeboard. So, first the event will be processed by channelChkn and then channelDeboard

Is it executed in different thread or in the same sender's thread

        RecipientListRouter router = new RecipientListRouter();
        router.setIgnoreSendFailures(true);
        router.setApplySequence(true);
        router.addRecipient("channelChkn","headers.get('eventSubType').contains('CHKN')");
        router.addRecipient("channelBkd","headers.get('eventSubType').contains('BKD')");
        router.addRecipient("channelBrd","headers.get('eventSubType').contains('BRD')");
        router.addRecipient("channelDeboard","headers.get('isDeBoarded') == true");
        router.setDefaultOutputChannelName(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME);
        LOGGER.info("********************* RecipientListRouter *********************"+router.getRecipients());
        return router;


问:
VSCode: How to set env variable for VSC runtime?
I'm wondering if it's possible to set environment variables for the VSC Runtime as a whole without launching from terminal?

As a simple example, if I want to set all_proxy="" for every extension that runs with VSCode (i.e. the Docker extension), the only way I know right now to accomplish this is:

Go to my terminal (e.g. iTerm or Hyper)

Set the environment variable, i.e. export all_proxy=""

Run code from the terminal, e.g. code /path/to/project-workdir.

Is there a way to get VSCode to load with these environment variables configured, but done on a project-specific basis without needing me to first manually set them in the terminal?

Yes, I am aware that I can set up terminal-based automation to automatically set environment variables when in a directory, but I'm wondering if this is possible for VSCode without resorting to terminal trickery?

答:
did you mean this?

terminal.integrated.env.linux


问:
How to make an interdepending form input with props in vue?
i want to build a reusable form component like

<buy-form :price="price" />
(which would make the price pre-set and readonly. i want to be able to pass any of the three fields' value amount, price and total

inside the form, there are 3 vuetify v-text-field s.

BuyForm.vue

```<code><template>
<v-card>
    <v-card-text>
      <crypto-input :value.sync="form.amount" :disabled="!!amount" label="Amount"/>
      <crypto-input :value.sync="form.price" :disabled="!!price" label="Price"/>
      <crypto-input :value.sync="form.total" :disabled="!!total" label="Total"/>
    </v-card-text>
    <v-card-actions>
      <v-spacer />
      <v-btn depressed dark :color="style">BUY</v-btn>
    </v-card-actions>
</v-card>
</template>

<script>
  import styles from '@/styles/_export.scss'
  import CryptoInput from './CryptoInput'

  export default {
    name: 'BuyForm',
    components: { CryptoInput },
    props: {
      label: {
        type: String,
        default: null,
      },
      price: {
        default: null,
      },
      amount: {
        default: null,
      },
      total: {
        default: null,
      }
    },
    data: () => ({
      form: {
        amount: null,
        price: null,
        total: null,
      },
      styles,
    }),
    mounted() {
      Object.keys(this.form).forEach((e) => {
        this.form[e] = this.$props[e]
      })
    },
// ...
</code>```

so far, so good. changes in the inputs reflect in the data.form object.

now of course i want to calculate the remaining field (i.e. i pass price, so users can input amount or total, and the other one will be calculated.)
so i set up a watcher for each field, but here's the problem:
those watchers fire all the time, because if users input amount, total is changed automatically, so total watcher fires, which in turn calculated again and so on.
in most (?) cases, this is fine, because the value will be the same.
but i've encountered some edge cases, where it breaks (clearing one field for example).
i've tried to start fighting all these problems with a gigantic mess of watcher logic

```<code>watch: {
      'form.amount': function(newVal) {
        if (!this.$props.amount) { // not disabled
          let { amount, price, total } = this.form
          if (this.$props.price) this.form.total = amount * price
          if (this.$props.amount) this.form.price = total / amount
        }
      },
      'form.total': function(newVal) {
        if (!this.$props.total) { // not disabled
          let { amount, price, total } = this.form
          if (this.$props.price) this.form.amount = total / price
          if (this.$props.amount) this.form.price = total / amount
        }
</code>```

and that's just the very basic idea, nowhere near "working" or even "good".

looking forward, the case where none of the field is disabled gives me headaches, because three fields will depend on each other, and each one will fire its watcher on being changed, and i'll have to be prepared for all that....

of course this feels super wrong. so my question is: is there a best practice to do this? this can't be the only way to do it? am i missing something obvious? is there maybe even a library that can be bent to do this task? i didn't find any, and i don't want to spend hours on this abomination just to end up with a super brittle and bloated mess.

thanks for any help :)

答:
I don't know the details of how your version of value.sync works so im gonna pretend that you are using regular v-model (with value prop and input event to propagate changes).

To trigger recalculation only on user input, instead of using watchers you should trigger them in on-change listeners, for example.:

<input
  :value="form.amount"
  @input="onAmountChange"
/>
```

<pre class="lang-js prettyprint-override"><code>methods: {
  onAmountChange (value) {
    this.form.amount = value;
    ... // recalculation logic
  }
}
</code>```

Or even go one step further to make your template cleaner, and do it using computed properties

<input v-model="formAmount"/>
```

<pre class="lang-js prettyprint-override"><code>computed: {
  formAmount: {
    get () {
      return this.form.amount
    },
    set (value) {
      this.form.amount = value;
      ... // recalculation logic
    }
  }
}
</code>```

Body:
i want to build a reusable form component like

<buy-form :price="price" />
(which would make the price pre-set and readonly. i want to be able to pass any of the three fields' value amount, price and total

inside the form, there are 3 vuetify v-text-field s.

BuyForm.vue

<template>
<v-card>
    <v-card-text>
      <crypto-input :value.sync="form.amount" :disabled="!!amount" label="Amount"/>
      <crypto-input :value.sync="form.price" :disabled="!!price" label="Price"/>
      <crypto-input :value.sync="form.total" :disabled="!!total" label="Total"/>
    </v-card-text>
    <v-card-actions>
      <v-spacer />
      <v-btn depressed dark :color="style">BUY</v-btn>
    </v-card-actions>
</v-card>
</template>

Body:
I don't know the details of how your version of value.sync works so im gonna pretend that you are using regular v-model (with value prop and input event to propagate changes).

To trigger recalculation only on user input, instead of using watchers you should trigger them in on-change listeners, for example.:

<input
  :value="form.amount"
  @input="onAmountChange"
/>

methods: {
  onAmountChange (value) {
    this.form.amount = value;
    ... // recalculation logic
  }
}

Or even go one step further to make your template cleaner, and do it using computed properties

<input v-model="formAmount"/>

computed: {
  formAmount: {
    get () {
      return this.form.amount
    },
    set (value) {
      this.form.amount = value;
      ... // recalculation logic
    }
  }
}