How do I preserve the colors of an image when I lower its overall opacity to almost transparent? (html javascript) [duplicate]

When I convert an image to almost transparent (1% opacity), either by using imageData or globalAlpha, the original color data is lost in the conversion. When I open up the saved image in any image editing software (I checked and the image editing software is not the problem here) and put it back to full opacity there, I notice that only 16 or 24 colors remain. The image looks like as if it was posterized.

For example, if my image had a color “#90F59A”, after the conversion, the color would now become “#AAFFAA”.

const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;

ctx2.clearRect(0, 0, canvas2.width, canvas2.height);

for (let i = 0; i < data.length; i += 4) {
    const red = data[i];
    const green = data[i + 1];
    const blue = data[i + 2];
    const alpha = data[i + 3];
    if (alpha == 0 || (red == 0 && green == 0 && blue == 0)) {
        // black pixels become fully transparent
        data[i] = 0;     // Red
        data[i + 1] = 0; // Green
        data[i + 2] = 0; // Blue
        data[i + 3] = 0; // Alpha
    } else {
        // all other pixels turn almost transparent
        data[i + 3] = 255 * 0.01;
    }
}
ctx2.putImageData(imageData, 0, 0);

I tried using globalAlpha and found that the quality was reduced. I then tried using imageData because I thought it would preserve the image data since I was modifying the image’s data itself (or the array or color values the image contains), but it also didn’t work.

I also tested if the color quality loss would happen with images that are more opaque (like 80%), and saw that the image quality did not get lower. I also tested with an opacity that is just a bit higher than 1% (like 3%) and saw that there was less reduction in color quality, so I assume the color quality loss was because of some computation with transparent pixels.

I was expecting the image to become almost transparent (1% opacity) but still have the colors be the same.

storybook error: “Cannot read properties of undefined (reading ‘tap’)”

trying to run storybook (v8.6.14) in a next.js 14 project with @storybook/nextjs,
but it keeps breaking on startup with this error:

TypeError: Cannot read properties of undefined (reading 'tap')

stack trace points to:
node_modules/next/dist/compiled/webpack/bundle5.js

looks like storybook is somehow using next’s internal webpack instead of its own.

already tried:

removed all addons (even @storybook/addon-styling-webpack)

cleared cache + reinstalled everything

tried forcing storybook to use its own webpack via @storybook/builder-webpack5 and aliasing webpack

made sure everything’s on webpack 5.101

still same thing, crashes the moment it starts

weird thing is – I had it working few times on another local clone of the same repo, but after working on it for a while, it started happening there also, so weird.. feels like cache problem but I really don’t know why non of the things I have done fixed it

I will appreciate your help 🙂

main.ts:

import type { StorybookConfig } from '@storybook/nextjs'

const config: StorybookConfig = {
  stories: [
    '../ui/**/*.stories.@(js|jsx|mjs|ts|tsx)',
  ],
  addons: [],
  framework: {
    name: '@storybook/nextjs',
    options: {},
  },
  staticDirs: ['../public'],
  docs: {
    autodocs: 'tag',
  },
}
export default config

How can I display dynamic menu items like the 7 Brew Menu using JavaScript?

I’m trying to build a dynamic coffee shop menu for a project, kind of like the 7 Brew Menu, where each category (like drinks, flavors, add-ons, etc.) updates based on user selection.

I’m using HTML, CSS, and vanilla JavaScript, but I’m not sure how to structure the data so it’s easy to update and display.

For example:

When a user clicks on “Iced Drinks,” it should show only iced drink items.

Each item should have a name, price, and maybe an image.

What’s the best way to store and render this kind of data — should I use an array of objects or fetch it from a JSON file?

Any advice or code examples would be super helpful!

What I tried:
I tried creating an array of menu items in JavaScript and displaying them using a simple forEach loop. It works, but all items show at once instead of updating when I select a category (like “Iced Drinks” or “Blended Drinks”).

What I expected:
I expected only the selected category items to display — similar to how the 7 Brew Menu updates depending on drink type.

