Running nuxt.render(req,res)

i want to run nuxt v3.11.2. but i don’t now nuxt.render is undefined in that version. I put the code inside file index.js. The code is in below

import main, { createHttpService } from "@tinqjs/tinjs-boot";
import express from "express";
import { build, loadNuxt } from "nuxt";
import cors from "cors";

const isDev = process.env.NODE_ENV !== "production";
const app = express();
app.use(cors());

main.default(async () => {
  const nuxt = await loadNuxt({ dev: true });

  if (isDev) {
    await build(nuxt);
  }
  app.use(nuxt.renderer);

  const listen = createHttpService(app);
  listen(3001, () => {
    console.log(`Service frontend nuxtjs ready`);
  });
});

i want to run in custom server function.

How I can pass the initialization config into my service worker?

I am making a library that initializes a firebase push notification. I want to achienve a hassle-free firebase configuration by letting the js to set it up for me.

import { initializeApp } from "firebase/app";
import { getMessaging, onMessage, getToken, isSupported } from "firebase/messaging";


function tokenHandle(currentToken,url) {
    if (currentToken) {
        console.log(currentToken);
    }
}

function uponGrantedPermissionHandler(messaging,vapidKey,serviceWorkerUrl,tokenNotificationUrl,workerAsModule){
    if ('serviceWorker' in navigator) {
        const workerConfig = workerAsModule?{ type: 'module' }:undefined
        
        serviceWorkerUrl = serviceWorkerUrl??"https://mycdn.com/firebase-messaging-sw.js";

        navigator.serviceWorker
        .register(serviceWorkerUrl, workerConfig)
        .then((registration) => {
                console.log(messaging)
                if (registration) {
                    console.log('Registration successful, scope is:', registration.scope)
                    getToken(messaging, { vapidKey })
                        .then((token)=>tokenHandle(token,tokenNotificationUrl))
                        .catch(error => console.error(error));
                }
            })
            .catch(function (err) {
                console.log('Service worker registration failed, error:', err)
            })
    }
}

function pushNotificationInit(firebaseConfig,vapidKey,tokenNotificationUrl,serviceWorkerUrl,workerAsModule){
    const app = initializeApp(firebaseConfig);
    isSupported().then((isSupported) => {
        
        if (!isSupported) {
            throw "Browser Is not Supported"
            return;
        }

        const messaging = getMessaging(app)


        Notification.requestPermission().then(function (permission) {
            console.log('permiss', permission)

            if (permission === 'granted') {
                uponGrantedPermissionHandler(messaging,vapidKey,serviceWorkerUrl,tokenNotificationUrl,workerAsModule)

                onMessage(messaging, (payload) => {
                    const n = new Notification(payload.notification.title, {
                        body: payload.notification.body,
                    });
                });
            }
        });
    }).catch((error)=>console.error(error));
}


export {pushNotificationInit};

what I want to do is to have an easy api to use and be as simple as:

import {pushNotificationInit} from './firebaseLib';

pushNotificationInit(firebaseConfig,vapidKey,"",null,true)

And pushNotificationInit to initialize the worker as well. But a common service worker for firebase is:


import { initializeApp } from 'firebase/app';
import { onBackgroundMessage,getMessaging } from 'firebase/messaging/sw'

const firebaseConfig = {
  // config
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
    
    // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background message body',
    icon: 'icon.png'
  };
    
  self.registration.showNotification(notificationTitle, notificationOptions);
});

What I want to do is to pass the config from core js into my service worker. Is there a way to do that?

Jspdf & Html2canvas -Image cut off while pdf contents “multiple” pages

I need to generate PDF from my web site page.
I have used JSPDF and HTML2Canvas for the same.
When I have tried to generate the PDF with large amount of data and image it has split image in 2 diffrent page. Please check attached screenshot for better understanding.
PDF Output
Below is my code snippet,

 const handleDownloadPDF = async () => {
    const cleanedDescription = description.replaceAll(/</?b>/g, '');
    const replacedDescription = cleanedDescription.replaceAll('&#58;', ':');

    const containerWithPadding = document.createElement("div");
    containerWithPadding.style.padding = "20px";

    const container = document.createElement("div");
    container.style.color = "#000000";
    container.innerHTML = replacedDescription;

    const spanElements = container.querySelectorAll("span");
    spanElements.forEach(span => {
      span.style.color = "#000000";
    });

    const imageElements = Array.from(container.querySelectorAll("img"));

    await Promise.all(imageElements.map(async img => {
      const imageUrl = img.src;
      const imageData = await fetch(imageUrl).then(res => res.blob());
      const dataUrl = await blobToDataURL(imageData);
      img.src = dataUrl;
    }));

    containerWithPadding.appendChild(container);

    const urlParts = window.location.pathname.split('/');
    const fileName = urlParts[urlParts.length - 1];

    html2pdf().from(containerWithPadding).save(`${project}_${fileName}.pdf`);
  };

  const blobToDataURL = (blob) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  };

