Color Thresholding JS, Average Image Color Detect JS

I had watched the following tutorial https://youtu.be/BTWPDboW38o?si=_21TOjCfrXC3VWIL and tried the same. What I expect is, I want to change the background color of document based on the color of video stream. But it is always returning rgb(0,0,0).
`

‘use strict’;

try {

const w = window,

    d = document,

    ng = navigator,

    id = e => {

        return d.getElementById(e)

    },

    cn = id('lh'),

    i = id('i'),

    o = id('o'),

    cx = cn.getContext('2d', {

        willReadFrequently: true

    }),

    face = r => ng.mediaDevices.getUserMedia({

        video: {

            facingMode: {

                exact: 'user'

            }

        }

    }).then(s => {

        i.srcObject = s;

        i.onloadedmetadata = e => {

            setInterval(() => {

                let c = 0,

                    k = -4,

                    h = cn.height = i.videoHeight,

                    w = cn.width = i.videoWidth,

                    dt = cx.getImageData(0, 0, w, h),

                    io = dt.data,

                    dl = io.length,

                    R, G, B;

                R = G = B = 0;

                cx.drawImage(i, 0, 0, w, h);

                o.src = cn.toDataURL('image/webp');

                while ((k += r * 4) < dl) {

                    ++c;

                    R += io[k];

                    G += io[k + 1];

                    B += io[k + 2]

                };

                ['R', 'G', 'B'].forEach(e1 => {

                    eval(e1 + '=' + `~~(${e1}/c)`)

                });

                let rgb = `rgb(${R},${G},${B})`;

                d.body.style.background = rgb

            }, -1)

        }

    });

face(4)

} catch (e) {

alert(e)

}`

I expect it should change the background color of document based on video stream.

Jittery Behavior on First Scroll in React Header Component

Description

I’m encountering an issue with the header component in my React based next.js web application. Upon the initial load of the page, when I first scroll, there’s a noticeable jittery behavior before the header hides as intended. Once this initial jittery behavior occurs, the header behaves perfectly fine for subsequent scrolls.

function Header() {
    const [mounted, setMounted] = useState(false);
    const { theme } = useTheme();
    const [prevScrollPos, setPrevScrollPos] = useState(0);
    const [visible, setVisible] = useState(true);

    useEffect(() => {
        const handleScroll = () => {
            const currentScrollPos = window.scrollY;
            setVisible(prevScrollPos > currentScrollPos || currentScrollPos < 200);
            setPrevScrollPos(currentScrollPos);
        };

        window.addEventListener("scroll", handleScroll);

        return () => window.removeEventListener("scroll", handleScroll);
    }, [prevScrollPos]);

    useEffect(() => {
        setMounted(true);
    }, []);

    if (!mounted) {
        return null;
    }

    return (
        <>
            {(theme === 'light' || theme === 'undefined' || theme === null) && visible && <LightHeader />}
            {theme === 'dark' && visible && <DarkHeader />}
        </>
    )
}

(I am using next-themes for theme switching. The mounting logic is to mitigate hydration error)

I suspect I might be missing a crucial React concept or best practice here. Could someone please provide insights into what might be causing this jittery behavior on the first scroll and how I can resolve it? Would de-bouncing help in this scenario? Additionally, could this issue be related to React Snapshot?

Any help or guidance would be greatly appreciated! Thank you.

Getting a wrong value while converting date from german locale to english using moment

All I want is to get the date value received in german language to english format for which i tried using moment library as given below

It does convert but unfortunately returns a wrong value.

moment('Mär 29, 2024', 'MMM DD, YYYY', 'de-DE').locale('en-US').format('MM/DD/YYYY')

// Expected Value - 03/29/2024
// received value - 01/29/2024

Is there a fix for this ?

How do I create a website that combines user input and standard text and converts it into a pdf?

There’s this annoying form that we have to fill in at work for every case in a word document. FIlling it in consists mostly of choosing what standard text applies, and removing the text that doesn’t apply. It takes a lot of work because you have to delete the text that you don’t use, and format it properly.

I want to create a website that generates the final text based on the decisions that the user makes. The user can choose/click the text that applies, and the rest of the text is automatically deleted. Here and there they can add their own text.

At the end, I want the website to convert the final text into a PDF.

In short, the website starts with a rough outline of the document and returns a final result based on client input and decisions that they make.

How would I tackle a project like this? What steps are required to complete the project?

I have thought about it myself, I think it should be something like this:

  1. Create the html

  2. Create the js that allows to remove text based on user input

  3. Ensure proper formatting

  4. Convert the website/html into pdf??

  5. (optional) add some css

