Google Recaptcha on explicit render for mulitple forms it returns “Invalid key type” error

I’m having some issues on implementing Google recaptcha validation on a single page having multiple forms.
Reading many posts on the argument has led me to this design, that includes the possibility of using html5 validations before submitting the recaptcha validAtion:

HTML side

<head>
....
<script src="https://www.google.com/recaptcha/enterprise.js?onload=CaptchaCallback&render=explicit" async defer></script>
</head>
<body>
...
<form id="contactFrm1">
...
<div id="RecaptchaField1" class="g-recaptcha" data-callback="formSubmit1"></div>
...
</form>
...
...
<form id="contactFrm2">
...
<div id="RecaptchaField2" class="g-recaptcha" data-callback="formSubmit2"></div>
...
</form>
..
</body>

Javascript Side

<script>
var CaptchaCallback = function() {
    jQuery('.g-recaptcha').each(function(index, el) {
            var widgetId = grecaptcha.enterprise.render(el, {'sitekey' : SITE_KEY});
        jQuery(this).attr('data-widget-id', widgetId);
    });
};
    
$(document).ready(function() {      
    $("#submit").click(function(){
    $('#contactFrm1').submit(function(event) {
    if (!grecaptcha.enterprise.getResponse(jQuery('#RecaptchaField1').attr('data-widget-id'))){
        event.preventDefault(); //prevent form submit
        grecaptcha.enterprise.execute(jQuery('#RecaptchaField1').attr('data-widget-id'));
                }
    });
    formSubmit = function() {
    $('#contactFrm1').submit();
            }
    }); 
});

//same logic for the second form
</script>

On rendering the page shows, for both of captcha widgets, “Note for site owner: Invalid key type”.

I’m sure about the validity of the key, due to the fact that using the “not explicit” rendering do not return any kind of error and, at last, the key is valid from the Google administration settings.

Can you please help me to understand what is wrong with this solution?
Thanks in advance

Some posts showed that the problem should be on the execute methods, that it’s expecting the widget_id, in a first version I didn’t provide it, but after introducing it the result hasn’t changed.
Google documentation is not really exhaustive…

How to remove Ref before leaving the screen in React / React native?

I would like to to remove Ref before leaving the screen in React / React native because it causes keyboard flickering on navigating back.

My code is:

 // To focus on the input field when the page loads
    const privateNotesInput = useRef<AnimatedTextInputRef | null>(null);
    const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);

    useHtmlPaste(privateNotesInput);

    useFocusEffect(
        useCallback(() => {
            focusTimeoutRef.current = setTimeout(() => {
                if (privateNotesInput.current) {
                    privateNotesInput.current.focus();
                }
                return () => {
                    if (!focusTimeoutRef.current) {
                        return;
                    }
                    clearTimeout(focusTimeoutRef.current);
                };
            }, CONST.ANIMATED_TRANSITION);
        }, []),
    );
    
    
     <InputWrapper
                        InputComponent={TextInput}
                        role={CONST.ROLE.PRESENTATION}
                        inputID={INPUT_IDS.PRIVATE_NOTES}
                        label={translate('privateNotes.composerLabel')}
                        accessibilityLabel={translate('privateNotes.title')}
                        autoCompleteType="off"
                        maxLength={CONST.MAX_COMMENT_LENGTH}
                        autoCorrect={false}
                        autoGrowHeight
                        containerStyles={[styles.autoGrowHeightMultilineInput]}
                        defaultValue={privateNote}
                        value={privateNote}
                        onChangeText={(text: string) => {
                            debouncedSaveNote(text);
                            setNote(text);
                        }}
                        ref={(el: AnimatedTextInputRef) => {
                            if (!el) {
                                return;
                            }
                            privateNotesInput.current = el;
                            updateMultilineInputRange(privateNotesInput.current);
                        }}
                    />

If someone knows how to solve it then please let me know. Thanks

Getting Angular error – TypeError – cannot read property of undefined when trying to fetch coordinates from database and marking a location on map

I am trying to implement a function where user searches for a ship, which sends a fetch request to the backend for fetching data of that ship from database, from which co-ordinates of that ship and then display them on map. But I keep getting cannot read property of undefined, even when backend is sending the data (I am using SpringBoot for the backend and Postgre is the database).

Angular Module script –

let myAngular = angular.module('searchApp', [])

