img.src gives different URL than the one shown in inspector

When I was inspecting an webpage (namely, any web page from Wayback Machine), I found that any <img> element’s .src when you used in JS snippet (or console) would be the original URL, while in inspector it shows the one with archive.org prefix:

enter image description here

(Same goes for Firefox.)

How does this happen? I don’t even know this is possible.

Furthermore, how can you get the one that is shown in inspector?

TypeScript – using recursive generics properly

I am trying to use recursive generics in a way I can get a lot of help from editor.

Here is an example:

interface ServiceEndpointNode {
  self: string;
  context?: Record<string, ServiceEndpointNode>
}

const ServiceEndpoints: ServiceEndpointNode = {
  self: 'BASE_URL',
  context: {
    songs: {
      self: 'GET_SONGS',
      context: {
        getSong: {
          self: 'GET_SONG',
        },
        getContributors: {
          self: 'GET_CONTRIBUTORS',
        }
      }
    }
  }
}

This works properly and the structure is strict, but I don’t got help from the editor. For example I want help like:

ServiceEndpoints.context.songs.context.getsong.self

But because I only told the typing that the context should be a string I don’t really receiving help about the traversable object. I guess I need to be include some generics or something, but don’t know how to achieve that. 🙁

So I want to have to maintain this strict structure, yet get help from the editor for all the possible routes, keys, etc.

Question in the dom about deleting a specific element [closed]

im making a small comment section and want to add a delete comment feature which pops up a modal to confirm delete or cancel and when i click cancel it just saves the previous parent element like in this picture [1]: https://i.stack.imgur.com/DA4d3.jpg. whenever i click cancel it just keeps adding so i really have hard times figuring this out and i need a bit of direction here. here’s my code [2]: https://i.stack.imgur.com/F7432.jpg

Using a let in a for loop with setTimeout function

If the arguments to functions are passed by value in javascript how come the console.log() below seems to get its input by reference? Shouldn’t each time it is invoked inside setTimeout just the value of i be passed and not its reference?

let i;