How does step 4 even work? And is step 3 straightforward? As in, when you convert a html website into a pdf, does it normally keep the formatting that you see or do I need to keep other things in mind.

I feel the least confident in step 4.

The best thing I’ve made up until now is a calculator, based on the final Odin project of the fundamental course.

how do a form programmatically by javascript

I have this input type on a website:

        <td>
        <input type="file" name="file" id="file" multiple="multiple" 
           onchange="react(this.form)" enctype="multipart/form-data" size="30">
       </td>

How can I do a Javascript command that a file is uploaded?

I know that I can define a value to an id like this document.getElementById("de").value="de"; and submit it by document.forms[0].submit()

but this is a file input.

Can anyone here tell me how I can do this?
Thanks

Pixi.JS Collision detection

I am making a 2D game in Pixi.JS and electron.

Here is my game.js:

const {Application, Graphics} = require("pixi.js")

import {Player} from "./src/player/player.js"

const app = new Application()


window.onload = initGame

async function initGame() {
    await app.init({background: '#1099bb',resizeTo:window});
    app.canvas.style.position = "absolute"
    app.canvas.style.top = "0px"
    app.canvas.style.left = "0px"

    document.body.appendChild(app.canvas)

    gameLogic()
}

async function gameLogic() {

    const player = new Player("Player", app)

    globalThis.objects = []

    const platform = new Graphics()

    platform.rect(0,0,150,600)
    platform.fill(0x0000FF)

    platform.x = app.screen.width / 2;
    platform.y = app.screen.height / 2 + 100;

    app.stage.addChild(platform)
    objects.push(platform)


    //Update
    app.ticker.add(gameLoop)
    app.ticker.add(()=> {player.update(app,globalThis.objects)})
    app.ticker.add(() => {console.log(player.isTouching(platform))})
}

async function gameLoop(delta) {
}


And here is my src/player/player.js:

const {Graphics} = require("pixi.js")

class Player {
    constructor(name,app) {
        this.player = new Graphics();

        this.player.rect(0,0,128,64)
        this.player.fill(0xFFFFFF)

        this.player.x = app.screen.width / 2;
        this.player.y = app.screen.height / 2 - 100;

        app.stage.addChild(this.player)

        document.addEventListener("keydown", (ev) => {
            if (ev.keyCode == 68) {
                this.player.x += 1;
            } else if (ev.keyCode == 65) {
                this.player.x -= 1;
            }
        })
    }
    update(app, delta) {
        app.stage.position.set(app.renderer.screen.width / 2, app.renderer.screen.height / 2);
        app.stage.pivot.set(this.player.x + 64, this.player.y + 32);
    
        globalThis.objects.forEach((Obj) => {
            if (!this.isTouching(Obj)) {
                this.player.y += 1;
            }
        })
    }


    isIn(object) {
        const playerBound = this.player.getBounds()
        const objectBound = object.getBounds()

        return(
            playerBound.x < objectBound.x + objectBound.width
            && playerBound.x + playerBound.width > objectBound.x
            && playerBound.y < objectBound.y + objectBound.height
            && playerBound.y + playerBound.height > objectBound.y
        )
    }
    isTouching(object) {
        const playerBound = this.player.getBounds();
        const objectBound = object.getBounds();

        return (
            playerBound.x <= objectBound.x + objectBound.width &&
            playerBound.x + playerBound.width >= objectBound.x &&
            playerBound.y <= objectBound.y + objectBound.height &&
            playerBound.y + playerBound.height >= objectBound.y
        );
    }
    
}

export {Player}

The problem is that in my update function, it watch if the player is touching all the platforms of the game, but don’t check if it is touching from up,down,left,right. How can split the isTouching function into four functions:

isUpTouching,
isDownTouching,
isLeftTouching,
isRightTouching.

Some AI give me that code:

isYTouching(object) {

  const playerBound = this.player.getBounds();

  const objectBound = object.getBounds();


  return (

    playerBound.y <= objectBound.y + objectBound.height &&

    playerBound.y + playerBound.height >= objectBound.y

  );

}

It returns me false, when the player touches once the platform it returns me true, and returns me true when the player don’t touch the platform after touching once.

I think it because it detect only the Y, and not X, so it doesn’t check the width of the player and the platform.

Display coverage report on browser

When you run tests in a GitHub Actions workflow, a coverage report will be generated. Now every time i run a test and a new coverage report is generated, I want to store the coverage folder in mongodb, and view the report of each generated coverage by opening the index.html on the browser, which is in Icov-report folder. To be able to view different reports, I will be using unique id like time stamp or run_id.

