p-multiSelect onchange prevent adding elements with the same index

I have multiselect option with 6 options from array. one of the option is a bit diffrent then the others(it lets adding remark and in the others not). when I am selecting this option and one of the fields x(the remark), after I removing it and selecting again but the field will be null (lets say in the first case I am adding reark and in the second time I’m not) so the multi select will add it twice! but I want 1 velue for every index(without care of the other fields).how should I do it? another place it different in getting the selected values from the server, when it should be selected after the user choosed it it seemes like he didn’t choose.

  <p-multiSelect *ngIf="_decision.decisionStatusId == eDecisionType.Reject || _decision.decisionStatusId == eDecisionType.ReturnedToUser" [required]="formGroup.hasError('remark-reasons-required')"
                   [options]="reasons" defaultLabel="" formControlName="remarks" [(ngModel)]="selectedReasons" optionLabel="hebName"
                   [ngClass]="_decision.decisionStatusId == eDecisionType.ReturnedToUser || _decision.decisionStatusId == eDecisionType.Reject ? '' : 'display-none'"
                   selectedItemsLabel="{0} "
                   (onChange)="onChangeReasonsValue($event)"></p-multiSelect>

.ts

onChangeReasonsValue(event: { value: ReviewDecisionReasonModel[] }): void {
    this.selectedReasons = event.value;
    this._decision.reasons = event.value;
    this.formGroup.markAsDirty();
    this.formGroup.markAsTouched();
    this.formGroup.updateValueAndValidity();
  }

same index values

Trying to convert Stacked BarPlot from D3 to Aframe

As the title suggests, I am trying to convert a Stacked BarPlot from D3 (version 4) to Aframe (using the AR.js library).

The D3 example I am using can be found here:

https://www.d3-graph-gallery.com/graph/barplot_stacked_basicWide.html

When I run the code in the browser, I can see 4 boxes (squares), stacked on top of the other corresponding boxes, however in a weird, layered fashion. I believe this is due to my ‘scale’ and ‘position’ attributes which are incorrectly reading in the data and rendering like they should. Or perhaps it’s how I appended the “a-entity” and then “a-box” to my “a-scene”. Or perhaps it’s neither / both (?)

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src='https://aframe.io/releases/0.9.2/aframe.min.js'></script>
<script src="https://raw.githack.com/jeromeetienne/AR.js/master/aframe/build/aframe- 
ar.min.js"></script>
<script src="https://raw.githack.com/donmccurdy/aframe-extras/master/dist/aframe- 
extras.loaders.min.js"></script>
<script>
THREEx.ArToolkitContext.baseURL = 
'https://raw.githack.com/jeromeetienne/ar.js/master/three.js/'
</script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
animation-component.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
randomizer-components.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
entity-generator-component.min.js"></script>
<script src="https://rawgit.com/mayognaise/aframe-mouse-cursor- 
component/master/dist/aframe-mouse-cursor-component.min.js"></script>
</head>

<body style="margin : 0px; overflow: hidden;">

<div id="data_by_age"></div>

<a-scene vr-mode-ui="enabled: false" embedded arjs='sourceType: webcam; 
sourceWidth:1280; sourceHeight:960; displayWidth: 1280; displayHeight: 960; 
debugUIEnabled: false;'>

<a-entity gps-entity-place="longitude: -73.766327; latitude: 41.032730;">
    <a-cursor fuse="true" color="yellow"></a-cursor>
</a-entity>
    <a-camera gps-camera rotation-reader></a-camera>

</a-scene>

<script type="text/javascript">

byAge();

function byAge() {

var scene = d3.select("a-scene");

d3.csv("../static/sample.csv", function(data) {

var subgroups = data.columns.slice(1)

var groups = d3.map(data, function(d){return(d.group)}).keys()

var color = d3.scaleOrdinal()
.domain(subgroups)
.range(['#011f4b','#03396c','#005b96', '#6497b1', '#b3cde0'])

var stackedData = d3.stack()
.keys(subgroups)
(data)

var data_scle = [];
var data_pos = [];

scene
.append("a-entity")
.selectAll("a-entity")
.data(stackedData)
.enter()
.append('a-entity')
.attr("fill", function(d) { return color(d.key); })
.selectAll("a-box")
.data(function(d) { return d; })
.enter().append("a-box")
.attr('rotation', '0 180 0')

.attr('scale', function (d,i) {
    return d + " " + d + " " + d;
})
// .attr('scale', function (d,i) {
//     var x =  i * 10;
//         var y = d;
//         var z = d;
//     data_scle[i] = {"x": x, "y": y, "z": z};
//     return x+" "+y+" "+z;
// })
.attr('position', function(d,i) {
    var x =  i * 175;
        // var y = 0;
        var y = d;
        var z = -500;
    data_pos[i] = {"x": x, "y": y, "z": z};
    return x+" "+y+" "+z;
  })

})

};