for (i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

remove unwanted json value if not present inside the another json object in node js /javascript

let data = getData();
let anotherObj = getAnotherObj();

let res = data.reduce((acc, curr) => {
  if (!acc[curr.system.name]) {
    acc[curr.system.name] = {};
  }

  let detailsObj = {};
  Object.keys(curr.DataDetails).forEach(key => {
    let values = curr.DataDetails[key];

    // special handling to flatten single attribute objects
    if (values.length === undefined || values.length === 0) {
      let keys = Object.keys(values);
      if (keys.length == 1 && typeof values[keys[0]] !== 'object') {
        detailsObj[key] = values[keys[0]];
        return;
      }
    }

    // clone values to output
    detailsObj[key] = !Array.isArray(values) ? Object.assign({}, values) : [...values];

    // find and replace ids
    let ids = jsonpath.query(detailsObj[key], '$..id');
    ids.forEach((id, i) => {
      if (id in anotherObj) {
        if (Array.isArray(detailsObj[key]))
          detailsObj[key].splice(i, 1, anotherObj[id]);
        else
          detailsObj[key] = anotherObj[id];
      }
    });
  });

  acc[curr.system.name][curr.system.id] = {
    title: curr.system.id,
    uid: curr.system.id,
    url: `/${curr.system.name}/${curr.system.id}`,
    ...detailsObj,
  };
  return acc;
}, {});

document.body.insertAdjacentHTML('beforeend', `<pre>${JSON.stringify(res, undefined, 1)}</pre>`);
console.log(res);



function getData() {
  return [{
      system: {
        id: "4gSSbjCFEorYXqrgDIP2FA",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        shortOption: {
          "en-us": "some value"
        },
        mediaFile: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "7kRzyt4PFo",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "2OspeCtNK0s",
            },
          },
        ],
        mediaGalary: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              linkType: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
        
      },
    },
    {
      system: {
        id: "1aBOO8tu3lUsjtICuIbUM5",
        type: "Entry",
        name: "User"
      },
      DataDetails: {
        short: {
          "en-us": "details of shorts"
        },
        shortSlugOption: {
          "hi-In": "options"
        },
        booleanField: {
          kl: "true"
        },
      },
    },
    {
      system: {
        id: "2pOUGnI1oRD7nsrYs600HA",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: [{
            sys: {
              type: "Link",
              link: "Entry",
              id: "66rzYr2BpWL",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Entry",
              id: "1VTBHdLTdSW",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "66rzYr2BpWL1VTBHdLTdSW",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        oneReference: {
          sys: {
            type: "Link",
            linkType: "Asset",
            id: "h2cPiuU9jIz",
          },
        },
        multiReference: [{
            sys: {
              type: "Link",
              link: "Asset",
              id: "gHcw3Z1Ko",
            },
          },
          {
            sys: {
              type: "Link",
              link: "Asset",
              id: "h2cPiuU9jIz",
            },
          },
        ],
      },
    },
    {
      system: {
        id: "cIb5mqEBRWDD6hrNmFmFE",
        type: "Entry",
        name: "new"
      },
      DataDetails: {
        testingNewValue: {
          "hi-IN": "jksdsdo"
        }
      },
    },
    {
      system: {
        id: "7kRzyt4PFrX13gHcw3Z1Ko",
        type: "Entry",
        name: "Dummy"
      },
      DataDetails: {
        testingNewValue: {
          "en-us": "kknksdo"
        }
      },
    }
  ];
}


function getAnotherObj() {
  return {
    "h2cPiuU9jIz": {
      status: true,
      tag: [],
      filename: "wallpapers-6.jpg",
      is_dir: false,
      parent_uid: null,
    },
    
    
    "2OspeCtNK0s": {
      status: true,
      tag: [],
      filename: "mediaFile1.jpg",
      is_dir: false,
      parent_uid: null,
    },
    "66rzYr2BpWL": {
      type: 'entry',
      tag: [],
      entry_details: "this is first entry ***",
      is_secret: false,
    },
    "1VTBHdLTdSW": {
      type: 'entry',
      tag: [],
      entry_details: "some other entry ***",
      is_secret: true,
    },
  };
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jsonpath.min.js"></script>

I am trying to put two object data in one output but by reading the link which is Asset

but in the multiple Array list the output is displaying as I want but the problem is while comparing the output from the anotherObj if the Id with that Obj is present it showing me the expected value which is data Asset replaced by the anotherObj

But I want to remove the value which is not matched with the object which are present inside the anotherObj

for eg:-

"mediaGalary": [
        {
          "sys": {
            "type": "Link",
            "link": "Asset",
            "id": "gHcw3Z1Ko"
          }
        },
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]

and

"mediaFile": [
    {
     "sys": {
      "type": "Link",
      "link": "Asset",
      "id": "7kRzyt4PFo"
     }
    },
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

look like this here “id”: “gHcw3Z1Ko” is not present inside the anotherObj so I want to remove it but don’t know how to remove it

as my expected output is like this

"mediaGalary": [
        {
          /**id:c**/
          "status": true,
          "tag": [],
          "filename": "wallpapers-6.jpg",
          "is_dir": false,
          "parent_uid": null
        }
      ]
and


"mediaFile": [
    {
     "status": true,
     "tag": [],
     "filename": "mediaFile1.jpg",
     "is_dir": false,
     "parent_uid": null
    }
   ]

if the given id is not present inside the anotherObj or any other id which are not present inside the anotherObj

Accessing specific values in a nested object

I have a nested object which looks like the below

{
    "Place One": {
        primary: "#000000",
        secondary: "#97233f",
        coordinates: {
            lat: 49.5013,
            lon: 87.0622
        }
    },
    "Place Two": {
        primary: "#000000",
        secondary: "#a71930",
        coordinates: {
            lat: 40.6013,
            lon: 81.0622
        }
    },
    "Place Three": {
        primary: "#9e7c0c",
        secondary: "#241773",
        coordinates: {
            lat: 40.5033,
            lon: 84.0622
        }
    }
}

I am trying to get access to each of the lat /lon variables to pass to a Leaflet React component

 <Marker
          key={park.properties.PARK_ID}
          position={[
            ***the lat***,
            ***the lon***
          ]}
        
        />

I’ve tried the below:

Object.fromEntries(
                Object.entries(teams).map(([key, { coordinates }]) => <Marker
                    position={[
                        coordinates.lat,
                        coordinates.lon
                    ]} />
                )

but cannot access the values.

can anyone please advise the best way to do this?

Styling background with ChartJs and React

I want to create a Line chart in React by using the chartJS library (‘react-chartjs-2’)

This is what I want to achieve, like background with some opacity belowe the line:

enter image description here

Code:

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import faker from 'faker';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Line Chart',
    },
  },
};

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: '#000000',
      fill: {
        target: 'origin',
        above: 'rgb(255, 0, 0)',   // Area will be red above the origin
        below: '#000000'    // And blue below the origin
      }
    },
    {
      label: 'Dataset 2',
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: 'rgb(53, 162, 235)',
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

export function App() {
  return <Line options={options} data={data} />;
}



Is it possible that this library doesn’t support it?

Maybe is there something that I should change?

Thanks a lot for any help

Best!

Animate box-shadow with JQuery

BoxShadow not working

$(document).ready(function () {
let r, g, b, rBorder, gBorder, bBorder, top, left;

setInterval(function () {
    r = Math.round(Math.random() * 255);
    g = Math.round(Math.random() * 255);
    b = Math.round(Math.random() * 255);
    rBorder = Math.round(Math.random() * 255);
    gBorder = Math.round(Math.random() * 255);
    bBorder = Math.round(Math.random() * 255);
    top = Math.round(Math.random() * window.innerHeight);
    left = Math.round(Math.random() * window.innerWidth);

    $('.element')
        .css({
            border: '0px solid #fff',
            boxShadow: `0px  green`
        })
        .animate({
            backgroundColor: `rgb(${r}, ${g}, ${b})`,
            borderWidth: '2px',
            borderColor: `rgb(${rBorder}, ${gBorder}, ${bBorder})`,
            boxShadow: `0px 0px 30px 0px rgb(${r}, ${g}, ${b})`,
            top: top,
            left: left
        }, 2000, 'linear');
});

});

Regex for appending special characters to an array

I am having tough time converting this scenario using regex “[“a”, “b”]” to [“a”, “b”] and [“a”, “b”] to “[“a”, “b”]”

I am able to achieve adding a double Quote before and after the brackets but couldn’t achieve the complete expectation scenario.
Any help and suggestion is much appreciated

how to refresh the html elements with javascript without adding the element repeatedly

I have this code

<input type="button" value="refresh" onclick="refresh()">

<div id="parent-id">
</div>

<script>
function refresh(){
 let h1 = document.createElemet("h1")
 h1.textContent = "Testing..."
 document.querySelector("#parent-id").appendChild(h1);
}
</script>

each time I click on refresh the a new h1 will be added
How can I refresh, without adding a new h1?
I have not only this element, I have a big code of 200 lines but with the same idea.
How can I refresh them without adding them again to the page ?

Is it possible to use something returns from python on Node JS

I need to use JS and also i have a python script that i have to use. With print statement JavaScript can use the python output but my python function returns list and integer so print format not useful for this case. For example i wrote a python script which contains function. But this JS code work with print function.

Python Code

import sys
def function(a,b):
    variable = a+b
    return variable

function(sys.argv[1],sys.argv[2])

JS Code

const express = require('express')
const {spawn} = require('child_process');
const app = express()
const port = 3000
app.get('/', (req, res) => {
 
 var dataToSend;
 // spawn new child process to call the python script
 const python = spawn('python', ['script2.py','num' ,'python']);
 // collect data from script
 python.stdout.on('data', function (data) {
  console.log('Pipe data from python script ...');
  dataToSend = data.toString();
  console.log(dataToSend)
 });
 // in close event we are sure that stream from child process is closed
 python.on('close', (code) => {
 // send data to browser
 res.send(dataToSend)
 });
 
})
app.listen(port, () => console.log(`Example app listening on port 
${port}!`))

Is there a way that use the python function returns use on JS as arg1,arg2,arg3

Component rerendering only after double click

I have a parent component that is passing products down into a subcomponent as state along with the product’s filters. For some reason I have to double click the “filters” in order for the parent component to rerender with the filtered products. I understand because it is running asynchronously it is not updating the state immediately, but how can I force the update and rerender to run as soon as I add a filter without using forceUpdate? Is this where redux would come in to play?

Parent component

    const [products, setProducts] = React.useState(data.pageContext.data);

    const handleCount = () => {
        setCount(count + 24);
    }

    return (
        <div style={{width: "100%"}}> 
        <Header/>
        <div style={{display: "flex", flexDirection: "row", justifyContent: "center"}}>
            <Sidebar 
            products={products}
            setProducts={setProducts}
            baseProducts={data.pageContext.data}
            />
            <div style={{display: "flex", flexDirection: "column"}}>
            <h1 style={{width: "50%"}}>Cast vinyl</h1>
            <h3>Product Count: {products.length}</h3>
            <ProductList>
            {products.slice(0, count).map(product => {
                return (
                    <a href={`/vinyl/${product.data.sku}`}><div>
                        {product.data.field_product_image.length > 0  ? 
                            <ProductImage images={data.data.allFiles} sku={`${product.data.sku}`}/> :
                            <StaticImage src="http://stagingsupply.htm-mbs.com/sites/default/files/default_images/drupalcommerce.png" width={250} alt=""/>}
                             <h3>{product.data.title}</h3>
                                <h5>{product.data.sku}</h5>
                    </div></a>
                    ) 
            })}
            </ProductList>
            <h3 onClick={handleCount}>Load more</h3>
            </div>
        </div>
        </div>
    )

Child Component

const Sidebar = ({ setProducts, baseProducts }) => {
    const [filters, setFilters] = React.useState([]);
    const [click, setClick] = React.useState(false);

    const handleClick = () => {
        setClick(!click);
    }

    const onChange = (e) => {
        if (!filters.includes(e)) {
            setFilters([...filters, e])
        }
        if (filters.length > 0) {
        const filteredProducts = baseProducts.filter(product => filters.includes(product.data.field_product_roll_size));
        setProducts(filteredProducts);
        }
    }

    const clearFilters = () => {
        setFilters([]);
        setProducts(baseProducts);
        setClick(false);
    }

    const rollSize = [...new Set(baseProducts.map(fields => fields.data.field_product_roll_size))]

    return (
        <SidebarContainer>
            <h3>Mbs Sign Supply</h3>
                <ul>Sub Categories</ul>
                    <a href="/vinyls/calendered_vinyl"><li>Calendered Vinyl</li></a>
                    <li>Cast Vinyl</li>
            <h3>Filters</h3>
            {filters.length > 0 ? <button onClick={clearFilters}>Clear Filters</button> : null}
            <li onClick={() => handleClick()}>Roll Size</li>
                {/*map through roll size array*/}
                {/*each size has an onclick function that filters the products array*/}
                {click ? rollSize.sort().map(size => {
                    return (
                        <span style={{display: "flex", flexDirection: "row", alignItems: "center", height: "30px"}}>
                        <Checkbox onClick={() => {onChange(size)}} />
                        <p >{size}</p>
                        </span>
                    )
                }) : null}
            <li>Width</li>

Thanks in advance