How do i do it? If there is any other better approach, please do suggest.

For now, this is my approach to store coverage in mongodb:-

store-coverage.js

const fs = require('fs');
const archiver = require('archiver');
const MongoClient = require('mongodb').MongoClient;
const core = require('@actions/core');
const {DefaultArtifactClient} = require('@actions/artifact');
const artifact = new DefaultArtifactClient();

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

const uniqueId = new Date().toISOString;

async function storeCoverageReport() {
  try {
    await client.connect();
    const db = client.db('coverage-reports');
    const collection = db.collection('reports');

    const rootDirectory = 'coverage'; // Path to the coverage folder
    const {id, size} = await artifact.uploadArtifact('coverage-report', {rootDirectory});
    
    console.log(`upload id and size: ${id}, ${size}`);
    const coverageReportBuffer = await compressCoverageFolder(rootDirectory);

    const result = await collection.insertOne({
      _id: uniqueId,
      coverageReport: coverageReportBuffer,
    });

    console.log(`Coverage report stored with ID: ${result.insertedId}`);
  } catch (err) {
    console.error('Error storing coverage report:', err);
  } finally {
    await client.close();
  }
}

async function compressCoverageFolder(rootDirectory) {
    const coverageReportArchive = archiver('zip');
    const coverageReportBuffer = [];
  
    coverageReportArchive.on('data', (chunk) => {
      coverageReportBuffer.push(chunk);
    });
  
    coverageReportArchive.on('end', () => {
      return Buffer.concat(coverageReportBuffer);
    });
  
    coverageReportArchive.directory(rootDirectory, false);
    await coverageReportArchive.finalize();
  
    return coverageReportArchive.pointer();
  }

storeCoverageReport();

CD workflow

name: CD Workflow

on:
  push:
    branches:
      - main
      - staging

env:
   EC2_HOST: ${{ github.ref == 'refs/heads/main' && secrets.EC2_HOST ||  secrets.STAGING_EC2_HOST }}
   EC2_USER: ${{ github.ref == 'refs/heads/main' && secrets.EC2_USER ||  secrets.STAGING_EC2_USER }}
   EC2_KEY: ${{ github.ref == 'refs/heads/main' && secrets.SSH_PRIVATE_KEY ||  secrets.STAGING_SSH_PRIVATE_KEY }}
   ACTIONS_RUNTIME_TOKEN: ${{ secrets.USER_PAT }}

jobs:
    deploy:
        runs-on: self-hosted
        steps:
            - name: Checkout
              uses: actions/checkout@v4
               
            - name: Set up Node
              uses: actions/setup-node@v4
              with:
                node-version: 18
               
            - name: Install dependencies
              run: npm ci

            - name: Run tests
              run: npm run test -- --json --outputFile=test-results.json
              continue-on-error: true # Continue even if tests fail to calculate coverage

            - name: Calculate test pass rate
              id: test_pass_rate
              run: |
               node -e 'const fs = require("fs");
               const testResults = JSON.parse(fs.readFileSync("test-results.json", "utf8"));
               const totalTests = testResults.numTotalTests;
               const passedTests = testResults.numPassedTests;
               const passRate = (passedTests / totalTests) * 100;
               console.log(`Test Pass Rate: ${passRate.toFixed(2)}%`);
               console.log(`::set-output name=pass_rate::${passRate.toFixed(2)}`);'

            - name: Check pass rate
              run: |
                 if (( $(echo "${{ steps.test_pass_rate.outputs.pass_rate }}" | cut -d'.' -f1) < 90 )); then
                   echo "Test pass rate is less than 90% in main branch."
                   exit 1
                 fi

            - name: Archive coverage report
              uses: actions/upload-artifact@v4
              with:
                name: coverage-report
                path: coverage/
                if-no-files-found: warn

            - name: Install MongoDB dependencies
              run: npm install mongodb

            - name: Store coverage report in MongoDB
              env:
                MONGODB_URI: ${{ secrets.MONGODB_URI }}
              run: |
                node .github/workflows/store-coverage.js  
            
            - name: Login to Docker
              uses: docker/login-action@v2
              with:
                username: ${{ secrets.DOCKER_HUB_USERNAME }}
                password: ${{ secrets.DOCKER_HUB_PASSWORD }}

            - name: Pull latest code into EC2, push latest code to container and Restart Server
              if: steps.test_pass_rate.outputs.pass_rate >= 90
              run: |
                echo "$EC2_KEY" > ec2_key.pem
                chmod 600 ec2_key.pem
                ssh -o StrictHostKeyChecking=no -i ec2_key.pem $EC2_USER@$EC2_HOST <<EOF
                # sudo usermod -aG docker $USER
                # newgrp docker
                # docker tag ondc-sellerapp-server omgvaibhav/ondc-sellerapp-server
                # docker push omgvaibhav/ondc-sellerapp-server:latest
                cd ~/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp
                git pull
                npm ci
                # use pm2 reload server for zero-downtime
                pm2 restart server
                EOF
  

