Calculation showing up as NaN on innerText

I have these two functions, which are very similar. The calculateMetric shows the output as an innerText as it should, but calculateImperial shows the output as NaN. I’m confused because when I console.log it right before I innerText it just to see if it works, it logs the correct answer. It just doesn’t innerText the answer.

calculateImperial = (weight, fullheight) => {
    bmi = (weight / (fullheight**2)) * 703;
    console.log(bmi);
    result.innerText = bmi.toFixed(1);
}

//metric calculation
calculateMetric = (weight, height) => {
    height = height/100;
    bmi = (weight/(height**2));
    result.innerText = bmi.toFixed(1);
}

Is there something I’m missing? I checked the typeof of all the relevant variables and since the calculation does work as it logs the correct answer, I just don’t see why it innerTexts NaN.

Add to string at specific index at for each occurence

I am trying to add to a string, in this instance I am wanting to alter the href and add a string to the beginning of each href in a string. I have figured out how to do it for one instance, but not if the string has more than one occurrence. Is there a best practice to accomplish this?

This is what I have to add to if there is just one occurrence (it also works with multiple, but will only alter the first occurrence).

  let stringOne = '<div>
    <p>A cool label</p>
    <a href="123idofanitem">Link 1</a>
    <p>A cool label</p>
    <span>
      <a href="1234idofanitem">Link 2</a>
    </span>
    <ul>
      <li>
        <a href="12345idofanitem">Link 3</a>
      </li>
      <li>
        <a href="123456idofanitem">Link 4</a>
      </li>
    </ul>
  </div>'

  let index = stringOne.indexOf('href="');
  let output = [stringOne.slice(0, index + 6),
     'https://www.google.com/',
      stringOne.slice(index + 6),].join('');//added +6 to account for href="

I am trying to replace all href with https://www.google.com/{existingHREF}

A final note would be that stringOne could have infinite amount of links in it, so that’s why I am trying to work my way to a solution where I could loop or something of the sort through all of them and replace them.

Displaying multiple polygons in google maps – each from different external geojson URLs and applying different styles

I’m trying to render multiple polygons in google maps that are each loaded from external individual geojson files that are independent and that each need to be styled differently.

There are many similar posts on the topic, but none that seem to address the loading of multiple independent external json files and each of which needs a different set of styles.

My JS code is as follows for each polygon to be displayed on a map. I note here that I’ve tried using different approaches for display below(2 of many). Whilst they both still display they are both with black strokes and what appears to be a 50% fill opacity regardless of the values I set for stroke and fill.

// MSOA polygon
var pathmsoa = map.data.loadGeoJson("msoa.json");
        var msoaplot = {
            strokeColor: '#ffffff',
            strokeOpacity: 0.5,
            strokeWeight: 2,
            fillColor: '#800105',
            fillOpacity: 0.1,
            path: this.pathmsoa,
        }
msoa = new google.maps.Polygon(msoaplot);

// LSOA polygon
var pathlsoa = map.data.loadGeoJson("lsoa.json");
        var lsoa = new google.maps.Polygon({
            path: this.pathlsoa,
            strokeColor: '#ff0000',
            strokeOpacity: 0.5,
            strokeWeight: 1,
            fillColor: '#800105',
            fillOpacity: 0.8,
        });

Both the above polygons display as follows:

output image

The only other additional point is that the console is returning an InvalidValueError: not an Array value, but I can’t fathom why – given the examples I’ve followed from different sources and with different approaches.

Any guidance/help appreciated.

Make PNG from HTML/CSS in Node.js

I am trying to make a HTML/CSS table that has a background image using the Puppeteer package.

The HTML/CSS I am rendering is like below.

