问:
How to calculate the total sales and make the displayed totals dynamic?
I need to show the total sales of my data to both sellers and cities. However, the values shown in the totals must be dynamic.

P.S. My table allows the user to select the rows, this is because the values are rendered according to each selection made. (This dynamism between the tables is already working perfectly).

The initial state of the Total is rendered with the general sum of all sellers and cities, below I show the tables with their respective totals, however, as shown in the image, the values are static and not dynamic.

I need it to be diahanic because if I select for example the seller João Luis and Miguel, the value to be shown in the total must be the sum of these two sellers.

I asked a question a while ago about How to add row in datatable - DC.js, a friend (@Gordon) who is helping me a lot in doubts with DC.js and Crossfilter told me to use crossfilter.add(). Unfortunately I couldn't do it the way suggested, so I'm here again with practically the same question (sorry for my stupidity).

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}
var adjustX = 10,
  adjustY = 40;

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(window.innerWidth - adjustX)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Cities Table
  citiesTable
    .width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .controlsUseVisibility(true)
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive
  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(300);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(300);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}</code>```

  <link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">

  <title>Chart</title>

                Total Sales
                Current Year
                Last Year

                Total City
                Current Year
                Last Year

                Sales
                Current Year
                Last Year

                City
                Current Year
                Last Year

```

答:
Sorry, I completely misread your last question. It was nice of you to accept the answer, but you really didn't have to do that. :)

In order to add totals, you can add a tfoot section to your table

```<code>            <tfoot>
              <tr>
                <th>TOTAL</th>
                <th id="total-current-year"></th>
                <th id="total-last-year"></th>
              </tr>
            </tfoot>
</code>```

and drive it with a NumberDisplay widget.

```<code>  const totalCYDisplay = dc.numberDisplay('#total-current-year')
    .group(totalAll)
    .valueAccessor(d => d.totalAno)
</code>```

The default formatting is .2s but numberDisplay accepts any d3-format instance.

If you don't like the animation, you can set .transitionDuration(0)

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}
var adjustX = 10,
  adjustY = 40;

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);
  const totalAll = cf.groupAll()
    .reduce(reduceAdd, reduceRemove, reduceInitial);
debugger;

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(window.innerWidth - adjustX)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // vendedors totals
  const totalCYDisplay = dc.numberDisplay('#total-current-year')
    .group(totalAll)
    .valueAccessor(d => d.totalAno)
  const totalLYDisplay = dc.numberDisplay('#total-last-year')
    .group(totalAll)
    .valueAccessor(d => d.totalHomologo)

  // Cities Table
  citiesTable
    .width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .controlsUseVisibility(true)
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive
  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(300);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(300);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}</code>```

  <link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">

  <title>Chart</title>

                Total Sales
                Current Year
                Last Year

                Total City
                Current Year
                Last Year

                Sales
                Current Year
                Last Year

                TOTAL

                City
                Current Year
                Last Year

```

Body:
I need to show the total sales of my data to both sellers and cities. However, the values shown in the totals must be dynamic.

P.S. My table allows the user to select the rows, this is because the values are rendered according to each selection made. (This dynamism between the tables is already working perfectly).

The initial state of the Total is rendered with the general sum of all sellers and cities, below I show the tables with their respective totals, however, as shown in the image, the values are static and not dynamic.

I need it to be diahanic because if I select for example the seller João Luis and Miguel, the value to be shown in the total must be the sum of these two sellers.

I asked a question a while ago about How to add row in datatable - DC.js, a friend (@Gordon) who is helping me a lot in doubts with DC.js and Crossfilter told me to use crossfilter.add(). Unfortunately I couldn't do it the way suggested, so I'm here again with practically the same question (sorry for my stupidity).

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}
var adjustX = 10,
  adjustY = 40;

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(window.innerWidth - adjustX)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Cities Table
  citiesTable
    .width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .controlsUseVisibility(true)
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive
  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(300);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(300);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});

#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}

  <link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">

  <title>Chart</title>

                Total Sales
                Current Year
                Last Year

                Total City
                Current Year
                Last Year

                Sales
                Current Year
                Last Year

                City
                Current Year
                Last Year

Body:
Sorry, I completely misread your last question. It was nice of you to accept the answer, but you really didn't have to do that. :)

In order to add totals, you can add a tfoot section to your table

            <tfoot>
              <tr>
                <th>TOTAL</th>
                <th id="total-current-year"></th>
                <th id="total-last-year"></th>
              </tr>
            </tfoot>

and drive it with a NumberDisplay widget.

  const totalCYDisplay = dc.numberDisplay('#total-current-year')
    .group(totalAll)
    .valueAccessor(d => d.totalAno)

The default formatting is .2s but numberDisplay accepts any d3-format instance.

If you don't like the animation, you can set .transitionDuration(0)

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}
var adjustX = 10,
  adjustY = 40;

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);
  const totalAll = cf.groupAll()
    .reduce(reduceAdd, reduceRemove, reduceInitial);
debugger;

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(window.innerWidth - adjustX)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // vendedors totals
  const totalCYDisplay = dc.numberDisplay('#total-current-year')
    .group(totalAll)
    .valueAccessor(d => d.totalAno)
  const totalLYDisplay = dc.numberDisplay('#total-last-year')
    .group(totalAll)
    .valueAccessor(d => d.totalHomologo)

  // Cities Table
  citiesTable
    .width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .controlsUseVisibility(true)
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive
  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(300);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(300);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});

#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}

<head>
  <!-- favicon -->
  <link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">
  <!-- bootstrap.css -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <!-- bootstrap-theme.css -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
  <!-- dc.css -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">
  <!-- jquery.js -->
  <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
  <!-- bootstrap.js -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <!-- d3.v5.js -->
  <script src="https://d3js.org/d3.v5.js"></script>
  <!-- crossfilter.js -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.js"></script>
  <!-- dc.js -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dc/3.1.8/dc.js"></script>

  <title>Chart</title>
</head>

<body>
  <div id="composite"></div>
  <div class="container-fluid">
    <div class="row content">
      <div class="col-md-12">
        <div class="col-md-6">
          <table class="table" id="totaisVendedores">
            <thead>
              <tr>
                <th>Total Sales</th>
                <th>Current Year</th>
                <th>Last Year</th>
              </tr>
            </thead>
          </table>
        </div>
        <div class="col-md-6">
          <table class="table" id="totaisCities">
            <thead>
              <tr>
                <th>Total City</th>
                <th>Current Year</th>
                <th>Last Year</th>
              </tr>
            </thead>
          </table>
        </div>
        <div class="col-md-6">
          <table class="table" id="vendedores">
            <thead>
              <tr>
                <th>Sales</th>
                <th>Current Year</th>
                <th>Last Year</th>
              </tr>
            </thead>
            <tfoot>
              <tr>
                <th>TOTAL</th>
                <th id="total-current-year"></th>
                <th id="total-last-year"></th>
              </tr>
            </tfoot>
          </table>
        </div>
        <div class="col-md-6">
          <table class="table" id="cities">
            <thead>
              <tr>
                <th>City</th>
                <th>Current Year</th>
                <th>Last Year</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</body>


