How to use Jest to check if async loaded content is rendered – ReactJS

I have a component that renders a list of data, given by a hook. My hook returns some data on the component mount so the component always has some items to render.

MyList component:

function MyList() {
  let {data} = useLoadData()
  return (
      <ul>
        {data.map(i => <li key={i}>{i}</li>)}
      </ul>
  )
}

Data loader hook:


function useLoadData() {
  const [data, setData] = useState([])

  const fetchData = useCallback((params) => {
    fetch("url")
        .then(res => res.json())
        .then(res => setData(res))
  }, [])

  useEffect(() => {
    fetchData()
  }, [])

  return {data, fetchData}
}

I want to use jest to check if the initial data was rendered or not, is there any way to do it?

Can I pass a string argument to an onclick javascript function?

In one script I have

<a href="javascript:void;" id="druck">

This is evaluated by javascript in another script (these are nested templates in django).
This should then open a new window in order to prepare a site that is more printer-friendly (still a way to go).


$(function() {
    var b = document.getElementById("druck");
    b.onclick = function() {
    
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');
        mywindow.document.write('<html><head><title>' + document.title + '</title>');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.min.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/dashboard.css' %}" type="text/css">');
        mywindow.document.write('</head><body>');

I would like to pass a string parameter from the first script to the second script, so that I can print the string as well. I am not fit in js, therefore I am asking how I can pass a string to such a href with an id and a javascript void function with onclick and so on.

Nodejs example for encode .ply to .drc

Looking for example code to convert 3d .ply to .drc (https://github.com/google/draco) compression in nodejs or javascript. Following draco3d document able to build command line tool and successfully convert ply to drc. But not sure how to achieve the same programmatically using nodejs or javascript solution. Examples are not clear in this below official documentation.

https://github.com/google/draco/tree/master/javascript/npm/draco3d

TIA

Javascript pure function import strategy

I have a class file, utility.js for all the common functions.
However some of the functions require certain library import
e.g: NetInfo library

utility.js

import NetInfo from "@react-native-community/netinfo";

export async function networkConnection() {
    const state = await NetInfo.fetch();
    return state.type;
}

However, in order for utility.js to be reusable in another project, another project has to have NetInfo installed. Is it a good practice if instead of importing modules directly, I import only when I need to use it, and pass the import object along to the function?

utility.js

export async function networkConnection({ NetInfo }) {
    const state = await NetInfo.fetch();
    return state.type;
}

and when using it

app.js

import NetInfo from "@react-native-community/netinfo";
import { networkConnection } from "./utility.js"

const network = networkConnection({ NetInfo })

This way, I can copy and paste utility.js to any project, without the need to install all the import packages. Also, this pattern seems to be able to resolve common Circular Dependencies error by limiting the import statement.

Is this the best practice for creating a common, reusable function file?

How can I query the XRPL to get the current XRP value of a currency. For example equilibrium (EQ/XRP pair)

I am wondering what is the simplest method to get the XRP value of a particular token on the XRPL. So for example EQ I can go to the Sologenic DEX exchange, pass in my XRP account address and it will give me the current asking price for the EQ/XRP pair. How would I get the lowest Selling and highest Buy prices for a particular pair programmatically from the ledger?

I am hoping there is some sort of node module which I can pass an address to and a pair then it will return the data I need?

I have been using the following node xrpl.js package but cannot figure out how to get what I need. https://js.xrpl.org/[https://js.xrpl.org/][1]

How to slightly go upper than tab panes

I’m using a Bootstrap panel like this:

<ul class="nav nav-tabs" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" data-toggle="tab" href="#tabs-1" role="tab">First Panel</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#tabs-2" role="tab">Second Panel</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#tabs-3" role="tab">Third Panel</a>
    </li>
</ul><!-- Tab panes -->
<div class="tab-content">
    <div class="tab-pane active" id="tabs-1" role="tabpanel">
        <p>First Panel</p>
    </div>
    <div class="tab-pane" id="tabs-2" role="tabpanel">
        <p>Second Panel</p>
    </div>
    <div class="tab-pane" id="tabs-3" role="tabpanel">
        <p>Third Panel</p>
    </div>
</div>

And due to the answer to this question, I added this Javascript code for enabling opening tabs on hyperlinks:

// Javascript to enable link to tab
var hash = location.hash.replace(/^#/, '');  // ^ means starting, meaning only match the first hash
if (hash) {
    $('.nav-tabs a[href="#' + hash + '"]').tab('show');
} 

So if I go to the link https://sitename.com/page#tabs-2, the tab-pane with an id of tabs-2 will be opened.

But I need to show the nav-tabs item as well. I mean the redirection to
https://sitename.com/page#tabs-2 must be a little bit upper in order to show the nav-tabs items.

So how can I do that?

Why does ‘node .’ always throw an error when I type it in cmd?

I just started with my first discord bot and I am really stuck with this problem. Everytime I write ‘node .’ it gives an error stating this ‘throw new TypeError(‘CLIENT_MISSING_INTENTS’);’can anybody tell me what I need to fix?

That’s all the code I got:

const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'myToken';

bot.on('ready', () =>{
    console.log('This bot is online!');
})

bot.login(token);

picture of the error

Cannot find module ‘node:events’

when i started the code i’ve got this error

Error: Cannot find module 'node:events'
Require stack:
- C:RAGEMPserver-filesnode_modulesdiscord.jssrcclientBaseClient.js
- C:RAGEMPserver-filesnode_modulesdiscord.jssrcindex.js
- C:RAGEMPserver-filespackagesDominoRPdiscordindex.js
- C:RAGEMPserver-filespackagesDominoRPindex.js
- C:RAGEMPserver-filesbinloader.mjs
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:893:15)
    at Function.Module._load (internal/modules/cjs/loader.js:743:27)
    at Module.require (internal/modules/cjs/loader.js:965:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:RAGEMPserver-filesnode_modulesdiscord.jssrcclientBaseClient.js:3:22)
    at Module._compile (internal/modules/cjs/loader.js:1076:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Module.require (internal/modules/cjs/loader.js:965:19)

this is my code

const Discord = require('discord.js');
const client = new Discord.Client();


client.on('ready', async () => {
   console.log('!!! => Discord bot has authenticated successfully...');
   sendMsgToServerStatus();

   
});

i have upgrade to node 16.13 but same thing. Can anyone help me?

How to convert base64 image data to data URL in react native?

I am using react-native-signature-canvas which returns the signature as a base64 image string. I want to send it to the API and before that, I want to convert it to the data URL. Can anyone help me? Also, I don’t want to store the file/image to the local storage..just wanna convert it to the DataUrl and send it to the API.

ASP .NET CORE MVC, html – choose default image if user didn’t choose any

I want the “Choose file” to be optional. That means if user does not click “Choose file”, the default image (/wwwroot/n-image/NoImage.png) is chosen. “Image” is a string property of Article object.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
  <div>
    <div class="form-group">
      <label asp-for="Image" class="control-label"></label>
      <br />
      <div class="custom-file">
        <input type="file" asp-for="Image" class="custom-file-input" id="FLFormFIle" />
      </div>
      <span class="text-danger"></span>
      <br />
    </div>

    <img id="FormFilePrv" src="" style="border:1px; top:20px;margin-left:120px;" />
    <div class="form-group">
      <br />
      <input type="submit" value="Utwórz artykuł" class="btn btn-primary" />
    </div>
  </div>
</form>

$(".custom-file-input").on("change", function() {
  var fileName = $(this).val().split("\").pop();
  document.getElementById('FormFilePrv').src = window.URL.createObjectURL(this.files[0])
  $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
})

What is the difference between these two singleton approaches in JS?

The way to solve the singleton pattern in JS (TS actually) is looks like this (the best approach if you ask me):

export default class Singleton {
    private static _instance: Selection

    constructor() {
        if (Selection._instance) {
            return Singleton._instance
        } else {
            Singleton._instance = this
        }
    }
}

And then:

import Singleton from './Singleton.ts'

const singleton_1 = new Singleton()
const singleton_2 = new Singleton()

singleton_1 === singleton_2 // true

But in this scenario I have to create new variables every time I need that class.

I can achieve exactly the same the easier way:

class Singleton {
    constructor() {
        // some logic
    }
}

export default new Singleton()
import Singleton from './Singleton.ts'

const wut = Singleton.field
Singleton.method('do something')

Am I getting something wrong or the first approach is a little bit excessive and complicated and the second one just do the same thing in more obvious way?

I understand that if I have static fields in my class, I couldn’t use it that way, but cases when you really need static fields are rare.

How to open specific Bootstrap tab by clicking on a link

I’m trying to add a Bootstrap tab panel goes like this:

<ul class="nav nav-tabs" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" data-toggle="tab" href="#tabs-1" role="tab">First Panel</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#tabs-2" role="tab">Second Panel</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#tabs-3" role="tab">Third Panel</a>
    </li>
</ul><!-- Tab panes -->
<div class="tab-content">
    <div class="tab-pane active" id="tabs-1" role="tabpanel">
        <p>First Panel</p>
    </div>
    <div class="tab-pane" id="tabs-2" role="tabpanel">
        <p>Second Panel</p>
    </div>
    <div class="tab-pane" id="tabs-3" role="tabpanel">
        <p>Third Panel</p>
    </div>
</div>

Now I need to give link to users to see the panes like this:

https://sitename.com/page#tabs-2

But this won’t work because the tab-pane with an id of tabs-2 does not have the .active class.

However, if I try loading https://sitename.com/page#tabs-1 The page properly redirects me to tab-pane with an id of tabs-1 (because it has .active class by default)

So how can I redirect users to different tab panes correctly?

Are there some different configurations for running java script in java spring boot

I wanted to do my input text box read-only when I clicked a link and get navigated to the same page. When I tried to run the code in my IDE, it was not running efficiently. It wasn’t making the text-boxes read-only. But when I ran the same code in an simple Html file it did run perfectly. Please help me in solving my issue. Below is my code of my jsp page.

<!DOCTYPE html>
<html>

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Mole Calculator | Chemistry Calculator</title>

</head>



<body>

    <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">

        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <h4>
                    <b>Chemistry Calculator</b>
                </h4>
            </a>

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">

                <ul class="navbar-nav  text-uppercase">

                    <li class="nav-item"><a class="nav-link active" aria-current="page" href="/Chemistry-Calculator/">Home</a></li>

                    <li class="nav-item"><a class="nav-link active" aria-current="page" href="/Chemistry-Calculator/about">About</a></li>


                </ul>

            </div>
        </div>
    </nav>

    <div class="container" style="padding-top: 5%;">

        <div class="card px-4 py-5" style="width: 650px;">
            <div class="card-block">

                <form action="/Chemistry-Calculator/Number-Of-Moles">

                    <div class="mb-3">
                        <label for="givenMass" class="form-label">Given Mass of
                            Substance</label> <input type="text" class="form-control" id="givenMass" aria-describedby="emailHelp" name="givenMass" value="${givenMass}" style="width: 600px">
                    </div>
                    <div class="mb-3">
                        <label for="molarMass" class="form-label">Molar Mass</label> <input type="text" class="form-control" id="molarMass" name="molarMass" value="${molarMass}" style="width: 600px">
                    </div>

                    <div class="mb-3">
                        <label for="moles" class="form-label">Moles</label> <input type="text" class="form-control" id="moles" name="moles" value="${moles}" style="width: 600px">
                    </div>

                    <input class="btn btn-outline-success" type="submit" value="Calculate">

                    <div class="btn-group">
                        <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Choose
                            what to calculate</button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" onclick="readonlyForMoles()" href="#">Calculate Moles</a></li>
                            <li><a class="dropdown-item" onclick="readonlyForMolarMass()" href="#">Calculate Molar
                                    Mass</a></li>
                            <li><a class="dropdown-item" onclick="readonlyForGivenMass()" href="#">Calculate Given
                                    mass</a></li>
                        </ul>
                    </div>

                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    <script>
        function readonlyForGivenMass() {
            document.getElementById("givenMass").readOnly = true;
            document.getElementById("molarMass").readOnly = false;
            document.getElementById("moles").readOnly = false;

        }

        function readonlyForMolarMass() {
            document.getElementById("givenMass").readOnly = false;
            document.getElementById("molarMass").readOnly = true;
            document.getElementById("moles").readOnly = false;
        }

        function readonlyForMoles() {
            document.getElementById("givenMass").readOnly = false;
            document.getElementById("molarMass").readOnly = false;
            document.getElementById("moles").readOnly = true;
        }
    </script>

</body>

</html>

OpenWeathermap country codes code proplem “city not found”

im writing a code for a weather journal app the thing is when i pass to fetch method the url of the site of openweathermap.com with the zip code and country code way it only accepts the country code as US it never accepts anyother country i tried so many but it never accepts any of those it only returns the data object of forecast to US anyother country it just show the message city not found here is my code:

const generate = document.getElementById('generate').addEventListener('click', function(){
    const zip = document.getElementById('zip').value;
    const countryCode = document.getElementById('countryCode').value;
    endPointData(zip,countryCode,apiKey);
})

const endPointData = async (zip,countryCode,apiKey) => {
    const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);

    try{
        const data = await res.json();
        console.log(data);
    }
    catch(error){
        // appropriately handles the errors.
        console.log("error",error);
    }
}

const postData = async (url='', data = {}) => {
    const response = await fetch(url,{
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
    });
    try{
        const newData = await response.json();
        return newData;
    }catch(error){
        console.log("error",error);
    }
}

Dealing with floating point precision in power function

I am having trouble coming up with a class to deal with floating point precision, specifically the pow program which generates the nth power of a number (the base or exponent can be negative or exist as a decimal). I have viewed others’ explanations and copied a lot of code, however the function still generates results with floating point errors:

class Core{
    to_fraction(decimal, tolerance = 0){
        var skipped = false; 
        if (isNaN(decimal) || isNaN(tolerance)) return; 
        for (var denominator = 1; (decimal * denominator) % 1 != 0; denominator++) if (Math.abs(Math.round(decimal * denominator) / denominator - decimal) < tolerance){skipped = true; break}; 
        if (skipped) return {numerator: Math.round(decimal * denominator), denominator: denominator, difference: Math.round(decimal * denominator) / denominator - decimal};
        if (!skipped) return {numerator: decimal * denominator, denominator: denominator};
    }

    dplaces(a){
        if (a.toString().split(".").length == 1) return 0; 
        return a.toString().split(".")[1].length; 
    }
}


class Correct{
    cf(a, b){
        return Math.pow(10, Math.max(core.dplaces(a), core.dplaces(b))); 
    }

    divide(a, b){
        var _cf = this.cf(a, b); 
        return (a * _cf) / (b * _cf); 
    }

    multiply(a, b){
        var _cf = this.cf(a, b); 
        return (a * _cf) * (b * _cf) / (_cf * _cf); 
    }

    subtract(a, b){
        var _cf = this.cf(a, b); 
        return ((a * _cf) - (b * _cf)) / _cf; 
    }

    add(a, b){
        var _cf = this.cf(a, b); 
        return ((a * _cf) + (b * _cf)) / _cf; 
    }

    pow(a, b){
        var fraction = core.to_fraction(b); 
        
        for (var count = 0, result = 1; count < fraction.numerator; count++) result = this.multiply(result, a); 
        
        result = result ** (1 / fraction.denominator); // Da problems starts here

        return result; 
    }

    factorial(number){
        if (number % 1 || !(Math.abs(number) >= 0)) return NaN; 
        if (number > 170) return Infinity;
        var result = 1;
        while (number > 1) result *= number--;
        return result;
    }
}

const core = new Core(), correct = new Correct(); 

console.log(correct.pow(7.154840569262962e+21, 1 / 5));

It seems that the problem starts on the second filled line of the pow function within the Correct class, however I cannot find or think of a method to avoid or change the stuff on that line.

This is extremely frustrating and rather unfortunate. Please suggest an alternative method (preferably in JavaScript or Node js) to achieve such effects or modify that line. Thank you!