Can anyone help me with the same?
Thanks in Advance

I need to generate PDF without split image in different page.

How to attach a cookie from my React Native front-end to the @rails/actioncable WebSocket connection?

I am using the React Native Cookies library to set a cookie on the front-end. I noticed that my Axios client automatically detects and attaches the cookie to all request that occur after the cookie has been set.

Now I need to also attach the cookie to my WebSocket connection which uses @rails/actioncable. I was hoping that it would work out of the box similarly to Axios, however, that doesn’t seem to be the case. I scoured the documentation but couldn’t find anything regarding this, which makes me think it’s either very simple or impossible with @rails/actioncable.

postcss Package subpath ‘./tailwind’ is not defined by “exports” in …..node-modulesflowbite-reactpackage.json

13:44:51 [vite] Internal server error: [postcss] Package subpath ‘./tailwind’ is not defined by “exports” in D:LiorMoraliProgramming(D)MERN-Blogclientnode_modulesflowbite-reactpackage.json
Plugin: vite:css
File: D:/LiorMorali/Programming(D)/MERN-Blog/client/src/index.css:undefined:NaN
at new NodeError (node:internal/errors:405:5)
at exportsNotFound (node:internal/modules/esm/resolve:366:10)
at packageExportsResolve (node:internal/modules/esm/resolve:713:9)
at resolveExports (node:internal/modules/cjs/loader:590:36)
at Module._findPath (node:internal/modules/cjs/loader:664:31)
at Module._resolveFilename (node:internal/modules/cjs/loader:1126:27)
at Function.resolve (node:internal/modules/helpers:188:19)
at _resolve (D:LiorMoraliProgramming(D)MERN-Blogclientnode_modulesjitidistjiti.js:1:251148)
at jiti (D:LiorMoraliProgramming(D)MERN-Blogclientnode_modulesjitidistjiti.js:1:253746)
at D:LiorMoraliProgramming(D)MERN-Blogclienttailwind.config.js:1:93

everything worked fine in my project then this error showed up
tried everything and nothing is working 🙁

D:LiorMoraliProgramming(D)MERN-Blogclientnode_modulesflowbite-reactpackage.json :

{
  "name": "flowbite-react",
  "version": "0.7.8",
  "description": "Official React components built for Flowbite and Tailwind CSS",
  "keywords": [
    "design-system",
    "flowbite",
    "flowbite-react",
    "react",
    "tailwind",
    "tailwindcss",
    "tailwind-css"
  ],
  "homepage": "https://flowbite-react.com",
  "bugs": "https://github.com/themesberg/flowbite-react/issues",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/themesberg/flowbite-react.git",
    "directory": "packages/ui"
  },
  "license": "MIT",
  "exports": {
    ".": {
      "types": "./lib/types/index.d.ts",
      "import": "./lib/esm/index.js",
      "require": "./lib/cjs/index.js"
    },
    "./components/*": {
      "types": "./lib/types/components/*/index.d.ts",
      "import": "./lib/esm/components/*/index.js",
      "require": "./lib/cjs/components/*/index.js"
    },
    "./package.json": "./package.json"
  },
  "main": "lib/cjs/index.js",
  "module": "lib/esm/index.js",
  "types": "lib/types/index.d.ts",
  "files": [
    "lib"
  ],
  "scripts": {
    "postpublish": "clean-package restore"
  },
  "dependencies": {
    "@floating-ui/core": "1.6.0",
    "@floating-ui/react": "0.26.10",
    "classnames": "2.5.1",
    "debounce": "2.0.0",
    "flowbite": "2.3.0",
    "react-icons": "5.0.1",
    "tailwind-merge": "2.2.2"
  },
  "peerDependencies": {
    "react": ">=18",
    "react-dom": ">=18",
    "tailwindcss": "^3"
  }
}

tried npm i
installing react-flowbite
installing tailwindcss