来源: stackexchange

问:
From array and array of objects extract property of objects as an array
I have an array:
var a = ['h1', 'h2', 'h3']

and array of objects:
var b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]

How do I find common part and extract id's only as a new array:

[3, 4, 5]

with pure javascript?

答:
If you need check names with the 'a' array.</p>

```<code>let a = ['h1', 'h2', 'h3']
let b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]
let result = []

b.forEach(item => {
  if (a.indexOf(item.name) >= 0) {
      result = [
          ...result,
          item.id
      ]
   }
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you need check names with the 'a' array.

let a = ['h1', 'h2', 'h3']
let b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]
let result = []

b.forEach(item => {
  if (a.indexOf(item.name) >= 0) {
      result = [
          ...result,
          item.id
      ]
   }
})


问:
Convert List<String[]> to Object[][] 2d array in Java
I am trying to transform a List of string arrays to 2D object arrays  Object[][].

Here is what I have so far. Is this correct?

```<code>private static Object[][] listToObject2dConvert(List<String[]> convertor) {
    Object[][] array = new Object[convertor.size()][];

    for (int i = 0; i < array.length; i++) {
        array[i] = new Object[convertor.get(i).length];
    }

    for (int i = 0; i < convertor.size(); i++){
        for (int j = 0; j < convertor.get(i).length; j++) {
            array[i][j] = convertor.get(i).length;
        }
    }
    return array;
}
</code>```

答:
The answer depends on whether you need to copy the contents out of the String[]s, or if it is acceptable to use those exact arrays.

If you can keep the exact arrays, it would be easiest to just do the following:

```<code>return convertor.toArray(Object[][]::new);
</code>```

However, if you need to copy the values out of the array, you could use streams to easily solve it:

```<code>return converter.stream()
                .map(s -> Arrays.copyOf(s, s.length, Object[].class))
                .toArray(Object[][]::new);
</code>```

Body:
I am trying to transform a List of string arrays to 2D object arrays  Object[][].

Here is what I have so far. Is this correct?

private static Object[][] listToObject2dConvert(List<String[]> convertor) {
    Object[][] array = new Object[convertor.size()][];

    for (int i = 0; i < array.length; i++) {
        array[i] = new Object[convertor.get(i).length];
    }

    for (int i = 0; i < convertor.size(); i++){
        for (int j = 0; j < convertor.get(i).length; j++) {
            array[i][j] = convertor.get(i).length;
        }
    }
    return array;
}

Body:
The answer depends on whether you need to copy the contents out of the String[]s, or if it is acceptable to use those exact arrays.

If you can keep the exact arrays, it would be easiest to just do the following:

return convertor.toArray(Object[][]::new);

However, if you need to copy the values out of the array, you could use streams to easily solve it:

return converter.stream()
                .map(s -> Arrays.copyOf(s, s.length, Object[].class))
                .toArray(Object[][]::new);


问:
Interpolating a variable into an XML node search
I am trying to insert a variable into an XML node query but I am ignorant of the syntax.

Here is what I tried:

```<code>declare @LineNumber int

select @LineNumber = 4

select T.value('(N4/F116)[1]','varchar(30)')
from @ClaimXML.nodes('/Envelope/Interchange/Group/Message/Loop2000/Loop2300/Loop2400[LX/F554=@LineNumber]/Loop2420') Trans(T)
where T.exist('NM1/F98_1[text()="PW"]') = 1

</code>```

The above query does not work but if I manually insert '4' instead of @LineNumber it works. How do I properly insert the @LineNumber scalar?

答:
Just to add to the solution in a comment here's an example to test this:

```<code>DECLARE @xml XML=
'<root>
  <a id="1" value="a1"/>
  <a id="2" value="a2"/>
  <a id="3" value="a3"/>
  <a id="4" value="a4"/>
  <a id="5" value="a5"/>
  <a id="6" value="a6"/>
</root>';
</code>```

--We can use sql:variable() to get an external variable's value into a XPath:

```<code>DECLARE @SomeVariable INT=3;

SELECT @xml.value('(/root/a[@id=sql:variable("@SomeVariable")]/@value)[1]','char(2)')
--result: "a3"
</code>```

--And we can use sql:column() to use a column's value (of the current row) to do the same:

```<code>DECLARE @tbl TABLE(SomeColumn INT);
INSERT INTO @tbl VALUES(1),(3),(6);

SELECT t.SomeColumn
      ,@xml.value('(/root/a[@id=sql:column("SomeColumn")]/@value)[1]','char(2)')