Error:

Run node .github/workflows/store-coverage.js  
Artifact name is valid!
Error storing coverage report: Error: The provided rootDirectory undefined does not exist
    at validateRootDirectory (/home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/upload/upload-zip-specification.js:37:15)
    at /home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js:49:62
    at Generator.next (<anonymous>)
    at /home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js:31:71
    at new Promise (<anonymous>)
    at __awaiter (/home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js:27:12)
    at uploadArtifact (/home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/upload/upload-artifact.js:47:12)
    at DefaultArtifactClient.<anonymous> (/home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/client.js:42:61)
    at Generator.next (<anonymous>)
    at /home/***/actions-runner/_work/ONDC-SellerApp/ONDC-SellerApp/node_modules/@actions/artifact/lib/internal/client.js:8:71

how to do 3d modelling of image on frontend with 3d.js

I am quite new to 3d front end development and looking for guidance on what all libraries are needed if i need to create a basic app where the user uploads the picture of his room and then able to replace the existing object(eg: chair, sofa or fan) with the list of options provided to him to get the look and feel of new objects will appear in the room.

tried with 3d.js but unable to figure out a way to create 3d model of a jpg and how to capture the object to be replaced

Should I separate single application into two application?

I have been developing react project with Asp as back-end now I have 2 app in my project
1.Checklist for User
2.Shift Management for Admin
these 2 app is not directly connected for each other I think it should at least have separate back-end and have 2 server.

I wonder if I should make 2nd project and move 2nd app to it? or just do code splitting? also is there a way to deploy 2 app in same port? because this is internal application and I worried about number of port used in my project, So I want to keep it to minimum if possible.

How point to other link after login

I’m writing to ask you for some help.

In my joomla 5 site, I created two homepages

  1. homepage1 (I set guest i.e. after logging in this page is no longer seen)

  2. homepage 2 (I set registered, and it is the one that users must see after logging in)

Now, beyond the creation of the home pages, this is just to make you understand, I need

the logo after login not to point to www.domainname.com but to www.domainname.com/hompage2

Can anyone give me some info on how to proceed?

Thank you.

Need to modify the code so that alert appears when user skips a drop down between already selected dropdowns

if (document.getElementById(‘actionId’).value == ‘recommendWithFin’)

{

var curRevSeqId = document.getElementById(‘currentReviewerSequence’).value;

var allRevLen = allReviewersArray.length;

if (allRevLen <= curRevSeqId) {

alert(‘You must select the next approver before recommending the quote.’);

valid= valid && false;

}

else {

for (var i= curRevSeqId;i<=allRevLen;i++)

{

if (allReviewersArray[i]==null || allReviewersArray[i]==”) {

alert(“Please do not skip approver”);

valid= valid && false;

}

}

}

}

I am trying to modify this code from the else part to generate an alert when a user skips any drop-down between previously selected drop-down. To provide more context, consider a scenario where there are 10 drop-downs. The user selects a value in the first drop-down and skips drop-downs 2 to 5, instead selecting the 6th drop-down. In this case, an alert should be triggered, indicating that no drop-down should be skipped between previously selected drop-down. However, it is important to note that the user is not required to select all 10 drop-down; it is their choice. Therefore, the alert should only appear when there is a drop-down skipped between already selected drop-down, and not when the user decides not to select every drop-down present. Can you please modify the code to incorporate this functionality?

Tried many logics but the array is considering all the drop downs and alert message is triggered

How to access objects dynamically? [duplicate]

This may look as a common question but I was not able to find an answer for this anywhere.
In my case it’s not the felid of the object but the object name which changers dynamically.

when debugged the variable “itemId” get stored with the value “solarPanel” (as intended)
what i was expecting was to get “Solar Panel testing” printed to the console

function DataBase (name, price, images, discription, shipping, remaining){
  this.name = name;
  this.price = price;
  this.images = images;
  this.discription = discription;
  this.shipping = shipping;
  this.remaining = remaining;
} 