How does Operational Transformation algorithm in ot.js handle conflicts between Insert and Delete?

Considering OT’s transform algorithm for an Insert operation and a Delete operation executed at the same time, on two different clients. Insert.pos is in the range [Delete.pos, Delete.pos + Delete.count - 1].

To keep both the intentions executed, we can turn the Delete operation into at most two delete operations, to keep both the insert intention and the delete intention executed. More specifically, [Delete.pos, Insert.pos - 1] and [Insert.pos + Insert.content.length, Delete.pos + Delete.count + Insert.content.length - 1].

However, it will turns an operation into two operations. Could it cause time complexity problem?


I later checked ot.js but found their behaviours different.

In Operational-Transformation/ot.js/lib/simple-text-operation.js, it just ignored the Insert operation.

if (a instanceof Insert && b instanceof Delete) {
      if (a.position <= b.position) {
        return [a, new Delete(b.count, b.position + a.str.length)];
      }
      if (a.position >= b.position + b.count) {
        return [new Insert(a.str, a.position - b.count), b];
      }
      // Here, we have to delete the inserted string of operation a.
      // That doesn't preserve the intention of operation a, but it's the only
      // thing we can do to get a valid transform function.
      return [noop, new Delete(b.count + a.str.length, b.position)];
    }

But in https://operational-transformation.github.io/ , the OT take the choice I mentioned in the top of passage (splitting the Delete operation into <=2 operations).

(You can try to remove orem ips in Alice and insert hi at pos = 5 in Bob to see effect.)

I am confused that two behaviors are different, and according to some blogs I see on the Internet, transform should be return only two operations, not two operation arrays (which means splitting is not allowed).

how to use jest to test sever, db setup in following code

