Unable to get both audio from microphone input and from shared screen

Using MediaRecorder API, it does not captured from “audioStream.getAudioTracks()” which is from microphone input. It only captured audio from “stream.getAudioTracks()” which is audio from shared screen.

Any reason why the audio is not being captured

Here is my code

    startButton.addEventListener('click', async () => {
    const displayMediaOptions = { video: true, audio: true };
    const audioMediaOptions = { audio: true };
    stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    audioStream = await navigator.mediaDevices.getUserMedia(audioMediaOptions);
        
    mergedStream = new MediaStream([...stream.getVideoTracks(), ...stream.getAudioTracks(),...audioStream.getAudioTracks()]);

    recorder = new MediaRecorder(mergedStream, { mimeType: 'video/webm; codecs=vp8' });

    recorder.addEventListener('dataavailable', (event) => {
        console.log({event});
        chunks.push(event.data);
    });

        recorder.addEventListener('stop', async () => {
            const blob = new Blob(chunks, { type: stream.getTracks()[0].getSettings().mimeType });
            chunks = [];
        });

        // Start recording
        recorder.start();

        // Wait for the 'stop' event to finish and fix the duration of the recorded video
        await recorder.addEventListener('stop');
    });

Difference between using constructor + function vs function with parameters in JavaScript

I am very new to programming and I have a very basic question…
What’s the difference between using constructor values in a function vs using parameters in a function?

Let’s say there’s a class called Add

class Add {
  constructor(number1, number2){
    this.number1 = number1;
    this.number2 = number2;
  }

  addNumbers (number1, number2){
    return number1 + number2;
  }

  addNumbersWithConstructor (){
    return this.number1 + this.number2;
  }
}

Both addNumbers and addNumbersWithConstructor do the same thing.

const AdditionMaker = new Add(1,2);
const result1 = AdditionMaker.addNumbers(3,2)
const result2 = AdditionMaker.addNumbersWithConstructor()
console.log(`result1 is ${result1}`) //5
console.log(`result2 is ${result2}`) //3

What’s the difference between addNumbers and addNumbersWithConstructor?

Firebase what state is a batched write in after a commit?

Question

After committing a batch using batch.commit() are the executed batch.set() operations cleared off the variable?

Explanation

Say i have a list of 1000 (or so) items that i need to write to Firestore.

I can cycle through them and on every 500th cycle i’ll just commit the batch.

Now this the loop continues (after the first 500 elements for example) to add the 501st, 502nd … up to 1000th element using batch.set()

Reaching 1000, the code needs to execute batch.commit() the second time, but if the batch variable was not reset after the first commit, 1000 elements will be in the batch leading to a crash

Example Code

function batchWrite () {
    const batch = writeBatch(db)
    somearray.foreach((element: any, index :Number) => {
        const someRef = doc(db, 'blablabla)
        batch.set(someRef, element)

        const indexDivBy500 = index / 500
        //True if index is divisible by 500 without remainder
        const commitBatch = (indexDivBy500 - Math.floor(indexDivBy500)) == 0; 
    
        if(commitBatch) {
            batch.commit()

            //something along the lines of batch.clear()?
            //because after the commit, the foreach may continue with index 501...
        }

    })
}

Javascript Electron https, node-fetch module not found

Here is my gate.html code:

<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self <' https://example.com.tr/validkeys.txt">
    <meta http-equiv='Content-Security-Policy' content="default-src 'self'; script-src 'self'">
    <title>License Gate</title>
    <link rel='stylesheet' href='./index.css'>
  </head>
  <body>
    <form id='license-gate'>
      <label for='key'>
        Please enter your license key
      </label>
      <input id='key' type='text' placeholder='Your license key'>
      <button type='submit'>
        Submit
      </button>
    </form>
  </body>
</html>

Here is my gate.js code (I preloaded this while opening my gate.html, see in my main.js)

const { ipcRenderer } = require('electron')
const https = require('https')


window.addEventListener('DOMContentLoaded', async () => {
  console.log('DOM content loaded')
  const gate = document.getElementById('license-gate')

  gate.addEventListener('submit', async event => {
    console.log('Submit button clicked')
    event.preventDefault()
    
    const key = document.getElementById('key').value;
    console.log('Entered key:', key)

    https.get('https://example.com.tr/validkeys.txt', (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        const keys = data.trim().split('n')
        console.log('Valid keys:', keys)

        if (keys.includes(key)) {
          console.log('Key is valid')
          ipcRenderer.send('key-validation-result', true)
        } else {
          console.log('Key is invalid')
          ipcRenderer.send('key-validation-result', false)
        }
      });
    }).on('error', (err) => {
      console.log('Error: ', err.message);
    });
  })
})

