Javascript: Async function appears to return null

I have written a function which in turn calls 2 async functions using await. It then returns a return value. When I output the return value, it shows null. Here is the code.

Function which calls 2 async functions.

async function yttExtractSFC(sfCfg, extCfg) {

    var result;
    var retVal;
    result = await yttGetSFToken(sfCfg);
    if (result.status == 'ok') {
        var accessTkn = result.data;
        result = await yttGetSFCData(sfCfg, extCfg, accessTkn);
        if (result.status == 'ok') {
            retVal = result.data;
        } else {
            retVal = result.status;
        }
    } else {
        retVal = result.status;
    }
    return retVal;
}

Here is the code I am testing with:

doRun () ;
async function doRun () {
    var x = await ysfc.yttExtractSFC(sfCfg,extCfg);
    console.log('got result:' + x.status + '/' + x.data) ;
}

No matter what the return value is, x.status and x.data are shown as ‘undefined’. So what am I doing wrong?

Textarea char count javascript in Jinja2 for-lopp

Guys I am trying to do a simple char count in textarea, and I know the code it’s working because I set it into other pages ass you can see in the picture.

As user type the progress bar shows the status at the end if hit the limit it gets red and shows the number of char from 50 until 0.

modal with progress bar working

Then, I try to apply the same code into a modal.

As you can see in the picture as well, I do have the progress bar but as I type does not work.

modal with progress bar not working

Her is my modal inside a jinja2 for loop:

<div class="modal fade" id="answer-{{post.Id}}" data-bs-backdrop="static" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
        <form class="needs-validation" novalidate action="{{url_for("answer_post", post_id= post.Id)}}" method="POST">
            <div class="accordion accordion-flush" id="accordion-modal">
                <div class="accordion-item">
                    <h2 class="accordion-header" id="flush-heading-post">
                        <span>{{post.Title}}</span>
                    </h2>
                </div>
            </div>

            <div class="modal-body">
                <label for="answer_post">Your Answer*</label>
                <textarea id="textarea_{{post.Id}}" type="text" name="answer_post" 
                    maxlength="500" placeholder="Elaborate your answer..." required>
                </textarea>
                
                <div class="progress mt-3">
                    <div class="progress-bar"></div>
                    <p class="remaining-chars"></p>
                </div>
                
            </div>

            <div class="modal-footer">
                <button type="submit" name="action" class="fp-blue-btn">
                    Answer
                </button>
            </div>
        </form>
    </div>
</div>

One thing I want to point out is that in my textarea for the other inputs I do not have this post.Id only textarea.

I added this Id because if I leave only id=”textarea” it apply the JS but only on the first post in the list the others nothing happens, so I tried to see if that would work but not.

The JS code is also inserted in the for loop scope so I thought would work fine but like I said it only apply for the first item in the list.

My JS that count the char and update the progress bar is as follows:

var textarea = document.getElementById("textarea_{{post.Id}}");
        var progressBar = document.getElementsByClassName("progress-bar");
        var remChars = document.getElementsByClassName("remaining-chars");

        function charCounter(inputField) {
            var maxLength = inputField.getAttribute("maxlength");
            var currentLength = inputField.value.length;
            var progressWidth = (currentLength / maxLength) * 100;
            
            progressBar.style.width = `${progressWidth}%`;
            remChars.style.display = "none";

            if (progressWidth <= 60) {
                progressBar.style.backgroundColor = "rgb(19, 160, 19)";
            } else if (progressWidth > 60 && progressWidth < 85) {
                progressBar.style.backgroundColor = "rgb(236, 157, 8)";
            } else {
                progressBar.style.backgroundColor = "rgb(241, 9, 9)";
                remChars.innerHTML = `${maxLength - currentLength} characters left`;
                remChars.style.display = "block";
            }
        }

        if (textarea != null){
            textarea.oninput = () => charCounter(textarea);
        }

So, that is what I’m having problems guys. If anyone have any idea how to make this JS apply to all textareas into my for-loop I appreciate.

PixiJS v8 -Custom filter: Coordinates issue