FROM @tbl t;
</code>```

The result

```<code>1   a1
3   a3
6   a6
</code>```

Body:
I am trying to insert a variable into an XML node query but I am ignorant of the syntax.

Here is what I tried:

declare @LineNumber int

select @LineNumber = 4

select T.value('(N4/F116)[1]','varchar(30)')
from @ClaimXML.nodes('/Envelope/Interchange/Group/Message/Loop2000/Loop2300/Loop2400[LX/F554=@LineNumber]/Loop2420') Trans(T)
where T.exist('NM1/F98_1[text()="PW"]') = 1

The above query does not work but if I manually insert '4' instead of @LineNumber it works. How do I properly insert the @LineNumber scalar?

Body:
Just to add to the solution in a comment here's an example to test this:

DECLARE @xml XML=
'<root>
  <a id="1" value="a1"/>
  <a id="2" value="a2"/>
  <a id="3" value="a3"/>
  <a id="4" value="a4"/>
  <a id="5" value="a5"/>
  <a id="6" value="a6"/>
</root>';

--We can use sql:variable() to get an external variable's value into a XPath:

DECLARE @SomeVariable INT=3;

SELECT @xml.value('(/root/a[@id=sql:variable("@SomeVariable")]/@value)[1]','char(2)')
--result: "a3"

--And we can use sql:column() to use a column's value (of the current row) to do the same:

DECLARE @tbl TABLE(SomeColumn INT);
INSERT INTO @tbl VALUES(1),(3),(6);

SELECT t.SomeColumn
      ,@xml.value('(/root/a[@id=sql:column("SomeColumn")]/@value)[1]','char(2)')
FROM @tbl t;

The result

1   a1
3   a3
6   a6


问:
How to query- Where In Array Key Value Laravel with Mongodb
This is my database Structure

```<code>{
    "_id":"5e4d4d6fc01c0000cc0009bd",
    "UID":"5e30376327050000b3006cde",
    "delevery_charge":25,
    "order_item":[
        {
            "id":"5e2f4a636c630000f20053bc",
            "Name":"XXXXX",
            "info":"5e26098d94500000870044ac",
        }
    ],
    "subtotal":110,
    "status":1,
    "updated_at":"2020-02-19T14:59:59.000Z",
    "created_at":"2020-02-19T14:59:59.000Z"
}
</code>```

I want to Find data where order_item=>info ID .. Im using Mongo db

```<code>$db = Table::where(''Dont Know what to do)->first();
</code>```

How can I do that ???

答:
I am not sure about mongoDB,but you can use json where clauses.

Laravel also supports querying JSON column types on databases that provide support for JSON column types. Currently, this includes MySQL 5.7 and PostgreSQL. To query a JSON column, use the -> operator:

```<code>$result = Table::where('order_item->info', 'SOME VALUE')->get();
</code>```

Body:
This is my database Structure

{
    "_id":"5e4d4d6fc01c0000cc0009bd",
    "UID":"5e30376327050000b3006cde",
    "delevery_charge":25,
    "order_item":[
        {
            "id":"5e2f4a636c630000f20053bc",
            "Name":"XXXXX",
            "info":"5e26098d94500000870044ac",
        }
    ],
    "subtotal":110,
    "status":1,
    "updated_at":"2020-02-19T14:59:59.000Z",
    "created_at":"2020-02-19T14:59:59.000Z"
}

I want to Find data where order_item=>info ID .. Im using Mongo db

$db = Table::where(''Dont Know what to do)->first();

How can I do that ???

Body:
I am not sure about mongoDB,but you can use json where clauses.

Laravel also supports querying JSON column types on databases that provide support for JSON column types. Currently, this includes MySQL 5.7 and PostgreSQL. To query a JSON column, use the -> operator:

$result = Table::where('order_item->info', 'SOME VALUE')->get();


问:
Excel OLE automation in a Windows service
I have a Windows service filling cells in an Excel Workbook via OLE Automation.

The save process is not working, the file is never saved.  But when done in a GUI app, the save process works.

The service user is an administrator account.  I suspect the interaction with the Desktop.

Any idea?

答:
Don't do this.  Find another solution.  Microsoft does not support or recommend OLE automation of Office software from anywhere but a workstation desktop session.  I can't paraphrase any better than what they say directly, so here's the advice (link above goes into more detail) :

All current versions of Microsoft Office were designed, tested, and configured to run as end-user products on a client workstation. They assume an interactive desktop and user profile. They do not provide the level of reentrancy or security that is necessary to meet the needs of server-side components that are designed to run unattended.

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.

If you need your service to store data, a database is probably a good choice.  Any users that require the data in an excel spreadsheet could populate their documents from the database.  You could even set up template documents to do this automatically.


问:
Is there a way to find/read the Sender Email Address using R, RDCOMClient
```<code>library("tm")
library("NLP")
library("dplyr")
library("readtext")
library("readxl")
library("foreach")
library("devtools")
library("RDCOMClient")
library("rlist")

WDF = vector()
OutApp <- COMCreate("Outlook.Application")
outlookNameSpace = OutApp$GetNameSpace("MAPI")

folderName = "Folder Name"
fld <- outlookNameSpace$GetDefaultFolder(6)
fld = fld$folders(folderName)
Cnt = fld$Items()$Count()
emails <- fld$items
df = data.frame(sno = 1:Cnt,Text = "",stringsAsFactors=FALSE)

for(i in 1:10){
  d = as.data.frame(emails(i)$Body(), stringsAsFactors=FALSE)
  df$Text[i] = d[1]
  df$Sender[i] = emails(i)[['SenderName']]
  df$To[i] = emails(i)[['To']]
  df$sub[i] = emails(i)[['subject']]
}
emails(2)[['SenderName']]
</code>```

I'm trying to get the senders Email Address by using following code :

```<code>emails(2)[['SenderEmailAddress']]
</code>```

But it ends up giving like this :

```<code>[1] "/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=E4CD239AB9F44AC4AC0A4015B6F4805A-RATINGSDIRE"
</code>```

答:
The problem is that exchange stores the sender address as either the normal smtp version of the address for external users, but for Exchange users it uses the MS Exchange address. To get the normal smtp address, you have to look up the exchange user on and get their normal smtp email address.

You may want to look at the extrospectr package on github. I haven't used it but it looks like it would give you a clean inbox like you're looking for.

If you look at the .lookup_exchange_sender function in the file read_inbox.R it shows how they handled looking up the address. First you have to look at what type of user the Sender is (which you can do by retrieving the Sender property of the MailItem, and then the AddressEntryUserType property, which has this enumeration). This ends up like emails(2)$Sender()$AddressEntryUserType().

Then then if it's an Exchange user, you would need to get the Sender property of the MailItem (which is an AddressEntry) and then use the GetExchangeUser method on the AddressEntry to return an ExchangeUser object. Once you have that you just need to access the PrimarrySMTPAddress property of the ExchangeUser.
When you put it all together, it looks like this: emails(2)$Sender()$GetExchangeUser()$PrimarySMTPAddress().

Link to extrospectr on github:
https://github.com/aecoleman/extrospectr

This explains the Outlook methodology for what's stored in the sender email property:
SenderEmailAddress property does not contain a standard email address for internal contacts

Body:
library("tm")
library("NLP")
library("dplyr")
library("readtext")
library("readxl")
library("foreach")
library("devtools")
library("RDCOMClient")
library("rlist")

WDF = vector()
OutApp <- COMCreate("Outlook.Application")
outlookNameSpace = OutApp$GetNameSpace("MAPI")

folderName = "Folder Name"
fld <- outlookNameSpace$GetDefaultFolder(6)
fld = fld$folders(folderName)
Cnt = fld$Items()$Count()
emails <- fld$items
df = data.frame(sno = 1:Cnt,Text = "",stringsAsFactors=FALSE)

for(i in 1:10){
  d = as.data.frame(emails(i)$Body(), stringsAsFactors=FALSE)
  df$Text[i] = d[1]
  df$Sender[i] = emails(i)[['SenderName']]
  df$To[i] = emails(i)[['To']]
  df$sub[i] = emails(i)[['subject']]
}
emails(2)[['SenderName']]

I'm trying to get the senders Email Address by using following code :

emails(2)[['SenderEmailAddress']]

But it ends up giving like this :

[1] "/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=E4CD239AB9F44AC4AC0A4015B6F4805A-RATINGSDIRE"


问:
Analyze and update dynamic table macro VBA
I'm trying to make a macro to analyze and update the dynamic table located in the second sheet of the workbook ("TD"), i made a macro but it displays the error '1004' ERROR DEFINED BY THE APPLICATION OR OBJECT, hope you can help me.</p>

```<code>Dim wsTD As Worksheet
Dim wbWs As Workbook

