how to pass the fetched data to the onclick function in the backticks

I am getting the songs data from the json file

const res = await fetch('./songApi/songs.json')
const fetchedSongs = await res.json()
entlet list = "";
fetchedSongs.map((song) => {
  list += `
    <div class="songitem" style="background:${song.background} ;">
    <img src=${song.coverpath} alt="agar tum sath ho">
    <span class="name">${song.SongName}</span>
    <span class="songlistplay">
    <span class="songTime">${song.time}</span>
    <i class="far fa-play-circle songitemplay" onClick="makeAllplays(${song})" ></i>
    </span>
    </div>`
})

onclick function

   makeAllplays(){}

but i can’t pass the data and i got this ERROR:

     Unexpected identifier (at index.html:1:22)

Is it possible to draw a line chart in chart.js with multiple lines and **multiple lables**

Suppose x1={1,4,7,9} | y1={10,20,35,40} and x2={2,3,6,9} | y2={15,23,30,35}. Now I want to draw a line chart in chart.js for it.

P.S. Scatter chart is not a solution because my website is generating data dynamically so I have to provide data in array only and scatter requires the data in very sophisticated manner.

My simple question is by any way, can we have different x axis points in line chart for different lines??

code for your reference:

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

<script>
var xValues1 = [50,60,70,80,90,100,110,120,130,140,150];
var yValues1 = [7,8,8,9,9,9,10,11,14,14,15];

var xValues2 = [54,64,74,84,94,104,114,124,134,144,154];
var yValues2 = [8,9,9,10,10,10,11,12,15,15,16];

new Chart("myChart", {
  type: "line",
  data: {
    labels: xValues1,
    datasets: [{
      fill: false,
      backgroundColor: "rgba(0,0,255,1.0)",
      borderColor: "rgba(0,0,255,0.1)",
      data: yValues1
    },
    {
      fill: false,
      backgroundColor: "rgba(0,0,255,1.0)",
      borderColor: "rgba(0,0,255,0.1)",
      data: yValues2
    }
    ]
  },
  options: {
    legend: {display: false},
    scales: {
      yAxes: [{ticks: {min: 6, max:16}}],
    }
  }
});
</script>

</body>
</html>

(for yvalues2, I want xvalues2)

Collision detection of 3d objects in p5.js

I am working on a infinite runner game, where 3d objects are involved – A rover and some obstacles, that move on a terrain. The game is made using p5.js WebGL functionality. I have almost completed the game, but the game should end when the rover hits any obstacle. I just want to know if I can detect the collision of both the 3d objects(the rover is a plane, and the obstacle is custom loaded model) and end the game…Simply, I want to know whether collision detection in WebGL is feasible, and if so how?
Please help me out on the same.
Thank you.

mousemove with two layers on top of each other (overlapping)

The closest to my question are: Mapbox gl js – overlapping layers and mouse event handling, Mapbox add popup on hover (layer), close on mouseleave, but keep open on popup hover and How to ignore mouse events on a mapbox layer – but they don’t answer it.

I have two layers, let’s imagine one is for a country, and another is for a city. Both of them a handled like this:

// CountryLayer.js
map.on("mousemove", "country-layer", e => {
   // show info about the country 
   featureProps = e.features[0] // display some notification from the props
   ...

// CityLayer.js
map.on("mousemove", "city-layer", e => {
   // show info about the city
   featureProps = e.features[0] // display some notification from the props
   ...

It’s done in different components. But when I mouseover city-layer mapbox thinks that I’m still “mousemoving” on top of the country-layer as well, so I get two notifications from separate components, where I need only one – in that case from the city-layer cause it’s on top of country-layer.

Handling the mousemove without layerId in one place is gonna be a mess and breaks all the good rules about programming. Creating external “event manager” which will track whether I’m hovering the city and if is so will remove mousemove event from country-layer – is complex. I didn’t find any good alternatives. At least, I would be glad to disable pointer events for a layer like this:

map.on("mousemove", "city-layer", e => {
   map.getLayer("country-layer").setStyle({ "pointer-events": false })
   featureProps = e.features[0]
   ...

or something like this. Is it possible? Is there more adequate way around it?

e.originalEvent.stopPropagation(); does not work

Node.js Returning a value from an async function – Electron

I am creating a project where I need to take a user input – pass it through a function and return the new value to the user – seems simple enough. I am new to async functions and have read everything I possibly can, and can’t works out if there’s a more fundamental issue I am missing. I will show the basic code, and then what I wish to achieve. I believe the issue, is that I am returning back the status of the function rather than the value, but just can’t work it out.

Basic Code:

ipcMain.on('gpt3', (event, args) => {
    async function gpt3(args) {
        generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file.
        event.reply('textRecieve', 'hello world'); // Sends 'Hello World' to the user (ipcRenderer 'textRecieve')
    }
    
    gpt3(args);

})

async function generateResponse(name, text) {
    let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
    let content = "";
    try {
      testshell.on('message', function (message) {
        console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
        return message; // attempting to return the 'Message' from the python file
      });
    } catch (error) {
      console.log("You've f*cked it somewhere my friend");
      console.log(error);
    } 
}

Python Script:

import sys

name = sys.argv[1]
text = sys.argv[2]

print(f'Python File: {name} Text: {text}')
sys.stdout.flush()

Returns: (as expected)

> Executing task: npm run start <


> [email protected] start
> electron .

Python File: james Text: hello world

What I’d Like it to do:

ipcMain.on('gpt3', (event, args) => {
    async function gpt3(args) {
        message = generateResponse('james', 'hello world'); // Takes a user's name & input and recieves a response from a python file, retunring the message to the 'message' variable.
        console.log(message);
        event.reply('textRecieve', 'message would send here'); // Sends the 'Message' to the user (ipcRenderer 'textRecieve')
    }

    gpt3(args);

  })


async function generateResponse(name, text) {
  let testshell = new PythonShell('./python/text_echo.py', { mode: 'text', args: [name, text]});
  let content = ""
  try {
    testshell.on('message', function (message) {
      console.log(message); // prints the output from the python file 'Python File: james Text: hello world'
      return message; // attempting to return the 'Message' from the python file
    });
  } catch (error) {
    console.log("You've f*cked it somewhere my friend")
    console.log(error)
  } 
  return content; // content needs to be message instead due to async nature it returns empty string
}

Returns:

> Executing task: npm run start <


> [email protected] start
> electron .

Promise { '' }
Python File: james Text: hello world

TLDR; I would like to take the ‘message’ generated through ‘generateResponse()’ and pass it through to my ‘event.reply()’. Instead, I am receiving what I believe to be the status of the Promise. Any help would be greatly appreciated. Thanks

How to split string of Arrays into actual Arrays? – javascript

I want to split a string of Arrays into an actual array in Javascript(react).

Original String :

[" 103.116.32.2",1225],[" 163.53.79.51",677],[" 103.116.32.30",651],[" 103.116.32.1",174],[" 10.6.27.6",40],[" 184.26.162.104",36],[" 184.26.162.97",35],[" 10.57.10.88",27],[" 172.16.59.56",24],[" 8.8.4.4",22],[" 103.116.32.26",18],[" 8.8.8.8",17],[" 103.116.32.14",16],[" 192.168.180.5",14],[" 216.239.35.0",10],[" 10.6.24.135",9]

Result I want :
nested array with these values

newArray = [
[" 103.116.32.2",1225], 
[" 163.53.79.51",677], 
[" 103.116.32.30",651] ...etc
];

What I have tried:

I have tried string.split(",") but this doesnt work because there is a comma inbetween the inner arrays. So the results gives newArray = [[” 103.116.32.2″] , [1225] , [” 163.53.79.51″] , [677]]

Advice for lots of data clientside in a browser session

I need some advice.

I’m looking for a way to work with a huge amount of data (800+mb) in the browser. This data should not be persistent. Users upload a csv file which they play with (filter) in the browser before doing anything with it. The columnnames in those csv files can vary wildly.

I was wondering what method to use here. Storing the data in memory in JavaScript variables does not work, as it crashes the page. I’ve been looking at indexedDB, which gives me the opportunity to keep the data in a database and even gives me filtering options. However this system is actually designed to store persistent data for offline use.
Preferably I would like to delete the database when loading a new file, create a new database with it’s own objectstore and fill it with new data. But I found that the database is not deleted as long as I don’t refresh the page and I cannot change it.

My questions: is using indexedDB a viable approach for this specific case? If yes, does anyone any pointers how to use it in this case? Are there other possibilities that I have overlooked?

classList.toggle(“”) is not working and there is no error in the console

I want my link to toggle a class active when it was clicked. Here, in this code alert is working but classList.toggle(“”) is not.

const subMenu = document.querySelectorAll(".sub-menu");
const subNavBar = document.querySelectorAll(".sub-nav-bar");

subMenu.forEach((e1) => {
  e1.addEventListener("click", () => {
    alert("2");
    subNavBar.forEach((e2) => {
      e2.classList.toggle("active");
    });
  });
});

Should the HTML element dispatch `beforeinput` events?

The MDN page for beforeinput clearly states that:

The DOM beforeinput event fires when the value of an <input>, <select>, or <textarea> element is about to be modified

This also seems to be true based on my simple reading of the spec:

Trusted Targets: Element (specifically: control types such as HTMLInputElement, etc.) or any Element with contenteditable attribute enabled

(emphasis mine)

However, no browser seems to implement it. I have checked Chrome, Safari and Firefox.

Am I understanding something incorrectly?

const sel = document.getElementById('pet-select')
sel.addEventListener('beforeinput', () => console.log('beforeinput!'))
sel.addEventListener('input', () => console.log('input!'))
<label for="pet-select">Choose a pet:</label>

<select name="pets" id="pet-select">
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
    <option value="parrot">Parrot</option>
    <option value="spider">Spider</option>
    <option value="goldfish">Goldfish</option>
</select>

Google Chart – Does not expand and does not display data range

The graph I created does not expand to the entire screen and does not show the range (units) at the bottom of the graph.

Here is my code:

google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawLogScales);

function drawLogScales() {
    var data = new google.visualization.DataTable();
    data.addColumn('date', 'X');
    data.addColumn('number', 'Total Entries');
    data.addColumn('number', 'Organic Google');
    data.addColumn('number', 'Google Ads');
    data.addColumn('number', 'Social Media');

    data.addRows([
        [new Date(2021, 0, 1), 0, 0, 0, 0],
        [new Date(2021, 1, 1), 16, 12, 2, 2],
        [new Date(2021, 2, 1), 50, 20, 20, 10],
        [new Date(2021, 3, 1), 100, 70, 15, 15],
        [new Date(2021, 4, 1), 60, 9, 40, 11],
        [new Date(2021, 5, 1), 260, 60, 100, 100],
        [new Date(2021, 6, 1), 500, 300, 100, 200],
        [new Date(2021, 7, 1), 1000, 700, 200, 100],
        [new Date(2021, 8, 1), 250, 220, 30, 0],
        [new Date(2021, 9, 1), 700, 400, 250, 50],
        [new Date(2021, 10, 1), 1300, 700, 400, 200],
        [new Date(2021, 11, 1), 700, 500, 120, 80],
        [new Date(2022, 0, 1), 1400, 1000, 340, 60],
        [new Date(2022, 1, 1), 1936, 903, 1000, 33],
        [new Date(2022, 2, 1), 2100, 1000, 400, 700],
        [new Date(2022, 3, 1), 2345, 1243, 1000, 102],
        [new Date(2022, 4, 1), 2000, 1500, 300, 200],
        [new Date(2022, 5, 1), 890, 300, 90, 500]
    ]);

    var options = {
        height: 500,
        hAxis: {
            title: 'Period',
            viewWindow: {
                min: new Date(2020, 11, 31),
                max: new Date(2022, 5, 3, 1)
            },
            gridlines: {
                count: -1,
                units: {
                    years: { format: ['yyyy'] },
                    months: { format: ['MMM yyyy'] },
                }
            },
            logScale: true
        },
        vAxis: {
            title: 'Entries',
            minValue: 0,
            logScale: false
        },
        colors: ['#2A7AED', '#279846', '#E84133', '#F9BF18']
    };

    var chart = new google.visualization.LineChart(document.getElementById('entries-number'));
    chart.draw(data, options);
}

This is the result:
The result

It’s not clear to me what I’m missing.

  1. Why does the graph not expand to the end?
  2. And why am I not shown the years and the month below the graph?

I would appreciate your assistance.

Pay through Metamask account but mint through central account

I would like my website users to pay for minting using their metamask account, but then when they press the mint button, I want the actual minting to be done via a central Ethereum account.

Before I had a simple website where in the index.html file, I had a react app that ran in the background listening for mint calls (code of App.js attached in the as the second code block).

But I have modified my approach. Now on my website server, I have a node.js app running that listens for Javascript API fetch Posts (see first code block below). The hash value gets sent from other websites via API Post – where all the minting is done in a central Ethereum account.

Now I want my website server to mint from both sources: hash sent from API POST and also from the same website. Now from the front end, I want the users to pay for the minting using their Ethereum account from their metamask wallet. In doing so the mint function in the App.js should be called (as I want to use the account coded in that function) from the front end after the user pays for the minting from his metamask wallet. I am hoping this can be done. Having another react app running may be too much as I don’t want two apps running (one to handle API Posts and one for the React app). Can I somehow make payment through the Metamask wallet and still call the mint function in the App.js?

const web3 = require('web3');
const ethers = require('ethers');
const express = require('express');
const path = require('path');
const LocationNFT = require('./abis/Location.json')
const fromAddress = <address>
const nftAddress = <address>

const app = express();
const port = 3000;    

app.use(express.urlencoded({extended: true}));

app.use(express.json()); 
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/posthash', async function (request, response) {  
  var hashValue = request.body.hash;
  console.log('Received hash: ' + hashValue);   
    
  if (!hashValue) {
        return response.status(400).send({ error:true, message: 'Please provide hash value' });
  } else{   
      const timestamp = Date.now();   
      var time = getTimestamp();
      console.log(time + ' Adding hash:::::', hashValue);
      
      //call the mint function
      var success = await mint(hashValue);    
      console.log('success' + success) ;
      response.send(success); 
  }
      
  var transactionRecord = {
    datetimestamp: time,
    hash: hashValue
  };
   response.json("Hash added to blockchain: " + hashValue);
});

 // mint the nft
async function mint(location) 
{  
    const Provider = require('@truffle/hdwallet-provider');
    const privateKey = <>;     
    let provider = ethers.getDefaultProvider('rinkeby');
    
    //maybe this is not needed
    var fromAddress  = <>;
   
    let wallet = new ethers.Wallet(privateKey, provider);
    let balancePromise = wallet.getBalance();
    console.log('balancePromise: ' + balancePromise + ' balancePromise ' + 
    JSON.stringify(balancePromise));
    balancePromise.then((balance) => {
        console.log('Balance before minting : ' + balance);
    });
    
    let transactionCountPromise = wallet.getTransactionCount();
    transactionCountPromise.then((transactionCount) => {
        console.log('transactionCount: ' + transactionCount);
    }); 

    //console.log ('wallet: ' + JSON.stringify(wallet));
    let nftAddress = <>;
    console.log ('nftAddress: ' + nftAddress);

    try {
          var mainContract = new ethers.Contract(nftAddress, LocationNFT.abi, wallet); 
          console.log("Mining...please wait.");

          if(mainContract) 
            console.log ('mainContract data there: ');          
         
          const nft2 = await mainContract.mintNFT(location)
          return nft2.hash;         

    } catch (e) {
      console.log(e) // This gets executed when process times out in ~30 minutes
    }

} //end of mint function

Before, I had a react app running in the background on my website server. Here is the code from the App.js

//App.js
import React, { Component, useState  } from 'react';
import Web3 from 'web3'
import './App.css';
import Location from '../abis/Location.json'

class App extends Component {
  async componentWillMount() {
    await this.loadWeb3()
    await this.loadBlockchainData()
  }

  async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      await window.ethereum.enable()
    }
    else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider)
    }
    else {
      window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!')
    }
  }

  async loadBlockchainData() {
    const web3 = window.web3
    // Load account
    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })

    const networkId = await web3.eth.net.getId()
    const networkData = Location.networks[networkId]
    if(networkData) {
      const abi = Location.abi
      const address = networkData.address
      const contract = new web3.eth.Contract(abi, address)
      this.setState({ contract })
      const totalSupply = await contract.methods.totalSupply().call()
      this.setState({ totalSupply })
      // Load Colors
      for (var i = 1; i <= totalSupply; i++) {
        const location = await contract.methods.locations(i - 1).call()
        this.setState({
          locations: [...this.state.locations, location]
        })
      }
    } else {
      window.alert('Smart contract not deployed to detected network.')
    }
  }

 // mint the nft
  mint = (location) => {
    this.state.contract.methods.mint(location).send({ from: this.state.account })
    .once('receipt', (receipt) => {
      this.setState({
        locations: [...this.state.locations, location]
      })
    })
  }
  
  constructor(props) {
    super(props)
    this.state = {
      account: '',
      contract: null,
      totalSupply: 0,
      locations: []
    }
  }

  render() {
    return (
      <div>
        <nav className="navbar navbar-dark fixed-top bg-dark flex-md-nowrap p-0 shadow">
          <a className="navbar-brand col-sm-3 col-md-2 mr-0"
            href="http://www.dappuniversity.com/bootcamp"
            target="_blank" rel="noopener noreferrer">
            Location Tokens
          </a>
          <ul className="navbar-nav px-3">
            <li className="nav-item text-nowrap d-none d-sm-none d-sm-block">
              <small className="text-white"><span id="account">{this.state.account}</span></small>
            </li>
          </ul>
        </nav>
        <div className="container-fluid mt-5">
          <div className="row">
            <main role="main" className="col-lg-12 d-flex text-center">
              <div className="content mr-auto ml-auto">
                <h1>Issue Token</h1>
                <form onSubmit={(event) => {
                  event.preventDefault()
                  const location = this.location.value
                  this.mint(location)
                }}>
                  <input type='text' className='form-control mb-1'
                    placeholder='e.g. #FFFFFF' ref={(input) => { this.location = input }}            />
                  <input type='submit' className='btn btn-block btn-primary' value='MINT'            />
                </form>
              </div>
            </main>
          </div>
          <hr/>
          <div className="row text-center">
            { this.state.locations.map((location, key) => {
              return(
                <div key={key} className="col-md-3 mb-3">                
                  <div>{location}</div>
                </div>
              )
            })}
          </div>          
        </div>
      </div>
    );
  }
}

