Web3js smart contract interaction gas and signing

So I can interact with a function within a smart contract.
I also know that to actually do the transaction I need something like this:

const contractObj = new web3.eth.Contract(abi, contractAddress)

const transaction= await contractObj .methods.NameofTheMethod(x).send({from:myAddress,gasLimit:value})

My question is: what is the next step? Because I put myAddress but I should sign this before send the transaction right?

Otherwise how will it be able to take the fee from the gas?

Web scrapping in Chrome Console- iterate over rows in mat-tab element

DISCLAIMER: I do not know JS, it is an assignment for my work.

I have been asked to withdraw scrape some data from a Google Marketing page using Chrome Console.

The HTML code I need to scrape looks like this:

The code in the console

I made the following code where I created a dictionary and then used document.Selector()to take the data but I only take it from one row.

var IntegrationDetails = [{}]

IntegrationDetails[0]["Property Name"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Advertiser"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Tracking ID"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Account"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Organisation name"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with reporting data"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with Cost Data"] = document.querySelector("JSPath").innerText

IntegrationDetails[0]["Integrations with Remarketing Lists"] = document.querySelector("JSPath").innerText

copy(IntegrationDetails)

I do not know how to iterate over every row in the mat-tab element and append each row to the dictionary.

In React Js Axios request getting CROS error

I used Axios for API, here is my code. I am getting CROS error.

axios({
      method: 'GET',
      headers : { 'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin' : '*',
                  'mode': 'cors',
                  'Authorization':'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N....'
                },
      url: baseURL,          
    }).then(function (response) {
          console.log(response);
    });

enter image description here

How to create a chart for showing sigma value like this

I need to create a stacked bar chart to show Six Sigma value as shown in the image

enter image description here

Here the values in the Y axis are static. But the values in the X axis are not evenly spaced. The image is not properly designed. I am attaching a picture to illustrate the values of the X axis according to the value of the bars. In the picture the yield column corresponds to the values on the bars.
enter image description here
Also I need to show the values on the bar as shown in the image.
I have tried to use chartjs 2 but I can not figure out how to make a custom spacing scale for the X axis.

My attempt at modifying the X axis ticks is given below

let chart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [{
      yAxisID: 'yAxis'
    }]
  },
  options: {
    scales: {
      xAxis: {
        type: 'logarithmic',
        position: 'right',
      }
    }
  }
});

Any recommendations other than chartjs for this functionality would also be highly appreciated

A text is displayed only right after my javascript is triggered

I wrote javascript codes.

By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.

My code could sent a text to the child window, but there’s no text displayed.
The text is displayed only when I keep clicking the button.

I think my code is overridden by a blank script or something, though I don’t write any other codes except for below.

Do you have any solution for this?

the parent window html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Parent Window</title>
</head>
<body>
  <input type="button" value="TEST_BUTTON" id="testButton">

  <script>
      var testButton = document.getElementById('testButton');
      testButton.addEventListener('click', function(event) {
        event.preventDefault();
        var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
        newWindow.postMessage('this is a content from the parent window.', '*');
        return false;
      },false);
  </script>
</body>
</html>

the child window html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Pop Up Window</title>
  </head>
  <body>
    <h1 id="mainText"></h1>
    <script type="text/javascript">
      var mainText = document.getElementById('mainText');

      window.addEventListener('message', function(event) {
        console.log(event.data);
        this.mainText.innerText = event.data;
      }, false)
    </script>
  </body>
</html>

can we use js variable name as class name in html

I want to concatinate class name with variable count which keep getting updated after each button click, for which I am getting error as “citysName is null”. can anyone suggest

