Is there an API I can use to generate random “subjects”/”objects”/”things”? [closed]

I am currently developing a JavaScript/HTML application where I want to generate a random “object”/”thing” as a subject for someone to draw. Just like this website here.

I see that they have an API but the API doesn’t seem to support anything from their entertainment category. Does anyone know of a similar API that could do the job?
Or am I better off generating/creating my own list of “things” and simply randomizing which shows on the screen? I feel like this would be a big task and I would like it to feel very randomized and non-repetitive but I feel like that may be my only option.

Angular variable reference persistence behavour after setting singleton instance to Undefined

I have this class, meant to work as a singleton,

export class SingletonClass {

    public static instance: SingletonClass | undefined;
    public name: string | undefined | null;

    static getInstance() {
        if (SingletonClass.instance == null || SingletonClass.instance == undefined)
            SingletonClass.instance = new SingletonClass()

        return SingletonClass.instance;
    }

    static destroy() {
        SingletonClass.instance = undefined;
    }
}

and a component class has this code,

  export class TestComponent implements OnInit {

    SingletonObject1: SingletonClass | undefined | null = SingletonClass.getInstance();
    SingletonObject2: SingletonClass | undefined | null;

    ngOnInit(): void {

      this.SingletonObject1!.name = "Name1";
      SingletonClass.destroy();

      this.SingletonObject2 = SingletonClass.getInstance();
      this.SingletonObject2.name = "Name2";
    }
  }

I expect both SingletonObject1 and SingletonObject2 to refer to the same singleton object, hence after running this code, value of the name property of both objects should be “Name2”. But what happens here is SingletonObject1.name has “Name1” and SingletonObject2.name has “Name2” as their values.

If I remove the SingletonClass.destroy(); it works as expected. So it seems even after calling SingletonClass.instance = undefined; SingletonObject1 holds the reference to previously created object.

Can someone explain why does it create two variable instances when it set the instence as undefined and how to modify the destroy method to remove the whole singleton object and keep the reference to the same location from both variables.

React lazy loading components

Im trying to lazy load a component but es-lint gives me warn:
Fast refresh only works when a file has exports. Move your component(s) to a separate file.

using React.component class does not change anything shown in register.jsx,
using const in login.jsx does the same as register.jsx

i tried many ways:

login.jsx


const LoginPage = () => {
    return(
        <>
            Todo:
        </>
    )
}

export default LoginPage;

register.jsx

import React from "react";


class RegisterPage extends React.Component {
    render() {




        return(
            <>
                Todo:
            </>
        )
    }
}

export default RegisterPage;

main.jsx

import React, { Suspense } from 'react'

const LoginPage     =   React.lazy(() => import('./routes/login'))
const RegisterPage  =   React.lazy(() => import('./routes/register'))

Filter array by object value deletes the wrong object

I’m using react with context and I want to delete an object. Here’s my code

Context.js

  export const postsReducer = (state, action) => {
  switch (action.type) {
    case "SET_POSTS":
      return {
        posts: action.payload,
      };
    case "CREATE_POST":
      return {
        posts: [action.payload, ...state.posts],
      };
    case "DELETE_POST":
      return {
        posts: state.posts.filter((post) => post._id !== action.payload._id),
      };
    default:
      return state;
  }
}; 

And on my Post.js

  const { dispatch } = usePostsContext();

  const handleDelete = async () => {
    const response = await fetch("/api/posts/" + post._id, {
      method: "DELETE",
    });
    const json = await response.json();
    if (response.ok) {
      dispatch({
        type: "DELETE_POST",
        payload: json,
      });
      console.log(json);
    }
  }; 

The response json is this:

content: "zxczxc"
createdAt: "2024-01-25T01:58:43.088Z"
title: "zxczxc"
updatedAt: "2024-01-25T01:58:43.088Z"
__v: 0
_id: "65b1c0533b847bc475694dca" 

This works, however it always deletes the last one in the array of posts and not the one filtered using the ._id

UPDATE
Here’s some additional code

    export const PostContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(postsReducer, { posts: null });

  return (
    <PostsContext.Provider value={{ ...state, dispatch }}>
      {children}
    </PostsContext.Provider>
  );
}; 

Here’s how I map the array
enter image description here

And the Delete button on the Post component
enter image description here

error when running firebase init functions

After running the firebase init functions command line it is returning the following error:

npm ERR! code 2
npm ERR! path /home/ramon/apicloud/node_modules/protobufjs
npm ERR! command failed
npm ERR! command /home/ramon/.cache/firebase/runtime/shell -c -- node scripts/postinstall
npm ERR! /bin/sh: 0: Illegal option --

npm ERR! A complete log of this run can be found in:
npm ERR! /home/ramon/.npm/_logs/2024-01-25T02_16_00_381Z-debug-0.log