</script>
</body>
</html>

Here is my csv file:

group, stronglyAgree, somewhatAgree, stronglyDisagree, notSureNoOpinion
eighteen, 21, 22, 11, 18, 28
thirtyfive, 33, 29, 11, 5, 22
fortyfive, 36, 23, 9, 8, 24
sixtyfive, 42, 24, 7, 10, 17

I’ve also seen github repos tailored specifically for making stacked bar chart components in Aframe, however I couldn’t seem to get it to work properly.

https://github.com/fran-aguilar/a-framedc/tree/master/src/components/barchartstack

Any help would be immensely appreciated.

How to get the sum of a key of consecutive array object and remove the duplicates?

I have a main array –

const arr = [
    {  description: 'Senior', amount: 50 },
    {  description: 'Senior', amount: 50 },
    {  description: 'Adult', amount: 75 },
    {  description: 'Adult', amount: 35 },
    {  description: 'Infant', amount: 25 },
    {  description: 'Senior', amount: 150 }
]

I want help with an es6 operation which will add the amount based on the key(description) and remove the duplicates.

Result array will somewhat look like –

const newArr = [
        {  description: 'Senior', amount: 120 },
        {  description: 'Adult', amount: 110 },
        {  description: 'Infant', amount: 25 },
        {  description: 'Senior', amount: 150 }
]

I have been using the reduce operator to achieve this using the solution, but that removes the non-consecutive objects as well.

It would be really helpful if someone can help me with some es6 operators to perform the same operation.

de.js replace node icon with svg icon

enter image description here
I want use my custom svg icon instead of the circle.
The svg icon is from online url, so, I can use d3.xml to download its content.

        nodes.descendants().forEach(item => {
        const {type, thumb, url} = item.data;
        if ('2d-vector' == type && !thumb) {
            d3.xml(url).then(data => {
                (g.selectAll('.node').node() as any).append(data.documentElement);
                // .attr('x', -15)
                // .attr('y', -15)
                // .attr('width', 30)
                // .attr('height', 30);
            });
            return url;
        }
    });

Above is my tring code, but, I cannot change the svg icon width, heigth.
The original svg icon is very large than the circle.

How do you find the standard errors and confidence intervals for nonlinear fit parameters in JavaScript?

I have been working on a personal project involving data fitting in JavaScript. The algorithm that I am using, fminsearch, seems to work well; my application consistently achieves r^2 values above .90 for accurate data. However, I feel that my analysis of the error is not complete without both confidence intervals and standard errors. I have viewed the following questions, but since they do not use JavaScript and I cannot find similar libraries in JavaScript, I am unsure how to continue:

https://stats.stackexchange.com/questions/92131/how-to-calculate-95-confidence-interval-for-non-linear-equation

https://stats.stackexchange.com/questions/285023/compute-standard-errors-of-nonlinear-regression-parameters-with-maximum-likeliho

I also looked at this JavaScript tensorflow question, yet I do not know how to use it for functions other than the ones solved for in the question:

Standard error of estimated parameters with tensorflow.js

If there is no robust algorithm that allows for standard errors and confidence intervals for any inputted nonlinear function, it would be nice to at least have an algorithm for the function Log[y] = Log[c] + a Log[x] + b (Log[x])^2. I am not fitting this function by converting to a quadratic as I have found that the fits are much more accurate when starting and ending in the same form.

If it helps, here is an example of the ideal analysis I want using Mathematica.