What actually happened:
All the menu items appeared together on the page, and the filter buttons didn’t change the displayed results.

Why doesn’t my v-model show the initial value in Vue 3?

I’m building a simple component in Vue 3 that uses v-model to bind an input field.
When I set the variable value inside mounted(), it updates correctly in the paragraph but the input itself stays empty.
Here’s my component:

<template>
  <div>
    <input type="text" v-model="name">
    <p>{{ name }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return { name: '' }
  },
  mounted() {
    this.name = 'John'
  }
}
</script>

I tried setting the initial value directly in the data() function and it worked, but I need to assign it dynamically later.
I also checked the browser console and saw no errors.
I expected the input to show “John” automatically when the component loads, but it only updates when I type something manually.
Why doesn’t the input reflect the data value on mount?

How do I change the Google PlaceAutocompleteElement width?

Unlike the past, Google’s new PlaceAutocompleteElement imposes its own styling on the input and it clashes with my site.

In particular, the width is not full-width / fill. I see Google allows a small handful of overrides. However, is there any way to ensure the autocomplete to fills its container?

In one example, the autocomplete is appended to the body and it does fill the width. In another example, the autocomplete appears to be constrained. But neither examples explain how the width is controlled.

I did try the following and it does not work:

const autocompleteElement = new window.google.maps.places.PlaceAutocompleteElement()
autocompleteElement.style.colorScheme = "light"
autocompleteElement.style.width="100%"
autocompleteElement.width = "100%"
myElement.appendChild(autocompleteElement)

Difference in date between Js code in React project and Browser

Currently creating a simple React project which displays the date and shows future / past dates based on the user inputting the number of days difference. The date I’ve inputted as the date to measure from doesn’t come up as the same when on the Browser. I have no idea why this has happened but I’m assuming its something with Vite because this doesn’t happen when not using it.
Code for displaying time
Browser Output