button.addEventListener('click', resp => {
    count = count +1;
    var card = document.createElement('card');
    card.innerHTML = `
                <img src="..." class="card-img-top" alt="...">
                <div class="card-body">
                  **<h5 class="card_title" + count></h5>
                  <h6 class="temp" + count></h6>
                  <p class="card-text" + count></p>**
                  <a href="#" class="btn-primary"></a>
                </div>
    `;
    card.className = 'card';
    var content = document.getElementById('id1');
    content.appendChild(card);
    **var citysName = document.querySelector('.card_title'+count);
    var description = document.querySelector('.card-text'+count);
    var temp = document.querySelector('.temp'+count);**
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
    .then(post => post.json())
    .then(data => {
        var cityName = data['name'];
        var temper = data['main']['temp'];
        var descrip = data['weather'][0]['description'];

        let ctemp = Math.round(temper-273);
        citysName.innerHTML = cityName;
        temp.innerHTML = ctemp + "°C";
        description.innerHTML = descrip;
    })
})

Changing attribute of subclass within D3 based on dictionary value

What is the best way to make sure I can differentiate each line by size based on the values of my dictionary.

Down below is a simplified example.

Problem is all lines would would adjust instead of my desired line.

draw.axis = function ()
{
    var element; 
    function axis(g){
        element = g.append("g"); 
        
        
        element 
            .append("g")
            .attr("class", axis dotted line)
            .attr("height", 100);  //default size 
        
    }
}

var size_adjuster = [    
    {size: "big",     adjusted: false  },
    {size: "regular", adjusted: false  },
    {size: "small",   adjusted: false  },
    {size: "small",   adjusted: true   },
    {size: "big",     adjusted: true   },
];

size_adjuster = function(){
    size_adjuster.forEach(function(item) {
        if(item.size == "big" && item.adjusted == false){
            item.adjusted == true; 
            d3.selectedAll("g.axis.line line")
                .attr("height", 200);
        }
        else if(item.size == "regular" && item.adjusted == false){
            d3.selectedAll("g.axis.line line")
                .attr("height", 100);
        }
        else if(item.size == "small" && item.adjusted == false){
            d3.selectedAll("g.axis.line line")
                .attr("height", 50);
        }
    });
}

new Date().getTime() gets milliseconds since page is loaded when passed as argument into a function

I’m trying to make a javascript animation with window.requestAnimationFrame. It should be triggered when a button is clicked (like the “dropping” animation of a dropdown menu appearing). I use the variable timeElapsed to calculate the time since the button is clicked, and calculate the new height of the object with timeElapsed. I pass the time when the button is clicked (start) as an argument of the function. According to my console, although start (computed outside the function) is computed correctly, for some reason it changes to the time since the page is loaded once it is passed into the function.

Here’s what I have so far:

function mobileAppear(sTime) {
    console.log(sTime); //Prints milliseconds since page is loaded
    currTime = new Date().getTime();
    timeElapsed = (currTime - sTime)/1000;
    newHeight = timeElapsed*10 ;
    wishlist.style.height = newHeight + "vh";
    if (newHeight < 66){
        window.requestAnimationFrame(mobileAppear);
    }
}

function toggleView() {
  //Some code here
  var start = new Date().getTime();
  console.log(start); // works fine
  if (window.innerWidth < 768){
    mobileAppear(start);
  }
  
}

What’s the problem here and how to fix that?

*Note: there’s probably another mistake in the chunk of code, but for now I’m trying to fix this one.

Getting error on two fixed and getting value of number of decimal places what does that mean?

I have the following code to find out the profit after tax.

var amount = 500;
var profit = 0;
var period = 24;
var invest = amount * period;
var totalamount = 0;

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const calculate = () => {
  rl.question("what is your annual income: ", function (income) {
    for (var i = 1; i <= period; i++) {
      profit = amount * 0.1;
      totalamount = amount + profit;
      if (i === 12) {
        totalamount = totalamount + income;
        if (totalamount > 18200 && totalamount < 45000) {
          totalamount = totalamount - 0.19 * (totalamount - 18200);
        } else if (totalamount > 45000 && totalamount < 120000) {
          totalamount = totalamount - (0.325 * (totalamount - 45000) + 10184);
        } else if (totalamount > 120000 && totalamount < 180000) {
          totalamount = totalamount - (0.37 * (totalamount - 120000) + 64026);
        } else if (totalamount > 180000) {
          totalamount = totalamount - (0.45 * (totalamount - 180000) + 86226);
        }
        console.log(i);
      }
     
      amount = totalamount + 500;
    }
    var numb = totalamount.toFixed(2);
    console.log(numb);
    
    console.log(invest);
  });
};

