How can I pass parameter to regex constructor, and used in String.matchAll method

I want to search words in a string, let’s say I input the word “test”, and it will return all results matching “test”, but I don’t know how to pass word I inputed to regex constructor. For example that shown below, if I directly enter /btestb/g in matchAll, then it all good, but what if I want to search different words, so I try /b${word}b/g, but doesn’t work.

Do you know any solution that I can use? Thanks in advance.

const word = "test";
const regex = `/b${word}b/g`;
const str = 'test1 test 2';
const array1 = [...str.matchAll(new RegExp(regex, "g"))];
const array2 = [...str.matchAll(new RegExp(/btestb/g, "g"))];

console.log(array1);
// expected output: Array ["test"] // however it return empty array []

console.log(array2);
// expected output: Array ["test"] // it do return expected result

How to remove products from shopify cart and set limit of 10 products

Here is my code what I want is to set total cart limit 10 if user try to add more than 10 item in cart cart will automatically update and it will remove additional items for example if there is 10 products in cart and user try to add 5 more than existing 5 items will be deleted if there is 11 then 1 item will be deleted I tried my best to achieve my requirement but I think I am missing something it’s not working properly

$(".addtocart_custom").click(function(evt){

  jQuery.getJSON('/cart.js', function (cart)
 {
    var items_new = cart.items;  
    var count = cart.item_count;
    var item_to_remove = count - 10 ;
   
    if (count >= 10)
    {
      var item_to_remove = count - 10;
      if(item_to_remove > 0) {
        for(var i=0;i<=items_new.length;i++)
        {
          var c_id = cart.items[i].id;
          var c_quantity= cart.items[i].quantity;

          if(c_quantity >= item_to_remove) {

            var data = { 'id': c_id , 'quantity':c_quantity - item_to_remove  }
            
            debugger;
            $.ajax({
              type: 'POST',
              url: '/cart/change.js',
              data: data,
              dataType: 'json',
              success: {

              }

            });

          }else{
            item_to_remove = item_to_remove - c_quantity;
            var data = { 'id': c_id , 'quantity':c_quantity - item_to_remove  }
            
            debugger;
            $.ajax({
              type: 'POST',
              url: '/cart/change.js',
              data: data,
              dataType: 'json',
              success: {

              }

            });
                
            }

        }
      }

    }
  });
});

Angular Material paginator hides the buttons and number of pages by the global background color

enter image description here
enter image description here

I implemented material paginator and the number of items per page and buttons(next and previous) are hided by the global backgroud color. I have attached 2 images and global background color of one of them is deactivated and can see the number of pages and buttons(next and previous).

I need to keep the background color and make visible the number of items per page and next and previous buttons.

I did read few releted articles and made few changes for example,

::ng-deep my-style-class {
   background-color: unset;
}

All of them were not worked.

Can you please give me a suggestion to make visible number of pages and next, previous buttons without disabing the global background color.

How to show all the values in a list based on the selected category?

I have a table with 4 columns. I am fetching all this data and storing it in an array for ease of selection. The user can select the category from the drop down (i.e. name="category"). Furthermore, onClick is being used to trigger the function (getProdNames) to allocate the value of col 3 to the textfield (i.e. name="prodNames"). But, how can I change this to show all the values of Col 3 based on the category selected (Col 2) value? So, user can mutli-select the product names.

Table Structure:

id category productName
1 toy ABC
2 toy DEF
3 hardware AJI

function:

<script>
function getProdNames(){
    
        var product_name = $('#category').find(':selected').data('product_name');
        
        $('#prodNames').val(product_name);

    }
    
</script>