Any help would be greatly appreciated, and have a wonderful day (:

Testing JSON with typescript

I need to validate JSON with typescript. I wanted to do this like so:

jsonFile.json

{
  "foo": "bar",
  "fiz": "baz",
  "potato": 4
}

JSONType.ts

type JSONType = typeof jsonFile;

jsonFile2.json

{
  "foo": 5,
  "fiz": false
};

and if I do this:

const jsonFile2: JSONType = JSONFile2

I want it to throw an errors for not matching types, and a missing property.

I essentially want to make sure two JSONs have the same structure, with one of them as the source of truth. How do I do that?

Emitters vs import function on modular JS – Which to choose

We can communicate between modules by:

  1. Using an Event Emitter
  2. Importing the function from an external module

Is there any best practice when it comes to choosing between the two?

I understand we can only import the function if we need a to use a returned value. But, when we don’t, how do we decide if we import the function or we use an event emitter to trigger the same function?

(In case it matters, I’m talking about front-end JS modules to combine with something like Rollupjs)

Import example

//app.js
import { say } from 'actions.js';

function demo(){
  .... 
  say('Hello');
}
//say.js
export function say(content){
   console.log(content);
}

Event Emitter example

//app.js
import { eventEmitter } from 'eventEmitter.js';
import 'say.js';

function demo(){
  .... 
  eventEmitter.emit('say', 'hello');
}
//say.js
import { eventEmitter } from 'eventEmitter.js';

eventEmitter.on('say', say);

function say(content){
   console.log(content);
}

The advantage I see when using Event Emitters is that we can prevent circular dependencies during the build. But I would love to see what other people think about this.

How can I configure Vite app to minify code in development environment?

I am working on a Vite/Vanilla JS application, and my team lead wants me to see if it’s possible to output minified code when running the code in the development environment. Apparently this will be important down the line when setting up CI/CD pipeline.

My understanding of how Vite works is that it serves Native ESM to the browser in the development environment, and only bundles + minifies the code in production mode. Upon running both dev and prod servers and inspecting the code, this seems to be true.

I’ve spent hours trying to figure out how I can force minify the code in development. First of all, Vite ships with both Terser and esbuild for minifying. According to the docs, it defaults to esbuild, and you can set build.minify: Terser in the config file if you want to use Terser. However as far as I can tell, there is no info in the docs (for Vite or either of the plugins) about force minifying in the dev environment.

Any ideas would be greatly appreciated. See below for my config file code:

vite.config.js

const { resolve } = require("path");
const { defineConfig } = require("vite");

module.exports = defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, "index.html"),
        login: resolve(__dirname, "./pages/login/login.html"),
        home: resolve(__dirname, "./pages/home/home.html"),
      },
    },
  }
});

package.json

{
  "name": "vite-www",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "^2.7.2"
  }
}

Google Sheets Data Collection from WooCommerce Orders not consistently firing

This is for a local BSA Troop and I was just trying to make it so when orders came through that they came through to a Google sheet in an organized way so the team can help manage the event.
I am also newer to Javascript, I use PHP/HTML5/CSS3 so I’m sure it’s something simple but the logic seems to be escaping me.

There are only 2 products in WooCommerce on the website.

One product has two variations: though the variation is carried through the title:

Tree Pickup Fundraiser - January 2nd, 2022

Tree Pickup Fundraiser - January 9th, 2022

So what I am trying to do is keep one column always the tree pickup and the second column donations. Though not all people will do Tree Pickup and not all people will do donations. Some will do just donations and some will do just tree pickup.

The issue I have found with my following code below is if both items are defined, donations & tree pickup, then it fires and seems to fire just fine. Though when one is not defined it does not work. I’m assuming I need to assign a value to the myData.line_items[1] but I’m not sure, when I tried to I may have done it incorrectly.

var product_name_2 = (myData.line_items[1].name) ? myData.line_items[1].name : ' ';

Or am I missing something else, any and all help is welcome! Apologies, Javascript I am still really new at.

//this is a function that fires when the webapp receives a GET request
function doGet(e) {
  return HtmlService.createHtmlOutput("request received");
}