Initially tried showing the current date with ‘new Date()’ but even with a specific date (e.g. new Date(‘october 04 2025’), a completely different date is logged by the console.

PayStackAPIError: Bearer Authorization header may not have been set | Unauthorized (401)

This is my first time of integrating payment gateway to my website using official paystack-node sdk package in my node.js application, but after following through the documentation i’m facing this error: PayStackAPIError: Bearer Authorization header may not have been set | Unauthorized (401).

This is my code sequence on the server side:

    const Paystack = require('paystack-node');
    const {PaystackPaymentSetupValidator,throwValidationError} = require('../utils/schemas');
    const router = require('express').Router();
    const ExpressError = require('../utils/express_error');
    const paystack = new Paystack(process.env.PAYSTACK_SECRET_KEY, process.env.NODE_ENV);
    const _isDevt = (process.env.NODE_ENV !== 'production');
    const callback_url = process.env.PAYSTACK_CALLBACK_URL;

// Middleware to validate Paystack requests
    const _validateRequest = async (req, resp, next) => {
        try{
            const {req_typ} = req.body;
            const {error} = await req_typ=='paystack-payment-setup-req'? PaystackPaymentSetupValidator.validate(req.body,{abortEarly:false}) : throwValidationError(req.body);
            if (error) {
                let msg = error? error.details.map(el => el.message).join('n# ') : 'Invalid Session Data!';
                if(_isDevt){
                    console.log('validation err:',error,msg);
                    msg = `n# ${msg}.`;
                } else {
                    msg = '';
                } // end if
                req.app.locals.appfx.log(new ExpressError('Validation Error',msg,0,req.body));
                return resp.send({error: {text: msg||'Invalid Request format.'}});
            } // end if
            return next();
        } catch(err) {
            if(_isDevt){
                console.log('catch err:',error);
            } // end if
            req.app.locals.appfx.log(error);
            return resp.send({error: {text:`Request Error!${_isDevt?`n${error}`:''}`}});
        } // end catch    
    } // end fx

    // Middleware to initialize Paystack
    const _initiatePayment = async (req, resp) => {
        try {
            const {email, amount, metadata} = req.body;
            const response = await paystack.initializeTransaction({
                email: email,
                amount: amount * 100, // Amount in kobo
                metadata: metadata || {},
                callback_url: callback_url
            });
            console.log('resp:',response);
            if(response.status) {
                return resp.send({success: {text: 'Paystack initialized successfully.', data: response.data}});
            } else {
                return resp.status(400).send({error: {text: 'Failed to initialize Paystack transaction.'}});
            } // end if
        } catch (error) {
            if(_isDevt){
                console.log('catch err:',error);
            } // end if
            req.app.locals.appfx.log(error);
            return resp.status(500).send({error: {text:`Request Error!${_isDevt?`n${error}`:''}`}});        
        } // end catch
    } // end fx

    // Middleware to verify Paystack transaction
    const _verifyPayment = async (req, resp, next) => {
        const {reference} = req.body||req.query;
        if(!reference) {
            return resp.status(400).send({error: {text: 'Transaction reference is required.'}});
        } // end if
        try {
            const response = await paystack.verifyTransaction({reference});
            // Handle successful verification (e.g., update order status)
            if(response.data.status && response.data.data.status === 'success') {
                req.transaction = response.data.data;
                return next();
            } else {
                return resp.status(400).send({error: {text: 'Transaction verification failed.'}});
            } // end if
        } catch (error) {
            if(_isDevt){
                console.log('catch err:',error);
            } // end if
            req.app.locals.appfx.log(error);
            return resp.status(500).send({error: {text: 'An error occurred while verifying the transaction.'}});
        } // end catch
    } // end fx

    // Define routes
    router.get('/', (req, resp) => {
        return resp.render('paystack', { title: 'Paystack Payment Gateway Handler', user: req.user, _csrf: req.app.locals._csrf, payment_setup_url:'payment_setup/initiate' });
    });
    router.route('/initiate').post(_validateRequest, _initiatePayment);
    router.route('/verify').post(_validateRequest, _verifyPayment, (req, resp) => {
        return resp.send({success: {text: 'Transaction verified successfully.', data: req.transaction}});
    });

    module.exports = router;

After running this, I get this error:
PayStackAPIError: Bearer Authorization header may not have been set | Unauthorized (401).

I was hoping for smooth running, please can anyone help me through this…

There is a syntax error somewhere within this code [closed]

There is a syntax error on the result line

I have watched so many videos but i need a good ttorial or help please

image is here – https://1drv.ms/i/c/36fc60b41c9287f8/EW6nARgyeilNgyVWKVhUDcMBiyytOFryjcX13FzUaMLdtg?e=t3XG7l

code–

<?php 
if(isset($_POST['create'])){
    $firstname = $_POST['firstname']; 
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];
    $phonenumber = $_POST['phonenumber'];
    $password = $_POST['password'];
    
    $sql = "INSERT INTO useraccounts (firstname, lastname, email, phonenumber, password) VALUES (?,?,?,?,?)";
    $stmtinsert = $db->prepare($sql);
    $result = $stmtinsert->execute([$firstname, $lastname, $email, $phonenumber, $password]);
    
    if($result){
        echo 'successfully saved';  
    }else{
        echo ('errors found, contact the admins');  
    }
}
?>

Asset not loading – Laravel | FilamentPHP v4 | SimpleLightBox

When I go to the info list, the lightbox does not load. I click on the photo and it opens in a new tab. I click back and click on the image again, and then the photo opens in the lightbox.

GitHub package:
https://github.com/solutionforest/Filament-SimpleLightBox

Package Version
1.0.0

PHP Version
8.4

Laravel Version
12

FilamentPHP Version 4.1.1

Which operating systems does with happen with?
macOS

INFOLIST:

Section::make('Galeria zdjęć')
                ->schema([
                    ImageEntry::make('gallery')
                        ->label('Galeria zdjęć')
                        ->view('filament.components.lightbox-gallery')
                        ->simpleLightbox(fn($record) => $record->getFirstMediaUrl('gallery')),
                ]),

VIEW:

@php
    $mediaItems = $getRecord()->getMedia('gallery');
