Triggering an in-app action when app opened by notification press [FCM][React Native][iOS]

I am developing a React Native app and am facing an issue with Firebase Cloud Messaging. The base notification functionality works well and has been used to send a number of notifications in production. However, I am trying to enhance my notification ability by triggering an in-app action when my app is opened via a notification press (currently, opening via notification takes the user to the home page).
I successfully implemented this in the iOS simulator – I click the notification and the action is triggered as expected. However, it is not working in Testflight. I am only concerned with what occurs when the app is in the background, and this is what I am testing in both scenarios (simulator vs. testflight)
I am using @react-native-firebase/messaging
and am not using any third-party libraries such as Notifee

The payload I am sending is: data: {“action”:”open_x_screen”}

This is the handler for the notification, found in my App.js

useEffect(() => {
    // Function to handle notification open
    const handleNotificationOpen = (remoteMessage) => {
      if (remoteMessage && remoteMessage.data && remoteMessage.data.action) {
        const action = remoteMessage.data.action;
        if (navigationRef.isReady()) {
          switch(action) {
            case 'open_x_screen':
              navigationRef.navigate('x_screen', { button: 'x' });
              break;
            case 'open_y_screen':
              console.log("Received")
              navigationRef.navigate('y_screen', { button: 'y' });
              break;
            case 'open_z_screen':
              navigationRef.navigate('z_screen', { button: 'z' });
            default:
              break;
          }
        }
      }
    };
    messaging().onNotificationOpenedApp(handleNotificationOpen);
    messaging().getInitialNotification().then(handleNotificationOpen);
  }, []);

I have not included the rest of my App.js because I believe this is more configuration related than code related, and I do not think the issue has to do with my use of navigationRef or other parts of my App.js. I am making this assumption based on the fact that it works in the simulator but not in Testflight

How to remove a specific element from an array that is in node.js using vanilla js?

I’m trying to put buttons on my page that delete posts the user has made, like on a social network. And I would like to know how I can remove a specific element in my code using js since the array is in node.js. Every time I refresh the page, the element that was deleted using the delete button appears again.

<script>
        const deleteBtn = document.querySelectorAll(".ri-close-line");
        const postDelete = document.querySelectorAll(".new-post");
        for(let i = 0; i < postDelete.length; i++) {
            deleteBtn[i].addEventListener("click", function () {
                postDelete[i].remove();
            });
        }
    </script>

This is the ejs code:

<% if (locals.PostArray) { %>
    <% for (let i = 0; i < PostArray.length; i++) { %>
            <% if (locals.createPost) { %>
    <div class="container-new-post">
        <div class="new-post post">
            <div class="image-profile-new-post-box">
                <img src="/images/profile.jpg" alt="Profile image" class="image-profile-new-post">
            </div>
            <div class="text-line-new-post">
                <div class="first-line-new-post">
                    <div>
                        <span class="profile-name-new-post"> XXX </span>
                        <span class="profile-user-new-post"> XXX </span>
                    </div>  
                    <div class="incons-new-post">
                        <i class="ri-pencil-line"></i>
                        <i class="ri-close-line post"></i>
                    </div>
                </div>
                <div class="text-new-post">
                       <form action="/text" method="POST">
                            <input type="text" name="text-post" value="<%= PostArray[i] %>" class="text-post-edit" contenteditable="false">
                       </form> 
                </div>
                <div class="last-line-new-post">
                    <div class="incons-new-post" id="incons-new-post1">
                        <i class="ri-chat-3-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post2">
                        <i class="ri-repeat-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post3">
                        <i class="ri-heart-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post4">
                        <i class="ri-bar-chart-grouped-line"></i>
                    </div>
                    <div class="incons-new-post" id="incons-new-post5">
                        <i class="ri-save-3-line"></i>
                        <i class="ri-share-line"></i>
                    </div>
                </div>
        </div>
    </div>
    <% } %>    
    <% } %>
    <% } %>

And this is my node.js code:

import express from "express";
import bodyParser from "body-parser";

const port = 3000;
const app = express();

var userIsAuthorized = false;
var createPostArray = []

let data0;

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