and it’s my main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const isDev = process.env.NODE_ENV === 'development'
const { ipcRenderer } = require('electron');


let mainWindow;

async function gateCreateWindowWithLicense(createWindow) { 
  const gateWindow = new BrowserWindow({
    resizable: false,
    frame: false,
    width: 1920,
    height: 1080,
    webPreferences: {
      preload: path.join(__dirname, 'gate.js'), //here, I'm preloading gate.js
      devTools: true,
    },
  })
  
 
  gateWindow.loadFile('gate.html')
 
  if (isDev) {
    gateWindow.webContents.openDevTools({ mode: 'detach' })
  }
   //ipcmain
  ipcMain.on('key-validation-result', async (event, isValid) => {
    if (isValid) {
      // Close the license gate window
      gateWindow.close()
  
      // Launch our main window
      createWindow()
    } else {
      // Show an error message
      const dialogOptions = {
        type: 'error',
        title: 'Invalid license key',
        message: 'The license key you entered is not valid. Please try again.',
        buttons: ['OK'],
        defaultId: 0,
        cancelId: 0,
      }
  
      await dialog.showMessageBox(dialogOptions, gateWindow)
    }
  })
} 

function createWindow() {
  const { screen } = require('electron');
  let factor = screen.getPrimaryDisplay().scaleFactor;
  // get the size of the screen
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;

  mainWindow = new BrowserWindow({
    width: 800/factor,
    height: 600/factor,
    useContentSize: true,
    webPreferences: {
      nodeIntegration: true,
      zoomFactor: 1.0 / factor,
      blinkFeatures: 'OverlayScrollbars'
    },
    autoHideMenuBar: true,
    fullscreenable: true,
  });
  // Update the title of the Electron app window when the website updates its title
  mainWindow.webContents.on('page-title-updated', (event, title) => {
    event.preventDefault();
    mainWindow.setTitle('Axiswiwo');
    
  });
  mainWindow.loadURL("http://www.thewebsitethatiwanttoopen.com/");
  mainWindow.on('closed', function () {
    mainWindow = null;
    
  });
  mainWindow.on('enter-full-screen', () => {
    mainWindow.setResizable(true); // set window to resizable in fullscreen mode
    mainWindow.maximize(); // maximize the window to fill the screen
  });
  mainWindow.on('leave-full-screen', () => {
    mainWindow.setResizable(true); // set window to resizable
    mainWindow.unmaximize(); // restore the window to its previous size
    mainWindow.setSize(800, 600); // resize the window to 800x600
    mainWindow.setAspectRatio(800 / 600);
  });

  // when the window is small, maximize it to fill the screen
  if (mainWindow.isMaximizable()) {
    mainWindow.maximize();
  }
} // end of createwindow

app.whenReady().then(() => {
  gateCreateWindowWithLicense(createWindow);
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow();
  }
});



So, When I open program, on developer tools console It says:Dev tools console error

So, It cannot preload gate.js either because of this.

I tried updating npm, installing “https” even It’s available in node.js already. Also, It cannot find “node-fetch” either. Same error occurs. I cannot use XmlHttpRequest because It violates content policy and I cannot have an access website panel right now. window.fetch couldn’t fetch data too. How can I fetch this data really I don’t know.