I am new at using PixiJS and Custom-Shaders/Filters and I’m trying to render a sprite with a filter, that affects the pixels at the position of the users mouse and turns them red, depending of the distance between the mouse and the pixel. But I just can’t get the position of the red right. Its always offset to the bottom and right.

main.js

const { Application, Assets, Filter, GlProgram, Sprite, Texture } = PIXI;

let app;
(async () => {
    app = new Application();
    await app.init({
        resizeTo: window,
        hello: true,
        preference: 'webgl',
    });
    document.body.appendChild(app.canvas);

    const texture = await Assets.load('./img/Haus1.png');
    const sprite = Sprite.from(texture);
    app.stage.addChild(sprite);

    const filter = new Filter({
        glProgram: new GlProgram({
            fragment,
            vertex: PIXI.defaultFilterVert
        }),
        resources: {
            localUniforms: {
                uLightPosition: { value: [0.0, 0.0], type: 'vec2<f32>' },
                uLightRadius: { value: 0.1, type: 'f32' },
            },
        },
    });

    sprite.filters = [filter];

    addEventListener("mousemove", (event) => {
        const x = (event.clientX - sprite.x) / sprite.width
        const y = (event.clientY- sprite.y ) / sprite.height
    
        filter.resources.localUniforms.uniforms.uLightPosition = [x, y];
    });

    let pixelRadius = 0.1
    addEventListener("wheel", (event) => {
        if (event.deltaY > 0) {
            pixelRadius = (pixelRadius * sprite.width + 5) / sprite.width
            filter.resources.localUniforms.uniforms.uLightRadius = pixelRadius
        }

        if (event.deltaY < 0) {
            pixelRadius = (pixelRadius * sprite.width - 5) / sprite.width
            filter.resources.localUniforms.uniforms.uLightRadius = pixelRadius
        }
    })
})();

fragment-shader:

const fragment = `
in vec2 vTextureCoord;
in vec4 vColor;

uniform vec2 uLightPosition;
uniform float uLightRadius;
uniform vec2 uResolution;
uniform sampler2D uTexture;

void main(void)
{
    float dist = distance(vTextureCoord, uLightPosition);

    float brightness = dist/uLightRadius;

    vec4 fg = texture2D(uTexture, vTextureCoord);

    fg.r = 1.0-brightness;
   
    gl_FragColor = fg;
}
    `

If you look at this link you can experience what I mean

As you hover over the sprite you can see an red light following your mouse. But its position is stretched weirdly and so it shifts apart from the mouse the more you get away from the 0, 0 Point pf the Texture. I want it always positioned at the mouse location.

First Time Pitching a Real-World Project to My Bootcamp — Need Advice on How to Prepare and Present It [closed]

I’m a student at Coding Temple (Python back-end specialization), and I’m about to pitch my first real-world project to my bootcamp for approval as part of our Tech Residency program. I could really use advice from anyone who’s been through something similar — whether you’re a former student, mentor, or instructor.

Here’s the situation:

I’ve connected with a single mom who recently launched a small business, and I want to help her by building a full e-commerce website with a custom API for products, customers, and orders. I also want to turn this into a team project where 2–3 other students can collaborate — both for experience and to make the build stronger.

The mission is twofold:

Give students hands-on experience working with a real client in a team environment

Support someone in the community who’s trying to create a better future through entrepreneurship

Project Summary:
Frontend: React or HTML/CSS/JS

Backend: Flask + SQLAlchemy

Database: MySQL

Auth: JWT

Payments: Stripe or PayPal

Features: Product listings, shopping cart, checkout, admin dashboard, and customer login

What I Need Advice On:
Since this is my first time proposing a project like this, I want to make sure I present it the right way to the school so it has the best chance of being approved.

What should I include in the proposal?
Should I provide wireframes, user stories, or a timeline?
How do I show that this will benefit both the client and the students involved?
What mistakes should I avoid as a first-time lead?

I’m also planning to involve the client in a lightweight way (getting feedback, reviewing milestones, etc.), but she’s non-technical, so I’m open to tips on managing that relationship too.