Set wbWs = ActiveWorkbook
Set wsTD = wbWs.Worksheets("TD")
wbWs.PivotTables(“TablaDinámica1”).PivotCache.Refresh
wbWs.PivotTables(“TablaDinámica2”).PivotCache.Refresh
</code>```

答:
You are trying to find your pivot table in a workbook wbWs not in a worksheet wsTD. Change it to:

```<code>wsTD.PivotTables("TablaDinámica1").PivotCache.Refresh
wsTD.PivotTables("TablaDinámica2").PivotCache.Refresh
</code>```

Body:
I'm trying to make a macro to analyze and update the dynamic table located in the second sheet of the workbook ("TD"), i made a macro but it displays the error '1004' ERROR DEFINED BY THE APPLICATION OR OBJECT, hope you can help me.

Dim wsTD As Worksheet
Dim wbWs As Workbook

Set wbWs = ActiveWorkbook
Set wsTD = wbWs.Worksheets("TD")
wbWs.PivotTables(“TablaDinámica1”).PivotCache.Refresh
wbWs.PivotTables(“TablaDinámica2”).PivotCache.Refresh

Body:
You are trying to find your pivot table in a workbook wbWs not in a worksheet wsTD. Change it to:

wsTD.PivotTables("TablaDinámica1").PivotCache.Refresh
wsTD.PivotTables("TablaDinámica2").PivotCache.Refresh


问:
Basic Select with Laravel Eloquent do not work
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

```<code>  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;
</code>```

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

答:
Everyone else is right that the first query returns a collection. But you're doing an extra query that is not needed here. This can be simplified to query the users table only once.</p>

```<code>$name = "Jason";
$User = User::where('name', '=', $name)->first();
//$User= User::find($UserID); remove this as it is not needed.

if(!$User) {
    return "User not found";
}

$demands = Demand::where('user_id', '=', $User->id)->get();
echo $demands;
</code>```

Body:
I have 2 table: User & Demands. Inside the table Demands, I have the user_id as a foreign key.
The User log in with a name (which I have throught the Session).
What I want to do is:
  - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code.
  - Search his ID thanks to his name.
  - Search all of his demands with his id.

  $name = "Jason";
  $UserID = User::select('id')->where('name', '=', $name)->get();
  $User= User::find($UserID);
  $demands = Demand::where('user_id', '=', $UserID)->get();
  echo $demands;

My array is then empty. But inside my database, I do have 3 demands of this user_id...

Do you guys have any clue please ?

Cordially.

Body:
Everyone else is right that the first query returns a collection. But you're doing an extra query that is not needed here. This can be simplified to query the users table only once.

$name = "Jason";
$User = User::where('name', '=', $name)->first();
//$User= User::find($UserID); remove this as it is not needed.

if(!$User) {
    return "User not found";
}

$demands = Demand::where('user_id', '=', $User->id)->get();
echo $demands;


问:
Python SyntaxError with format string and object literal
This code produces SyntaxError:

```<code>f'something_{{ 'BEAM': '.', 'GRIN': '.', 'GRIN31': '/' }[coin]}'
</code>```

Is it possible to use object literals this way for an inline "select"?

答:
Yes, it's possible, here a example:

```<code>$ test1 = 'abc'
$ test2 = '123'
$ test3= 'foo'
$ coin = 'foo'
f"something_{ { test1: '.', test2: '.', test3: '/' }[coin]}"
>>> something_/
</code>```

on f-string syntax, the brackets is represents by double {{ or }} => { or }, that's why first 2 { has an empty space between them.

Body:
This code produces SyntaxError:

f'something_{{ 'BEAM': '.', 'GRIN': '.', 'GRIN31': '/' }[coin]}'

Is it possible to use object literals this way for an inline "select"?

Body:
Yes, it's possible, here a example:

$ test1 = 'abc'
$ test2 = '123'
$ test3= 'foo'
$ coin = 'foo'
f"something_{ { test1: '.', test2: '.', test3: '/' }[coin]}"
>>> something_/

on f-string syntax, the brackets is represents by double {{ or }} => { or }, that's why first 2 { has an empty space between them.


问:
How to use draggable sections like on iGoogle?
When viewing iGoogle, each section is able to be drag-and-dropped to anywhere else on the page and then the state of the page is saved. I am curious on how this is done as I would like to provide this functionality as part of a proof of concept?

UPDATE

How do you make it so that the layout you changed to is saved for the next load? I am going to guess this is some sort of cookie?

答:
Any up-to-date client side framework will give that kind of functionality.

jQuery

YUI

GWT

Prototype

Just to name a few...

Regarding the "saving" (persistency, if you will) of the data, this depends on the back-end of your site, but this is usually done via an asynchronous call to the server which saves the state to a DB (usually).

OwnerDisplayName: Ascalonian

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Yuval A

ContentLicense: CC BY-SA 2.5


问:
Removing from array during enumeration in Swift?
I want to enumerate through an array in Swift, and remove certain items. I'm wondering if this is safe to do, and if not, how I'm supposed to achieve this.

Currently, I'd be doing this:

```<code>for (index, aString: String) in enumerate(array) {
    //Some of the strings...
    array.removeAtIndex(index)
}
</code>```

答:
Just to add, if you have multiple arrays and each element in index N of array A is related to the index N of array B, then you can still use the method reversing the enumerated array (like the past answers). But remember that when accessing and deleting the elements of the other arrays, no need to reverse them.</p>

```<code>Like so, (one can copy and paste this on Playground)

var a = ["a", "b", "c", "d"]
var b = [1, 2, 3, 4]
var c = ["!", "@", "#", "$"]

// remove c, 3, #

for (index, ch) in a.enumerated().reversed() {
    print("CH: \(ch). INDEX: \(index) | b: \(b[index]) | c: \(c[index])")
    if ch == "c" {
        a.remove(at: index)
        b.remove(at: index)
        c.remove(at: index)
    }
}