myAngular.controller('SearchController', function($scope, $rootScope) {
        $scope.check = false;
        $scope.searchResult = '';

        $scope.searchValues = function() {
            var searchText = document.getElementById('mySearch').value;
            fetch(`/shipdata/${searchText}`)
                .then(response => response.json())
                .then(data=>{
                    $scope.searchResult = data;
                    $scope.check = true;
                    console.log($scope.searchResult)

                })
                .catch(error => {
                    console.error('An error occurred while fetching:', error);
                    $scope.searchResult = 'Error occurred while fetching data';
                }
            );
        }

        let setValues = function (){
            if ($scope.searchResult &&
                $scope.searchResult.positionReportDTO &&
                $scope.searchResult.shipStaticDataDTO &&
                $scope.searchResult.positionReportDTO.Longitude &&
                $scope.searchResult.positionReportDTO.Latitude &&
                $scope.searchResult.shipStaticDataDTO.ShipName) {
                $rootScope.shipLocation = {
                    latitude: $scope.searchResult.positionReportDTO.Latitude,
                    longitude: $scope.searchResult.positionReportDTO.Longitude,
                    shipname: $scope.$scope.searchResult.shipStaticDataDTO.ShipName
                };
            } else {
                console.log("VALUES NOT FOUND")
            }
        };

        function checkAndDo() {
            if (!$scope.check) {
                setTimeout(checkAndDo, 100); // Check again after 100 milliseconds
            } else {
                setValues();
            }
        }
        checkAndDo();

        $scope.plot = function(){
            {

                let myIcon = L.icon({
                    iconUrl: '../images/ship.png',

                    iconSize:     [38, 95], // size of the icon
                    iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
                    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
                });

                $scope.plotLatitude = $rootScope.shipLocation.latitude
                $scope.plotLongitude = $rootScope.shipLocation.longitude
                $scope.plotShipName = $rootScope.shipLocation.shipname
                console.log($scope.plotLatitude, $scope.plotLongitude)
                L.marker([$scope.plotLatitude, $scope.plotLongitude], {icon: myIcon}).addTo(map).bindPopup('Ship Name: ' + $scope.plotShipName).openPopup()
                map.setView($scope.plotLatitude, $scope.plotLongitude)

            }
        }

    });

Please can anyone help me understand what might be causing the error, and how to fix it

I dont how to use “path” in app.use(). It gives me a result that I was not expected

I am new in express.js and I want to know how to use “path” in app.use() excatly. When I try the code which is following, I get a result but I am so confusing. Can you explain why the result is like that. Thank you so much.

My code is following:

const express = require('express');
const router = express.Router()
const app  = express();
const port = 3000;

app.listen(port, ()=>{
    console.log("Running");
})

app.use("/test",router)
// app.use()


router.get("/test",(req,res,next)=>{
    console.log("test 1");
    console.log(req.originalUrl);
    next()
})


router.get("/",(req,res,next)=>{
    console.log("first /");
    console.log(req.originalUrl);
    next()
})
router.get("/test",(req,res,next)=>{
    console.log("test 2");
    console.log(req.originalUrl);
    next()
})

router.get("/",(req,res,next)=>{
    console.log("second /");
    console.log(req.originalUrl);
    next()
})

And, I did test in “http://localhost:3000/test” but the result is not as I expected. Console output is :

first /
/test
second /
/test

But I was expected that result will be

test 1
/test
test 2
/test

Why is it like that? Could you explain to me? Thank you so much.

ERROR TypeError: Cannot read property ‘putVocabularies’ of undefined, js engine: hermes

I’m currently developing an app. I’m new to aws-amplify everything was working completely fine until my baby sister deleted my node modules by mistake. After reinstalling my node modules I get these two errors

ERROR TypeError: Cannot read property ‘putVocabularies’ of undefined, js engine: hermes

ERROR Invariant Violation: “main” has not been registered. This can happen if:

  • Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
  • A module failed to load due to an error and AppRegistry.registerComponent wasn’t called., js engine: hermes

if im correct i know main can come up if the wrong dependencies are installed.

Please i was very close to completing my project and this have me at a major set back

I tried reinstalling aws-amplify install as well as aws-amplify-react-native but nothing works I get the same error over and over

index array checkbox not functioning

The checkbox that is created next to the task can not be set to the checked position which would create a line across the task. When opening console I don’t get any errors only an issue which is:

(A form field element has neither an id nor a name attribute)

Which when clicking on the checkbox increments up.
I am not sure how to assign a name or attribute to the checkbox as this is what i assume the problem is.

This is the function that would create the check box and list item in the java script file.