//this is a function that fires when the webapp receives a POST request
function doPost(e) {
  var myData             = JSON.parse([e.postData.contents]);
  var order_number       = myData.number;
  var order_created      = myData.date_created;  
  var scout              = myData.customer_note;
  var street             = myData.billing.address_1;
  var street_2           = myData.billing.address_2;
  var city               = myData.billing.city;
  var zip_code           = myData.billing.postcode;
  var product_name       = myData.line_items[0].name;
  var product_qty        = myData.line_items[0].quantity;
  var product_total      = myData.line_items[0].total;
  var product_name_2     = myData.line_items[1].name;
  var product_qty_2      = myData.line_items[1].quantity;
  var product_total_2    = myData.line_items[1].total;
  if (product_name_2 == "Donation" || typeof product_name_2 == 'undefined')
  {
    var first        = product_name;
    var first_qty    = product_qty;
    var first_total  = product_total;
    var second       = product_name_2;
    var second_total = product_total_2;
  }
  else
  {
    var first        = product_name_2;
    var first_qty    = product_qty_2;
    var first_total  = product_total_2;
    var second       = product_name;
    var second_total = product_total;
  }
  var order_total        = myData.total;
  var billing_email      = myData.billing.email;
  var billing_first_name = myData.billing.first_name;
  var billing_last_name  = myData.billing.last_name;
  var phone              = myData.billing.phone;

  var timestamp = new Date();
  var sheet = SpreadsheetApp.getActiveSheet();

  sheet.appendRow([timestamp,order_number,order_created,scout,street,street_2,city,zip_code,first,first_qty,first_total,second,second_total,order_total,billing_email,billing_first_name,billing_last_name,phone]);
}```

HTML5 Canvas Charts in a list and long loading time

I have a long table with 100 items per site. Every item has a canvas chart, which takes a lot of time for loading at the first time. Is there any options (without cache, i do it already) to create a picture or reduce the loading time? Thanks!

 <canvas width="135" height="40" data-rate="' . $fiatrate . '" data-fiat="'. $fiatprefix[$options['currency']] .'" data-color="' . (($options['chart_color'] !== '') ? hex2rgb($options['chart_color']) : (($coin->percent_change_24h >= 0) ? '10,207,151' : '239,71,58')) . '" data-gradient="50" data-border="2" data-points="' . implode(',', array_slice($options['weekly'][$coin->slug], -24)) . '"></canvas>

How to pass Object as parameter to a function onclick

Hi everyone I am facing some issues while trying to pass JSON object as a parameter to function!
but on that function, while consoling log the data I am getting [object:object].
Here is my code:-

 function buildTable(data){
        var table = document.getElementById('myTable');
        table.innerHTML ="";
        for(var i =0; i<data.length; i++){
            var row = `<tr class="item-id-${data[i].id}"> <td>${data[i].name}</td> <td>${data[i].audio_muted}</td> <td>${data[i].video_muted}</td> <td><button id="audio_handle" class="btn btn-primary" onclick="handleMembers('${data[i]}')">Video</button></td>`

            table.innerHTML += row;

        }
    }

 function handleMembers(data){
        console.log("data = >",data); //= [object:object]
    }

The issue is when I am calling handle function from the button inside template literal string I m getting [object:object] as output

Where I am going wrong kindly help me.

timezone selection menu for Vuejs

While Vuetify makes datepicker very simple, but timezone not so much.

I did some research, and I found this nice one

HTML

<div class="container">
  <p></p>

  <p>
    <select class="js-Selector"></select>
  </p>

  <ul>
    <li><strong>UTC time:</strong> <span class="js-TimeUtc"></span></li>
    <li><strong>Local time:</strong> <span class="js-TimeLocal"></span></li>
  </ul>
</div>

JS

const dateTimeUtc = moment("2017-06-05T19:41:03Z").utc();
document.querySelector(".js-TimeUtc").innerHTML = dateTimeUtc.format("ddd, DD MMM YYYY HH:mm:ss");

const selectorOptions = moment.tz.names()
  .reduce((memo, tz) => {
    memo.push({
      name: tz,
      offset: moment.tz(tz).utcOffset()
    });
    
    return memo;
  }, [])
  .sort((a, b) => {
    return a.offset - b.offset
  })
  .reduce((memo, tz) => {
    const timezone = tz.offset ? moment.tz(tz.name).format('Z') : '';

    return memo.concat(`<option value="${tz.name}">(GMT${timezone}) ${tz.name}</option>`);
  }, "");

document.querySelector(".js-Selector").innerHTML = selectorOptions;

document.querySelector(".js-Selector").addEventListener("change", e => {
  const timestamp = dateTimeUtc.unix();
  const offset = moment.tz(e.target.value).utcOffset() * 60;
  const dateTimeLocal = moment.unix(timestamp + offset).utc();

  document.querySelector(".js-TimeLocal").innerHTML = dateTimeLocal.format("ddd, DD MMM YYYY HH:mm:ss");
});

document.querySelector(".js-Selector").value = "Europe/Madrid";

const event = new Event("change");
document.querySelector(".js-Selector").dispatchEvent(event);

I have no idea how to begin to migrate this into my Vue.js project.

How would one add a timezone selection menu to their Vuejs project?