<head>
    <style>
        table {
            background-image: url('./pent.png');
            background-size: 200px, 200px;
            background-repeat: no-repeat;
            background-color: rgba(255, 255, 255, 0.7);
            background-blend-mode: overlay;
            background-position: center center;
            border: 1px solid #b3adad;
            border-collapse: collapse;
            padding: 5px;
        }
        table th {
            border: 1px solid #b3adad;
            padding: 5px;
            color: #313030;
        }
        table td {
            border: 1px solid #b3adad;
            text-align: center;
            padding: 5px;
            color: #313030;
        }
    </style>
</head>
<body>
    <table style="white-space:nowrap">
        <thead>
            <tr>
                <th><br></th>
                <th>Header</th>
                <th>Header</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>&nbsp;Row<br></td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>Row</td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>Row&nbsp;</td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>&nbsp;Row</td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>&nbsp;Row</td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>&nbsp;Row</td>
                <td>1</td>
                <td>0.52</td>
            </tr>
            <tr>
                <td>Row&nbsp;</td>
                <td>150</td>
                <td></td>
            </tr>
        </tbody>
    </table>
</body>
</html>

which launched in chrome renders an image like below

enter image description here

However, when I use Puppeteer like below, it doesn’t render the background image regardless it being local or uploaded to the web and given as URL.

async function makeImage() {
    const browser = await puppeteer.launch({headless: "new", defaultViewport: {width: 245, 
    height: 270}});
    const page = await browser.newPage();
    await page.setContent(`
HTML CODE ABOVE
`);
    await page.screenshot({path: 'embed.png'});
    await browser.close();
}

Puppeteer outputs an image like below.

enter image description here

I have seen this issue from the Puppeteer github about local images but because I have tried using online images which won’t be a problem according to the post, I have no idea how to solve this problem.

Also, I will prefer a local solution that does not use a local server. However, any solution will be thankful if it can solve this problem.

js update nested objects with only specified properties

I would like to update an object, with a series of nested objects held within. I want to be able to do this by passing an ‘updating’ object which contains some keys present in the original object, but may omit some others. Any keys present within the updating object should overwrite the original object’s relevant keys. However, any keys which were ommited in the updating object should remain within the orignal object.

Considering an example object like so:

let obj = {
    a:{
        b:{
            c:1,
            d:2,
        },
        e:{
            f:3
        }
    }
}

Using some method, apply the following object to obj

{
    a:{
        b:{
            c:"boo"
        }
    }
}

this update should update obj.a.b.c while maintaining obj.a.b.d and obj.a.e

I have tried using the Object.assign(obj,{ a:{ b:{ c:"boo" } } }) method. However doing so returns the following – which is not what i need.

{
    a:{
        b:{
            c:"boo"
        }
    }
}

As shown, obj.a.e and obj.a.b.c are no longer present, although they were not specified in the updating object – i would like these keys to remain.

How to use variable type ‘any’ as key to a value?

I’m new to JS and React. I’m trying to display a certain image based on the public domain.

I have a dictionary in JS which looks like this:

export const urls = {
    'jp' : '/images/tea.svg',
    'us' : '/images/coffee.svg',
}

In my .tsx file, I null-check the public domain.

const domain = process.env.PUBLIC_DOMAIN !== null ? process.env.PUBLIC_DOMAIN : 'us';