function passwordCheck(req, res, next) {
    if (req.body.password === "XXXX" && req.body.email === "XXXX") {
        userIsAuthorized = true;
    }
    next();
}

app.use(passwordCheck);

app.get("/", (req, res) => {
    res.render("login.ejs")
});

app.post("/check", (req, res) => {
    if(userIsAuthorized === true) {
        res.redirect("/home");
    } else {
        res.redirect("/");
    }
});

app.get("/home", (req, res) => {
    res.render("index.ejs", {
        createPost: data0,
        PostArray: createPostArray, 
    })
});

app.post("/post", (req, res) => {
    const textPost = req.body["createPost"];
    data0 = textPost;
    createPostArray.push(textPost);
    res.redirect("/home");
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

I tried putting the array in js and using the array variable in vanilla js, but that didn’t work.

How can I use selenium to iterate over pages on a Website?

I’m trying to write a piece of code in Python to scrape the following website for all the listed urls.

https://yavapai.arizonataxsale.com/index.cfm?folder=previewitems

What I’ve run into is that the site uses javascript, where you page through to access all the data. I failed using beautifulSoup because it is unable to iterate through all the pages since there is only one website url and it can’t interact with javascript to go page by page. I tried the select function but couldn’t get it to work.

I’ve started to try to figure out selenium, but haven’t had any luck either, I’m not very familiar with this package.

Been completely stumped on this for the last week, I know I’m missing something!If anyone is able to help or point me in the right direction I would be really grateful!

SGF Grammar Parser with Peggy

Ideally, I would like to parse SGF’s complete grammar. However, at this point, I’m stuck at trying to handle the recursive part only. Here’s my feeble attempt at it so far:

import { generate } from "peggy"

const grammar = /* peggy */ `
  string = .*

  parensList = '(' string parensList ')'
             / string
`

const sgf1 =
  "(;GM[1]FF[4]CA[UTF-8]AP[Sabaki:0.52.2]KM[6.5]SZ[19]DT[2023-12-25];B[pd];W[dd];B[pq];W[dp])"

const parser = generate(grammar)

const parse = parser.parse(sgf1)

console.log(parse)
// Prints this:
// [
//   '(', ';', 'G', 'M', '[', '1', ']', 'F', 'F', '[', '4',
//   ']', 'C', 'A', '[', 'U', 'T', 'F', '-', '8', ']', 'A',
//   'P', '[', 'S', 'a', 'b', 'a', 'k', 'i', ':', '0', '.',
//   '5', '2', '.', '2', ']', 'K', 'M', '[', '6', '.', '5',
//   ']', 'S', 'Z', '[', '1', '9', ']', 'D', 'T', '[', '2',
//   '0', '2', '3', '-', '1', '2', '-', '2', '5', ']', ';',
//   'B', '[', 'p', 'd', ']', ';', 'W', '[', 'd', 'd', ']',
//   ';', 'B', '[', 'p', 'q', ']', ';', 'W', '[', 'd', 'p',
//   ']', ')'
// ]

Peggy is the successor of Peg.js.

I think I’m failing to identify how to make this recursive properly. How do I make it identify a ( and get into another level with parensList? (I think I need to define string without ( and ) as well…)

What I’m expecting as a result is some sort of tree or JSON like this:

<Branch>{
  moves: [
    <Move>{
      [property]: <Array<String>>
    },
    ...
  ],
  children: <Array<Branch>>
}

But this would be fine as well:

<NodeObject>{
  data: {
    [property]: <Array<String>>
  },
  children: <Array<NodeObject>>
}

SGF is basically a text-based tree format for saving Go (board game) records. Here’s an example — SGF doesn’t support comments, and it’s usually a one-liner, the code below is just to make it easier to read and understand —:

(
  ;GM[1]FF[4]CA[UTF-8]AP[Sabaki:0.52.2]KM[6.5]SZ[19]DT[2023-12-25] // Game Metadata
  ;B[pd] // Black's Move (`pd` = coordinates on the board)
  ;W[dd] // White's Move
    ( // Parentheses denote a branch in the tree
      ;B[pq]
      ;W[dp]
    )
    (
      ;B[dp]
      ;W[pp]
    )
)

The whole grammar is this:

Collection     = { GameTree }
GameTree       = "(" RootNode NodeSequence { Tail } ")"
Tail           = "(" NodeSequence { Tail } ")"
NodeSequence   = { Node }
RootNode       = Node
Node           = ";" { Property }
Property       = PropIdent PropValue { PropValue }
PropIdent      = UcLetter { UcLetter }
PropValue      = "[" Value "]"
UcLetter       = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
                 "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
                 "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"

You can use the editor Sabaki to create SGF files.

Why window.innerHeight is bigger than real on mobile?

I am using Intersection Observer API to handle when specific DOM elements are in the visible area. It works perfectly in the browser but when I switch to mobile (in Chrome DevTools) it has a strange behavior. When I am scrolling the elements remain as intersected long after they leave the visible area.

I noticed that window.innerHeight and document.documentElement.clientHeight differ significantly in that case. For example, if I choose iPhone 12 Pro (390x844px), document.documentElement.clientHeight is 844 as expected but window.innerHeight is 1920.

Where does this difference come from? What I can do to make Intersection Observer API work as expected in mobile too?

This is the related code that I have in my React component:

    const [isIntersecting, setIsIntersecting] = useState(false)
    const ref = useRef<HTMLDivElement>(null)

    useEffect(() => {
        const observer = new IntersectionObserver(([entry]) =>
            setIsIntersecting(entry.isIntersecting),
            {
                rootMargin: "-100px 0px -100px 0px"
            })
        
        observer.observe(ref!.current!);

        return () => observer.disconnect();
    }, [])

    return (
        <div ref={ref}>Content</div>
    )

-100px is desired effect and works as expected on PC.

Using JavaScript to connect to an Access database without site visitors being able to write to it

Small company, limited funds, we will be upgrading our server from Windows 7 Pro to Windows Server 2016. The site has been using Classic ASP connected to an Access (mdb) database, my understanding is that Server 2016 does not support ASP. I have been asked to convert it to using JavaScript since that will not require any additional expense. Before I tell them I can do this I have some questions regarding security.

  • Is it possible for JavaScript to read/write to an Access database?
  • Can this be done in a manner that it “cannot” be hacked?
  • Would I just need to set permissions on the server?
  • Can it be setup so that site visitors can read the database without being able to write to it?
  • That users on the server can read and write to the database?
  • What string would I use to connect to the database?
  • Would the same string be used in pages running on the server that could write to the database?

Switching to a different database is not an option, the company uses an application they wrote themselves that uses Access. I can do the code conversion from ASP to JavaScript but I want to make sure it will be secure before I waste my time. If it is not possible, any suggestions?

I have not tried anything yet, I want to know if it is even possible. If so, what string to use to connect.

Issue accessing an object key in javascript

I’m currently doing a coding challenge and I am having trouble accessing the dna key for my new method (compareDNA) I keep getting an error and I am not sure how to fix this. `

// Returns a random DNA base
const returnRandBase = () => {
    const dnaBases = ['A', 'T', 'C', 'G'];
    return dnaBases[Math.floor(Math.random() * 4)];
};

// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
    const newStrand = [];
    for (let i = 0; i < 15; i++) {
        newStrand.push(returnRandBase());
    }
    return newStrand;
};


const pAequorFactory = (specimenNum, dna) => {
    return {
        specimenNum: specimenNum,
        dna: dna,
        mutate() {
            let randomIndex = Math.floor(Math.random() * dna.length);
            let selectedDna = dna[randomIndex];
            console.log(`The original DNA base is ${dna[randomIndex]} at index ${randomIndex}`)
            let random = returnRandBase();
            if (random != selectedDna) { //This will ensure that the random base is NOT equal to the selectedDNA
                this.dna.splice(randomIndex, 1, random) //Changes the dna at the selected index, deletes 1 and replaces with random
            } else {
                console.log('Duplicate DNA found... generating new DNA.')
            }
            return dna;

        },
        compareDNA(pAequorObj) {
            let count = 0;
            for (let i = 0; i < this.dna.length; i++) {
                if (this.dna[i] === pAequorObj.dna[i]) {
                    count++;
                }
            }
        }
    }
}

I’ve checked other students solutions online and they have used the same method as I have, however, their solution works fine? Am I missing something silly here? Thanks.

This is the error I get:

Process exited with code 1
Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'dna')
    at compareDNA (/Users/shibazhussain/Desktop/Code cademy projs/mystery-organism-starter/main.js:37:42)
    at <anonymous> (/Users/shibazhussain/Desktop/Code cademy projs/mystery-organism-starter/main.js:51:22)
    at Module._compile (internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (internal/modules/cjs/loader:1435:10)
    at Module.load (internal/modules/cjs/loader:1207:32)
    at Module._load (internal/modules/cjs/loader:1023:12)
    at executeUserEntryPoint (internal/modules/run_main:135:12)
    at <anonymous> (internal/main/run_main_module:28:49)

Controlling an external web page through javascript code (cross-origin)

I am trying to let an user control an external webpage using his mic. Now im at that point, that accessing elements from that webpage from my javascript code is not allowed due to cross-origin policy.
I understand the problem if i try to access that page, if its running in an iframe in my page. But is it possible to open a new tab and control that through mine ?

I have built the same functionality with python running on my pc, by using https://www.selenium.dev/documentation/webdriver/. This program opens a browser window and then I can get every element from the webpage, click buttons and input text.
Why cant I do the same thing from my webpage? (I understand the cross-origin policy)

Are there any ideas how i can solve my problem or has somebody another idea how to solve that use case?

document.getElementById{} is returning null

const carousel = document.getElementById("carousel_id");

i am trying to access carousel by this line but i am getting an error that carousel is null. i am pasting the relevant code below. this is the error that i am getting

main.js:96 Uncaught TypeError: Cannot read properties of null (reading 'style')
    at slideVideo (main.js:96:11)
    at HTMLElement.onclick (index.html:1:1)

function toggleVideoSection(showVideo) {
  const wrapper = document.querySelector(".wrapper");
  wrapper.style.display = showVideo ? "flex" : "none";
}
let videoIndex = 0;
videos = document.querySelectorAll("video");
buttons = document.querySelectorAll(".button");
const wrapper = document.querySelector(".wrapper");
const carousel = document.getElementById("carousel_id");

function slideVideo() {
 videoIndex = videoIndex === videos.length ? 0 : videoIndex < 0 ? videos.length - 1 : videoIndex;
 carousel.style.transform = `translate(-${videoIndex * 100}%)`;
 console.log("hello")
};
const updateClick = (e) => {
 videoIndex += e.target.id === "next" ? 1 : -1;
 slideVideo(videoIndex);
};
buttons.forEach((button) => button.addEventListener("click", updateClick));
    <section class="wrapper">
      <i class="fa-solid fa-arrow-left button" id="prev"></i>
      <div class="image-container">
        <div class="carousel" id="carousel_id">
            <video src="../../assests/images/AI Assistant Police-website.mov" autoplay muted loop controls controlsList="nodownload"></video>
            <video src="../../assests/images/AI Legal assisstant.mp4" autoplay muted loop controls controlsList="nodownload"></video>
            <video src="../../assests/images/ai-health.mov" autoplay muted loop controls  controlsList="nodownload"></video>
            <video src="../../assests/images/arab-lady.mp4" autoplay muted loop controls controlsList="nodownload"></video>
            <video src="../../assests/images/arab-men.mp4 human - Trim.mp4" autoplay muted loop controls controlsList="nodownload"></video>
            <video src="../../assests/images/cafe.mp4" autoplay muted loop controls controlsList="nodownload"></video>
            <video src="../../assests/images/digital human - Trim.mp4 human - Trim.mp4" autoplay muted loop controls  controlsList="nodownload"></video>
            <video src="../../assests/images/edited.mp4" autoplay muted loop controls controlsList="nodownload"></video>
        </div>
        <i class="fa-solid fa-arrow-right button" id="next" onclick="slideVideo()"></i>
      </div>
    </section>
    <script src="../../main.js" ></script>

i am trying to access the carousel but its not working

Firebase Authentication in web: No response after user input

Trying to implement web app using Firebase Authentication. However, running into an error: after entering email and password information, regardless of if it is correct or not, getting no response, but the page being refreshed.

Here is my login.html:

<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
</head>
<body>
    <form onsubmit="login(event)">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br>
        <button type="submit">Login</button>
    </form>


    <script src="https://www.gstatic.com/firebasejs/10.7.2/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.2/firebase-firestore-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.2/firebase-auth-compat.js"></script>
    <script type = "modules" src="login.js"></script>

</body>
</html>

Here is my login.js code:

import { initializeApp } from 'firebase/app';
import firebase from 'firebase/app';
import 'firebase/auth';

import { getAuth, onAuthStateChanged, signOut, createUserWithEmailAndPassword, signInWithEmailAndPassword, connectAuthEmulator } from 'firebase/auth';

const firebaseApp = initializeApp({
    apiKey: "some-placeholder",
    authDomain: "some-placeholder",
    databaseURL: "some-placeholder",
    projectId: "some-placeholder",
    storageBucket: "some-placeholder",
    messagingSenderId: "some-placeholder",
    appId: "some-placeholder",
    measurementId: "some-placeholder"
});

const auth = getAuth();

var email = document.getElementById("email");
var password = document.getElementById("password");

function login(e){
    e.preventDefault();
    var obj = {
        email: email.value,
        password: password.value,
    };
    signInWithEmailAndPassword(auth, obj.email, obj.password)
    .then(function(success) {
        window.location.href = '/chat'
        alert("Logged in successfully")
        console.log(succes)
    }).catch(function(err){
        alert("login error"+err);

    })
    console.log(obj)
}

Also, I am getting an error in console, which I think is connected to authentication not working:
enter image description here

I am not sure why this error is occurring, because this login.js file is located in the same folder as the entire project and login.html

I tried to change src=”login.js” to src=”C:UserskodilOneDriveDocumentsBrowserbackuplogin.js”, but it did not help.

To note, not planning to implement sign in option
Users added by owner only should be able to sign in:
enter image description here

Return fetch stream from Fastify

My Fastify server needs to proxy a request to another service, and when I get the response I am trying to just pass the stream back down to the client, but the response is empty. Here’s an example I created using a popular open API; Star Wars API.

const fastify = require("fastify")({ logger: true });

// return JSON from SWAPI - works!
fastify.get("/api/json", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  const json = await response.json();
  return reply.send(json);
});

// return stream from SWAPI - doesn't work
// response is an empty object: {}
fastify.get("/api/stream", async (request, reply) => {
  const response = await fetch("https://swapi.dev/api/people/1/");
  return reply.send(response.body);
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

Above is the entire server file, but you can also clone my GitHub repo if you want to:
https://github.com/TJBlackman/fastify-stream-test

Thanks in advanced for the help!

I need a working star rating system in html [closed]

I am currently making a website for my school, dont ask why. I need a properly working star rating system that other users on my website can see the average rating to and people could write their own reviews. I have tried so much but I can’t find the type of answers I’m looking for. Please help me.

Feel free to use whatever backend programming languages you would like.

Difficulty with push method while creating a function

I want to create a function that logs out “I have 1 bottle. I have 2 bottles. I have 3 bottles” and so on, to the console.
But I keep getting the statement below.

enter image description here

let word=[]
function test() {
    let x=1
    if (x<=1) {
        word.push("bottle")
        console.log("I have "+ x + " " + word)
    }else if (x>1){
        word.push("bottles")
        console.log("I have "+ x +" " + word)
    }
  
    x++
}
test()

How to get UserId in OAuth2 Callback?

I am trying to implement OAuth2 where the Authorization server is Notion

My flow is as follows –

  1. [client] User navigates to my website and clicks button to authorize with Notion
  2. [Notion Auth server] user gives permission to certain pages within their workspace and notion redirects to my call back
  3. [server] I have the the access code and call Notion Auth server to get the token
  4. [Notion Auth server] Receives access code and sends back token
  5. [server] I have the token and would like to store it in Redis with the user id

I cannot figure out a way to get the user id in my call back to associate it with the token? Notion doesn’t seem to have any pass through parameters where I could send the user Id. I know I must be misunderstanding something, but I can’t figure out how to do it.