print("-----")
print(a) // ["a", "b", "d"]
print(b) // [1, 2, 4]
print(c) // ["!", "@", "$"]
</code>```

Body:
I want to enumerate through an array in Swift, and remove certain items. I'm wondering if this is safe to do, and if not, how I'm supposed to achieve this.

Currently, I'd be doing this:

for (index, aString: String) in enumerate(array) {
    //Some of the strings...
    array.removeAtIndex(index)
}

Body:
Just to add, if you have multiple arrays and each element in index N of array A is related to the index N of array B, then you can still use the method reversing the enumerated array (like the past answers). But remember that when accessing and deleting the elements of the other arrays, no need to reverse them.

Like so, (one can copy and paste this on Playground)

var a = ["a", "b", "c", "d"]
var b = [1, 2, 3, 4]
var c = ["!", "@", "#", "$"]

// remove c, 3, #

for (index, ch) in a.enumerated().reversed() {
    print("CH: \(ch). INDEX: \(index) | b: \(b[index]) | c: \(c[index])")
    if ch == "c" {
        a.remove(at: index)
        b.remove(at: index)
        c.remove(at: index)
    }
}

print("-----")
print(a) // ["a", "b", "d"]
print(b) // [1, 2, 4]
print(c) // ["!", "@", "$"]


答:
There are two problems.

First, you can't use single quotes in the dict display, because the string parser doesn't consider the braces to "separate" them; the first ' closes the string literal. (Or rather, you need to use different quotes or escape the quotes to avoid unintentionally closing the f-string.)

Second, {{ is a single literal { in an f-string; you need to separate them with a space.

```<code>>>> coin = "GRIN"
>>> f'something_{ { "BEAM": ".", "GRIN": ".", "GRIN31": "/" }[coin]}'
'something_.'
</code>```

Title: Python SyntaxError with format string and object literal

Body:
There are two problems.

First, you can't use single quotes in the dict display, because the string parser doesn't consider the braces to "separate" them; the first ' closes the string literal. (Or rather, you need to use different quotes or escape the quotes to avoid unintentionally closing the f-string.)

Second, {{ is a single literal { in an f-string; you need to separate them with a space.

>>> coin = "GRIN"
>>> f'something_{ { "BEAM": ".", "GRIN": ".", "GRIN31": "/" }[coin]}'
'something_.'


问:
How to create array of given length and same number?
When using SUMSERIES I need to specify "the array or range containing the coefficients of the power series" but I want to make it so the number of elements is dynamic while the element itself (1) remains the same.
Example:

SUM FROM 0 TO N of x^1,5

```<code>(cell) Length of series N : 7  -- > SUMSERIES(1,5;0;1;{1,1,1,1,1,1,1})
</code>```

But I should be able to change the seven for a 3 and get --> SUMSERIES(1,5;0;1;{1,1,1})

In Java for example you'd declare and instantiate the array --> int[] arr = new int[N];

And then fill in a loop --> for(int i = 0; i <arr.length; i++) {arr[i] = 1,5}

Thanks in advance and sorry if the explanation isn´t clear, it's my first time around hehe

答:
try:

```<code>=ARRAYFORMULA(SIGN(TRANSPOSE(ROW(INDIRECT("A1:A"&A1)))))
</code>```

and then:

```<code>=INDEX(SUMSERIES(1,5; 0; 1; SIGN(TRANSPOSE(ROW(INDIRECT("A1:A"&A1))))))
</code>```

Body:
When using SUMSERIES I need to specify "the array or range containing the coefficients of the power series" but I want to make it so the number of elements is dynamic while the element itself (1) remains the same.
Example:

SUM FROM 0 TO N of x^1,5

(cell) Length of series N : 7  -- > SUMSERIES(1,5;0;1;{1,1,1,1,1,1,1})

But I should be able to change the seven for a 3 and get --> SUMSERIES(1,5;0;1;{1,1,1})

In Java for example you'd declare and instantiate the array --> int[] arr = new int[N];

And then fill in a loop --> for(int i = 0; i <arr.length; i++) {arr[i] = 1,5}

Thanks in advance and sorry if the explanation isn´t clear, it's my first time around hehe

Body:
try:

=ARRAYFORMULA(SIGN(TRANSPOSE(ROW(INDIRECT("A1:A"&A1)))))

and then:

=INDEX(SUMSERIES(1,5; 0; 1; SIGN(TRANSPOSE(ROW(INDIRECT("A1:A"&A1))))))


问:
Update parent table column only if all the values of child table rows are a specific value
I have 2 tables, orders and order_items. Each order can have multiple order_items.

An order has an id and orderStatus:

An order_item as id, orderId and orderItemStatus:

I want to update the status of order's from OPEN to FULFILLED if all an order's order_items have status of ISSUED. If at least one order_item is not ISSUED, the order status should remain as OPEN. How can I do this?

答:
You can use a NOT EXISTS subquery as condition.

```<code>update order o
set o.orderStatus = 'FULFILLED'
where o.orderStatus = 'OPEN'
  and not exists (
    select *
    from order_item i
    where i.orderId = o.id
      and i.orderItemStatus <> 'ISSUED'
  )
</code>```

This will only update orders which have status 'OPEN' and have no items with status 'ISSUED'.

Body:
You can use a NOT EXISTS subquery as condition.

update order o
set o.orderStatus = 'FULFILLED'
where o.orderStatus = 'OPEN'
  and not exists (
    select *
    from order_item i
    where i.orderId = o.id
      and i.orderItemStatus <> 'ISSUED'
  )

This will only update orders which have status 'OPEN' and have no items with status 'ISSUED'.


问:
JavaScript Debugging
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You

答: I like Firebug, plugin for Firefox.</p>

Title: JavaScript Debugging

Body: I like Firebug, plugin for Firefox.


答:
You could check for orders_item with status ISSUED if this is the unique status </p>

```<code>    update orders o
    inner join (
      select orderID, count( dictinct orderItemStatus)
      from order_item
      group by orderID
      having count( dictinct orderItemStatus) = 1
    )  t on t.orderID = o.id
    inner join order_item i on i.orderID  = o.id
      AND orderItemStatus  = 'ISSUED'