Any advice, templates, or stories from your own experience would be greatly appreciated. This project means a lot to me, and I want to do it justice.

Thanks in advance
— Jose

How to fit all components on a single screen

I’m developping the frontend for a project however I struggle a bit.
I would like my app to fit the screen without any scroll.
When I add some components to my main view, I start to have scrollbars on X and Y even though my component should have a height of 100%.
You can find all the code here.

You can see the list is overflowing the screen, I would like a scrollbar on it and not on the whole page.
Overflowing components

Here’s a reproducible example (you’ll need react and @mui/material):

import Box from '@mui/material/Box'
import TextField from "@mui/material/TextField";
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Stack from "@mui/material/Stack";
import { Typography } from '@mui/material';

function App() {
  return (
    <Box sx={{ height: '100vh', width: '100vw' }}>
      <Box sx={{ display: 'flex' }}>
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            overflow: 'auto',
          }}
        >
          <Stack
            spacing={2}
            sx={{
              alignItems: 'left',
              mx: 3,
              pb: 5,
              mt: { xs: 8, md: 0 },
            }}
          >
            <Stack
              direction="row"
              sx={{
                display: { xs: 'none', md: 'flex' },
                width: '100%',
                alignItems: { xs: 'flex-start', md: 'center' },
                justifyContent: 'space-between',
                maxWidth: { sm: '100%', md: '1700px' },
                pt: 1.5,
              }}
              spacing={2}
            >
              <Typography>
                Header 1
              </Typography>
              <Typography>
                Header 2
              </Typography>
            </Stack>
            <Stack sx={{ width: '15%' }}>
              <TextField
                variant="outlined"
                size="small"
                placeholder="Search for object"
              />
              <Box sx={{ bgcolor: 'background.paper', overflow: 'auto' }}>
                <List >
                  {[...Array(50)].map((item, index) => (
                    <ListItem key={index} disablePadding>
                      <ListItemButton>
                        <ListItemText primary={'OBJECT_' + index} />
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
              </Box>
            </Stack>
          </Stack>
        </Box>
      </Box>
    </Box>
  )
}

export default App

Thank you for you help.

Image preprocessing in pure JS that is functionally identical to Torchvision’s transforms pipeline

I am trying to rewrite the following Python function in pure JS. The second function example is done in NodeJS but with as much plain JS as possible, because I wish to also run it in the browser.

from PIL import Image
import numpy as np
from torchvision import transforms

def preprocess_image(image_path, img_size=224):
    image = Image.open(image_path).convert('RGB')

    transform = transforms.Compose([
        transforms.Resize(img_size, interpolation=transforms.InterpolationMode.BICUBIC),
        transforms.CenterCrop(img_size),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
    ])

    tensor = transform(image).unsqueeze(0)
    return tensor.numpy().astype(np.float32)

So the goal is to take image input and resize the smallest size to 224, then do a center crop of 224×224 and normalize it. Below is an attempt at doing the same in JS, but the preprocessed image is sadly quite a bit different.

const { createCanvas, loadImage } = require('canvas');

async function preprocessImage(imagePath, size = 224) {
    const image = await loadImage(imagePath);
    const scale = Math.max(size / image.width, size / image.height);
    const w = Math.round(image.width * scale);
    const h = Math.round(image.height * scale);

    // resize
    const tempCanvas = createCanvas(w, h);
    const ctx = tempCanvas.getContext('2d');
    ctx.drawImage(image, 0, 0, w, h);

    // enter crop 224x224
    ctx.drawImage(
    tempCanvas,
    (w - size) / 2, (h - size) / 2, size, size,
    0, 0, size, size                           
    );

    const { data } = ctx.getImageData(0, 0, size, size);

    // normalize
    const mean = [0.485, 0.456, 0.406];
    const std = [0.229, 0.224, 0.225];
    const floatData = new Float32Array(3 * size * size);

    for (let i = 0; i < size * size; i++) {
      for (let c = 0; c < 3; c++) {
        const pixel = data[i * 4 + c] / 255; // normalize to [0,1]
        floatData[c * size * size + i] = (pixel - mean[c]) / std[c];
      }
    }

    return floatData;
}

Google Forms multi-select question often states that it “has changed” and needs to be re-selected when using pre-filled form links

I have a specific issue with a Google Form I have set up. It has a multi-select question where users are asked to select from a list of names.

However, this list of names is dynamically populated from a Google Sheet function that, every few hours, will grab the up-to-date names from the sheet and edit the multi-select question to have just those names. It does that with this code:

// Runs automatically via a trigger every few hours
function updateForm() {
  const FORM_ID = "<ID for the Google Form>";
  const FORM_CHECKBOXES_ID = "<ID for the multi-select question>";

  const form = FormApp.openById(FORM_ID);
  const checkboxes = form.getItemById(FORM_CHECKBOXES_ID).asCheckboxItem();
  const checkboxesChoices = getFormCheckboxChoices(); // Gets the list of names as a string array

  checkboxes.setChoiceValues(checkboxesChoices);
}

Also, links to the form are generated on a regular basis for users to press that are pre-filled with specific names checked depending on context. This is the main way people access this Google Form.

This has worked great, up until recently where I’ve noticed that when people try and submit their filled-in form, it denies the submission with a red text:

The question has changed. Please review your response

Picture of "The question has changed. Please review your response" issue

When the user unselects and reselects the checked items, THEN it allows the user to submit. If a user accesses the base form WITHOUT using a pre-filled link and then selects names from the list, then it also works first try.

I can’t figure out why this is happening. Any ideas?

How to prevent the main thread death after some worker throws an error?

Cant find an answer on how to save my main thread after some workers thread throws an error? As an illustration i can provide something like this:

// this is the main thread
for await(const something of someAsyncIterator){
  const worker=new Worker('worker.js',{type:'module'})
  worker.onerror=()=>{
    worker.terminate()
    console.log('Error is handled, show must go on!')
  }
  console.log(`
    Some other stuff is cycling on here
    but the workers revolution is going to kill me
    by throwing some error at my face! Save me!
  `)
}

// this is worker.js
throw '*Evilishly laughing*'

// and this is what im getting in my console
error: Uncaught (in worker "") (in promise) "*Evilishly laughing*"
error: Uncaught (in promise) Error: Unhandled error in child worker.
    at Worker.#pollControl (ext:runtime/11_workers.js:204:19)
    at eventLoopTick (ext:core/01_core.js:178:7)
Press any key to continue . . .

Im using Deno in particularly but i guess its a V8 behaviour.

How to override color theme of Mui toolpad Dashboard from primary blue to any other color

Iam developing a dashboard using mui toolpad dashboard,and i want to customize the theme color of active sidebar icons from blue to different color but iam not able to. can anyone suggest how to override the blue color by adding custom colors. i have tried many ways here is one example.

import { ThemeProvider, CssBaseline } from '@mui/material'; 
import theme from './theme';

const router = createBrowserRouter([
 {
Component: App,
children: [
  {
    path: '/',
    Component: Layout,
    children: [
      {
        path: '/',
        Component: FirstPage,
      },
      {
        path: '/dashboard',
        Component: Dashboard,
      },
      {
        path: '/contact',
        Component: Contact,
      },
      {
        path: '/users',
        Component: Users,
      },
     ],
    },
   ],
 },

]);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(

 <React.StrictMode>
    <ThemeProvider theme={theme}>
       <CssBaseline />
       <RouterProvider router={router} />
    </ThemeProvider>
</React.StrictMode>

);

reportWebVitals();

How do I implement a live product box customization feature using JavaScript? [closed]

I’m building a feature for a packaging website (PackagingUnit.com) that lets users customize their own custom box before placing an order. The tool should allow users to:

Select dimensions (width, height, depth)

Pick material and quantity

Upload a logo or design

See a live preview of the custom box

I’m using HTML/CSS for layout and plan to handle logic with JavaScript — possibly using Canvas or SVG for the live preview. I’m not sure how to structure the code for real-time updates and visual rendering based on user input.

Are there any libraries or JS frameworks that make this kind of custom box configurator easier to build? Or should I build the rendering logic manually?

Any guidance or examples would be appreciated.

I created a basic HTML form where users can input box dimensions and upload a file. I also started working with JavaScript to dynamically update box dimensions, but I got stuck on how to visually render a live 2D or 3D box preview.

I tried using and some basic draw functions, but it doesn’t scale well when users enter different dimensions. I was expecting to create a more flexible live preview for a custom box that updates in real-time as the user adjusts inputs, similar to how t-shirt or mug design tools work.

I’d like advice on how to structure this properly or if there’s a library to help.

FirebaseUI: Email link authentication link results in “Requested action is invalid”

I have a Python/Flask app running on Google App Engine and I use Firebase Auth with FirebaseUI. I’ve had Google sign-in providers working for some time but I’m now adding email link based sign-ins. I’m able to successfully get the email, but clicking the sign-in link results in an error message on the page:

The requested action is invalid.

The JS console contains another error:

handler.js:220 Request is missing required data

I can’t find anything in the logs relating to this error, and I’ve quadruple checked all the relevant settings in Firebase Console such as authenticated domains, API key permissions, etc.

Here’s my Javascript for invoking FirebaseUI:

var uiConfig = {
    callbacks: {
      signInSuccessWithAuthResult: () => false,
    },
    signInOptions: [
      {
        provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
        signInMethod: firebase.auth.EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD,
        forceSameDevice: false,
        emailLinkSignIn: function () {
          return {
            url: window.location.href,
            // Always true for email link sign-in, according to the docs.
            handleCodeInApp: true,
          };
        },
      },
      {
        provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        customParameters: {
          prompt: "select_account",
        },
      },
    ],
    signInFlow: "popup",
    signInSuccessUrl: redirect_url,
    tosUrl: "https://example.com/terms",
    privacyPolicyUrl: "https://example.com/terms",
  };

  var ui = new firebaseui.auth.AuthUI(firebase.auth());
  ui.start("#firebaseui-auth-container", uiConfig);

Here’s my Firebase config used:

{
    'apiKey': 'API-KEY-HERE',
    'authDomain': 'auth.example.com',
    'projectId': 'MYPROJECT2',
    'appId': 'APP-ID'
}

The email I receive contains a link that looks like this (note that auth.example.com is maintained by Firebase):

https://auth.example.com/__/auth/handler?apiKey=API-KEY&mode=signIn&oobCode=C49X_zEgdOj_cFl3sLh784gnEg-808Q06e7L80VeFPUAAAGXkK4k6Q&continueUrl=https://dev-dot-MYPROJECT2.appspot.com/signin&lang=en

I can’t figure out what’s going on, and even the Gemini AI in the Firebase Console has been no help. Anyone have any ideas what I’m missing here?

workable Firebaseui and Firebaseui Auth both js and css files

I can’t find a more up to date version of Firebaseui.js, Firebase-ui-auth.js, and Firebase-ui-auth.css files from the gstatic.com website. The only version that I can find to date is 6.0.1 which has an inherent flaw (defining an element using ‘name’ instead of ‘id’) that’s failing to load an element in my index.html file.

Odd because this should be a standard set up for a standard authorisation process for signing in with an email (or google, or facebook, or anonymous) address.

I’m also open to using some other more reliable SDK if it can provide me with a standard sign in / on page to enter my website, that includes all the options ie. sign on with Google, etc.

Using Google’s Firebase, especially the Authorisation components that should set up your index.html file with all the buttons and input fields for sign in/on.

NIFI – INSTALLATION FAILURE

i am tryiying to set up NIFI 2.3.0 on my local windows laptop and i have set up java 21.

Issue:

After unzip and navigating to bin and intiating nifi-cmd start the nifi gets started and during the logs check its getting check with below issue.Not sure what goinf wrong i have checked the permissions as well.
enter image description here

enter image description here