How to assign a unique identifier to individual quantity for subscription item

I am using Stripe to handle payments and I have to generate customized invoices instead of stripe generated invoices.
I need help with how to identify the following uniquely when looping through invoice line items from webhook invoice.payment_succeeded

Subscription Item ID Quantity
subscription_item_id_1 1
subscription_item_id_1 2

I tried adding a same priceId again as different subscription item instead of increasing the quantity but stripe doesnt allow adding multiple subscription items with same price ID.
I want to assign a Id called as entityId everytime we are increasing quantity.

Express API endpoint invokation issue

I have created an API in Express js. An endpoint is not reachable by React application. Although the same endpoint can be accessed through Postman.

Express Application

import express from 'express';
import cors from 'cors';

const app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

import { riskRouter } from './routes/risk.js';
app.use('/api/risk', riskRouter);

app.all('*', async (req, res) => {
  return res.status(500).send({ message: 'Request handler not found!'});
});

risk.js contents

import express from 'express';
const router = express.Router();

router.delete('/listitems/:id', validateToken, async (req, res) => {
  const listId = req.params.id;
  const { listItems } = req.body

  listItems.forEach(async item => {
    await pool
    .query(`delete from list_items where list_id = ? and item_id = ?`,
      [listId, item.item_id])
    .then((result) => {
    })
    .catch((error) => {
      return res.status(500).send({ message: error.message });
    });
  });

  return res.status(200).send({ message: 'List items successfully deleted' });
});

export { router as riskRouter }

React code for deletion of items:

    if (deletedItems.length > 0) {
      let url = `${config.API_URL}/risk/listitems/${listId}`;

      axios
      .delete(url , {listItems: deletedItems}, { headers: { token: jwt } })
      .then((res) => {
        props.setRefresh();
      })
      .catch((err) => {
        errorInSave = true;
        console.log(err);
      });
    }

The given code should delete the requested records from table. But whenever I make a request through React, it returns with the following error:

{
message: ‘Request handler not found!’
}

When I create an API request from Postman client, it works perfectly fine.

Stripe and NextJS 13 Create Checkout Session

I am getting a 500 error and I have narrowed down the bug to my priceId being undefined. I feel like I have defined the priceId but whatever I do it still isn’t working. I have successfully used a GET request to list all the prices I have made in my Stripe dashboard. So, since I did create all the prices I know I just have to retrieve the price.id and use that.

I will post screenshots of my code below. Any help would be appreciated. Been stuck on this for hours. Even tried Stripe support but I know it’s a coding error somewhere.

api/payment – route.jsx

    import { NextResponse } from "next/server";
import Stripe from "stripe";

export async function POST(request) {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
  const { data } = request.body;
  const session = await stripe.checkout.sessions.create({
    line_items: [
      {
        price: priceId,
        quantity: 1,
      },
    ],
    mode: "payment",
    success_url: "http://localhost:3000/success",
    cancel_url: "http://localhost:3000/cancel",
  });

  return NextResponse.json(session.url);
}

Pricing Card.jsx – component client side – I did console.log(price.id) inside of the the handleSubscription function and I do get the price.ids.

function PricingCard({price}) {

const handleSubscription = async (e, price) => {
      e.preventDefault();
      console.log(price.id)
      const {data} = await axios.post('/api/payment', {
       priceId: price.id,
      });
      window.open(data)
      console.log(data)
    }

    return (
        <div className="border-gray-100 shadow-2xl border-4 text-center mt-10 max-w-[1040px]">
      <div>
        <div className="bg-gray-100 h-28 items-center font-bold">
          <h4 className="text-3xl">{price.nickname}</h4>
          <p>{dynamicSubTitle(price)}</p>
          <h3 className='text-xl mt-2'>First 2,000lbs Included</h3>
        </div>
        <div>
          <div className="flex flex-col items-center justify-center pt-4">
            <h1 className="text-5xl font-bold">
              {(price.unit_amount / 100).toLocaleString("en-US", {
                style: "currency",
                currency: "USD",
              })}{" "}
            </h1>
            <h3 className="pl-1 mt-2">Additional weight just $.05 /lb</h3>
          </div>
          <ul className='flex justify-center'>
            <li className="text-xl font-bold">{dynamicDescription(price)}</li>
          </ul>
          {/* <pre>{JSON.stringify(price, null, 4)}</pre> */}
          <button
            onClick={(e) => handleSubscription(e, price)}
            className="mt-8 flex w-full justify-center rounded-md border border-transparent bg-[#f1592a] py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
          > Rent This Dumpster
          </button>
        </div>
      </div>
    </div>
    )
}