</code>```

Title: Update parent table column only if all the values of child table rows are a specific value

Body:
I have 2 tables, orders and order_items. Each order can have multiple order_items.

An order has an id and orderStatus:

An order_item as id, orderId and orderItemStatus:

I want to update the status of order's from OPEN to FULFILLED if all an order's order_items have status of ISSUED. If at least one order_item is not ISSUED, the order status should remain as OPEN. How can I do this?

Body:
You could check for orders_item with status ISSUED if this is the unique status

    update orders o
    inner join (
      select orderID, count( dictinct orderItemStatus)
      from order_item
      group by orderID
      having count( dictinct orderItemStatus) = 1
    )  t on t.orderID = o.id
    inner join order_item i on i.orderID  = o.id
      AND orderItemStatus  = 'ISSUED'


问:
How to fix kubectl Error from server (NotFound): the server could not find the requested resource
I was install kubectl by the official instruction, but when i've try kubectl apply -f i've get " Error from server (NotFound): the server could not find the requested resource " error.

The Internet says that it's because the Client and Server Version of kubectl is different.

I'll check the verision of kubectl:

Client Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.2", GitCommit:"59603c6e503c87169aea6106f57b9f242f64df89", GitTreeState:"clean", BuildDate:"2020-01-18T23:30:10Z", GoVersion:"go1.13.5", Compiler:"gc", Platform:"linux/amd64"}

Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"dirty", BuildDate:"2017-06-22T04:31:09Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}

If it is official install, why version so different? And is it really problem of this error?

I also have docker, docker-compose and minikube.

OS Linux Mint

答:
Downgrade your kubectl version. And please mention the official doc you followed to install initially.

sudo apt-get install -qy kubectl=1.16.3-00

On second note I think David is right. Maybe you have mismatch in api in your manifest and the k8s version.


问:
How to extract JSON data with PHP
I'm trying to extract the value from the event key (delivered) using PHP. I thought the follow would work below but I'm getting no results. I know this is probably a simple thing to do and probably looking too far into it.

How I am trying to extract the value

```<code>$status = json_decode($status, true);
echo $status[1]['event'];
</code>```

Here is my JSON file

```<code>{
   "events":[
      {
         "email":"email@gmail.com",
         "date":"2020-02-17T22:16:58.000+01:00",
         "subject":"PHPMailer SMTP test",
         "messageId":"<hdskjfjsdhfsjdkfdksh>",
         "event":"delivered",
         "tag":"",
         "from":"test@gmail.com"
      }
   ]
}
</code>```

Any help would be appreciated :)

答:
The first issue is that your JSON file is wrong formatted. It should be:

```<code>{
 "events": [
  {
   "email": "email@gmail.com",
   "date": "2020-02-17T22:16:58.000+01:00",
   "subject": "PHPMailer SMTP test",
   "messageId": "74483437597589347843758934759",
   "event": "delivered",
   "tag": "",
   "from": "test@gmail.com"
  }
 ]
}
</code>```

Second, $status[1]['event'] is also wrong. You should use $status['events'].

Title: How to extract JSON data with PHP

Body:
I'm trying to extract the value from the event key (delivered) using PHP. I thought the follow would work below but I'm getting no results. I know this is probably a simple thing to do and probably looking too far into it.

How I am trying to extract the value

$status = json_decode($status, true);
echo $status[1]['event'];

Here is my JSON file

{
   "events":[
      {
         "email":"email@gmail.com",
         "date":"2020-02-17T22:16:58.000+01:00",
         "subject":"PHPMailer SMTP test",
         "messageId":"<hdskjfjsdhfsjdkfdksh>",
         "event":"delivered",
         "tag":"",
         "from":"test@gmail.com"
      }
   ]
}

Any help would be appreciated :)

Body:
The first issue is that your JSON file is wrong formatted. It should be:

{
 "events": [
  {
   "email": "email@gmail.com",
   "date": "2020-02-17T22:16:58.000+01:00",
   "subject": "PHPMailer SMTP test",
   "messageId": "74483437597589347843758934759",
   "event": "delivered",
   "tag": "",
   "from": "test@gmail.com"
  }
 ]
}

Second, $status[1]['event'] is also wrong. You should use $status['events'].


问:
Transforming a data frame with one column to many columns in R
Currently my data frame consists of 1 column with 2326 rows. I want to transform my data frame to consist of 11 rows. More specifically, my current data frame look like

```<code>John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2
</code>```

etc.

I want my data frame to look like:

```<code>John Doe        7  45  42  978  3  6  8  9  0  11
Sally Jenkins   2
</code>```

Each person is a row and then their statistics are each a separate column in the row. Some people are missing a statistic so I can not separate based on the number of rows between each person's name.

I have tried using t() as well as reshape(transform()). Do you have any suggestions on where to go next?

答:
1) One option is to create a grouping variable based on the presence of alphabets, summarise by creating a list output and use unnest_wider to change that list to a set of new columns

```<code>library(dplyr)
library(tidyr)
library(stringr)
df1  %>%
      group_by(grp = cumsum(str_detect(col1, "[A-Za-z]"))) %>%
      group_by(coln = first(col1), .add = TRUE) %>%
      slice(-1) %>%
      summarise(out = list(as.list(as.numeric(col1))))  %>%
      unnest_wider(c(out)) %>%
      ungroup %>%
      select(-grp) %>%
      rename_at(-1, ~ str_c('new_col', seq_along(.)))
# A tibble: 2 x 11
#  coln          new_col1 new_col2 new_col3 new_col4 new_col5 new_col6 new_col7 new_col8 new_col9 new_col10
#  <chr>            <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>     <dbl>
#1 John Doe             7       45       42      978        3        6        8        9        0        11
#2 Sally Jenkins        2       NA       NA       NA       NA       NA       NA       NA       NA        NA
</code>```

2) Or using base  R (No packages used)

```<code>grp <- with(df1, ave(col1, cumsum(grepl('[A-Za-z]', col1)),
     FUN = function(x) x[1]))
aggregate(values ~ ind, stack(split(as.numeric(df1$col1[duplicated(grp)]),
           grp[duplicated(grp)])),  FUN = I)