I already reinstalled npm and node and it still didn’t solve the problem. Any suggestion?

part of the Firebase Cloud Functions documentation that tells you how to start the project.

To initialize your project:

Run firebase login to log in via the browser and authenticate the Firebase CLI.
Go to your Firebase project directory.

Run firebase init firestore. For this tutorial, you can accept the default values when prompted for Firestore rules and index files. If you haven’t used Cloud Firestore in this project yet, you’ll also need to select a starting mode and location for Firestore as described in Get started with Cloud Firestore.

Run firebase init functions. The CLI prompts you to choose an existing codebase or initialize and name a new one. When you’re just getting started, a single codebase in the default location is adequate; later, as your implementation expands, you might want to organize functions in codebases.

The CLI gives you two options for language support:

JavaScript
TypeScript See Write Functions with TypeScript for more information.
For this tutorial, select JavaScript.

The CLI gives you an option to install dependencies with npm. It is safe to decline if you want to manage dependencies in another way, though if you do decline you’ll need to run npm install before emulating or deploying your functions


the end of error stack with the error:

3116 verbose stack Error: command failed
3116 verbose stack     at ChildProcess.<anonymous> (/snapshot/firepit/node_modules/npm/node_modules/@npmcli/promise-spawn/lib/index.js:63:27)
3116 verbose stack     at ChildProcess.emit (node:events:537:28)
3116 verbose stack     at maybeClose (node:internal/child_process:1091:16)
3116 verbose stack     at ChildProcess._handle.onexit (node:internal/child_process:302:5)
3117 verbose pkgid [email protected]
3118 verbose cwd /home/ramon/apicloud
3119 verbose Linux 6.5.0-14-generic
3120 verbose node v18.5.0
3121 verbose npm  v8.19.4
3122 error code 2
3123 error path /home/ramon/apicloud/node_modules/protobufjs
3124 error command failed
3125 error command /home/ramon/.cache/firebase/runtime/shell -c -- node scripts/postinstall
3126 error /bin/sh: 0: Illegal option --
3127 verbose exit 2
3128 timing npm Completed in 51906ms
3129 verbose unfinished npm timer reify 1706148960471
3130 verbose unfinished npm timer reify:build 1706149011539
3131 verbose unfinished npm timer build 1706149011540
3132 verbose unfinished npm timer build:deps 1706149011540
3133 verbose unfinished npm timer build:run:postinstall 1706149011561
3134 verbose unfinished npm timer build:run:postinstall:node_modules/protobufjs 1706149011561
3135 verbose code 2
3136 error A complete log of this run can be found in:
3136 error     /home/ramon/.npm/_logs/2024-01-25T02_16_00_381Z-debug-0.log

Detecting Style Changes and Getting Their Respective Values

I am trying to detect style changes in the HTML tag and get the resulting changes. But most the tutorials usually just show how to detect the change but not how to extract the information about the changes.

var variables_observer=new MutationObserver(function(mutations){
 mutations.forEach(function(mutation){
  
  var STYLE = STYLE THAT CHANGED
  var VALUE = STYLE VALUE THAT CHANGED

  console.log(STYLE);
  console.log(VALUE);

 });    
});
var target=document.documentElement;
variables_observer.observe(target,{attributes:true,attributeFilter:['style']});

For example, if I add a variable to my style --size1:100px is added to my style:

Before:

<html>

After:

<html style="--size1:100px">

Console:

--size1
100px

Does mutation give any change data? And what exactly changed and how it changed?

Need solution for extracting queryparams from URL of the browser when called from window.location.replace [closed]

Problem: I have a Nodejs application where I need to make a call to one of the endpoints from a HTML file. This endpoint endpoint when called from Java script in index.html using window.location.replace(‘endpoint’), and test it in browser, it returns with a set of query Params in the browser.

I need to be capturing this whole URL that’s returning the query Params in the javascript method of index.html as a response.

If I try using fetch/await fetch/xmlHttpRequest, I get a CORS ERROR when I call my endpoint. This way of using window.location, helped me get rid of CORS in the response of the browser. Hence would want to understand how do I capture the URL once loaded.

ERR_MODULE_NOT_FOUND [nodemon] app crashed – waiting for file changes before starting

I have a project structured as follows:

  • social-project
    • api
      • controllers
        • auth.js
      • routes
        • connect.js

In my auth.js file, I’m trying to import connect.js using the following import statement:

import { db } from "../connect.js";

However, despite double-checking the relative paths and ensuring the correct file structure, I’m still getting the “Cannot find module” error.

I’ve double-checked the file structure and import statements.
I’ve restarted nodemon and my Node.js application.

Here is the entire error:

Node.js v18.16.1
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/Valeria/Desktop/social-project/api/connect.js' imported from /Users/Valeria/Desktop/social-project/api/controllers/auth.js
    at new NodeError (node:internal/errors:399:5)
    at finalizeResolution (node:internal/modules/esm/resolve:326:11)
    at moduleResolve (node:internal/modules/esm/resolve:945:10)
    at defaultResolve (node:internal/modules/esm/resolve:1153:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v18.16.1
[nodemon] app crashed - waiting for file changes before starting...

Here is my connect.js

import mysql from "mysql";



export const db = mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"",
    database:"social"

});

Here is my auth.js

import { db } from "../connect.js";
import bcrypt from "bcrypt.js";




export const register = (req, res)=>{

    const q = "SELECT * FROM users WHERE username = ?"

    db.query(q, [req.body.username], (err,data)=>{
        if(err) return res.status(500).json(err);
        if(data.length) return res.status(409).json("User already exists");

        const salt = bcrypt.genSaltSync(10);
        const hashedPassword = bcrypt.hashSync(req.body.password, salt);

        const q = "INSERT INTO users (`username`, `email`,`password`, `name`) VALUES (?)";
        
        const values = [req.body.username,req.body.email, hashedPassword,req.body.name];

        db.query(q, [values], (err, data) => {
            if (err) return res.status(500).json(err);
            return res.status(200).json("Registration successful");
        });


    });

};


export const login = (req, res)=>{

}
export const logout = (req, res)=>{

}

Any assistance or insights into resolving this issue would be greatly appreciated. Thank you!

I’m testing my project through Insomnia and receiving

Error: Couldn’t connect to server

http://localhost:8800/api/auth/register

My JSON:

{
    "username":"test",
    "email":"[email protected]",
    "password":"123456",
    "name":"John Doe"
}

How can I handle asynchronous processing within quill.clipboard.addMatcher when using the quill.js library in Tauri?

How can I handle asynchronous processing within quill.clipboard.addMatcher when using the quill.js library in Tauri? Specifically, I’m struggling to extract and use the result from a promise returned by the invoke function within the matcher callback.

In Tauri, I’m using the quill.js library. I want to find images when a user pastes content, send the image URLs to the backend, download the images locally on the backend, and then return the local URLs. However, I’m unsure how to achieve this.

I’ve discovered the quill.clipboard.addMatcher('img', function(node, delta) { ... }) method, which allows me to access the ‘img’ nodes in the clipboard. I’ve attempted to implement it as follows:

quill.clipboard.addMatcher('img', function(node, delta) {
    return new Delta().insert({image: localize(node.src)});
});

async function localize(node){
    let src = node.src;
    if (src.slice(0, 4) === 'http') {
        console.log(`${src} begins with http`);
    }
    return invoke('localize', {src: src});
}

However, the invoke function, which calls the backend code, returns a promise. I’m unsure how to extract the URL from the promise and return a processed delta object within the addMatcher callback.

I’m open to alternative solutions. Perhaps I should provide a function to addMatcher that calls an async function that directly scans the HTML document for ‘img‘ nodes and replaces them then return the unaltered delta.

why doesn’t signal list update when add a new item? Preact signals

I met an issue that my todo list never update when I click the button to add a new todo item even tho console.log shows the list is updated already. But everything would works fine if i change to react hooks. Can anyone help? Thanks!

import { signal, effect } from "@preact/signals-react"
import { useState } from "react"