Php:

    <select id="category" name="category" onClick="getProdNames();>
            <option> <?php
                        // Attempt select query execution
                        $sql = "SELECT * FROM TABLE1";
                        if($result = $mysqli->query($sql)){
                            if($result->num_rows > 0){
                                    while($r = $result->fetch_array()){
                                       echo "<option    
                                            data-productName='$r[1]' 
                                            data-color='$r[2]'
                                            value='$r[0]'> $r[0] </option>";}
                            } } ?>
            </option>
    </select>

//Display Product Names based on the selected category here in the form of multi select list

<select name="prodNames" id="prodNames"  class="form-control" multiple>
    </select>

Desire Output:
If user selects toy. This should trigger the onClick function to show all the productNames associated with this cateogory. Hence, the following output based on this example:

ABC
DEF

Need help splitting date to new line in Doughnut Chart js

I’m using a permutation of @Cmyker’s code (see here) to have text in the center of a doughnut chart, but I’m having trouble getting the date setting I made to break into another line instead of sticking to the same line as the rest of the text. I’ve tried adding /n on the end of the text where I want it to break but that doesn’t seem to be working, any advice on this?

//Date for chart
let today = new Date();
var date = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();

//Chart
window.onload = function(){
  //dataset
  var data = {
    labels: [" Akaun 1"," Akaun 2"],
    datasets: [{
      data: [1300.00, 895.75],
      backgroundColor: ["#430092","#36A2EB"],
      hoverBackgroundColor: ["#430092","#36A2EB"],
      cutout: ["70%"],
    }]
  };

  //init & config
  var chart = new Chart(document.getElementById('myChart'), {
    type: 'doughnut',
    data: data,
    options: {
      responsive: true,
      legend: { display: false},
      labels: { font: {size: 12}}
    }
  });

  const centerDoughnutPlugin = {
      id: "annotateDoughnutCenter",
      beforeDraw: (chart) => {
        let width = chart.chartArea.left + chart.chartArea.right;
        let height = chart.chartArea.top + chart.chartArea.bottom;
        let ctx = chart.ctx;

        ctx.restore();
        //Font setting
        let fontSize = (height / 250).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        ctx.textAlign = "center";

        let text = "Balance as of: n" + date;

        //Center text
        let textX = width / 2;
        let textY = height / 2;

        console.log("text x: ", textX);
        console.log("text y: ", textY);

        ctx.fillText(text, textX, textY);
        ctx.save();
      },
    };

  Chart.register(centerDoughnutPlugin);
}
<canvas id="myChart">
</canvas>

Aggregation pipeline redisplay cascading variables

I’d like to pull guestAttends from my event model and display the value for each individual event. Right now, the aggregation query is working but my page is only displaying the value from the FIRST event in the model and carrying it down the index, instead of populating each with its respective value.

How do I get it to display the event-specific value?

Here’s my function/route:

module.exports.showArtist = async (req, res,) => {
    const artist = await Artist.findById(req.params.id).populate('events');
    if (!artist) {
        req.flash('error', 'Cannot find that Artist');
        return res.redirect('/artists');
    }
    const artistId = artist._id;
    let totalGuests = 0;
    let attendedGuests = 0;
    const eventData = await Event.aggregate([
        {
            "$match": {
                "artist": artistId
            }
        },
        {
            $project: {
                _id: 1,
                name: 1,
                guests: 1,
                totalGuests: { $cond: { if: { $isArray: "$guests" }, then: { $size: "$guests" }, else: "NA" } },
                attendedGuests: {
                    $size: {
                        $filter: {
                            input: "$guests",
                            as: "guest",
                            cond: {
                                $and: [{
                                    $eq: ["$$guest.attended", "Y"]
                                }]
                            }
                        }
                    }
                }
            }
        }
    ])
    if (eventData && Array.isArray(eventData) && eventData.length > 0) {
        totalGuests = eventData[0].totalGuests;
        attendedGuests = eventData[0].attendedGuests;
    }
    const guestSignups = JSON.stringify(totalGuests);
    const guestAttends = JSON.stringify(attendedGuests);
    res.render('artists/show', { artist, guestSignups, guestAttends });
}

And here’s my page displaying the value:

<% for (let events of artist.events ) {%>

  <div class="card mb-3 shadow">
      <div class="row">
          <div class="col-md-8">
              <div class="card-body">
                  <h5 class="card-title"><%= events.event_name %> </h5>
                  <p class="text"><%= events.description %> </p>
                  <p class="text"><%= events.eventData %> </p>
                  <p class="text">Guests signed up <%= guestSignups %> </p>
                  <p class="text">
                      <small class="text-muted"><%= events.description %> </small>
                  </p>
                  <a class="btn btn-primary" href="/events/<%= events.id %>">View Event</a>
              </div>
          </div>
      </div>
  </div>
<% }%>

Where am I going wrong?

Why ajax doesn’t send my JS variable to PHP?

I’m trying to send JS variables to a PHP script (which is included in the page I try to make ajax work)

index.php

include 'PHP/display.php';
<button id="click" onclick="show();">Click !</button>

<script>
  function show(){
    var str = "Yes";
    $.ajax({
      method : 'post',
      url : 'PHP/display.php',
      data: {
        str : str
      },
      success: function(data) {
        console.log(data);
      }
    });
  }
</script>

display.php

<?php
  echo isset($_POST['str']) ? $_POST['str'] : "No";
?>

This keeps displaying “No”, but the console shows me the “Yes” I want

This code is my first try with ajax, that’s why I try to keep it simple, but it doesn’t work.

I’ve been looking for hours on StackOverflow and not one solution works for me.

Maybe i’m missing something, please help me 🙁

JavaScript importing module confusion

When I am importing ‘http’ module, I use

Var http = require('http');
http.createServer(function(req,res){......
}.listen(8080)

But when I am importing express module, I use

const express = require('express');
const app = express();
app.get('/', (req,res)=>{........
}
app.listen()

Why do I need to create const app = express(); but not const app = http(); in the code?

Convert string into variable in array automatically

I have a problem when Im trying to convert a string to a variable in an array.

The variables are:

const n = 1; const s = -1;

The array string:

let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n']; 

I want to convert automatically to this variable array:

let walk = [n, s, n, s, n, s, n, s, n, n];

I’m trying to split but the array still string not a var:

let text = walks.toString().split(',').join('-')
console.log(text)

UnBuffer and Convert to String

I am using Avalanchejs a Javascript SDk to generate an address. After installing all dependencies and running the code. I get a new address, but the address shows up in a format. I tried to use the Buffer.from(‘xxx’) method and then toString(). But it did not work. How can I convert the into a string ?

JS code:

const avalanche = require("avalanche")
const { Avalanche, BinTools, Buffer, BN } = require("avalanche")

const bintools = BinTools.getInstance()

const myNetworkID = 12345 //default is 1, we want to override that for our local network
const avalancheX = new Avalanche("localhost", 9650, "http", myNetworkID)
const xchain = avalancheX.XChain() //returns a reference to the X-Chain used by AvalancheJS

const myKeychain = xchain.keyChain()
const newAddress1 = myKeychain.makeKey() 
console.log(newAddress1.pubk)
var buf = Buffer.from(newAddress1.pubk);
console.log(buf.toString());

Terminal Output:

<Buffer 03 cd ab 4d e6 7d ee c5 9f c6 0d 27 e8 3b d2 da ee 84 ce f3 77 20 70 c9 8d 66 47 c7 36 91 ec 1f 07>
'�;������w pɍfG�6��

why is Bluetooth.then not a function?

I am writing a Javascript program to print out device information.

I have two services: ‘battery_service’ and ‘device_information’, and the characteristic under ‘battery_service’ is ‘battery_information’.

I want to implement some code in separate functions to make it neater, but when I want to do so, I get the following error:

deviceInfo3.js:11 Uncaught TypeError: bluetoothDevice is not a function

from calling the function below:
My getBatteryFunction:

 function getBatteryPercent()
  {
    bluetoothDevice
    .then(
      value => {
        console.console.log("Battery = "+value.getUint8(0))
        document.getElementById("battery").value=value.getUint8(0);
      }
    )
  }

and this is my main driver function when the button is clicked:

var bluetoothDevice;

function onScanButtonClick() {
  let options = {filters: []};

  
    options.filters.push({services: ['battery_service', 'device_information' ]});

  console.log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice(options)
  .then(device => {
    bluetoothDevice = device;
    bluetoothDevice.addEventListener('gattserverdisconnected', onDisconnected);
    return device.gatt.connect();
  })
  .then((server) => {
    // Set the isConnected variable to true
    bluetoothDevice.isConnected = true;
    console.log('Getting Accelerometer service (UUID: ' + 'battery_service' + ')... ');
    // Get the accelerometer service (if it's not enabled, the error will be caught below)
    return server.getPrimaryServices();
  })
  .then(services => {
    console.log("Getting characteristics...");
    let queue=Promise.resolve();
    services.forEach(service => {
      console.log(service.uuid);
      switch(service.uuid) {
        
        case ('0000180f-0000-1000-8000-00805f9b34fb'): {
          getBatteryPercent();
        }
      }
      
    })
  })
}

How can I achieve this?

Is this a reasonble implementation of a queryable promise subclassing a native ES6 Promise?

I’m updating some old code (not mine originally) that uses Bluebird promises. I’d rather use native ES6 Promises instead, but the old code uses a function Promise doesn’t have, one to check if promises have been settled.

This is related to a similar question (Is there a way to tell if an ES6 promise is fulfilled/rejected/resolved?), but the solution given there is very different, so I wanted to know if the following code is a reasonable approach to the problem.

export class QueryablePromise<T> extends Promise<T> {
  private _isRejected = false;
  private _isResolved = false;
  private _isSettled = false;

  then<TResult1 = T, TResult2 = never>(
    onResolved?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
    onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
  ): Promise<TResult1 | TResult2> {
    const newResolved = onResolved && ((value: T): TResult1 | PromiseLike<TResult1> => {
      this._isResolved = true;
      this._isSettled = true;
      return onResolved(value);
    });
    const newRejected = onRejected && ((reason: any): TResult2 | PromiseLike<TResult2> => {
      this._isRejected = true;
      this._isSettled = true;
      return onRejected(reason);
    });

    return super.then(newResolved, newRejected);
  }

  catch<TResult = never>(
    onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
  ): Promise<T | TResult> {
    const newRejected = onRejected && ((reason: any): TResult | PromiseLike<TResult> => {
      this._isRejected = true;
      this._isSettled = true;
      return onRejected(reason);
    });

    return super.catch(newRejected);
  }

  finally(
    onFinally?: (() => void) | undefined | null
  ): Promise<T> {
    const newFinally = onFinally && ((): void => {
      this._isSettled = true;
      return onFinally();
    });

    return super.finally(newFinally);
  }

  get isRejected(): boolean { return this._isRejected; }
  get isResolved(): boolean { return this._isResolved; }
  get isSettled(): boolean { return this._isSettled; }
}

Basically I’m wrapping each callback passed to then, catch, and finally in another function which sets the appropriate flags and then calls the original callback. Flags could easily be set redundantly many times this way, but I don’t see that as being much of a problem.

I tried to think of a way to solve this problem using the constructor for my promise subclass, and somehow put a wrapper around the original executor argument to intercept invocations of resolve and reject, but couldn’t quite put my head around a way to implement that type of solution.

I also tried simply adding my own separate then, catch, and finally callbacks in a constructor for this subclass, with each having nothing to do but set my status flags, but oddly enough that resulted in a stack overflow, the constructor being called recursively until it blew up.

How to add v-on:change event attribute after DOM mounted in Nuxt.js or Vue.js?

I want to add element and event attribute like @change in my latest Nuxt.js project.
Element and attribute were added, I expected, but @change event never happen in added element.
My code like below.

<template>
 <div class="addHere">added input element here</div>
</temaplate>
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'

@Component({ components: {} })
export default class extends Vue {
 mounted() {
    this.$nextTick(() => {
      // make new input element
      let newInput: any = document.createElement('input')
      newInput.type = 'checkbox'
      newInput.id = 'new_checkBox'
      newInput.name = 'new_checkBox'
      newInput.setAttribute('v-on:change', 'myFunc()')
      
      // add input element to div tag
      const parentDiv = document.getElementsByClassName('addHere')
      parentDiv.appendChild(newInput)
     } 
 }
 myFunc() {
    console.log('you selected!')
 }
}

</script>

I want to use vue.js reactive system like input event.
Is it possible to add event after DOM mounted in Vue.js?

Trying to access object in Api array and count length

Trying to access the mythic object and print the length of mythic’s that exist in the account but unsure how to access it as its nested in the array. Api output is below Javascript. Just not sure exactly what I can use to get its length as I used json.mythic.length and that did not work. And Thank you very much to anyone who is able to help me with this problem.

function MyFunction(e) {

      e.preventDefault();
      var username = document.getElementById("username").value
      document.getElementById("search").innerHTML = username;
      
      

const data = {
    username, limit: 3000, offset: 0, rarities: [], markers: [], onSale: "", search: "" }
      
fetch("https://prod-eternal-backend.onrender.com/api/v1/moment/list" ,{
     
   
    method: "POST",
     
    
    body: JSON.stringify(data),
     
    headers: {
        "Content-type": "application/json; charset=UTF-8"
    }

})

 

.then(response => {
    return response.json();
})
 

.then(json => {

    

    console.log(json);
    document.getElementById("moments").innerHTML ="Total Moments = " +  json.moments.length;
    var mythics = json.mythic.length * 50;
    document.getElementById("gamer").innerHTML ="Gamer Score = " +  mythics;
    
})
}

{
    "moments": [
        {
            "id": 114375,
            "playId": 536,
            "setId": 16,
            "serialNumber": 4,
            "username": "pattonh84",
            "userId": 1230,
            "userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
            "influencer": "YuggieTV",
            "influencerId": "YuggieTV",
            "influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
            "playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
            "rarity": "mythic",
            "createdAt": "2021-10-25T00:11:54.734962Z",
            "setName": "Flow State",
            "circulationCount": 30,
            "title": "How Strong Could It Be?",
            "imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
            "packName": "Flow State",
            "clipDate": "2021-09-26T02:55:28Z",
            "tags": [
                "funny"
            ],
            "description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
            "game": "IRL",
            "twitter": "yuggietv",
            "staked": false,
            "autographStatus": "false",
            "discordUtility": false,
            "markers": null
        },
        {
            "id": 108262,
            "playId": 565,
            "setId": 16,
            "serialNumber": 1,
            "username": "pattonh84",
            "userId": 1230,
            "userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
            "influencer": "Amouranth",
            "influencerId": "Amouranth",
            "influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/Amouranth.jpg",
            "playbackId": "101L8XUOTCKkJW3USj6rtiJm5k4iTAwTIMqcxfPsr8QA",
            "rarity": "mythic",
            "createdAt": "2021-10-22T17:07:38.357172Z",
            "setName": "Flow State",
            "circulationCount": 30,
            "title": "Mare Awareness",
            "imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/amouranth+pretending+to+be+a+horse.png",
            "packName": "Flow State",
            "clipDate": "2021-09-26T04:21:46Z",
            "tags": [
                "funny"
            ],
            "description": "Now a popular gif, this clip showcases a horse performance complete with galloping and internal monalogue.",
            "game": "Just Chatting",
            "twitter": "Amouranth",
            "staked": false,
            "autographStatus": "pending",
            "autographRequestId": 2071,
            "discordUtility": false,
            "markers": null
        },
        {
            "id": 114393,
            "playId": 536,
            "setId": 16,
            "serialNumber": 22,
            "username": "pattonh84",
            "userId": 1230,
            "userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
            "influencer": "YuggieTV",
            "influencerId": "YuggieTV",
            "influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
            "playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
            "rarity": "mythic",
            "createdAt": "2021-10-22T03:35:24.934307Z",
            "setName": "Flow State",
            "forSale": true,
            "circulationCount": 30,
            "price": 200,
            "title": "How Strong Could It Be?",
            "imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
            "packName": "Flow State",
            "clipDate": "2021-09-26T02:55:28Z",
            "tags": [
                "funny"
            ],
            "description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
            "game": "IRL",
            "twitter": "yuggietv",
            "staked": false,
            "autographStatus": "false",
            "discordUtility": false,
            "productId": 67358,
            "markers": null
        }
    ],
    "totalMoments": 3
}