function renderTasks () {
    const taskList = document.getElementById("added-task")
    taskList.innerHTML = "";
    tasks.forEach((task, index) => {
        const li = document.createElement("li");
        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.checked = task.completed;
        checkbox.addEventListener("change", () => toggleTask(index));
        li.appendChild(checkbox);

This is the body from the index.html file

<div class="container">
    <input type="text" id="addTaskInput" placeholder="Add Task">
    <button class="add-task-btn" onclick="addTask()">Add Task</button>
    <ul id="added-task"></ul>
</div>

This is the style sheet that crosses off the listed item.

.task.completed {
    text-decoration: line-through;
    color: #ccc;
}

in react native is there any way to transform long text to scroll horizntal like in books?

i have a long text from a json file and i want to view it horizntal in pages like PageViewris there any way to do that? here is my code :

    <ScrollView style={customStyles.container}>
      <View style={customStyles.verses}>
        {verses.map((verse: string, index: number) => (
          <Pressable
            style={({ pressed }) => [
              {
                backgroundColor: pressed ? 'rgb(210, 230, 255)' : 'white',
              },
              customStyles.wrapperCustom,
            ]}
            onPress={async () => {
              sheetRef.current.open()
              const versesParse = verse.toString()
              // await AsyncStorage.setItem(verses, 'versesParse')
              // console.log('doneeeeeee');

            }

            }
            key={index}
          >
            <Text key={index} allowFontScaling={false} selectable={true} style={customStyles.verse}
            >
              <Text selectable={true} adjustsFontSizeToFit style={{ flex: 1, }}>
                {verse}
                {/* <Text>{index + 1}</Text> */}
                {/* <Image source={verseBullet} resizeMode="contain" style={customStyles.verseBullet}></Image> */}
              </Text>
            </Text>
          </Pressable>
        ))}
      </View>
    </ScrollView>

here is what i get`

using Three.js in Nextjs 14 – ReferenceError: document is not defined

I know this specific error has been asked here multiple times but i think this situation is unique enough to deserve its own post.

So i Just started thinkering with three.js in nextjs 14.
Everything seems to work perfectly locally but i still see the following error:
ReferenceError: document is not defined

I think there’s a point in here somewhere that uses the document to early to create the canvas i think but i haven’t located it yet as i suppose it will be in the threejs code itself.

Anyone here done something similar like this and knows where this issue get triggered?

"use client";
export const dynamic = "auto";
import { ISSPosition, fetchISSPosition } from "@/lib/api";
import { convertCoordsToSphere } from "@/lib/functions";
import React, { useRef, useEffect, useState } from "react";
import * as THREE from "three";

const earthRadius = 10;
const scene = new THREE.Scene();

// Fog setup
...

// Camera and renderer setup
...

const renderer = new THREE.WebGLRenderer({
  alpha: true,
  antialias: true,
});

// Lighting setup
...

// Earth model setup
const geometry = new THREE.SphereGeometry(earthRadius, 64, 64);
const earthMat = new THREE.MeshPhongMaterial({
  shininess: 350,
  map: new THREE.TextureLoader().load("/earth_texture.jpg"),
  bumpMap: new THREE.TextureLoader().load("/earth_texture.jpg"),
});
const earth = new THREE.Mesh(geometry, earthMat);
earth.receiveShadow = true;
earth.rotation.x = 0.3;
scene.add(earth); // Add Earth to the scene upfront

// ISS model setup
...

const animate = () => {
  requestAnimationFrame(animate);
  earth.rotation.y -= 0.001;

  renderer?.render(scene, camera);
};

const ThreeScene = () => {
  const [issPosition, setIssPosition] = useState<ISSPosition>();
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const fetchISSData = async () => {
      setIssPosition(await fetchISSPosition());
    };

    const intervalId = setInterval(fetchISSData, 5000);

    if (typeof window !== "undefined") {
      containerRef.current?.appendChild(renderer.domElement);
    }

    animate();

    const handleResize = () => {
      if (renderer) {
        let size =
          window.innerWidth * 0.8 > 800 ? 800 : window.innerWidth * 0.8;
        renderer.setSize(size, size);
      }
    };

    handleResize();
    window.addEventListener("resize", handleResize);

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  useEffect(() => {
    const animate = () => {
      requestAnimationFrame(animate);

      if (issPosition) {
        const pointCoords = convertCoordsToSphere(
          Number(issPosition.iss_position.latitude),
          -Number(issPosition.iss_position.longitude),
          earthRadius
        );

        issPoint.position.copy(pointCoords.applyMatrix4(earth.matrix));
        scene.add(issPoint);
      }

      renderer.render(scene, camera);
    };

    animate();
  }, [issPosition]);

  return (
    typeof window !== "undefined" && (
      <>
        <div className="m-auto max-w-fit" ref={containerRef}></div>
        {issPosition ? (
          <div className="flex flex-col gap-2 mb-8 w-fit justify-center items-center mx-auto">
            <span>Latitude: {issPosition?.iss_position.latitude}</span>
            <span>Longitude: {issPosition?.iss_position.longitude}</span>
          </div>
        ) : (
          <div className="flex gap-4 justify-center">
            <p className="mb-4">Locating ISS</p>
            <i className="border-b- border-primary w-4 h-4 rounded-full animate-spin"></i>
          </div>
        )}
      </>
    )
  );
};

export default ThreeScene;

I got this error for multiremote capabilities whre I want to use object model: Error: ReferenceError: $ is not defined

I need help on how to use object model when I have multiremote capabilities as below:
Fyi, this is webdriverio, and use multiremote appium and chromedriver

   capabilities: {

        myBrowser: {
            "host": "localhost",
            "port": 9515,
            "path": "/",
            capabilities: {
                browserName: 'chrome',
                //browserVersion: '122.0.6261.39'
            }
        },
        myMobile: {
            "host": "localhost",
            "port": 4723,
            capabilities: {
                platformName: 'Android',
                'appium:deviceName': 'Pixel 4',
                'appium:platformVersion': '11.0',
                'appium:automationName': 'UIAutomator2', //make sure it's in UIAutomator2, not UiAutomator2
                'appium:app': path.join(process.cwd(), 'app\android\ApiDemos-debug.apk')
            }
        }
    },

Let say, my screen object are as below:

class TestScreen{
    get firstText(){
        return $('//android.widget.TextView[@content-desc="Accessibility"]');
    }

    async clickText(){
        await this.firstText.click();
    }
}

module.exports = new TestScreen();

So I tried it in my spec file, but it failed:

const { firstText } = require("../screen/test-screen.spec");


describe('test run', () =>{
    it('test run', async () => {
        await myMobile.firstText.click();
        
    })
})

I want the code to be able to use object model with the multiremote capabilities

Why can’t typescript infer these correlated types?

Having the following code:

const foo = (flag: boolean) => {
  if (flag) {
    return {
       success: true,
       data: {
         name: "John",
         age: 40
       }
    }
  }

  return {
    success: false,
    data: null
  }
}    

const result = foo(true);

if (result.success) {
   console.log(result.data.name); // TS error: 'result.data' is possibly 'null'
}

Why can’t typescript infer that data always exists if flag is set to true?

I know I can fix this by defining a return type for the function, but it’d be good if TS automatically infers it.

Javascript: Change a function parameter that has a default value without having to change the preceding ones [duplicate]

How to modify a default parameter in a javascript function, knowing that the previous parameters must remain default?

function f(a = 'a', b='b', c='c') {
  return [a, b, c];
}

f( c ='some value here'); //must return ['a', 'b', 'some value here']

I want something similar to what can be done in python.

def f(a = 'a', b = 'b', c ='c'):
    return [a, b, c]

f(c = 'some value here') #will return ['a', 'b', 'some value here']

Is there any way to do this ?

Create Event on Teamup Calendar permissions error

I am attempting to create an event in my Teamup calendar from javascript.

I send:

{ 
  method: 'POST',
  contentType: 'application/json',
  headers: 
  {  
    Accept: 'application/json',
    'Teamup-Token': <api_token>,
    Authorization: 'Bearer <auth_code>' 
  },
  payload: '{"subcalendar_ids":[0],"start_dt":"2024-08-24T14:15:22Z","end_dt":"2024-08-24T14:15:22Z","all_day":false,"tz":"Europe/London","remote_id":"string","title":"Test Title","notes":"Test Desc\n","location":"Home, EX6 6LQ","who":"Test Organiser","signup_enabled":false,"comments_enabled":false}',
  muteHttpExceptions: true 
}
To: https://api.teamup.com/<mycalendarurl>/events

But get:

{"error":{"id":"no_permission","title":"No permission","message":"You do not have the required permissions to do this. This may be due to a change in permissions of your link since you loaded the calendar. Please refresh the calendar."}}

I have requested the <auth_code> authentication token immediately before posting this request.
I haven’t changed permissions, and dont understand what “Please refresh the calendar” means (have quit from my browser, gone back to my calendar, refreshed that webpage etc…)

I am using <mycalendarurl> generated specifically for api calls with modify permissions in the Sharing section of the Teamup dashboard.
I generated <api_token> from the Request Teamup API Key page on the Teamup website

I can find no documentation on the required subcalendar_ids key, and have used 0 as per the example code hoping that indicates the first calendar

This is very close to working because it complains about the dates ‘does not match any accepted ISO8601 date format.’ if I include the 000 millisecond part from toISOString() as opposed to the permissions issue.

MongoDB cross-server document update is not working

I’m using microservice architecture where i have multiple servers. in first server i have user schema for users and when I’m trying to update something from different server, but it’s not updating anything, and also I’m not getting any error.

  //getting users collection without schema and i'm able to read the document with this but not             able to update anything
 `const mongoose = require("mongoose");
 const User = mongoose.model("User", {}, "users");
 module. Exports = User;`

i don’t know if there any policy for security, or any restriction to update from cross-server connection

i asked ChatGPT, Gemini: say’s i can update document, but i don’t know what I’m doing wrong