#            ind                            values
#1      John Doe 7, 45, 42, 978, 3, 6, 8, 9, 0, 11
#2 Sally Jenkins                                 2
</code>```

data

```<code>df1 <- structure(list(col1 = c("John Doe", "7", "45", "42", "978", "3",
"6", "8", "9", "0", "11", "Sally Jenkins", "2")), class = "data.frame",
row.names = c(NA,
-13L))
</code>```

Body:
Currently my data frame consists of 1 column with 2326 rows. I want to transform my data frame to consist of 11 rows. More specifically, my current data frame look like

John Doe
7
45
42
978
3
6
8
9
0
11
Sally Jenkins
2

etc.

I want my data frame to look like:

John Doe        7  45  42  978  3  6  8  9  0  11
Sally Jenkins   2

Each person is a row and then their statistics are each a separate column in the row. Some people are missing a statistic so I can not separate based on the number of rows between each person's name.

I have tried using t() as well as reshape(transform()). Do you have any suggestions on where to go next?

Body:
1) One option is to create a grouping variable based on the presence of alphabets, summarise by creating a list output and use unnest_wider to change that list to a set of new columns

library(dplyr)
library(tidyr)
library(stringr)
df1  %>%
      group_by(grp = cumsum(str_detect(col1, "[A-Za-z]"))) %>%
      group_by(coln = first(col1), .add = TRUE) %>%
      slice(-1) %>%
      summarise(out = list(as.list(as.numeric(col1))))  %>%
      unnest_wider(c(out)) %>%
      ungroup %>%
      select(-grp) %>%
      rename_at(-1, ~ str_c('new_col', seq_along(.)))
# A tibble: 2 x 11
#  coln          new_col1 new_col2 new_col3 new_col4 new_col5 new_col6 new_col7 new_col8 new_col9 new_col10
#  <chr>            <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>     <dbl>
#1 John Doe             7       45       42      978        3        6        8        9        0        11
#2 Sally Jenkins        2       NA       NA       NA       NA       NA       NA       NA       NA        NA

2) Or using base  R (No packages used)

grp <- with(df1, ave(col1, cumsum(grepl('[A-Za-z]', col1)),
     FUN = function(x) x[1]))
aggregate(values ~ ind, stack(split(as.numeric(df1$col1[duplicated(grp)]),
           grp[duplicated(grp)])),  FUN = I)
#            ind                            values
#1      John Doe 7, 45, 42, 978, 3, 6, 8, 9, 0, 11
#2 Sally Jenkins                                 2

data

df1 <- structure(list(col1 = c("John Doe", "7", "45", "42", "978", "3",
"6", "8", "9", "0", "11", "Sally Jenkins", "2")), class = "data.frame",
row.names = c(NA,
-13L))


问:
Unity AddExplosionForce() does not apply the explosion
When the 'C' key is pressed a new cube is created with a rigid body and added as a child object of 'GameObject'. However, when 'F' is pressed I add explosion to all the child objects but nothing happens. I tried AddForce() and that works fine, it is just AddExplosionForce(). I have just started working with unity so it might be a silly mistake.

Here is my script Update method:

```<code>void Update()
{
    if (Input.GetKeyDown(KeyCode.C) || Input.GetMouseButtonDown(0))
    {
        Vector3 pos = transform.position;
        cube = Instantiate(cubePrefab, pos, Quaternion.identity);
        GameObject ParentCube = GameObject.Find("GameObject");
        cube.transform.parent = ParentCube.transform;
    }
    if (Input.GetKeyDown(KeyCode.F))
    {
        foreach (Transform currentCube in transform)
        {
            Vector3 pointOfExplosion = new Vector3(transform.position.x - 1, transform.position.y - 1, transform.position.z - 1);
            currentCube.GetComponent<Rigidbody>().AddExplosionForce(20, pointOfExplosion, 10, 1);
        }
    }
}
</code>```

答:
Is your object to which explosion is added within your 10 units? Also have you tried the overloaded version of AddExplosionForce with the last argument "mode" as an "Impulse"?

From Unity documentation:

Add an instant force impulse to the rigidbody, using its mass.

Apply the impulse force instantly with a single function call. This mode depends on the mass of rigidbody so more force must be applied to push or twist higher-mass objects the same amount as lower-mass objects. This mode is useful for applying forces that happen instantly, such as forces from explosions or collisions. In this mode, the unit of the force parameter is applied to the rigidbody as mass*distance/time

Body:
When the 'C' key is pressed a new cube is created with a rigid body and added as a child object of 'GameObject'. However, when 'F' is pressed I add explosion to all the child objects but nothing happens. I tried AddForce() and that works fine, it is just AddExplosionForce(). I have just started working with unity so it might be a silly mistake.

Here is my script Update method:

void Update()
{
    if (Input.GetKeyDown(KeyCode.C) || Input.GetMouseButtonDown(0))
    {
        Vector3 pos = transform.position;
        cube = Instantiate(cubePrefab, pos, Quaternion.identity);
        GameObject ParentCube = GameObject.Find("GameObject");
        cube.transform.parent = ParentCube.transform;
    }
    if (Input.GetKeyDown(KeyCode.F))
    {
        foreach (Transform currentCube in transform)
        {
            Vector3 pointOfExplosion = new Vector3(transform.position.x - 1, transform.position.y - 1, transform.position.z - 1);
            currentCube.GetComponent<Rigidbody>().AddExplosionForce(20, pointOfExplosion, 10, 1);
        }
    }
}


问:
Open default app on windows 10 using bash shell
For some reason using explorer from command line does not yield the expected result when opening a nested folder or file:

```<code>explorer dir1/dir2/file
</code>```

I found out, if all occurences of slashes are replaced by double black slashes then the command works out. So, I wrote this little shell script that would customize the desired input path:

```<code>_path="${1//\//\\\\}"
echo "explorer $_path"
explorer "$_path"
</code>```

Unfortunately explorer opens the default Documents folder no matter which path I am providing, while the aimed behaviour is achieved, if I do copy the output by echo and paste it to the terminal...

My environment:

https://github.com/git-for-windows/git-sdk-64

```<code>$ uname
MSYS_NT-10.0-18363
</code>```

答: Replace explorer with start in the shell script

Body:
For some reason using explorer from command line does not yield the expected result when opening a nested folder or file:

explorer dir1/dir2/file

I found out, if all occurences of slashes are replaced by double black slashes then the command works out. So, I wrote this little shell script that would customize the desired input path:

_path="${1//\//\\\\}"
echo "explorer $_path"
explorer "$_path"

Unfortunately explorer opens the default Documents folder no matter which path I am providing, while the aimed behaviour is achieved, if I do copy the output by echo and paste it to the terminal...

My environment:

https://github.com/git-for-windows/git-sdk-64

$ uname
MSYS_NT-10.0-18363


问:
FetchRequest not possible inside a Sheet?
I have a SwiftUI App which have a MainView and this is calling a sheet like

```<code>this:.sheet(isPresented: $showingSheetFilter) {
    FilterView()
}
</code>```

The FilterView looks like this:

```<code>import SwiftUI

struct FilterView: View {

    @FetchRequest(
        entity: Category.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Category.title, ascending: true)
        ]

    ) var categories: FetchedResults<Category>

    var body: some View {
        List {
            ForEach(categories, id: \.self) { (cat: Category) in
                Text(cat.title!)
            }
        }.onAppear {
            print(self.categories.count)
        }
    }
}
</code>```

If I call the sheet I get an Dump:

```<code>Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
</code>```

In the onAppear. If I remove the onAppear I get it in the ForEach.

Why this is happening?

答:
As I commented to question at my environment all works fine. The only difference I see is that I pass context in my view-in-sheet explicitly as below

```<code>Button("Test Sheet") { self.isSheet = true }
    .sheet(isPresented: $isSheet) {
        TestListView().environment(\.managedObjectContext, context)
}
</code>```

Please try to do the same. Just in case.

Body:
I have a SwiftUI App which have a MainView and this is calling a sheet like

this:.sheet(isPresented: $showingSheetFilter) {
    FilterView()
}

The FilterView looks like this:

import SwiftUI

struct FilterView: View {

    @FetchRequest(
        entity: Category.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Category.title, ascending: true)
        ]

    ) var categories: FetchedResults<Category>

    var body: some View {
        List {
            ForEach(categories, id: \.self) { (cat: Category) in
                Text(cat.title!)
            }
        }.onAppear {
            print(self.categories.count)
        }
    }
}

If I call the sheet I get an Dump:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

In the onAppear. If I remove the onAppear I get it in the ForEach.

Why this is happening?

Body:
As I commented to question at my environment all works fine. The only difference I see is that I pass context in my view-in-sheet explicitly as below

Button("Test Sheet") { self.isSheet = true }
    .sheet(isPresented: $isSheet) {
        TestListView().environment(\.managedObjectContext, context)
}

Please try to do the same. Just in case.


问:
Kendo UI Autocomplete And Multi Select server side filter set value using JavaScript
I am using Kendo UI controls KendoUI Autocomplete & KendoUI MultiSelect. I need to change those control values & its display programmatically on client side without user acting on those controls.

How to reproduce the behavior:

Please look at this JS fiddle link, there are two Autocomplete controls.

Please type couple of characters in each control and select a result from auto suggestions.

Then click on on Reverse button, JS attempts to change (reverse) values, but that will no complete, without user clicking on the result populated on the auto suggest.

How can I avoid user selecting the results? If user clicks on Reveres both controls should have new selected values and its display should reflect it as well. If I click on Show Selection, that should show new selected values? I have similar issue with MultiSelect as well, If believe if I get this solved, same solution would be applicable for MultiSelect as well.

HTML

```<code><div class="demo-section k-content">
  <h4>Find a product</h4>
  <input id="From" style="width: 100%;" placeholder="From" />
  <div class="demo-hint">Hint: type "che"</div>
  <br />
  <input id="To" style="width: 100%;" placeholder="To" />
  <div class="demo-hint">Hint: type "unc"</div>
  <br />
  <p>Please select From and To then clcik on reverse</p>
  <button id="reverse">
    Reverse
  </button>
  <button id="show">
    Show Selection
  </button>
  <p id="result">

  </p>