'''

<Image src={urls[domain]}/>

My editor is giving an error at the usage of ‘domain’:

Type 'undefined' cannot be used as an index type.ts(2538)
const domain: string | undefined

I’ve also tried type-casting process.env.PUBLIC_DOMAIN to a string, but it did not work either.

Please let me know how to resolve this, or if there’s a better approach. I’d really appreciate it.

Insert images into advertising frames of a 3D modeled advertising bicycle within a web page

I need to apply mesh to the advertising frames of an advertising bicycle Modeled in 3D in blender, to know the label of that layer and insert an image according to the 3D structure of the advertising box

now I only have a three.js code to insert images on each side of the cube using an html interface using a cube with three.js, but how would I do it to a 3D object that is not basic? In case someone can clarify this problem for me and solve it correctly, I would appreciate it. I would appreciate it, thank you. (by the way the image is in Spanish) example of my idea preview to insert images into a 3D model

Why is variable value incorrect in callback function?

Why is the loading variable in my useInterval callback function not correct? When the callback function is called, the loading variable in the function is always true even though the loading prop in InfoPage eventually is false. How would I fix this?

const InfoPage = ({ loading, fetchDataFn }) => {
  const [lastIntervalTs, setLastIntervalTs] = useState(new Date().valueOf())
  const [lastFetchTs, setLastFetchTs] = useState(new Date().valueOf())

  const refetchData = () => {
    const ts = new Date().valueOf()
    setLastFetchTs(ts)
    setLastIntervalTs(ts)

    fetchDataFn()
  }

  useInterval(() => {
    if (!loading) {
      setLastIntervalTs(new Date().valueOf())
    }
  }, 5000)

  const currentTs = new Date().valueOf()
  if (currentTs - lastFetchTs > 15000) {
    refetchData()
  }
}
const useInterval = (callback, delay = 0) => {
  const savedCallbackRef = useRef(callback)
  const intervalIdRef = useRef()

  useEffect((): void => {
    savedCallbackRef.current = callback
  }, [callback])

  useEffect(() => {
    intervalIdRef.current && clearInterval(intervalIdRef.current)
    if (delay != null) {
      intervalIdRef.current = setInterval(savedCallbackRef.current, delay)
    }
    return () => intervalIdRef.current && clearInterval(intervalIdRef.current)
  }, [delay])
}

Unresponsive select box in materialize

enter image description hereI’m using materialize with a node backend and js front end. I’m trying to submit a form. I have the following:

<div class="container">
  <div class="row">
    <div class="col s6">
      <div class="card">
        <div class="card-content">
          <span class="card-title">Form Example</span>
          <div class="input-field">
            <input type="text" id="zip" name="zip" class="validate" pattern="d{5}"title="Please enter a 5-digit zip code" />
            <label for="zip">Zip Code</label>
          </div>

          <div class="input-field">
            <select id="area" name="area" class="validate">
              <option value="2000">2,000 sqft</option>
              <option value="3000">3,000 sqft</option>
           </select>
            <label for="area">Area</label>
          </div>
        </div>
        <div class="card-action">
          <a class="waves-effect waves-light btn" id="submitButton">Submit</a>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="hot-container" class="mt-4">
  <!-- Handsontable grid will be displayed here -->
</div>

I have an error with the second field(Area) which is greyed out and half visible. It is unresponsive. What am I doing wrong?

How to get all the current cookies ruining on a react app so I could analyze them?

I am trying to create a custom cookies solution that is compatible with GDPR and CCAP. I don’t want to use those ready cookie banners that simply do the work because you don’t have control over them. I want a custom solution, either by trying to create one myself or if there is any good recommendation for this current issue. As of now, I am struggling to get the cookies that are currently running on my production build, for some reason the values are always empty. I am using ‘universal-cookie’ from npm, but I still think there might be something missing. The problem is, I saw a ready-made cookie solution that works by importing a script to your HTML file in the public folder, and it is so cool; it simply gets all the cookies and states the use of each one as well as categorizing them into their related categories. But due to the current requirements, the need for a custom solution is necessary.

import UniversalCookie from 'universal-cookie';

useEffect(() => {
    // Create an instance of UniversalCookie
    const cookies = new UniversalCookie();

    // Get all cookies on your domain
    const allCookies = cookies.getAll();

    // Iterate through and display all available cookies
    for (const cookieName in allCookies) {
      const cookieValue = allCookies[cookieName];
      console.log(cookieName + ' = ' + cookieValue);
    }
  }, []);

Call stack error on button click – Next.js

I have the following button that reaches out to /api/reviews/react:

"use client"

import useFetch from "@/hooks/useFetch";
import { thumbsDown, thumbsUp } from "@/public/icons";
import HTTPMethod from "http-method-enum";
import Image from "next/image";

export default function ReactOnPost({id, reactedBy, user}: {id: string, reactedBy: string[], user: string}) {

  const [data, error, loading, sendFetch] = useFetch();

  const hasReacted = (reactedBy: string[], user: string) => {
    let didReact = false;
    for (let i = 0; i < reactedBy.length; i++) {
        if (reactedBy[i] === user) {
          didReact = true;
          break;
        }
    }
    return didReact;
  }

  const reacted = hasReacted(reactedBy, user)

  if (reacted) {
    return <p>You already reacted. <button className="standard-clear-btn" style={{width: 50, height: 50, fontSize: "1rem"}}>Undo</button></p>
  }
  
    return (
        <div className="reactions">
            <Image src={thumbsUp} alt="Vote up" onClick={() => {
        sendFetch ("/api/reviews/react", HTTPMethod.PATCH, {
          id,
          like: true,
          userId: user
        })
      }}/>
            <Image src={thumbsDown} alt="Vote down" onClick={() => {
        sendFetch ("/api/reviews/react", HTTPMethod.PATCH, {
          id,
          like: false,
          userId: user
        })
      }}/>
        </div>
    );
}

The api endpoint works fine and the data is updated however upon refreshing the page (to show the data) I get an error: Error: Maximum call stack size exceeded.

useFetch hook:

import HTTPMethod from "http-method-enum";
import { useState } from "react";

export default function useFetch() {
    const [data, setData] = useState(null);
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(false);

    const sendFetch = async (url: string, method: HTTPMethod, body: any): Promise <any> => {
        try {
            setLoading(true);
            const rawResponse = await fetch(url, {
                method,
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    body,
                }),
            });

            const response = await rawResponse.json();

            if (!response.ok) {
                throw new Error(response.message)
            }
            setData(response);
        } catch (error: any) {
            console.log(error)
            setError(error);
        } finally {
            setLoading(false);
        }
    };

    return [data, loading, error, sendFetch];
}

FullReview parent component:

import { Stars } from "@/app/app/components";
import { ReactOnPost } from "@/app/app/components";
import { User, Review } from "@/mongo";
import { currentUser } from "@clerk/nextjs";

export default async function FullReview({ reviewData }: { reviewData: any }) {
    const { title, stars, text, id,  createdAt, author } = reviewData;

    const signedInUser = await currentUser()

    const signedInUserStore = await User.findOne ({userId: signedInUser?.id})

    const user = await User.findOne({_id: author})

    const review = await Review.findOne ({author})

    return (
        <div className="full-review">
            <Stars count={stars}/>
            <article>
                <b>{title}:</b>
                <p>{text}</p>
            </article>
            <hr />
            <div className="actions">
            <ReactOnPost id={id} reactedBy={review.reactedBy} user={signedInUserStore._id}/>
            <span>
                {review.likes} votes
            </span>
                <span className="date">
                    Written on {createdAt.toString()} by {user.businessName}
                </span>
            </div>
        </div>
    );
}

What’s going on here? This error only happens when I use the UI to reach the endpoint. The same call stack error doesn’t exist when I use postman to reach the endpoint.

Appian technology to replace traditional Java application

I am curious how feasible is to use Appian to replace a complex web application that uses Java, JavaScript, jQuery, AJAX, , ORM, Oracle stored procedures, reports developed using crystal reports that query data from stored procedures with thousand lines of code?

Are all the features/extensibility available in the Java/Microsoft platforms there in Appian?

I heard Appian is 70% drag and drop and 30% low code.

Thanks

Uncaught TypeError: Cannot read properties of undefined (reading ‘args’) at saveVttFiles (:4:37) at :139:1

My code :
function saveVttFiles(options)
var youtubeArgs = ytplayer.config.args;
var videoName = youtubeArgs.title;
var playerCaptionsTracklistRenderer = youtubeArgs.raw_player_response.captions.playerCaptionsTracklistRenderer;]

I was expecting it to work but it didnt so I want to remove the args and still it doesnt worl [ im a beginner sorry ]