export default PricingCard;

react-calendar onChange TS2769: No overload matches this call Error

I used the response calendar library.

The default code suddenly gives an onChange prop error. What should I do? (It worked before.)

My code

`import React, {useState} from ‘react’;
import Calendar from “react-calendar”;

function App() {

const [value, onChange] = useState(new Date());

return (
    <div>
        <Calendar
            onChange={onChange}
            value={value}
        />
    </div>
);

}

export default App;`

Error message

TS2769: No overload matches this call.   Overload 1 of 2, ‘(props: CalendarProps | Readonly): Calendar’, gave the following error.     Type ‘Dispatch<SetStateAction>’ is not assignable to type ‘(value: Value, event: MouseEvent<HTMLButtonElement, MouseEvent>) => void’.       Types of parameters ‘value’ and ‘value’ are incompatible.         Type ‘Value’ is not assignable to type ‘SetStateAction’.           Type ‘null’ is not assignable to type ‘SetStateAction’.   Overload 2 of 2, ‘(props: CalendarProps, context: any): Calendar’, gave the following error.     Type ‘Dispatch<SetStateAction>’ is not assignable to type ‘(value: Value, event: MouseEvent<HTMLButtonElement, MouseEvent>) => void’.

I checked npm version, config files and re-install. But it still don’t working.

Why does my useCallback function cause an infinite loop in my useEffect?

I have a function called getContentfulProjectById. It essentially fetches a contentful project by the id passed to it.

const getContentfulProjectById = async (projectId) => {
    try {
      const entries = await client.getEntries({
        content_type: "projects",
        "fields.projectId": projectId,
      });
      store.dispatch(setSelectedProject(entries));
    } catch (error) {
      console.log(`Error Fetching Programs:${error}`);
    }
  };

The component uses the hook useParams to obtain the projectId parameter, passes that to the function which I’ve invoked through a useCallback function I’ve named queryForProject and I pass the function and the result of useParams to the dependency array. I then call this function in a useEffect. I pass the queryForProject as a dependency to the useEffect and it results in an infinite loop. If I were to remove the function from the dependency array, I don’t see the loop but I see the warning that I need to pass the function as a dependency.

  const { projectId } = useParams();

  const { getContentfulProjectById } = useContentful();

  const queryForProject = useCallback(async () => {
    await getContentfulProjectById(projectId);
    setIsLoading(false);
  }, [getContentfulProjectById, projectId]);

  useEffect(() => {
    queryForProject();
  }, [queryForProject]);

Getting Keytar Error While Installing Node Module on MacBook Pro

I am trying to install a node package on my MacBook Pro and anytime I install the package, I get this error.