export default App;

This is the code in the index.html file I am currently working on to check for metamask account. I want users to pay using their matamask wallet using their account within the wallet.

<script type="text/javascript">     
    window.addEventListener('load', function () 
    {
        if (typeof web3 !== 'undefined') {              
            console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
            window.web3 = new Web3(web3.currentProvider);
        } else {
            console.log('No Web3 Detected... using HTTP Provider')              
        }
        web3.eth.defaultAccount = web3.eth.accounts[1]; 
    })
    
    addEventListener('DOMContentLoaded', function() {
        loadWeb3();
        loadBlockchainData();    
    });

    async function loadWeb3() {
        console.log('Inside loadWeb3() fn')
        if (window.ethereum) {
            window.web3 = new Web3(window.ethereum)
            await window.ethereum.enable()
            console.log('window.ethereum')
        }
        else if (window.web3) {
            window.web3 = new Web3(window.web3.currentProvider)
        }
        else {        
            console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
        }
}

async function loadBlockchainData() {
    console.log('Inside loadBlockchainData() fn')
    const web3 = window.web3
    // Load account
    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })
    console.log('web3' + web3)
    
    const networkId = await web3.eth.net.getId()
    const networkData = Location.networks[networkId]
    if(networkData) {
      const abi = Location.abi
      const address = networkData.address
      const contract = new web3.eth.Contract(abi, address)
      this.setState({ contract })
      const totalSupply = await contract.methods.totalSupply().call()
      this.setState({ totalSupply })
      // Load Locations
      for (var i = 1; i <= totalSupply; i++) {
        const location = await contract.methods.locations(i - 1).call()
        this.setState({
          locations: [...this.state.locations, location]
        })
      }
    } else {
      window.alert('Smart contract not deployed to detected network.')
    }
}