calculate();

When I run this code I’m getting the error, ‘TypeError: totalamount.toFixed is not a function’. also when I change the period to 24 to check for 2 years and console.log(totalamount) getting a value with such large number of decimal points. Not sure why and what that means and would appreciate if someone could help me out. I’m not sure how to call the value with large points so couldnt google it either. The value with large decimal points I’m talking about is this:
11761.35607196549810005001176.13560719655500NaN500NaN500NaN500NaN500NaN500NaN500NaN500NaN500NaN500NaN500NaN

Organize multiple Webpack entry file dependencies

How to organize JS reusable components with their own dependencies in 3rd part bundles (e.g. vendor/ subdirectories) with webpack different entry files/configs?

Description:

I have following structure with entrypoints and components

app/
  assets/
    index.js
  package.json
  webpack.config.js

vendor/
  my-utils-bundle/
    assets/
      components/
        MyMath.js
    package.json
    webpack.config.js

In my includable within different entry files/webpack configs MyMath.js components there’s node_modules/ dependency to package e.g. mathjs with following line:

import { pi, pow, round, sqrt } from 'mathjs'

....some code below...

P.S. mathjs dependency package provided in this bundle (vendor/my-utils-bundle/package.json)

Then when i run yarn dev to compile my assets in app/assets/index.js there’s following error:

"./vendor/my-utils-bundle/assets/components/MyMath.js" contains a reference to the file "mathjs".
This file can not be found, please check it for typos or update it if the file got moved.

Question:

How can i use this MyMath.js components as includable class in app/assets/index.js and maybe also in other “bundles” (e.g. vendor/my-other-bundle)?

Looks that I could install this mathjs dependency also in app/package.json but then it seems that on application level i should think about bundles JS dependencies that sounds not as the best solution.

Error when checking if string contains “->”

I am looking to go through the two strings seen below and check if it contains “->” and if that it True, I would like to check that the text after it does not contain any text, if both true, it should run through the code. So in the first NTE, it should go through just fine, while when NTE is “TEST” it should stop and not modify anything, but instead its throwing an error.

NTE = “Exceptions:->1/1/22”
NTE = “TEST”

I am using the below if to check if it contains “->” but its not working properly

 /* Single input message case */
 // Create the output message 
 var next = output.append(input[0]);
 var lib    = require('DateHelper');

 var ODS;
 var NTEcnt;
 var ODScnt;
 var NTE;
 var result;
 var date1;
 var longDate;
 var quantity;

 NTEcnt = next.getRepeatCount('CommonOrders[0]/DietaryOrder/NTE');
 //log.debug("NTEcnt:"+ NTEcnt); //gives count of NTE segments

 ODScnt = next.getRepeatCount('CommonOrders[0]/DietaryOrder/ODS');
 //log.debug("ODScnt:"+ ODScnt);  //gives count of ODS segments

 for(var i = 0; i < NTEcnt; i++) {
        NTE = next.getField('CommonOrders[0]/DietaryOrder/NTE['+ i +']/Comment[0]');
        log.debug("NTE: "+ NTE);
    
        result = NTE.split("->")[0] + "->"; // split "splits" the string into an array based on the delimiter "->"
        //log.debug("Before >: "+ result);
        
        
        function includesMatch(lookupValue, testString){
            var re = new RegExp(lookupValue, 'i'); //Here the 'i' means that we are doing a case insensitive match
            return testString.match(re) !== null
        }

        //if(!includesMatch(NTE, "->")){
            if(NTE.search("->") != -1){         
                
                var contains = true;
                log.debug("it contains ->");
                date1 = NTE.split("->")[1]; // splits the string into an array based on the delimiter "->"
                log.debug("After >: "+ date1);

            } else {
                var contains = false;
                log.debug("it does not contain ->");
            }
    
if(contains = true){
if(date1.length>=6){
    var dateTimeSec = lib.FormatDate(date1, 'MM/dd/yy','MM/dd/yyyy');
    var dateTimeORC = lib.FormatDate(date1, 'MM/dd/yy','yyyyMMdd'+"000000");
    var whatDate= lib.isDate(dateTimeSec);
    log.debug('My date = ' + dateTimeSec);
    log.debug('My date ORC long = ' + dateTimeORC);
    log.debug('My date = ' + whatDate);
} else {
    quantity = date1;
}
} else {

}



if(contains = true){    
    if(result == 'Packet:->' || result == 'Serving:->' || result == 'Can/Carton/Bottle:->'){
        for(var j = 0; j < ODScnt; j++){
        ODS = next.getField('CommonOrders[0]/DietaryOrder/ODS['+ j +']/DietSupplementOrPreferenceCode[0]/Identifier');
            if(ODS == '500DIET70' || ODS == '500DIET71' || ODS == '500DIET72' ||  ODS == '500DIET73' || ODS == '500DIET76' ||  ODS == '500DIET77'){
                
                    next.setField('CommonOrders[0]/ORC/QuantityTiming[0]/Quantity/Quantity','1');
                    next.setField('CommonOrders[0]/ORC/QuantityTiming[0]/Quantity/Quantity',quantity); //rewrite ORC_7.1
                    
                    log.debug("Quantity of NTE :"+ quantity);
                    
                    next.setField('CommonOrders[0]/ORC/QuantityTiming[0]/StartDateTime',dateTimeORC); //rewrite ORC_7.4
                    log.debug("Longer Date : "+ dateTimeORC);
            } //end if
        }  //end for
    } //end if
                        

} else {

}


}   