@endphp

@if ($mediaItems->count())
    <div class="flex flex-wrap gap-2">
        @foreach ($mediaItems as $media)
            <a
                href="{{ $media->getUrl('fullhd') }}"
                data-fslightbox="gallery"
            >
                <img
                    src="{{ $media->getUrl('thumb') }}"
                    class="h-24 rounded shadow"
                    alt="media"
                />
            </a>
        @endforeach
    </div>
@endif

Indexed DB code does not run inside a click event?

I cannot add a record to the db when inside a click event

var indexed_DB='atest';  
var db;
var request = indexedDB.open(indexed_DB);//see above
var zzz;
request.onupgradeneeded = function(event) { 
  var db = event.target.result;
  var objectStore = db.createObjectStore("barcode", {keyPath: "id"});
};

function one_line_barbones(s){
    request.onsuccess = function(event) {
      db = event.target.result;
      
      var transaction = db.transaction(["barcode"], "readwrite");
      var objectStore = transaction.objectStore("barcode");
      var request = objectStore.add(s);
    };//request.onsuccess = function(event) {
}//function one_line_barbones(something){


 $("button").click(function(){
 alert('t');//this will alert 't' so  works fine, so this click event is triggered
 zzz={id: '123',cn: 234456};//works fine when NOT wrapped in this function
 one_line_barbones(zzz); //Save data to indexed db right here and works fine when NOT wrapped in this function
 });

Well by removing the click event function the record is added perfectly.

Does anyone know how to get this code to work inside the click event?

Thanks,
Jim

How remove duplicate objects by lower index from array

I have function which add errors to array and if error it’s with same values it just removing that, and keep one

   setErrorField(errorArray.filter((value:any, index:any, self:any) =>
        index === self.findIndex((t:any) => (
          t.field === value.field,
          t.errorType === value.errorType
        ))
      ))

But it’s removing object with higher index ,but I need remove objects with lower index, basically I just need to do this function in reverse

I appreciate any idea. Cheers

Text Pagination based on the display element size (React)

I divide a text into the pages based on each page will have max 100 words. However, I want to divide the text based on the display element size (w, h).

What I want to achieve:

  1. Find the available size (w, h) of element displaying the text
  2. Fill the with the words as long as no overflow.
  3. When overflow will happen, create a next page for the rest of the text.
  4. Keep applying 2nd and 3rd steps until no words left.

I assume I need:

  1. A method: finds the current size (w, h) of the element as the size changes.

  2. A method: calculateHeight(currentWidth, currentHeight, text) returns calculatedHeight for the text input.

    2.1. Calculate the height, starting from word1 until wordX by adding words into the page.

    2.2. if the calculatedHeight is larger than the currentHeight, the rest of the text will be on the next page.

  3. Implement the 2nd step until no words left.

My question:

  • Am I doing an overkill to achieve this? Is there a better way?

Vue 3 Payment Success Page API Called Twice in Production After Stripe Redirect

I’m building a Vue 3 SPA with Vuex and Vue Router. On my Payment Success page, I call an API to assign purchased drinks:

created() {
  this.buyDrink()
},

methods: {
  buyDrink() {
    const payload = { cart: this.cartItems, payment_id: sessionStorage.getItem('payment_id') }
    mydrinksService.giftDrinkToFriend(payload)
      .then(res => { ... })
      .catch(err => { ... })
  }
}

The page works fine in development, but in production, this API call fires twice after a successful Stripe payment.
The root component (App.vue) looks like this:

<router-view v-slot="{ Component }" class="wrapper">
  <transition :name="isBack ? 'slide-right' : 'slide-left'">
    <component :is="Component" />
  </transition>
</router-view>

I suspect the double call happens due to component remounts or Stripe redirects, but I’m not sure.

What I’ve tried:

  • Checked that created() only calls the API once in dev.
  • Confirmed that Stripe redirects to the Payment Success route once.

Question:
Why would a Vue 3 SPA component call an API twice in production but not in development?
How can I ensure the API is only called once, even after Stripe redirects or route transitions?