`

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require("dotenv");

const app = express();
dotenv.config();

const PORT = process.env.PORT || 8070;
app.use(cors());
app.use(bodyParser.json());
const URL = process.env.MONGODB_URL;

mongoose.connect(URL, {
        

        useNewUrlParser: true,  
        useUnifiedTopology: true
        
});

const connection = mongoose.connection;
const labRouter = require('./routes/lab.js');
app.use("/lab", labRouter);
connection.once("open", () => {
        console.log("Mongodb Connection success!")
});

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

i want to test server listen on port and mongodb connection. but i am not understand how to write the test code. also i get errors on mocking.

Convert JS file to ReactJs component

I want to convert this JS project to a react functionnal component, I’m begining on React and want some help to start, have you an idea please ?

JS file

var colors = ["#f38630","#6fb936", "#ccc", "#6fb936"];
var wrap = gsap.utils.wrap(-100, 400);

//initially colorize each box and position in a row
gsap.set(".box", {
  backgroundColor: (i) => colors[i % colors.length],
  y: (i) => i * 50
});


gsap.to(".box", {
  duration: 5,
  ease: "none",
  y: "-=500", //move each box 500px to right
  modifiers: {
    y: gsap.utils.unitize(wrap) //force y value to wrap when it reaches -100
  },
  repeat: -1
});


//toggle overflow
const overflow = document.querySelector("#overflow");
overflow.addEventListener("change", applyOverflow);

function applyOverflow() {
  if(overflow.checked) {
    gsap.set(".wrapper", {overflow: "visible"});
  } else {
    gsap.set(".wrapper", {overflow: "hidden"});
  }
}

This is my demo example

DEMO LINK

How would I clear the comments form when the submit button is pressed? Next-js 14

I am unsure how I would write the code to clear the previous inputted comment in my comment form once the submit button has been pressed, so the user doesn’t have to delete the previous input before typing in a new comment. here is my code, any help would be greatly appreciated!
I am not sure if I would have to split the page up, and put the comments form in a seperate components folder, along with the vercel database request.

import { notFound } from "next/navigation";
import Image from "next/image";
import { revalidatePath } from "next/cache";
import Link from "next/link";
import { HiPencilAlt } from "react-icons/hi";
import RemoveBtn from "@/app/components/RemoveBtn";
import RemoveBtnComments from "@/app/components/RemoveBtnComments";
export default async function Page({ params }) {
 //get single post
 console.log(params.singlePost);
 const post = (
   await sql`SELECT * FROM posts01 WHERE post_id = ${params.singlePost} `
 ).rows[0];
 const comments = (
   await sql`SELECT * FROM comments01 WHERE post_id = ${params.singlePost}`
 ).rows;
 //handle posts
 async function handleComments(formData) {
   "use server";
   const comment = formData.get("comment");
   const username = formData.get("username");
   await sql`INSERT INTO comments01 (username, comment, post_id)
        VALUES (${username}, ${comment}, ${post.post_id}) `;
   console.log("comment saved");

   revalidatePath(`/allPosts/${params.singlePost}`);
 }
 if (!post) {
   notFound();
 }
 return (
   //display posts
   <>
     {/* //div that contains all */}
     <div>
       {/* //div that contains post */}
       <div>
         <h2 className="text-2xl font-bold mb-4">{post.title}</h2>
         <div className="flex justify-end gap-5">
           {/* delete post */}
           <RemoveBtn post_id={post.post_id} />
           {/* //edit button */}
           <Link href={`${params.singlePost}/editPost`}>
             <HiPencilAlt size={24} />
           </Link>
         </div>
         <h3 className="text-lg mb-4">{post.content}</h3>
         {/* display image_url */}
         {post.image_url ? (
           <Image
             src={post.image_url}
             alt={`image of ${post.title}`}
             width={300}
             height={300}
           />
         ) : (
           <h3>Image unavailable</h3>
         )}
       </div>
       {/* //comments */}
       <div>
         <h4 className="text-xl font-bold mb-4">Comments</h4>
         <div className="mb-4">
           <form action={handleComments} className="text-black flex">
             <input
               name="username"
               placeholder="Username"
               value={comments.username}
               className="mr-2 px-4 py-2 border border-gray-300 rounded-md"
             />
             <input
               name="comment"
               placeholder="Comment..."
               value={comments.comment}
               className="flex-1 mr-2 px-4 py-2 border border-gray-300 rounded-md"
             />
             <button
               type="submit"
               className="px-4 py-2 bg-blue-500 text-white font-bold rounded-md hover:bg-blue-600"
             >
               Submit
             </button>
           </form>
         </div>
         <div>
           {comments.map((comment) => (
             <div
               className="bg-gray-100 rounded-md p-4 mb-4"
               key={comment.comment_id}
             >
               <p className="font-bold text-lg mb-2">{comment.username}</p>
               <div>
                 <p>{comment.comment}</p>
               </div>
               {/* delete comment */}
               <div className="flex justify-end gap-5">
                 <RemoveBtnComments comment_id={comment.comment_id} />
               </div>
             </div>
           ))}
         </div>
       </div>
     </div>
   </>
 );
}

javascript sorting strings starting with a number not working

I am trying to sort an object of strings, which would work with the normal sort function, but I am not able to get it working as the strings start with a number:

e.g.:

{ value: "10 items", value: "5 items", value: "100 items", value: "20 items" }

I want to make it ascending, so it becomes:

5 items
10 items
20 items
100 items

I’ve been trying to use:

data.sort((a, b) => a > b ? 1 : -1).map((a) => { return a;}

But that still shows it as:

10 items
100 items
20 items
5 items

PHP how to recreate the random order of an array after chunk

For an online game I create an initial PHP array with 36 values: A-Z 0-9. A random script remix the array, i.e

[0] R
[1] 4
[2] N
[3] d
...
[35] 8

Once done the script assigns 6 signs to each of the 6 players via a chunk($arr,6).

Player 1 [0] = [R,4,n,d,O,M]
Player 2 [1] = [p,2,s,Z,k,u]
...
Player 6 [5] = [J,r,V,5,z,8]

The question is: once the table of players has been reordered alphabetically, is there an algorithmic way to recreate the initial distribution?

To simplify the question:

Initial array

[0] = abc
[1] = def
[2] = ghi
[3] = jkl
[4] = mno
[5] = pqr

Random order permutation [0,1,2,3,4,5] -> [2,5,0,3,1,4]:

[2] = ghi
[5] = pqr
[0] = abc
[3] = jkl
[1] = def
[4] = mno

Result:

new order     [0]   [1]   [2]   [3]   [4]   [5] 
value         ghi   pqr   abc   jkl   def   mno
former order  [2]   [5]   [0]   [3]   [1]   [4] -> random permutation

To retrieve former order I must find the way to produce the array [2,4,0,3,5,1]:

 new order   [2]   [4]   [0]   [3]   [5]   [1]          
 value       abc   def   ghi   jkl   mno   pqr  -> initial array order

How to obtain this array [2,4,0,3,5,1] from random permutation [2,5,0,3,1,4] ?