2022-01-16 03:38:48,798 DEBUG [ ] NTE: TEST
2022-01-16 03:38:48,798 DEBUG [ ] it does not contain ->

enter image description here

Javascript: How to write records into a file line by line separated by a comma but without a trailing comma at the end

I’ve got a file of records (one per line):

Record1
Record2
Record3

I’m using the fs and the readline modules for that:

        const rs = fs.createReadStream('input.txt');
        const ws = fs.createWriteStream('output.json', { encoding: "utf8" });
        const rl = readline.createInterface({
            input: rs,
            crlfDelay: Infinity,
        });
        ws.write('[');
        for await (const line of rl) {
            ws.write(`${line},n`);
        }
        ws.end(']');

But this loop will also toss in a trailing comma at the end of the file which is bad cos trailing commas are not allowed in JSON.

The problem is that I don’t want to read the whole file into memory and I don’t know the number of records in advance.

Edit:

This is a simple example, but in the real code, the record gets transformed to a json record, but it’s irrelevant.

How can I group an array with nested array?

Does anyone know a simple way to group an array with nested array?
For example, i have an array of animals:

[
  ['Cat', 'Dog', 'Monkey'],
  ['my pet', 'it is animals', 'terrestrial animals']
]

I want to make new array with format that’s grouped by ['Cat', 'Dog', 'Monkey']:

[
  {
    groupTitle: 'Cat',
    relations: ['my pet', 'it is animals', 'terrestrial animals']
  },
  {
    groupTitle: 'Dog',
    relations: ['my pet', 'it is animals', 'terrestrial animals']
  },
  {
    groupTitle: 'Monkey',
    relations: ['my pet', 'it is animals', 'terrestrial animals']
  }
]

How can i do it?
Thanks!

getting function error suddenly code that works fine

I Am learning javascript and everything was fine until I Add more functions
that not related to other functions already exist and it starts returning bugs in console for functions that there was no error for them therefore code is alright beacuse in tutrial it works just fine so Im using live server extension and vs code i already changed vs code to atom and it does not make any differnce so the errors come form no where for find method or innerhtml

How to order two arrays as a result

I mean:
I have two arrays, number and name

const number = ['91xxxx','1xxxx','92xxxx']
const name = ['Abhi','Arun','Aaron']

Here I want to order these two arrays in the following manner:

1st number in array that is number[0], its name must be name[0] and number[1], for name[1], like that.

But That arrays are user preference, what I mean is users can add their on number and name there unlimitedly but i want to keep in the above manner, How should I do????