export default function SignalsTodolist() {
  const todos = signal(["eat", "sleep", "play video game"])
  const newTodo = signal("")

  const addNewTodo = (e) => {
    e.preventDefault()
    todos.value = [...todos.value, newTodo.value]
    console.log(todos.value)
    newTodo.value = "" // Use setNewTodo to update the state
  }

  // const resetToto = () => {
  //   newTodos(["eat", "sleep", "play video game"])
  // }

  return (
    <div>
      Create a todo list with signals。
      <br />
      <br />
      <input
        type="text"
        value={newTodo}
        onChange={(e) => (newTodo.value = e.target.value)}
        placeholder="Type to add..."
      />
      <button type="submit" onClick={addNewTodo}>
        add new todo
      </button>
      <br />
      {newTodo}, {todos} {/* To display the array */}
      <ul>
        {todos.value.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  )
}

enter image description here

Internally function returns correctly, outside return value changes [duplicate]

I’m noticing that the console.log(result) returns the correct value, however console.log(value) returns an object. Shouldn’t they be the same?

async function getValueFor(key) {
  let result = await SecureStore.getItemAsync(key);
  console.log('result is ' + result)
  return result || ''
}
let value = getValueFor('Key')
console.log('value is ' + value)

I even tried changing the second block to:

let value = 'test'
getValueFor('Key').then(data => value = data)
console.log('value is ' + value)

This ends up returning ‘test’ every time for value, while console.log(result) is still correct.

Is there a way to end to end test an application that relies on passkey for authentication?

We are using a 3rd party application to authenticate our users before they login to carry out transactions with our product.
The authentication is tightly coupled with our backend as we verify the login creds at backend .
We use webdriverIO for our end to end tests. We would like to run our end to end tests replicate the real world scenario as close as possible.

Is there a way to emulate authentication simulators for Passkey based authentication? or what are a few strategies used by companies out there?

We tried using a stub for skipping the authentication process, but it did not feel safe/secure to us.
We asked the 3rd party authentication providers for test accounts. They do not have/support any test accounts yet.

“Type Not Usable in Add-on Platform” Error When Using CardService in Google Apps Script

I am developing a Google Workspace add-on using Google Apps Script. I am encountering an issue while using CardService to create a UI that displays a list of GitHub repositories. The functionality I am trying to implement is to fetch and display a list of GitHub repositories as checkboxes, based on the user-provided GitHub username and token.

The problem occurs in the fetchRepositories function when constructing and returning a card using CardService. The error message is as follows:

The type of value returned from Apps Script is not usable in the add-on platform. Please call the 'build' function before returning this value.

This error only appears when the else block is executed, specifically when fetching the list of GitHub repositories using the username and token stored in user properties. Here’s a snippet of the code in question:

function fetchRepositories(e) {
  // ... some code omitted ...

  if (e) {
    // Processing user input
    var formInput = e.formInput;

  if (!formInput.githubUsername || !formInput.githubToken) {
      return CardService.newActionResponseBuilder()
        .setNotification(CardService.newNotification()
          .setType(CardService.NotificationType.ERROR)
          .setText("GitHub Username and Token are required."))
        .build();
    }
  } else {
    var userInfo = getUserCredentials();
    username = userInfo.username;
    token = userInfo.token;
  }

  var repos = getGitHubRepos(username, token);

  if (!repos) {
    return CardService.newActionResponseBuilder()
      .setNotification(CardService.newNotification()
        .setType(CardService.NotificationType.ERROR)
        .setText("Failed to fetch repositories."))
      .build();
  }

  var repoCheckboxes = CardService.newSelectionInput()
    .setType(CardService.SelectionInputType.CHECK_BOX)
    .setTitle("Select Repositories")
    .setFieldName("selectedRepos");

  repos.forEach(function(repo) {
    repoCheckboxes.addItem(repo.name, repo.name, false);
  });

  var card = CardService.newCardBuilder()
    .addSection(CardService.newCardSection().addWidget(repoCheckboxes))
    .addSection(
      CardService.newCardSection()
        .addWidget(CardService.newTextButton()
          .setText("Add Selected Commits to Calendar")
          .setOnClickAction(CardService.newAction()
            .setFunctionName("addSelectedCommitsToCalendar"))))
      .build()

  return CardService.newActionResponseBuilder()
    .setNavigation(CardService.newNavigation().pushCard(card))
    .build();
}

The getGitHubRepos function calls the GitHub API and returns a list of repositories. I am using the returned repos array to create a list of checkboxes.

I am seeking advice on what to check and modify to resolve this issue. Thank you.

ReactJS Get data from firestore with a WHERE clause condition [duplicate]

So this is my current code, I am able to get the chats from the firestore database and storing the data in useChats which is being called by other components.
This is working and data is returned.

My issue is when I am trying to perform a filter using where clause on 2 fields part of the collection.

What I’m trying to achieve is getting all the chats where firstPartyUserId = 48 OR secondPartyFullName = 48

This is my firestore structure

enter image description here

This is the code that gets all the chats without filtering

import { initializeApp } from "firebase/app";
import { getFirestore, collection } from "firebase/firestore";
import { useCollectionData } from "react-firebase-hooks/firestore";

const FirebaseChats = () => {
  const firebaseConfig = {
        // creds here
  };

  const app = initializeApp(firebaseConfig);
  const firestore = getFirestore(app);
  
  const chatsRef = collection(firestore, "chats");
  const useChats = () => useCollectionData(chatsRef, { idField: "id" });

  console.log(useChats)

  return {app, firestore, useChats, firebaseConfig}
}


export default FirebaseChats;

I have tried something like this but kept on returning undefined

const conditions = [
    where("firstPartyUserId", "==", 48),
    where("secondPartyFullName", "==", "48"),
  ];

  // Create a query with OR conditions
  const filteredQuery = query(chatsRef, ...conditions);

  // Use the query directly in the useCollectionData hook
  const [useChats] = useCollectionData(filteredQuery, { idField: "id" });

  console.log(useChats);

PDF Button – JavaScript

I am making a fillable pdf and I am trying to add a button that when pushed, adds a line underneath and duplicates a text field box in that new line (it’s basically a + sign that adds a new line with the textbox from that line). All the code I’m trying isn’t working!

Here is what I tried already!