Why is my XML not being Formatted Properly?

I have been handed a chunk of code from a developer that no longer works for us, and I am new to the regex game so to speak, so apologies if the answer seems simple.

the goal is to format an XML response into something that is readable and here is the code I have been presented with:

formatXml: function (xml) {
    if (xml.indexOf('<') == -1) {
        return xml;
    }

    //remove all white spaces
    xml = xml.replace(/>s+|s+</g, function (m) {
        return m.trim();
    });

    // remove extra variables
    xml = xml.substring(xml.indexOf('<'), (xml.lastIndexOf('>') + 1));

    var formatted = '';
    var reg = /(>)(<)(/*)/g;
    xml = xml.replace(reg, '$1rn$2$3');
    var pad = 0;
    jQuery.each(xml.split('rn'), function (index, node) {
        var indent = 0;
        if (node.match(/.+</w[^>]*>$/)) {
            indent = 0;
        } else if (node.match(/^</w/)) {
            if (pad != 0) {
                pad -= 1;
            }
        } else if (node.match(/^<w[^>]*[^/]>.*$/)) {
            indent = 1;
        } else {
            indent = 0;
        }

        var padding = '';
        for (var i = 0; i < pad; i++) {
            padding += '      ';
        }

        formatted += padding + node + 'rn';
        pad += indent;
    });

    return formatted;
}

The xml that is sent into this looks something like the following portion:

    "\u003cns3:oadrPayload\n\t\t\t\t\txmlns\u003d\"http://www.w3.org/2000/09/xmldsig#\" \n\t\t\t\t\txmlns:ns2\u003d\"http://docs.oasis-open.org/ns/energyinterop/201110\" \n\t\t\t\t\txmlns:ns3\u003d\"http://openadr.org/oadr-2.0b/2012/07\" \n\t\t\t\t\txmlns:ns4\u003d\"http://docs.oasis-open.org/ns/energyinterop/201110/payloads\" \n\t\t\t\t\txmlns:ns5\u003d\"urn:ietf:params:xml:ns:icalendar-2.0\" \n\t\t\t\t\txmlns:ns6\u003d\"urn:ietf:params:xml:ns:icalendar-2.0:stream\" xmlns:ns7\u003d\"http://www.w3.org/2005/Atom\" \n\t\t\t\t\txmlns:ns8\u003d\"http://docs.oasis-open.org/ns/emix/2011/06/power\" \n\t\t\t\t\txmlns:ns9\u003d\"http://www.opengis.net/gml/3.2\" \n\t\t\t\t\txmlns:ns10\u003d\"http://docs.oasis-open.org/ns/emix/2011/06\" \n\t\t\t\t\txmlns:ns11\u003d\"http://docs.oasis-open.org/ns/emix/2011/06/siscale\" \n\t\t\t\t\txmlns:ns12\u003d\"http://www.w3.org/2009/xmldsig11#\" \n\t\t\t\t\txmlns:ns13\u003d\"http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties\" \n\t\t\t\t\txmlns:ns14\u003d\"urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07\"\u003e\n\t\t\t\t\t\u003cns3:oadrSignedObject\u003e\n\t\t\t\t\t\t\u003cns3:oadrResponse ns2:schemaVersion\u003d\"2.0b\"\u003e\n\t\t\t\t\t\t\t\u003cns2:eiResponse\u003e\n\t\t\t\t\t\t\t\t\u003cns2:responseCode\u003e200\u003c/ns2:responseCode\u003e\n\t\t\t\t\t\t\t\t\u003cns2:responseDescription\u003eOK\u003c/ns2:responseDescription\u003e\n\t\t\t\t\t\t\t\t\u003cns4:requestID\u003e123456789abc\u003c/ns4:requestID\u003e\n\t\t\t\t\t\t\t\u003c/ns2:eiResponse\u003e\n\t\t\t\t\t\t\u003c/ns3:oadrResponse\u003e\n\t\t\t\t\t\u003c/ns3:oadrSignedObject\u003e\n\t\t\t\t\u003c/ns3:oadrPayload\u003e"

and what is being returned is this:

    "u003cns3:oadrPayloadntttttxmlnsu003d"http://www.w3.org/2000/09/xmldsig#" ntttttxmlns:ns2u003d"http://docs.oasis-open.org/ns/energyinterop/201110" ntttttxmlns:ns3u003d"http://openadr.org/oadr-2.0b/2012/07" ntttttxmlns:ns4u003d"http://docs.oasis-open.org/ns/energyinterop/201110/payloads" ntttttxmlns:ns5u003d"urn:ietf:params:xml:ns:icalendar-2.0" ntttttxmlns:ns6u003d"urn:ietf:params:xml:ns:icalendar-2.0:stream" xmlns:ns7u003d"http://www.w3.org/2005/Atom" ntttttxmlns:ns8u003d"http://docs.oasis-open.org/ns/emix/2011/06/power" ntttttxmlns:ns9u003d"http://www.opengis.net/gml/3.2" ntttttxmlns:ns10u003d"http://docs.oasis-open.org/ns/emix/2011/06" ntttttxmlns:ns11u003d"http://docs.oasis-open.org/ns/emix/2011/06/siscale" ntttttxmlns:ns12u003d"http://www.w3.org/2009/xmldsig11#" ntttttxmlns:ns13u003d"http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties" ntttttxmlns:ns14u003d"urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07"u003entttttu003cns3:oadrSignedObjectu003enttttttu003cns3:oadrResponse ns2:schemaVersionu003d"2.0b"u003entttttttu003cns2:eiResponseu003enttttttttu003cns2:responseCodeu003e200u003c/ns2:responseCodeu003enttttttttu003cns2:responseDescriptionu003eOKu003c/ns2:responseDescriptionu003enttttttttu003cns4:requestIDu003e123456789abcu003c/ns4:requestIDu003entttttttu003c/ns2:eiResponseu003enttttttu003c/ns3:oadrResponseu003entttttu003c/ns3:oadrSignedObjectu003enttttu003c/ns3:oadrPayloadu003e"

But it should be this:

    "<ns3:oadrPayload
                xmlns="http://www.w3.org/2000/09/xmldsig#" 
                xmlns:ns2="http://docs.oasis-open.org/ns/energyinterop/201110" 
                xmlns:ns3="http://openadr.org/oadr-2.0b/2012/07" 
                xmlns:ns4="http://docs.oasis-open.org/ns/energyinterop/201110/payloads" 
                xmlns:ns5="urn:ietf:params:xml:ns:icalendar-2.0" 
                xmlns:ns6="urn:ietf:params:xml:ns:icalendar-2.0:stream" xmlns:ns7="http://www.w3.org/2005/Atom" 
                xmlns:ns8="http://docs.oasis-open.org/ns/emix/2011/06/power" 
                xmlns:ns9="http://www.opengis.net/gml/3.2" 
                xmlns:ns10="http://docs.oasis-open.org/ns/emix/2011/06" 
                xmlns:ns11="http://docs.oasis-open.org/ns/emix/2011/06/siscale" 
                xmlns:ns12="http://www.w3.org/2009/xmldsig11#" 
                xmlns:ns13="http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties" 
                xmlns:ns14="urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07">
                <ns3:oadrSignedObject>
                    <ns3:oadrResponse ns2:schemaVersion="2.0b">
                        <ns2:eiResponse>
                            <ns2:responseCode>200</ns2:responseCode>
                                <ns2:responseDescription>OK</ns2:responseDescription>
                            <ns4:requestID>123456789abc</ns4:requestID>
                        </ns2:eiResponse>
                    </ns3:oadrResponse>
                </ns3:oadrSignedObject>
            </ns3:oadrPayload>"

Why is it that the regex in formatXml doesn’t remove all of the escaped characters and the “” characters?
Also, what can I add in to this to be able to replace the u003d with =, u003c with <, and u003e with >?

Search database stored in .txt file format?

  • Solutions I could think of using Python and Pandas to get the records out and store them Postgres. Then search the database. That would be ideal.

  • Another would be to use javascript to search the text data records without extracting them.
    Not a best practice.

Which brings me to my question: Is there a clean way to extract databases stored in text files using Python?

How to create a Generic CRUD service in Nodejs via TypeORM

I am attempting to create a generic service that should take a ‘given’ Entity to perform basic CRUD operations.

Thus far, I have tried:

export type UserEntity<E> = { new (): E } | Function;

class AuthenticationService<E> {
  private userEntity: UserEntity<E>;

  constructor(userEntity: UserEntity<E>) {
    this.userEntity = userEntity;
  }

  async login(email: string, password: string) {
    // const user = await getRepository(this.userEntity).findOneOrFail({ email });
    const user = await this.userEntity?.findOneOrFail({ email });

    const validPassword = argon2.verify(user?.password, password);
    if (!validPassword) {
      throw new ErrorHandler(401, ErrorMessage.INVALID_EMAIL_PASSWORD);
    }

    const accessToken = JWTHelpers.generateToken(user, {
      secret: config.ACCESS_TOKEN_SECRET,
      expiry: '300s',
    });

    const refreshToken = JWTHelpers.generateToken(user, {
      secret: config.REFRESH_TOKEN_SECRET,
      expiry: '1y',
    });

    user.tokens = user.tokens.concat(refreshToken);
    await user.save();

    Reflect.deleteProperty(user, 'password');

    return { accessToken, refreshToken };
  }

This approach doesn’t seem to work and as a result, compiler throws various types of errors – for instance:

  1. Property 'findOneOrFail' does not exist on type 'UserEntity<E>'. Property 'findOneOrFail' does not exist on type 'Function'.

    Which is thrown from this declaration: const user: E = await this.userEntity?.findOneOrFail({ email });

  2. Property 'password' does not exist on type 'NonNullable<E>'.
    thrown at: const validPassword = argon2.verify(user?.password, password);

I am very open to suggestions on how to best approach / fix these issues.

Thanks in advance.

How to make function work only for one button? Bootstrap-5 scroll to modals bottom

What I want to achieve is to create two buttons:
1: that opens modal window
2: opens same modal and scrolls to bottom

code:


$('#menu-item-6706').on('click', function (){

    $('#exampleModal').on('shown.bs.modal', function (event) {

        
        $("#exampleModal .modal-body").animate({ scrollTop: $('#exampleModal .modal-body').prop("scrollHeight")}, 'slow');
        
        });

});

Here is full jsfiddle snippet: https://jsfiddle.net/mkx2auhj/1/

Script is almost working:

If you trigger for the the first time “launch demo modal” it opens modal.
If you trigger “Contact” it opens modal and scrolls to bottom. So it’s correct.

The problem is if you hit “launch demo modal” again it scrolls to bottom again, which is not desirable. I want it to open standard modal like the first time.

`Duplex.from()` throws `The “iterable” argument must be an instance of Iterable. Received an instance of Object`

Im highly confused. The Duplex.from() method can take a object as src and creates fromt he object properties readable & writable a duplex stream:

converts readable and writable into Stream and then combines them into Duplex where the Duplex will write to the writable and read from the readable.

Why does my example not work?

const { PassThrough, Duplex } = require("stream");


const loopback = new PassThrough();


const duplex = Duplex.from({
    writable: loopback,
    readable: loopback
});


duplex.on("data", (chunk) => {
    console.log("Data on duplex", chunk)
});


duplex.write("Hello World");

My expected outcome is that the a duplex stream is created, and if so, that outputs the same i give as input. (Same as “echo”, or plain passthrough stream)

Error message:

[nodemon] starting `node index.js`
internal/streams/from.js:32
    throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "iterable" argument must be an instance of Iterable. Received an instance of Object
    at new NodeError (internal/errors.js:322:7)
    at from (internal/streams/from.js:32:11)
    at Function.Readable.from (internal/streams/readable.js:1368:10)
    at Object.<anonymous> (/home/marc/projects/test-stream/index.js:7:23)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'ERR_INVALID_ARG_TYPE'
}

Can some one explain to my why i cant create a duplex stream from the a object?

Im a bit lost, since the docs say you can pass a object as argument, but the error message says “must be an instance of Iterable”. As far as i know, a object is iterable. So whats the problem here?

Reactjs change state (color) onMouseDown

CONTEXT: I have this matrix which is mainly made of some instances of a react component i’ve created earlier called “Cell”. Each time a cell is clicked it changes it’s state.color to red.

Problem: Looking for an approach to turn them red onMouseDown ( as you’re making a square translucent selection in windows explorer) besides onClick

Cell.js :

import * as React from 'react';

class Cell extends React.Component {
    state = {
        color: '#bbdefb',
    };

    onChange = () => {
        this.setState({color: 'red'});
    };

    render() {
        return (
            <div
                style={{
                    backgroundColor: this.state.color,
                    display: 'inline-block',
                    width: 20,
                    height: 20,
                    opacity: '60%',
                    outlineStyle: 'solid',
                    inlineStyle: 'solid',
                    outlineWidth: '1px',
                    inlineWidth: '1px',
                    outlineColor: '#1a237e',
                }}
                onClick={this.onChange}
            />
        );
    }
}

export default Cell;

Main.js :

import {Box} from '@mui/material';
import * as React from 'react';
import MathGrid from '../../core/Components/MathGrid/MathGrid';
import Cell from './Cell';
// =====================================================================================================================
//  D E C L A R A T I O N S
// =====================================================================================================================
const ROWS = 7;
const COLUMNS = 10;
const PADDING = 8;
const SX = {
    root: {
        width: '100%',
        height: '100%',
    },

    footer: {
        position: 'absolute',
        backgroundColor: 'red',
        display: 'flex',
        left: PADDING,
        top: '70%',
        right: PADDING,
        height: '100px',
    },
    counter: {
        position: 'absolute',
        top: '50%',
        left: '50%',
    },

    matrix: {
        position: 'absolute',
        left: PADDING,
        top: 0,
        right: PADDING,
        bottom: PADDING,
    },
    math1: {
        height: '100%',
        width: '100%',
        backgroundPosition: 'calc(50% + 10px) calc(50% + 10px)',
        pointerEvents: 'none',
    },
};

// =====================================================================================================================
//  C O M P O N E N T
// =====================================================================================================================

const generateMatrix = () => {
    return [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ];
};

class Main extends React.PureComponent {
    state = {matrix: generateMatrix()};
    render() {
        const matrix = this.state.matrix;
        const rows = [];
        for (let i = 0; i < matrix.length; i++) {
            for (let j = 1; j < matrix.length / 2; j++) {
                if (i > j) {
                    rows.push(this.renderRow(matrix[i], i));
                }
            }
        }
        return (
            <Box sx={SX.root}>
                <Box sx={SX.matrix}>{rows}</Box>
            </Box>
        );
    }

    // -----------------------------------------------------------------------------------------------------------------
    //  I N T E R N A L
    // -----------------------------------------------------------------------------------------------------------------

    renderRow = (row, index) => {
        console.log(row);
        const cells = [];
        for (let i = 0; i < row.length; i++) {
            cells.push(<Cell key={i} />);
        }
        return <Box key={index}>{cells}</Box>;
    };
}

// =====================================================================================================================
//  E X P O R T
// =====================================================================================================================
export default Main;

Can’t get For loop to execute more than once

I have several links on my page and a function that generates the preview of each one like this:

Its supposed to loop and generate the preview for each link but it only does it one. Why is that?

function parselinks() {
 var links = document.getElementsByClassName('linkprev');
 for(var link of links) {
  if(link.innerHTML =='') {
    var data = {key: 'fe2964d7c80ef2b8f6ba046ae9e8c0a5', q: link.getAttribute('href') }
    fetch('https://api.linkpreview.net', {
     method: 'POST',
     mode: 'cors',
     body: JSON.stringify(data),
    }).then(res => res.json()).then(response => {
     var linktitle = response.title;
     var linkdesc = response.description;
     var linkimg = response.image;
     link.innerHTML = `
      <span><img src="${linkimg}" alt=""></span>
      <h2>${linktitle}</h2>
      <br>
      <p>${linkdesc}</p>
     `;
    })
  }
 }
}

parselinks();
img {width:100px;}
span {
    float: left;
}
span, h2, p {
    font-size: 15px;
    line-height: 80%;
}
<a href="https://yahoo.com" class="linkprev"></a>
<a href="https://facebook.com" class="linkprev"></a>
<a href="https://twitter.com" class="linkprev"></a>
<a href="https://instagram.com" class="linkprev"></a>

How can I iterate over an element in an array but not move from the index until a condition is fulfill?

Hi fam happy Valentine’s.
I’m not looking for a code solution but some insights about how could I go about iterating over an array let’s call it array = [1, 1, 1], and not moving to the next element in the array until a condition is fulfilled. For example I want to start at index 0 and only go to the next index (1) after the value of such index is (modified/changed) to be greater than the value of the index before it. At 0 index we have the value 1, I want before moving to index 1 to change the value of index 1 to be greater then the value of index 0. Something like this if we have array = [1, 1, 1] I want to iterate over the array, start at 0 index. Compare if the value of 0 index is greater or equal than the value of index 1 (the next index) If so than add 1 to the value of index 1 until that value is greater than the value of index 0. First iteration we get array = [1, 2, 1].
Next iteration we get array = [1, 2, 3].

At this point I have tried to iterate over the array with a for loop grab each element, compare and add 1 to the element but when I get to the last element it does not add anything since I am at the end of the array and there is no item to loop over. I get array = [1, 2, 2] Please help fam. This is what I have so far.

     // array 
     const array = [1, 1, 1]
    
    // iterating over array
    for (let i = 0; i < array.length; i++) {
        // compare
        if (array[i] >= array[i + 1]) {
            // increase next number by 1
            array[i + 1] += 1
        }
    }

How to display nested leafs in a Chart.js Treemap?

I want to display data in as a nested treemap using chartjs-chart-treemap.

Everything works fine with flat / single-depth data, but I am having trouble understanding how to make a hierarchical structure work.

I’ve studied the examples but they’ve not given me any clear insight.

Simplified, the data I have is:

  • A (50% through children)
    • C (25% through children)
      • C1 (12.5% through children)
        • C1a: 6.25%
        • C1b: 6.25%
      • C2: 12.5%
    • D: 25%
  • B: 50%

This should give a Treemap similar to this:

    +-------+------+-------+------+
    |  C1a  |      |              |
    +-------+  C2  |              |
    |  C1b  |      |              |
    +-------+------+      B       +
    |              |              |
    |       D      |              |
    |              |              |
    +-------+------+-------+------+

The only thing I have found is to keep adding groups:

[
  {"name": "A",   "l0": "/", "l1": "A", "l2":  "",  "l3":   "", "l4":    "", "value":  0},
  {"name": "B",   "l0": "/", "l1": "B", "l2":  "",  "l3":   "", "l4":    "", "value": 50},
  {"name": "C",   "l0": "/", "l1": "A", "l2": "C",  "l3":   "", "l4":    "", "value":  0},
  {"name": "C1",  "l0": "/", "l1": "A", "l2": "C",  "l3": "C1", "l4":    "", "value":  0},
  {"name": "C1a", "l0": "/", "l1": "A", "l2": "C",  "l3": "C1", "l4": "C1a", "value":  6.25},
  {"name": "C1b", "l0": "/", "l1": "A", "l2": "C",  "l3": "C1", "l4": "C1b", "value":  6.25},
  {"name": "C2",  "l0": "/", "l1": "A", "l2": "C",  "l3": "C2", "l4":    "", "value": 12.5},
  {"name": "D",   "l0": "/", "l1": "A", "l2": "D",  "l3":   "", "l4":    "", "value": 25}
]

But that looks like a hack to me, which would indicate that there is probably a better way to do this?

What I have thus far is:

  const data = [
    {name: "A",   l0: "/", l1: "A", l2:  "",  l3:   "", l4:    "", value:  0},
    {name: "B",   l0: "/", l1: "B", l2:  "",  l3:   "", l4:    "", value: 50},
    {name: "C",   l0: "/", l1: "A", l2: "C",  l3:   "", l4:    "", value:  0},
    {name: "C1",  l0: "/", l1: "A", l2: "C",  l3: "C1", l4:    "", value:  0},
    {name: "C1a", l0: "/", l1: "A", l2: "C",  l3: "C1", l4: "C1a", value:  6.25},
    {name: "C1b", l0: "/", l1: "A", l2: "C",  l3: "C1", l4: "C1b", value:  6.25},
    {name: "C2",  l0: "/", l1: "A", l2: "C",  l3: "C2", l4:    "", value: 12.5},
    {name: "D",   l0: "/", l1: "A", l2: "D",  l3:   "", l4:    "", value: 25},
  ];

  const ctx = document.querySelector('canvas').getContext("2d");

  let config = {
    type: 'treemap',
    data: {
      datasets: [{
        tree: data, key: 'value',
        groups: ['l0', 'l1', 'l2', 'l3', 'l4', 'name'],
      }]
    },
  };

  new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-chart-treemap.min.js"></script>

<canvas></canvas>

Is there a better way than just adding groups to achieve nested leafs in the treemap?

how to find array element using auto generated id in mongodb

currently, I am struggling with how the MongoDB document system works. I want to fetch array elements with an auto-generated id but how to fetch that specific data that I don’t know.

my current schema is

const ItemPricesSchema = new mongoose.Schema({
    _id : {
        type: String
    },
    ItemsPrices: {
        type: [{
            barcode : {
                type: String
            },
            itemName : {
                type: String
            },
            price : {
                type: String
            }
        }]
    }
});

current data is stored in this way

{
    "_id": "[email protected]",
    "ItemsPrices": [
        {
            "barcode": "345345",
            "itemName": "maggie",
            "price": "45",
            "_id": "620a971e11120abbde5f4c3a"
        },
        {
            "barcode": "356345",
            "itemName": "monster",
            "price": "70",
            "_id": "620a971e11120abbde5f4c3b"
        }
    ],
    "__v": 0
}

what I want to achieve is that I want to find array elements through ids

if I want a specific array element with id “620a971e11120abbde5f4c3b” what should I do??
I have tried $unwind , $in, $match…

the result should be like

{
    "_id": "[email protected]",
    "ItemsPrices": [
        {
            "barcode": "356345",
            "itemName": "monster",
            "price": "70",
            "_id": "620a971e11120abbde5f4c3b"
        }
    ],
    "__v": 0
}

Split array of objects into new array or objects based on given value

I have an array of objects that look something like this;

value = [{id:1, count:50},{id:1, count:25}]

I need below three senario as below.
scenario :- 1

result1 = [
  [ { id: 1, qty: 25 } ],
  [ { id: 1, qty: 25 } ],
  [ { id: 2, qty: 25 } ]
]

scenario:- 2

  result2 = [ [ { id: 1, qty: 50 }, { id: 2, qty: 25 } ] ]

scenario:-3

[ [ { id: 1, qty: 50 }, { id: 2, qty: 15 } ], [ { id: 2, qty: 10 }] ]

I have resolved scenario 1 and scenario 2, however getting logic issues in scenario 3.

please see below JS code

let temp = 0;
        let arr = [];
        let result = [];
        let receive_list = [
            { id: 1, qty: 50 },
            { id: 2, qty: 25 },
        ]
        const packing_weight = 65;
            receive_list.forEach(item => {
            let availableQty = item.qty;//50
            while (availableQty > 0) {
                if (availableQty >  packing_weight) {
                    arr.push({ id: item.id, qty: packing_weight });
                    availableQty = availableQty - packing_weight; //25
                    temp += packing_weight;
                }
                else {
                    arr.push({ id: item.id, qty: availableQty });
                    temp += availableQty;
                    availableQty = 0;
                }
                if(temp === packing_weight){
                    result.push(arr);
                    temp = 0;
                    arr = [];
                }
            }
        })

I need below result which I am getting empty array result = [] instead of below result [ [ { id: 1, qty: 50 }, { id: 2, qty: 15 } ], [ { id: 2, qty: 10 }] ]

Javascript regex exec vs match

Ignoring the g flag, are exec and match the same thing but in reverse order — i.e., inverses?

const str = "Hello";
const reg = /he/i;
console.log(reg.exec(str));
console.log(str.match(reg));
console.log(JSON.stringify(reg.exec(str)) === JSON.stringify(str.match(reg)));

Or, minus ordering and g, are they ever used in different ways and/or have different characteristics?

Uncaught Error: Couldn’t find a style target. This probably means that the value for the ‘insert’ parameter is invalid

I am working on a React project. Whenever I log out from the system, I get this error in the console.

injectStylesIntoStyleTag.js:114 Uncaught Error: Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.
    at insertStyleElement (injectStylesIntoStyleTag.js:114:1)
    at addStyle (injectStylesIntoStyleTag.js:208:1)
    at modulesToDom (injectStylesIntoStyleTag.js:81:1)
    at module.exports (injectStylesIntoStyleTag.js:239:1)
    at Module../common/components/auth/login-button.css (login-button.css?987d:9:17)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Module../common/components/auth/login-button.tsx (app-header.tsx:65:3)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <noscript id="jss-insertion-point"></noscript>
    <noscript id="static-css-insertion-point"></noscript>
    <noscript id="style-loader-insertion-point"></noscript>
    <script src="/env-config.js"></script> 
  </head>

  <body>
    <div id="root"></div>
     
  </body>
</html>

how to get an image with text on paste event

I am having a problem getting an image that has been pasted and copied with the user along with some text, I made my paste function as follows.

const PasteFunction = (event) => {
  let paste = (event.clipboardData || window.clipboardData).getData("text");
  if (
    paste.includes("svg") ||
    paste.includes("jpg") ||
    paste.includes("jpeg") ||
    paste.includes("gif") ||
    paste.includes("pdf") ||
    paste.includes("tiff") ||
    paste.includes("raw") ||
    paste.includes("png") ||
    paste === "" ||
    paste === undefined ||
    paste === null
  ) {
    event.preventDefault();
    return;
  }
  var text = (event.originalEvent || event).clipboardData.getData(
    "text/html"
  );
  document.execCommand("insertHTML", true, text);
};

what currently happens is that, if the user copies only the image, I prevent it from being pasted in my richContentText, but if the user decides to copy an image with a portion of text, this code that I currently have cannot recognize that this text has an image, and lets it pass automatically… which if something that im trying to prevent.

So as long as there is text, inside the clipboardData it will be pasting it even if it has an image or not in that data… does anyone have an idea how I can find this out?

example I would like to prevent the user from pasting the content of the image I show below if he decides to copy it along with the image

enter image description here