let solarPanel = new DataBase("Solar Panel testing", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let solarLight = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let electricScooter = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let windTurbineDom = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let windTurbinePor = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let waterTurbine = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let solarCharger = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let itemEight = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);
let itemNinee = new DataBase("Solar Panel", 400, ["blankItem.png"], "This is a greate item", 50, 10);



let buyBtn = document.getElementsByClassName("itemAddCartBtn");
console.log(buyBtn);
for (let i = 0; i < buyBtn.length; i++){
  buyBtn[i].addEventListener("click", function(){
    let itemId = this.parentElement.getAttribute("id");

    // when I debugged the code it got executed as intended up to this point
    //the error occured in the line below

    console.log([itemId].name); //itemId is defined but [itemId].name is undifined
  });
}

chat gpt suggested to replace the “console.log([itemId].name);”
with “console.log(window[itemId].name);”
but that did not worked …
in the both instances the console was printed with the word “undefined”

Handling errors in MSAL Redirect – reactjs login with microsoft sso

We are currently trying to catch an error, when a user with a company Azure AD Account tries to access the application, but does not have access to the tenant where the application resides (Multi-tenant authorization has been setup on the app).

The user enters their credentials, and gets the below error when trying to login (which is the desired and expected behavior and which we are unable to capture):

User Login Error

The user has to cancel the authentication flow (as an automatic redirect back to the app does not occur on this error), which in turn does not allow us to capture that specific error (or any errors during the login process).

Is there a method we can utilize from either the MSAL Service or the Broadcast Service that will allow us to capture errors from the Azure Login Page (pictured above).

We’ve cloned the following repository from Microsoft to test error capturing during the login process (using clean, working code from a trusted source, which we confirmed works as intended):

https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/redirects.md

We’ve found that the logging used in the MSAL Configuration (however verbose), does not actually capture the errors from the redirect flow. The closest we’ve come to capturing the error, was adding the below code to catch the BrowserAuthError (user_cancelled the flow) and logging it to the console.

How can I make my text visible when my custom curser hovers over it

I have a circle that follows my cursor. I was wondering if I can add an effect so when the circle hovers over the text it inverts only the text so you are able to see the text even when the white circle is on top of it.

I have tried to make the text black when I hover over it using CSS but it wont work because the words are too big so the text out of the circle blend in with the background.

document.addEventListener('DOMContentLoaded', () => {
  const interBubble = document.getElementById('circle');
  let curX = 0;
  let curY = 0;
  let tgX = 0;
  let tgY = 0;

  function move() {
    curX += (tgX - curX) / 10;
    curY += (tgY - curY) / 10;
    interBubble.style.transform = `translate(${Math.round(curX)}px, ${Math.round(curY)}px)`;
    requestAnimationFrame(() => {
      move();
    });
  }

  window.addEventListener('mousemove', (e) => {
    tgX = e.clientX;
    tgY = e.clientY;

    if (e.target.tagName === 'P' ||
      e.target.tagName === 'A' ||
      e.target.tagName === 'BUTTON' ||
      e.target.parentNode.tagName === 'BUTTON') {
      interBubble.classList.add('big');
    } else {
      interBubble.classList.remove('big');
    }
  });

  move();
});
Body {
  background-color: black;
  overflow: hidden;
}

div {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2;
}

p {
  color: white;
  font-size: 30px;
}

p:hover {
  color: black;
}

:root {
  --trans-bounce: cubic-bezier(.4,2.2,.6,1.0);
  --trans-time: .4s;
}

.mouseFollowCircle {
  width: 30px;
  height: 30px;
  border-radius: 999px;
  position: absolute;
  z-index: 1;
  top: -15px;
  left: -15px;
  box-shadow: 0 0 10px white;
  background-color: white;
  pointer-events: none;
  backdrop-filter: blur(2px);
  transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), border var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce);
}

.mouseFollowCircle.big {
  width: 70px;
  height: 70px;
  border-radius: 999px;
  position: absolute;
  z-index: 1;
  top: -35px;
  left: -35px;
  box-shadow: 0 0 10px white;
  background-color: white;
  pointer-events: none;
  backdrop-filter: blur(2px);
  transition: width var(--trans-time) var(--trans-bounce), height var(--trans-time) var(--trans-bounce), border var(--trans-time) var(--trans-bounce), top var(--trans-time) var(--trans-bounce), left var(--trans-time) var(--trans-bounce), background-color var(--trans-time) var(--trans-bounce);
}
<div><p>Hello World</p></div>
<section class="mouseFollowCircle" id="circle"></section>