</div>
</code>```

JS

```<code> $(document).ready(function() {
   $("#result").html("");
   $("#From").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });
   $("#To").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   $("#reverse").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();

     $departure.search(destinationStation.icao_id);
     $departure.select($departure.ul.children().eq(0));
     $departure.value(destinationStation.DisplayName);
     $departure.trigger("change");
     $departure.close();

     $destination.search(departureStation.icao_id);
     $destination.select($destination.ul.children().eq(0));
     $destination.value(departureStation.DisplayName);
     $destination.trigger("change");
     $destination.close();

   });

   $("#show").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();
     var from = JSON.stringify(departureStation);
     var to = JSON.stringify(destinationStation);
     $("#result").html("From :" + from + "<br/><br/><br/><br/>To: " + to);
   });
 });
</code>```

答:
One main issue is that you have serverFiltering: true and asynchronous activity is happening.

The search method will cause a filter to be applied to the dataSource, which in turn causes a server interaction that will fire event dataBound upon completion.

A kendoAutoComplete opens its drop down during typing and will leave it open while additional filtering (implicit searching) occurs for each new keystroke.

Solution:

Install dataBound event handlers that check if the swap action was forced, and if so automatically select the first drop down item.

Use ready-function-scoped flag variables to indicate swapping is happening

Swap click handler will:

Set the flag variables

Invoke programmatic search

From docs, search will collaterally open the DDL.

dataBound handlers:

force DDL selection because flag is active.

close DDL

trigger change

toggle flag variable off

JS from this Dojo

```<code> $(document).ready(function() {

   $("#From").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataBound: function(e) { swap1() },
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   $("#To").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataBound: function(e) { swap2() },
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   var one_swapping = false;
   var two_swapping = false;

   function swap1() {
     if (one_swapping) {
       var ac = $("#From").data('kendoAutoComplete');
       ac.select(ac.ul.children().eq(0));
       ac.close();
       ac.trigger("change");
       one_swapping = false;
     }
   }

   function swap2() {
     if (two_swapping) {
       var ac = $("#To").data('kendoAutoComplete');
       ac.select(ac.ul.children().eq(0));
       ac.close();
       ac.trigger("change");
       two_swapping = false;
     }
   }

   $("#swap").click(function(e) {
     $("#result").html("");

     var one = $("#From").data("kendoAutoComplete");
     var two = $("#To").data("kendoAutoComplete");

     var one_val = one.element.val();
     var two_val = two.element.val();

     one_swapping = true;
     one.search(two_val);  // force the filter

     two_swapping = true;
     two.search(one_val);  // force the filter
   });

   $("#show").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();
     var from = JSON.stringify(departureStation);
     var to = JSON.stringify(destinationStation);
     $("#result").html("From :" + from + "<br/><br/><br/><br/>To: " + to);
   });
 });
</code>```

Body:
I am using Kendo UI controls KendoUI Autocomplete & KendoUI MultiSelect. I need to change those control values & its display programmatically on client side without user acting on those controls.

How to reproduce the behavior:

Please look at this JS fiddle link, there are two Autocomplete controls.

Please type couple of characters in each control and select a result from auto suggestions.

Then click on on Reverse button, JS attempts to change (reverse) values, but that will no complete, without user clicking on the result populated on the auto suggest.

How can I avoid user selecting the results? If user clicks on Reveres both controls should have new selected values and its display should reflect it as well. If I click on Show Selection, that should show new selected values? I have similar issue with MultiSelect as well, If believe if I get this solved, same solution would be applicable for MultiSelect as well.

HTML

Find a product

  <input id="From" style="width: 100%;" placeholder="From" />

Hint: type "che"

  <input id="To" style="width: 100%;" placeholder="To" />

Hint: type "unc"

Please select From and To then clcik on reverse

  <button id="reverse">
    Reverse
  </button>
  <button id="show">
    Show Selection
  </button>

JS

 $(document).ready(function() {
   $("#result").html("");
   $("#From").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });
   $("#To").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   $("#reverse").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();

     $departure.search(destinationStation.icao_id);
     $departure.select($departure.ul.children().eq(0));
     $departure.value(destinationStation.DisplayName);
     $departure.trigger("change");
     $departure.close();

     $destination.search(departureStation.icao_id);
     $destination.select($destination.ul.children().eq(0));
     $destination.value(departureStation.DisplayName);
     $destination.trigger("change");
     $destination.close();

   });

   $("#show").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();
     var from = JSON.stringify(departureStation);
     var to = JSON.stringify(destinationStation);
     $("#result").html("From :" + from + "

To: " + to);
   });
 });

Body:
One main issue is that you have serverFiltering: true and asynchronous activity is happening.

The search method will cause a filter to be applied to the dataSource, which in turn causes a server interaction that will fire event dataBound upon completion.

A kendoAutoComplete opens its drop down during typing and will leave it open while additional filtering (implicit searching) occurs for each new keystroke.

Solution:

Install dataBound event handlers that check if the swap action was forced, and if so automatically select the first drop down item.

Use ready-function-scoped flag variables to indicate swapping is happening

Swap click handler will:

Set the flag variables

Invoke programmatic search

From docs, search will collaterally open the DDL.

dataBound handlers:

force DDL selection because flag is active.

close DDL

trigger change

toggle flag variable off

JS from this Dojo

 $(document).ready(function() {

   $("#From").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataBound: function(e) { swap1() },
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   $("#To").kendoAutoComplete({
     dataTextField: "ProductName",
     filter: "contains",
     minLength: 2,
     dataBound: function(e) { swap2() },
     dataSource: {
       type: "odata",
       serverFiltering: true,
       transport: {
         read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
       }
     }
   });

   var one_swapping = false;
   var two_swapping = false;

   function swap1() {
     if (one_swapping) {
       var ac = $("#From").data('kendoAutoComplete');
       ac.select(ac.ul.children().eq(0));
       ac.close();
       ac.trigger("change");
       one_swapping = false;
     }
   }

   function swap2() {
     if (two_swapping) {
       var ac = $("#To").data('kendoAutoComplete');
       ac.select(ac.ul.children().eq(0));
       ac.close();
       ac.trigger("change");
       two_swapping = false;
     }
   }

   $("#swap").click(function(e) {
     $("#result").html("");

     var one = $("#From").data("kendoAutoComplete");
     var two = $("#To").data("kendoAutoComplete");

     var one_val = one.element.val();
     var two_val = two.element.val();

     one_swapping = true;
     one.search(two_val);  // force the filter

     two_swapping = true;
     two.search(one_val);  // force the filter
   });

   $("#show").click(function(e) {
     $("#result").html("");
     var $departure = $("#From").data("kendoAutoComplete");
     var $destination = $("#To").data("kendoAutoComplete");

     var departureStation = $departure.dataItem();
     var destinationStation = $destination.dataItem();
     var from = JSON.stringify(departureStation);
     var to = JSON.stringify(destinationStation);
     $("#result").html("From :" + from + "<br/><br/><br/><br/>To: " + to);
   });
 });