Why my javascript code doesn’t work when I set up laguage selector?

I set up a language selector to translate two language numbers, but it doesn’t work, can someone check my code. I use if and else code, but the code seems to get some error. I tried to fix it, but it still does not work.
enter image description here

<html>
<head>
 <style>
 body, input{
  font-size:20;
  }
  body{
  text-align: center;
  }
 </style>
 
    <script>
    function translate()
    {
        var digNum = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
        var freNum = ["une","deux","Trois","quatre","cinq","six","Sept","huit","neuve","Dix"];
        var gemNum = ["ein","zwei","drei","vier","fünf","sechs","Sieben","acht","neun","zehn"];
        if ("languageSelector"="French"){
        document.getElementById("output").textContent = freNum[digNum.indexOf(document.getElementById("num_input").value)] || 'translate';
        }
        else if("languageSelector"="German"){
        document.getElementById("output").textContent = gemNum[digNum.indexOf(document.getElementById("num_input").value)] || 'translate';
        }   
      return translate;
    }   

    </script>
</head>

<body>
    <h1>Amazing Translator</h1>
    <form>
    <input type="number" id="num_input" size="30" placeholder="Enter a number here" />
    </form>
    
    <br >   
     <select id="languageSelector">
      <option>French</option>
      <option>German</option>
     </select>
    <br />
    
    <br >
    <button onclick="window translate()">Translate</button>
    <br />
    
    <h2>This translate is</h2><p id="output">translate</p>

</body> 
</html>

Moving your Async/Await fetch to another file react

How would you move your Async/Await request to another file? It works fine when it is in the main file it is being called from. However it does not work when I am trying to move it to another file and import it to main app.js to then console.log it.

My fetch request is as follows.