npm ERR! code 1
npm ERR! path /opt/homebrew/lib/node_modules/@medable/mdctl-cli/node_modules/keytar
npm ERR! command failed
npm ERR! command sh -c prebuild-install || node-gyp rebuild
npm ERR! CXX(target) Release/obj.target/keytar/src/async.o
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | darwin | arm64
npm ERR! gyp info find Python using Python version 3.9.6 found at "/Library/Developer/CommandLineTools/usr/bin/python3"
npm ERR! gyp info spawn /Library/Developer/CommandLineTools/usr/bin/python3
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/opt/homebrew/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/opt/homebrew/lib/node_modules/@medable/mdctl-cli/node_modules/keytar/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/opt/homebrew/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/obafemiomotayo/Library/Caches/node-gyp/19.8.1/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/obafemiomotayo/Library/Caches/node-gyp/19.8.1',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/opt/homebrew/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/obafemiomotayo/Library/Caches/node-gyp/19.8.1/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/opt/homebrew/lib/node_modules/@medable/mdctl-cli/node_modules/keytar',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! gyp info spawn make
npm ERR! gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
npm ERR! In file included from ../src/async.cc:4:
npm ERR! In file included from ../../nan/nan.h:174:
npm ERR! ../../nan/nan_callbacks.h:55:23: error: no member named 'AccessorSignature' in namespace 'v8'
npm ERR! typedef v8::Local<v8::AccessorSignature> Sig;
npm ERR!                   ~~~~^
npm ERR! In file included from ../src/async.cc:4:
npm ERR! ../../nan/nan.h:2536:8: error: no matching member function for call to 'SetAccessor'
npm ERR!   tpl->SetAccessor(
npm ERR!   ~~~~~^~~~~~~~~~~
npm ERR! /Users/obafemiomotayo/Library/Caches/node-gyp/19.8.1/include/node/v8-template.h:814:8: note: candidate function not viable: no known conversion from 'imp::Sig' (aka 'int') to 'v8::SideEffectType' for 7th argument
npm ERR!   void SetAccessor(
npm ERR!        ^
npm ERR! /Users/obafemiomotayo/Library/Caches/node-gyp/19.8.1/include/node/v8-template.h:807:8: note: candidate function not viable: no known conversion from 'imp::NativeGetter' (aka 'void (*)(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &)') to 'v8::AccessorGetterCallback' (aka 'void (*)(Local<v8::String>, const PropertyCallbackInfo<v8::Value> &)') for 2nd argument
npm ERR!   void SetAccessor(
npm ERR!        ^
npm ERR! In file included from ../src/async.cc:4:
npm ERR! In file included from ../../nan/nan.h:2884:
npm ERR! ../../nan/nan_typedarray_contents.h:34:43: error: no member named 'GetContents' in 'v8::ArrayBuffer'
npm ERR!       data   = static_cast<char*>(buffer->GetContents().Data()) + byte_offset;
npm ERR!                                   ~~~~~~~~^
npm ERR! 3 errors generated.
npm ERR! make: *** [Release/obj.target/keytar/src/async.o] Error 1
npm ERR! gyp ERR! build error 
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/opt/homebrew/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:203:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:512:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:293:12)
npm ERR! gyp ERR! System Darwin 22.4.0
npm ERR! gyp ERR! command "/opt/homebrew/Cellar/node/19.8.1/bin/node" "/opt/homebrew/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd /opt/homebrew/lib/node_modules/@medable/mdctl-cli/node_modules/keytar
npm ERR! gyp ERR! node -v v19.8.1
npm ERR! gyp ERR! node-gyp -v v9.3.1
npm ERR! gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/obafemiomotayo/.npm/_logs/2023-04-09T17_05_23_177Z-debug-0.log

I have uninstalled and reinstalled node severally but the issue still persists. I have also uninstalled and reinstalled node-gyp and keytar separately but still no avail. I am running out of ideas here. What could be the issue?

javascript adding first letter in first name and second name add two first letters then concat them together

I don’t know why it doesn’t return any thing but I am sure the function and the callback function is well written.
Why it doesn’t want to return?

here is my code

function createID(i1,i2){
    if((i1.length && i2.length) > 0 ){
       var f = i1.charAt(0).toLowerCase();
       var d = i2.slice(0,2).toUpperCase();
        return f.concat(d);
     }
     else{
       return 'error';
     }
}

createID('john','two');

To get first letter of first string then the two letters of the second string and concatenate them together

How to get all members

So I want my bot to say Listening to X amount of Members I want to collect all members from all guilds my DC bot is in any help?

Basically explained my problem Above!

unable to impliment infinityscoll v4 with dynamic gallery php masonry

i am trying to impliment infnite scrolling with my images . all of my images are in a folder called img (50 images) i am displaying 10 images per page. when i am trying to append the images via infinite scrolling i am unable to do that. i am running into error . Can anyone suggest me how to impliment infinite scrolling plugin on this. any suggestion would be helpful.

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Image Gallery with Infinite Scrolling and Masonry</title>
    <style>
        .gallery {
    display: flex;
    flex-wrap: wrap;
}

.gallery-item {
    width: 25%;
    padding: 10px;
}

.gallery-item img {
    width: 100%;
}

.pagination {
    display: none;
}

@media screen and (max-width: 768px) {
    .gallery-item {
        width: 50%;
    }
}

@media screen and (max-width: 480px) {
    .gallery-item {
        width: 100%;
    }
}
    </style>
</head>
<body>
    <div class="gallery">
        <?php
        // Retrieve all the available image names from a directory and save them into an array
        $dir = "img/";
        $images = glob($dir."*.{jpg,jpeg,png,gif}", GLOB_BRACE);

        // Calculate the total number of pages based on the number of images and the number of images per page
        $images_per_page = 10;
        $total_pages = ceil(count($images) / $images_per_page);

        // Retrieve the current page number from the URL query string or set it to 1 if it's not present
        $current_page = isset($_GET["page"]) ? $_GET["page"] : 1;

        // Calculate the starting index and ending index of images to display based on the current page number and the number of images per page
        $start_index = ($current_page - 1) * $images_per_page;
        $end_index = $start_index + $images_per_page;

        // Generate HTML code for each image in the directory and display it on the webpage
        for ($i = $start_index; $i < $end_index && $i < count($images); $i++) {
            echo '<div class="gallery-item">';
            echo '<a href="'.$images[$i].'" data-lightbox="gallery">';
            echo '<img src="img/placeholder.jpg" data-src="'.$images[$i].'" alt="Gallery Image">';
            echo '</a>';
            echo '</div>';
        }
        ?>
    </div>

    <?php if ($current_page < $total_pages): ?>
    <div class="pagination">
        <a href="?page=<?php echo $current_page + 1; ?>"></a>
    </div>
    <?php endif; ?>


    <script src="https://code.jquery.com/jquery-3.6.4.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-infinitescroll/4.0.1/infinite-scroll.pkgd.js"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/17.3.0/lazyload.min.js"></script>
    <script src="app.js"></script>
    <script type="text/javascript">
$(document).ready(function() {
    var lazyLoadInstance = new LazyLoad({
        elements_selector: ".gallery img",
        threshold: 500,
        callback_loaded: function(element) {
            var masonryInstance = $(".gallery").data("masonry");
            masonryInstance.layout();
        }
    });

    var $container = $(".gallery");
    $container.imagesLoaded(function() {
        $container.masonry({
            itemSelector: ".gallery-item",
            columnWidth: ".gallery-item",
            percentPosition: true,
        });
    });

    $(".gallery").infinitescroll({
        navSelector: ".pagination",
        nextSelector: ".pagination a:first",
        itemSelector: ".gallery-item",
        loading: {
            finishedMsg: "No more images to load.",
            img: "https://i.imgur.com/6RMhx.gif"
        },
        path: function() {
            var nextPage = this.pageNumber + 1;
            if (nextPage <= <?php echo $total_pages; ?>) {
                return "index.php?page=" + nextPage;
            } else {
                return null;
            }
        }
    }, function(newElements) {
        $(newElements).imagesLoaded(function() {
            $container.masonry("appended", $(newElements));
            lazyLoadInstance.update();
        });
    });
});
    </script>
</body>
</html>

i have tried the documentation of infinitescroll

let elem = document.querySelector('.container');let infScroll = new InfiniteScroll( elem, {// optionspath: function() {var nextPage = this.pageNumber + 1;if (nextPage <= <?php echo $total_pages; ?>) {return "index.php?page=" + nextPage;} else {return null;}},append: '.gallery-item',history: false,});

this doesn’t worked . i couldnot understand how to pass the path . as i am able to access via ‘ index.php?page=3 ‘ . any suggestion would be helpful.

WebGPU: Drawing white shape on white background becomes black as soon as alpha blending is enabled?

In WebGPU, I’m trying to draw an alpha-blended quad. Something is missing, but I don’t know what.

What I did

  • setting blend mode in pipeline fragment target to add/src:src-alpha/dest:one-minus-src-alpha
  • setting fragment alpha to zero (so it should be invisible)
  • draw a white shape on a white background

Now, it will be black! A white shape on a white background becomes black, as soon as srcFactor is set. Why is that? Some flag missing? Or is it a bug? It should be all white. Happened in current Chrome Canary.

  • changing fragment alpha to 1 works (all white), regardless of srcFactor
  • changing fragment alpha to 0.5 doesn’t work (grey quad on white background), regardless of srcFactor
  • changing srcFactor to one is white

It seems as if this is a bug in Chrome Canary. The alpha blending seems to fail to read the actual pixel values from the destination render attachment, and instead always uses black color as background? Or am I missing something obvious?

Here’s the full code:

    const canvas = document.querySelector('#canvas');
    canvas.width = canvas.height = 500;
    
    const adapter = await navigator.gpu.requestAdapter();
    const device = await adapter.requestDevice();
    
    
    const context = canvas.getContext('webgpu');
    const swapChainFormat = navigator.gpu.getPreferredCanvasFormat();
    
    const swapChain = context.configure({
        device,
        format: swapChainFormat,
        alphaMode: "opaque",
    });
    
    function render() {
        const commandEncoder = device.createCommandEncoder({});
        const textureView = context.getCurrentTexture().createView();
    
        const module = device.createShaderModule({
            label: 'generated accunulation shader',
            code: `
                @vertex fn vs(
                    @builtin(vertex_index) vertexIndex : u32
                ) -> @builtin(position) vec4f {
                    var pos = array<vec2f, 6>(
                        vec2f(-1.0, -1.0),  // center
                        vec2f( 1.0, -1.0),  // right, center
                        vec2f(-1.0,  1.0),  // center, top
                    
                        vec2f(-1.0,  1.0),  // center, top
                        vec2f( 1.0, -1.0),  // right, center
                        vec2f( 1.0,  1.0),  // right, top
                    );
            
                    return vec4f(pos[vertexIndex]*0.5, 0.0, 1.0);
                }
    
                @fragment fn fs() -> @location(0) vec4f {
                    var color = vec4f(1,1,1,0); // color set to white
    
                    color.a = 0; // alpha set to zero, should be invisible
                    return color;
                }
            `,
        });
    
        const pipeline = device.createRenderPipeline({
            label: 'transparent shader',
            layout: 'auto',
            vertex: {
                module,
                entryPoint: 'vs',
            },
            fragment: {
                module,
                entryPoint: 'fs',
                targets: [{ 
                    format: swapChainFormat,
                    blend: {
                        color: {
                            operation: 'add',
                            srcFactor: 'src-alpha',
                            //destFactor: 'one-minus-src-alpha',
                        },
                        alpha: {},
                    }
                }],
            },
        });
    
        const renderPassDescriptor = {
            colorAttachments: [{
                view: textureView,
                loadOp:'clear',
                storeOp: 'store',
                clearValue: [1,1,1,1]
            }],
        };
    
        const accumulationPass = commandEncoder.beginRenderPass(renderPassDescriptor);
        accumulationPass.setPipeline(pipeline);
        accumulationPass.draw(6); // number of vertices
        accumulationPass.end();
    
        device.queue.submit([commandEncoder.finish()]);
    }
    
    render()

See this neat website for trying it live:
https://06wj.github.io/WebGPU-Playground/#/Samples/HelloCanvas

undesired outcome