Add web server to existing web design

I have an existing website entirely made of html, css and javascript. I would like to add some php to be able to run the website on my own server. The website is at the moment mede up by 5 html files with designed hyperlinkts to get the users between the headers. I now wonder what approach i should take to make the website run on my own server. Would i do best in just redo the whole website and reuse design, html and scripts wherever possible or is there a simpleyr way? As i see it now i would have to change a lot of design to remake these hyperlinks to submit forms to be able to start doing anything with php?

JAVASCRIPT nested loops – triangle exercise from user input

I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number. Each line the number is increased by 1. I can’t get my code to increase by 1. Anyone have any suggestions? Thanks

let num = prompt("Enter a number");

//Check if its a number
num = parseInt(num);

//loop 1
for (i = 1; i <= 6; i++) {

  //loop 2
  for (y = 0; y < i; y++) {
    document.write(num);
  }

  document.write("<br>");
}
<p id="num"> </p>

How can you access data in an Excel Spreadsheet using javascript

I have a website that uses some JavaScript to access data in a .xlsx file from a Microsoft Excel Spreadsheet. When testing I was able to access it by having the file in the same folder, however in practice my company uses SquareSpace, and the way to access their files is more complicated than I would like, since I need to set it up so that the less tech savvy people in the company can reupload and update the spreadsheet. Preferably, I’d like to have it so that my script is accessing the file directly from OneDrive. I know it’s possible to display a spreadsheet on from OneDrive on SquareSpace (or any website) by embedding it. But I don’t need to display the spreadsheet, I need my code to read the data in the spreadsheet and respond to it. Essentially, is there a way to connect a website to a Microsoft Excel document and save the data as JavaScript variables?