export default async function APIrequests() {
  async function fetchMoviesJSON() {
    const response = await fetch(
      `http://www.randomAPIkeylinkhere.com/APIKEY`
    );
    const movie = await response.json();
    console.log(movie);
    return movie;
  }

my app.js after importing the APIrequests.js function

console.log(APIrequests)

All Is a in my dev console is text of my async await code. I know to fix this error while using promise you have to return the actual fetch. Not sure how its done using async/await. Image link of error attached.

return i get instead of response object

Max-Heap implementation: How to make first 3 nodes always the highest?

So I’ve been trying to do an implementation of the Max Heap. The use I want to give to it is that, at any one time, I want the first 3 elements of the heap (that is, the root and it’s two children) to always be the highest in the whole heap. I thought the heap property would guarantee this, but not a single implementation example I have come across has been able to solve the fact that sometimes, there are elements in one level of the heap that are lower than an element in a higher level.
This is the implementation I’ve been using, basically by using examples I have found on the internet as reference:

let createHeap = function(){
  return {
    arr:[],
    size: 0,
    getParent: function(i) { return Math.floor((i-1)/2) },
    getLeft: function(i) { return (2*i + 1) },
    getRight: function(i) { return (2*i + 2) },
    insert: function(val){
      let i = this.size
      this.size++
      this.arr[i] = val;
      if(i!=0){
        for(let j = this.getParent(i);j>=0;j--){
          this.heapify(j)
        } 
      }
    },
    heapify: function(i){
      let largest = i;
      let leftIndex = this.getLeft(i)
      let rightIndex = this.getRight(i)
      if (leftIndex < this.size && this.arr[leftIndex] > this.arr[largest])
        largest = leftIndex
      if (rightIndex < this.size && this.arr[rightIndex] > this.arr[largest])
        largest = rightIndex;

      if (largest != i) {
        let temp = this.arr[largest];
        this.arr[largest] = this.arr[i]
        this.arr[i] = temp

        this.heapify(largest);
      }
    }
  }
}

Now, the problem is, when I insert the following values in this order: 1, 2, 3, 4, 5
The result I get for the heap is:

5
|
4 2
|
1 3

Which is clear when you read what the code does, but doesn’t seem to conserve heap property as far as I got to understand what heap property means. The code is clearly missing something to get to do what I want it to do, but I don’t want to implement changes that would increase the complexity too badly, so I wanted to ask:

  1. Does anyone know if the implementation is wrong or if it was never meant to do what I want it to do?(first 3 elements of the heap always the highest in whole heap)
  2. What would be the best way of implementing this without increasing the complexity too much?

How can I show the result of a mysql query with filters in node js and handlebars

I have the following code for the query

router.get('/a', isLoggedIn, async(req,res)=>{
    const data = await pool.query('SELECT * FROM supporting_documents ORDER BY date desc')
    const report = await pool.query('SELECT * FROM report_weekly ORDER BY semana asc ')
    res.render('math/a', {data,report})
})

 .hbs

        <h2>Monto:{{#each mes}}
            {{else}}
            No hay montos
            {{/each}}</h2>

How could I show the result? In the console.log it shows me the result of the sum, how could I show that result with handlebars?

React controlled MUI form field components

I feel like I am missing the obvious but I can’t seem to find another posts that addresses the issue I am having. I am trying to allow an end user the ability to set a location for an object but either entering the information into a form or by clicking a location on a map. I have a react page with three components.

  1. A Parent container component that holds the other two components.
import {useState} from 'react';
import Box from '@mui/material/Box';

import ObjSetLocationForm from './ObjSetLocationForm';
import ObjSetLocationMap from './ObjSetLocationMap';

export default function LoadSetLocationSet( props ) {
    const [prevLat, setPrevLat] = useState("43.5666694");
    const [prevLng, setPrevLng] = useState("-101.0716746");
    const [newLat, setNewLat] = useState();
    const [newLng, setNewLng] = useState();

    function setCoords(coords){
        setNewLat(coords.lat);
        setNewLng(coords.lng);
    }


    return(
        <Box>
            <ObjSetLocationForm prevLat={prevLat} prevLng={prevLng} newLat={newLat} newLng={newLng} setCoordsFx={setCoords} />
            <ObjSetLocationMap prevLat={prevLat} prevLng={prevLng} newLat={newLat} newLng={newLng} setCoordsFx={setCoords} />
        </Box>
    );
}
  1. A Map component that shows a single point on a map A and allows the end user to click on the map to set the point to a new location (lat/lng) and is a child of the Parent container. I will not post all the code to this component because it is pretty big but the important part is that when a user clicks on the map the new lat/lng values are passed back up to the parent component by calling the setCoords function like so.
        props.setCoordsFx({lat: e.lngLat.lat, lng: e.lngLat.lng});

I have verified that this is working correctly and is passing the values correctly.

  1. A Form component that is the second child of the parent container and allows the end user to enter a Lat/Lng to change the position of the single point on the map. This component is where I am having issues. I have two MUI TextFields in an html form that I want to set to the lat/lng values when the user clicks on the map. When I run through the debugger I can see the values getting passed down to this component from the parent and I can even see that the state values that control the components are getting set but the TextFields values never change.
import {useState, useEffect, useContext} from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';


export default function LoadSetLocationSet( props ) {
    const [newLat, setNewLat] = useState(props.newLat);
    const [newLng, setNewLng] = useState(props.newLng);
  

    function handleSubmit(e) {
        e.preventDefault();

        // Save values to DB.
    } 

    return(
        <Box>
            <form id="SelLocationForm" onSubmit={handleSubmit}>
                <Box sx={{textAlign:'center'}}>
                    <Typography variant="h6" sx={{display:'inline'}}>Current Location</Typography>
                    <Box sx={{display:'flex', alignItems:'center', justifyContent:'center'}}>
                        <Stack direction="row" spacing={3}>
                            <Box>
                                <Box>
                                    <Typography>Latitude</Typography>
                                </Box>
                                <Box>
                                    <Typography>{props.prevLat}</Typography>
                                </Box>
                            </Box>
                            <Box>
                                <Box>
                                    <Typography>Longitude</Typography>
                                </Box>
                                <Box>
                                    <Typography>{props.prevLng}</Typography>
                                </Box>
                            </Box>
                        </Stack>
                    </Box>
                </Box>


                <Box sx={{textAlign:'center', pt:2}}>
                    <Typography variant="h6" sx={{mb:2}}>Enter the Latitude and Longitude or click the new location on the map</Typography>
                    <Typography variant="h6" sx={{display:'inline'}}>New Location</Typography>
                    <Box sx={{display:'flex', alignItems:'center', justifyContent:'center'}}>
                        <Stack direction="row" spacing={3}>
                            <Box>
                                <TextField
                                    id="tbLatitude"
                                    label="Latitude"
                                    type="text"
                                    size="small"
                                    value={newLat}
                                    onChange={(e) => {setNewLat(e.target.value);}}
                                />
                            </Box>
                            <Box>
                                <TextField
                                    id="tbLongitude"
                                    label="Longitude"
                                    type="text"
                                    size="small"
                                    value={newLng}
                                    onChange={(e) => {setNewLng(e.target.value);}}
                                />
                            </Box>
                            <Box sx={{display:'flex', alignItems:'center', justifyItems:'center'}}>
                                <Button variant="contained" type="submit">Set</Button>
                            </Box>
                        </Stack>
                    </Box>
                </Box>
            </form>
        </Box>
    );
}

As you can see I am attempting to use controlled TextFields. So here are my questions/problems:

  1. If setting the default value to a prop value is “anti pattern” how am I supposed to set the default value for form fields if they are a controlled form field?

  2. As I stated earlier when the user clicks on a location on the map it should refresh the form child component and set the values for my controlled form fields to the values passed in but this is not working. How can I accomplish this?

I thought I understood things as I have been doing react for a little bit now but I seem to be lost. Sorry for the newbie question.

image-rendering: pixelated makes pixels inconsistent sizes even when upscaling by integers

I let the user pick an image, I convert the resulting File object to an ImageBitmap using createImageBitmap(), I render that ImageBitmap onto a <canvas> with no scaling applied, then I upscale that canvas using CSS by saying:

canvas{
    transform-origin: top left;
    transform: scale(2);
    image-rendering: pixelated;
}

When I select a .png file containing pixel art where every pixel in the .png is exactly one pixel in the pixel art (this is the image I’m using, for reference), I expect that scaling this .png up by any integer value should create an image where each pixel is consistently square. In this case, going from 1×1 to 2×2.

However for some reason my result looks like this: image depicting issue

Notice how some pixels are rendered 1×1, others 2×2, and some even appear to be 1×2 or 2×1. Why is this happening?

Snippet to further demonstrate issue:

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const img = document.createElement("img");
img.src = "https://oops-studio.com/downloads/demospritesheetforso.png";// I'm confortable using a remote image as the source here since I own this domain and can guarantee that the image will not be removed

img.addEventListener("load", () => {
  canvas.width = img.width;
  canvas.height = img.height;

  ctx.drawImage(img,0,0);
});
body{
  background: black;
}
canvas{
  transform-origin: top left;
  transform: scale(2);
  image-rendering: pixelated;
}
<canvas id="canvas"></canvas>

Next.js GetServerSideProps custom wrapper TypeScript

I created a wrapper for GetServerSideProps SSR function to reduce repetition but I have problem with typing it correctly with TypeScript. Here’s the wrapper:

type WithSessionType = <T extends {}>(
  callback: GetServerSideProps<T>
) => GetServerSideProps<{ session: Session | null } & T>

//                                                 v error
const withSession: WithSessionType = (callback) => async (ctx) => {
  const session = await getSession(ctx)
  const result = await callback?.(ctx)
  const props = result && 'props' in result ? result.props : {}
  return {
    ...result,
    props: {
      session,
      ...props,
    },
  }
}

The error:

Type '(ctx: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { session: Session | null; }; redirect: Redirect; } | { ...; } | { ...; }>' is not assignable to type 'GetServerSideProps<{ session: Session | null; } & T, ParsedUrlQuery, PreviewData>'.
  Type 'Promise<{ props: { session: Session | null; }; redirect: Redirect; } | { props: { session: Session | null; }; notFound: true; } | { props: { session: Session | null; }; }>' is not assignable to type 'Promise<GetServerSidePropsResult<{ session: Session | null; } & T>>'.
    Type '{ props: { session: Session | null; }; redirect: Redirect; } | { props: { session: Session | null; }; notFound: true; } | { props: { session: Session | null; }; }' is not assignable to type 'GetServerSidePropsResult<{ session: Session | null; } & T>'.
      Type '{ props: { session: Session | null; }; }' is not assignable to type 'GetServerSidePropsResult<{ session: Session | null; } & T>'.
        Type '{ props: { session: Session | null; }; }' is not assignable to type '{ props: ({ session: Session | null; } & T) | Promise<{ session: Session | null; } & T>; }'.
          Types of property 'props' are incompatible.
            Type '{ session: Session | null; }' is not assignable to type '({ session: Session | null; } & T) | Promise<{ session: Session | null; } & T>'.
              Type '{ session: Session | null; }' is not assignable to type '{ session: Session | null; } & T'.
                Type '{ session: Session | null; }' is not assignable to type 'T'.
                  '{ session: Session | null; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.ts(2322)

Usecase (that works):

export const getServerSideProps = withSession(async () => {
  return {
    props: {
      custom: 'custom string type',
    },
  }
})

Here is a computed type of getServerSideProps:

const getServerSideProps: GetServerSideProps<{
    session: Session | null;
} & {
    custom: string;
}, ParsedUrlQuery, PreviewData>

It works fine and even InferGetServerSidePropsType infers types correctly but the mentioned error still occurs.

correct auto completion

Any idea how can I make the TypeScript happy here?
Also looking forward suggestions and tips regarding this kind of wrapper if you have any.

im traying to resize an image with javascript but it wont work how can i change the size (width, height) for each element of the image?

so in my program I’m traying to change the size of the parts of an image (boots, horn, background, bull) but when I try to change the size of 1 individual part of the image it wont work here is the code im doing…

const layerConfigurations = [
  {
    layersOrder: [
      { name: "background" },
      { name: "bull" },
      { name: "boots" },
      { name: "horn" },
    ],
  },
];

const shuffleLayerConfigurations = false;

const debugLogs = false;

const format2   = {
  name: "bull",
  width: 423,
  height: 353,
  };

const format   = {
  name: "background",
    width: 1239,
    height: 652,
  };
   
    const format3  = {
      name: "boots",
      width: 297,
      height: 122,
      };
   
      const format4  = {
        name: "horn",
        width: 272,
        height: 189,
        }; ```

I believe the error is here because when I change the size of "background" it successfully changes it, but it will ignore the rest of the code and change the other elements to the same size I've tried many things but it wont work someone please help enter code here... is there anything I have to add/erase to make this work. (im very new to JavaScript so I've been stuck for a long time)..............

Cannot read and send form input value to db, nodejs express post api?

I have written a route to register customers like this:

customerRouter.post(
    '/register', 
    expressAsyncHandler( async (req, res) => {
    const { firstname, lastname, Email, Password } = req.body;
  
    const registerCustomer = await Customers.create({
        firstName: firstname,
        lastName: lastname,
        email: Email,
        password: Password
    })
  
    if (!registerCustomer) {
        res.status(401).send({
            message: "Invalid Customer data",
        });
    }else{
        res.send({
            id: registerCustomer.id,
            firstname: registerCustomer.firstName,
            lastname: registerCustomer.lastName,
            email: registerCustomer.email,
            isAdmin: registerCustomer.isAdmin,
            token: generateToken(registerCustomer)
        });
    };
  
  })
  );

I also have a register screen/page that allows users to register and should send inputs to the backend, the code for the screen is like this:

const RegisterScreen = {
    after_render: () =>{
        document.getElementById('register-form').addEventListener
        ('submit', async (e) => {
            e.preventDefault();
            showLoading();
            const data = await register({
                firstname: document.getElementById('firstname').value,
                lastname: document.getElementById('lastname').value,
                email: document.getElementById('email').value,
                password: document.getElementById('password').value,
            });
            hideLoading();
            if(data.error){
                showMessage(data.error);
            }else{
                setCustomerInfo(data)
                document.location.hash ='/';
            }
        });
    },
    render: () => {
        if(getCustomerInfo().firstName){
            document.location.hash = '/';
        }
        return `
        <section class="menu-section">
        <div class="form-container">
            <form id="register-form">
                <ul class="form-items">
                    <li>
                    <h1>Register!</h1>
                    </li>
                    <li>
                    <label for="firstName"> First Name :</label>
                    <input type="name" name="firstName" id="firstname"/>
                    </li>
                    <li>
                    <label for="lastName"> Last Name :</label>
                    <input type="name" name="lastName" id="lastname"/>
                    </li>
                    <li>
                        <label for="email"> Email :</label>
                        <input type="email" name="email" id="email"/>
                    </li>
                    <li>
                        <label for="password">Password : </label>
                        <input type="password" name="password" id="password"/>
                    </li>
                    <li>
                        <label for="password">Re-Enter Password : </label>
                        <input type="password" name="repassword" id="repassword"/>
                    </li>
                    <li>
                        <button type="submit" class="btn btn-default">Register!</button>
                    </li>
                    <li>
                        <div>
                            Already have an account?
                            <a href="/#/signin"> Sign in!</a>
                        </div>
                    </li>
                </ul>
            </form>
        </div>
        </section>
        `;
    },
};

The fields in my database are written like this: “firstName” “lastName” “email” “password” “isAdmin”:

module.exports = (sequelize, DataTypes) => {
    const Customers = sequelize.define("Customers", {
      firstName: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      lastName: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      email: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      isAdmin: {
        type: DataTypes.BOOLEAN,
        default: '0',
      }
    });
  
    return Customers;
  };

my server.js looks like this:

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import data from './data';
import customerRouter from './routers/customerRouter'

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use("/api/customers", customerRouter);

const db = require("./models");

app.get('/api/products', (req, res)=>{
  res.send(data.products)
})
app.get('/api/products/:id', (req, res) =>{
  const product = data.products.find((x) => x.id === req.params.id);
  if(product){
    res.send(product);
  }else{
    res.status(404).send({message: 'Product Not Found!'});
  }
})

app.use((err, req, res, next)=>{
  const status = err.name && err.name === 'ValidationError' ? 400 : 500;
  res.status(status).send({message: err.message});
})

db.sequelize.sync().then(() => {
  app.listen(5000, () => {
    console.log('Server running on port http://localhost:5000');
  });
});

When I run my registering route in postman it works fine, and is able to register customers through postman, but when I try to enter the values from screen/frontend I get the error: “notNull Violation: Customers.firstName cannot be. null etc.” for each single field.

I have a signin route and screen that is similar which is able to request data and compare and authenticate it. I´m not to sure where I went wrong. Thanks for any suggestions in advance.

Click on radio button affter all with same name

I have a page with many radio with same name

a demo is available here

https://jsfiddle.net/4twyohjx/2/

Problem I have it’s when I click on one, that affect other.

kidSection can be added via ajax

Js code of event,

$("#kidsSection").on('click', '.kidsTutorYes', function(e) {

  $(this).parent().parent().nextAll('.kidTutor, #kidsSectionAdd').eq(0).removeClass('visually-hidden');

});

$("#kidsSection").on('click', '.kidsTutorNo', function(e) {

  $(this).parent().parent().nextAll('.kidTutor, #kidsSectionAdd').eq(0).addClass('visually-hidden');

});

MongoDB parameters to filter through array

I have a problem through an array with mongoDB parameters… assuming I have this two arrays

const diversityArray = ['video', 'gps']
const entries = [
  {
    name: 'First entry',
    slug: 'first',
    diversity: 'image, video'
  },
  {
    name: 'Second entry',
    slug: 'second',
    diversity: 'image, gps'
  },
  {
    name: 'Third entry',
    slug: 'third',
    diversity: 'iframe'
  }];

How could I do this but with mongoDB parameters? I want to filter all the items in the array that contains one or more of the items on the diversityArray.

const filtered = entries.filter(item => diversityArray.some(data => item.diversity.includes(data)));

I need to do this because I have a larger and more complex array coming from Builder.io Headless CMS and I want to do the filter in the query.

I have this code right now:

    const sets = await builder.getAll('open-dataset', {
      options: { noTargeting: true },
      limit: 100,
      query: {
        data: {
          date: { $gt: newMinYear, $lt: newMaxYear },
          title: { $regex: search, $options: 'i' },
          diversity: ...what I want to do
        }
      }
    });

Thanks!

Crypto.sign() function to sign a message with given private key

I need to sign a message with crypto.sign() function in NodeJS to get a valid JWT.
I have a private key (base 64) like this:

Dm2xriMD6riJagld4WCA6zWqtuWh40UzT/ZKO0pZgtHATOt0pGw90jG8BQHCE3EOjiCkFR2/gaW6JWi+3nZp8A==

And I tried to get a signature:

const getJWT = () => {
  const privateKey =
    "Dm2xriMD6riJagld4WCA6zWqtuWh40UzT/ZKO0pZgtHATOt0pGw90jG8BQHCE3EOjiCkFR2/gaW6JWi+3nZp8A==";
  const payload = {
    iss: "test",
    aud: "test.com",
    iat: 1650101178,
    exp: 1650101278,
    sub: "12345678-1234-1234-1234-123456789123"
  };
  const token = encode(payload, privateKey);
  return token
};

const encode = (payload, key) => {
  const header = {
    typ: "JWT",
    alg: "EdDSA"
  };
  const headerBase64URL = base64url(JSON.stringify(header));
  const payloadBase64URL = base64url(JSON.stringify(payload));
  const msg = Buffer.from(`${headerBase64URL}.${payloadBase64URL}`);
  const keyDecoded = Buffer.from(key, "base64");
  const signature = crypto.sign("Ed25519", msg, keyDecoded); //Here is the problem
  const signatureBase64url = base64url(Buffer.from(signature));
  return `${msg}.${signatureBase64url}`;
};

I received this error:

internal/crypto/sig.js:142
  return _signOneShot(keyData, keyFormat, keyType, keyPassphrase, data,
         ^

Error: error:0909006C:PEM routines:get_name:no start line

  library: 'PEM routines',
  function: 'get_name',
  reason: 'no start line',
  code: 'ERR_OSSL_PEM_NO_START_LINE'

How can I adapt my private key to a valid format?

Error: Type ‘JQuery cannot be used as an index type

I’m trying to make a function that “grays out” a datatable when a checkbox is unchecked.

error on regionalSettingsData[activeTabId][columnName][row][visibility].is(true); and regionalSettingsData[activeTabId][columnName][row][visibility].is(false);

JavaScript:

     $uiComponent.find("input[name='EnableNightlyCreation']").on('change', (event) => {
            let disable = $(event.target);
            const activeTabPane = $uiComponent.find('div.tab-pane.active');
            const activeTabId = activeTabPane.prop('id');
            const table = activeTabPane.find('table');
            const row = disable.data('row');
            const columnName = disable.data('columnName');
            const tabledata = regionalSettingsData[activeTabId];
            const checkbox = table.find('input[type="checkbox"]');
            let  visibility = table.find('visible');
          
            if (disable.is('checked')) {
                regionalSettingsData[activeTabId][columnName][row][visibility].is(true);

            }
            else {
                regionalSettingsData[activeTabId][columnName][row][visibility].is(false);
            };

        });