How to register a boolean type when compiling TypeScript bindings with Emscripten?

I have some Emscripten binding code (a self-contained, trivial example of which is shown below) that converts my C++ status_t return-value class into a boolean that JavaScript code can deal with efficiently. (i.e. a status_t representing an error condition is converted to JavaScript-false, while a status_t representing success is converted to JavaScript-true)

This works great when compiling the code to JavaScript, but when I try to compile the code to TypeScript (using emscripten’s --emit-tsd option, it errors out with the error Error: Missing primitive type to TS type for 'status_t'.

Is there some way to make this work when generating TypeScript bindings, in a way that is similar to how it works for JavaScript bindings, or am I just out of luck here?

// Works great to generate JavaScript bindings:
// emcc  -lembind -sEXPORTED_RUNTIME_METHODS=ccall,cwrap -sWASM_BIGINT -sMODULARIZE=1 -sEXPORT_ES6=1 -sEXPORT_NAME="CPPBindings" -sENVIRONMENT=web -lembind -std=c++17 typescript_status_t_binding_problem.cpp -o output_bindings.js

// Doesn't work to generate TypeScript bindings ("Error: Missing primitive type to TS type for 'status_t'")
// emcc  -lembind -sEXPORTED_RUNTIME_METHODS=ccall,cwrap -sWASM_BIGINT -sMODULARIZE=1 -sEXPORT_ES6=1 -sEXPORT_NAME="CPPBindings" -sENVIRONMENT=web -lembind -std=c++17 typescript_status_t_binding_problem.cpp --emit-tsd output_bindings.d.ts

#include <emscripten/bind.h>
#include <emscripten/wire.h>

using namespace emscripten;

class status_t
{
public:
   status_t() : _errStr(NULL) {/* empty */}
   status_t(const char * errStr) : _errStr(errStr) {/* empty */}

   bool IsOK()    const {return (_errStr == NULL);}
   bool IsError() const {return (_errStr != NULL);}

   const char * GetErrorString() const {return _errStr;}

private:
   const char * _errStr;
};

// Tell embind how to convert status_t <-> JavaScript bool
template <> struct internal::BindingType<status_t>
{
    using WireType = bool;
    static WireType toWireType(status_t s, rvp::default_tag)
    {
       if (s.IsOK()) return true;
                else return false;
    }
    static status_t fromWireType(WireType v) {return v ? status_t() : status_t("Error");}
};
EMSCRIPTEN_BINDINGS(status_t)
{
   internal::_embind_register_bool(internal::TypeID<status_t>::get(), "status_t", true, false);
}

class SomeExampleClass
{
public:
   SomeExampleClass() {/* empty */}

   status_t DoSomething() {return status_t();}
   status_t EpicFail() {return status_t("epic fail!");}
};

EMSCRIPTEN_BINDINGS(SomeExampleClass)
{
   class_<SomeExampleClass>("SomeExampleClass")
      .constructor<>()
      .function("DoSomething", &SomeExampleClass::DoSomething)
      .function("EpicFail",    &SomeExampleClass::EpicFail);
}

Set Glightbox elements based on a sequence (of images)

I have a working lightbox (using Glightbox), but I’m wondering if there is a simpler way to set the elements (images in a sequence) than just listing them individually – as I will eventually have several elements with many images in their galleries.

This is what I have that works:
(The lightbox opens by clicking on a div.)

<div class="glightbox"></div>
const myGallery = GLightbox({
    elements: [],
});

myGallery.setElements([ {
            'href': 'https://website.com/folder/1.jpg',
        },
        {
            'href': 'https://website.com/folder/2.jpg',
        },
        {
           'href': 'https://website.com/folder/3.jpg',
        }]);

var galleryImg = document.querySelector('.glightbox');

galleryImg.addEventListener('click', function() {
  myGallery.open();
});

I saw something similar to the following on youtube tutorial, and I think it’s headed in the right direction, but I just couldn’t get it to work:

elements.forEach((idx) => {
    elements.style.backgroundImage = `url(https://website.com/folder/${idx+1}.jpg)`
})

I’m very (very) new to javascript, so please forgive me if this has a super simple solution that I’ve missed.

Regular expression case insenstive modifier working inconsistently

I am trying to make a portion – but not the entirety – of a regular expression case insenstive.

^(?i:JAN|FEB|JUN)$

will match JAN, FEB, JUN, jun – but not jan or feb

^(?i:FEB|JAN|FDX)$

will match FEB, Jan, jan, JAN, FDX – but not feb or fdx

The actual regular expression has other parts that should remain case sensitive so I can’t just use a global modifier… but I can’t figure out even the small pieces above.

Anything obvious?

Death of stack overflow [closed]

Does building a community based around condescending new users contribute to the death of said online community? How can I repair a community that is dying, as shown here after years of abusing new users?

I suspect there is a better way to do things than relying on LLMs and stack could be saved somehow. I doubt it though, more than likely this post will be banned or I will be told, in a demeaning way to post elsewhere. When this inevitably happens I think I will have made my point.

enter image description here

Why does my CSS Grid container grow in height even with `height: 500px` set?

I’m using CSS Grid with grid-auto-flow: column and grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)).

I’ve explicitly set a fixed height on the container (height: 500px), but when one of the grid items contains long content (like a paragraph), the container appears to grow vertically.

.container {
  height: 500px;
  width: 500px;
  margin: 200px auto;
  background-color: black;
  box-shadow: 0 6px 20px rgb(0 0 0 / 0.2);
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

.box {
  color: white;
  font-size: 1.5rem;
  text-align: center;
}

body {
  background-color: bisque;
}
  <body>
<div class="container">
  <div class="box" style="background-color: #e53935">FIRST</div>
  <div class="box" style="background-color: #d81b60">SECOND</div>
  <div class="box" style="background-color: #8e24aa">Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse ipsa hic nemo veniam voluptate tempore quod et numquam adipisci asperiores cumque optio, incidunt enim odit saepe deleniti accusamus eveniet labore.
  Veniam voluptatibus a laborum nam odit ratione necessitatibus doloribus perferendis hic incidunt? Nulla quam repellendus eveniet necessitatibus, eum, odio vel officiis atque illum perspiciatis id? Totam, perspiciatis voluptatibus? Ducimus, placeat.
  Tenetur, aliquid? Asperiores eligendi alias assumenda, quo dolor porro vero molestias commodi temporibus quis libero deserunt numquam magnam fuga? Quisquam numquam obcaecati officiis expedita nulla reiciendis quia porro maxime sapiente!
  Aliquid voluptatem modi animi omnis culpa similique veniam quas ipsa, sequi porro ea ut maiores quo error repellendus nobis rerum perspiciatis dolorem adipisci totam libero. Modi minus cum ad repudiandae.</div>
  <div class="box" style="background-color: #5e35b1">FOURTH</div>
  <div class="box" style="background-color: #3949ab">FIFTH</div>
  <div class="box" style="background-color: #1e88e5">SIXTH</div>
  <div class="box" style="background-color: #00acc1">SEVENTH</div>
  <div class="box" style="background-color: #00897b">EIGHTH</div>
</div>
  </body>

Questions:

  • Why does the height appear to grow beyond the 500px I set?

Note:

  • I am looking to understand the Grid behavior upon using grid-auto-flow: column with
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr))

Node Express MVC authentication local strategy passport js

I am trying to split up my app using model view controller but having a issue with the passport local strategy. I am able to see my users in the database and add them with the sign up form. When trying to authenticate them using basic username and password I trace the code getting to the authentication file then the app dies there. I am missing a import or access to my database via the way my app is setup. Here is my github

https://github.com/jsdev4web/pre-authentication-lesson

I am a confused why the local strategy is not working and finding few articles and fewer examples on the docs. Anyone familiar with this can point me in the right direction?
enter image description here

enter image description here

(#12) singular statuses API is deprecated for versions v2.4 and higher [closed]

{
“error”: {
“message”: “(#12) singular statuses API is deprecated for versions v2.4 and higher”,
“type”: “OAuthException”,
“code”: 12,
“fbtrace_id”: “A9iuFXSE1yMaL-5EaPc3f-5”
}
}

{
“error”: {
“message”: “(#12) singular statuses API is deprecated for versions v2.4 and higher”,
“type”: “OAuthException”,
“code”: 12,
“fbtrace_id”: “A9iuFXSE1yMaL-5EaPc3f-5”
}
}s

How can I shrink my text to fit it’s container

I’ve got a block of text which is too wide on a mobile device. What I’m wanting to do is to shorten it on load and for each change of device width just in case. I’ve got a method at the moment which works when I’m step-debugging but not if there are no debug hooks.

I think this is an issue with how my code is being run, but I don’t know how I can improve this to be more robust.

Here is my code so far linked to this issue:

...
  9 jQuery(document).ready(function ( event ) { 
 10          
 11         // ## ALIAS ## 
 12     $ = jQuery; 
...
 30     const init = _ => {
 31 
 32         overlay();
 33         lightbox();
 34         pagination_setup();
 35         shrink_to_fit();
 36     }
 37 
 38     _window.resize( _ => {
 39 
 40         shrink_to_fit();
 41     });
...
170     const shrink_to_fit = _ => {
171 
172         let text = $('h1, h2, h3, h4, h5, h6');
173 
174         text.each( function( i, v ) {
175 
176             v = $(v);
177             v.css( 'font-size', '' ); // Returns text to normal for growing device widths
178             let p_width = parseInt( v.parent().width() );
179             let f_size = parseInt( v.css( 'font-size' ) );
180      
181             while ( parseInt( v.prop( 'scrollWidth' ) ) > p_width && f_size > 10 ) {
182                 
183                 v.css('font-size', --f_size + 'px' );
184             }   
185         } );
186     }   
187 
188     init();
189 }); 

The current behaviour when I’ve not got a breakpoint in the foreach is that one run shrinks the text to 9px and the next run removes any change in sizing back to default.

I’ve attempted vanilla JS but using v.style.fontSize returns null because the initial size is in an external file.

Does anyone know what I can do to fix this, or something I can utilise instead to make this whole process bullet proof?
TIA

Unable to signIn a user without email confirmation AWS Amplify

I recently set up authentication on Cognito via Amplify and am trying to set up mail verification. This verification can be done as long as the user has just created an account.
However, I can’t send the code for mail verification via the sendUserAttributeVerificationCode function in the “aws-amplify/auth” package because my user needs to be authenticated to call it. What do I do if my user registers, leaves the page without checking his e-mail and tries to log in again?
If I delete the localStorage from my browser, I have no way of recovering the account? The account has already been created, so I can’t re-create an account with the same e-mail address, and I can’t log in because I haven’t checked my e-mail address.

RTK Query selector not updating

I’m using RTK Query to build a new app that monitors system status. I have a getStatus API endpoint that reports various data about battery charge and temperature.

In my component I access it like this:

const {data} = useGetStatusQuery();

When I console log data I see the log hit every 10 seconds, since I’ve got a call to that endpoint happening on my root component to keep the data current:

useGetStatusQuery(undefined, {
    pollingInterval: 10000,
    skipPollingIfUnfocused: false, // keep polling even if not focused
});

I’d like to access the status data more granularly, looking at one specific sensor or status property, so I followed the docs and built a statusSlice and created some selectors in it. They look like this:

import {apiSlice} from "@/services/apiSlice.ts";

export const statusSlice = createSlice({
    name: 'status',
    reducers: {},
    selectors: {},
})

export const selectStatusResult = apiSlice.endpoints.getStatus.select()

export const selectSensorGroups = createSelector(
    selectStatusResult,
    statusResult => statusResult?.data?.sensorGroups ?? []
)

export const selectSensorGroupById = createSelector(
    selectSensorGroups,
    (state: RootState, sensorGroupId: string) => sensorGroupId,
    (sensorGroups, sensorGroupId) => sensorGroups.find(sensorGroup => sensorGroup.sensorGroupID === sensorGroupId)
) 

In my component I changed the data fetch to look like:

const {data} = useGetStatusQuery();
const groups = useAppSelector(selectSensorGroups);
const group = useAppSelector((state) => selectSensorGroupById(state, SENSOR_ID_BATTERY));

Console logging the the groups and group data shows that they do get populated as expected, however these values don’t update when the state updates on the 10 second interval like the data value does.

I don’t understand why not?

Will passing an HTML reference to a React Custom Hook cause performance issues if the hook runs a lot? [duplicate]

I understand I can pass a reference to an HTML element to my React custom hook in react such as following:

let myCustomHook(elem:React.RefObject<any>) {
// logic
}

However, passing by reference actually passing by reference or does it copy the object? Keep in mind I am passing the ref not ref.current.

The reason I am asking this question is that I am having performance issues, and I do not know if passing by an HTML Element to a hook is a bad idea due to the hook running a lot.

Would appreciate any comments or answers on the issue.

ApplePayConfig – debit card payments not working ? (flutter/Stripe)

debit cards unavailable for this purchase

I’m trying to pay with a debit card. it currently works with credit card.

Here is my config json:

final String defaultGooglePay = '''{
  "provider": "google_pay",
  "data": {
    "environment": "PRODUCTION",
    "apiVersion": 2,
    "apiVersionMinor": 0,
    "allowedPaymentMethods": [
      {
        "type": "CARD",
        "tokenizationSpecification": {
          "type": "PAYMENT_GATEWAY",
          "parameters": {
            "gateway": "stripe",
            "stripe:version": "2018-10-31",
            "stripe:publishableKey": "${dotenv.env['STRIPE_PUBLISHABLE']!}"
          }
        },
        "parameters": {
          "allowedCardNetworks": ["VISA", "MASTERCARD"],
          "allowedAuthMethods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
          "billingAddressRequired": true,
          "billingAddressParameters": {
            "format": "FULL",
            "phoneNumberRequired": true
          }
        }
      }
    ],
    "merchantInfo": {
      "merchantName": "CLUBLINK UK"
    },
    "transactionInfo": {
      "countryCode": "GB",
      "currencyCode": "GBP"
    }
  }
}''';

final defaultGooglePayConfig =
    PaymentConfiguration.fromJsonString(defaultGooglePay);

final String defaultApplePay = '''{
  "provider": "apple_pay",
  "data": {
    "merchantIdentifier": "*****",
    "displayName": "CLUBLINK",
    "merchantCapabilities": ["3DS", "debit", "credit"],
    "supportedNetworks": ["visa", "mastercard"],
    "countryCode": "GB",
    "currencyCode": "GBP",
    "requiredBillingContactFields": null,
    "requiredShippingContactFields": null,
    "shippingMethods": null,
    "tokenizationSpecification": {
      "type": "PAYMENT_GATEWAY",
      "parameters": {
        "gateway": "stripe",
        "stripe:version": "2025-04-30",
        "stripe:publishableKey": "${dotenv.env['STRIPE_PUBLISHABLE']!}"
      }
    }
  }
}''';      

final defaultApplePayConfig =
    PaymentConfiguration.fromJsonString(defaultApplePay);

Here is my Deno function

import Stripe from "npm:stripe@^15.8.0";
import { createOrRetrieveCustomer } from "../utils/supabase.ts"; 

const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);

Deno.serve(async (req) => {
    const body = req.body;

    if (!body) {
        return new Response("No body", { status: 400 });
    }

    const reader = body.getReader();
    const chunks: Uint8Array[] = [];
    let done = false;

    while (!done) {
        const { value, done: doneReading } = await reader.read();
        if (value) {
            chunks.push(value);
        }
        done = doneReading;
    }

    const fullBody = new Uint8Array(
        chunks.reduce((acc, chunk) => acc + chunk.length, 0),
    );
    let offset = 0;
    for (const chunk of chunks) {
        fullBody.set(chunk, offset);
        offset += chunk.length;
    }

    const text = new TextDecoder().decode(fullBody);
    const data = JSON.parse(text);
    const connectedAccountId = data.connectedAccountId;
    const amount = data.amount;
    const authHeader = req.headers.get("Authorization")!;
    const customer = await createOrRetrieveCustomer(authHeader);

    try {
        const paymentIntent: Stripe.PaymentIntent = await stripe.paymentIntents.create({
            amount: Number(amount),
            currency: "gbp",
            customer: customer.id,
            payment_method_types: ['card'], 
            payment_method_options: {
                card: {
                    request_three_d_secure: 'automatic', 
                },
            },
            application_fee_amount: Math.round(amount * 0.025),
            transfer_data: {
                destination: connectedAccountId,
            },
        });

        const res = {
            clientSecret: paymentIntent.client_secret,
        };

        return new Response(JSON.stringify(res), {
            headers: { "Content-Type": "application/json" },
            status: 200,
        });

    } catch (error) {
        console.error("Stripe Error:", error); 
        return new Response(JSON.stringify({ error: error.message }), { 
            headers: { "Content-Type": "application/json" },
            status: 400, 
        });
    }
});

I was expecting when trying to purchase a ticket I would have the options of all my cards in my apple wallet. Only my credit card would show, but when using credit card the payment would process correctly.

Fullscreen scrollable layout with video and content below

I ma trying to replicate youtube layout where when you enter fullscreen on any video, you get video fullscreen, but then if you use mousewheel, you can still scroll down to content (open any youtube video and try).

I made a rough demo (but the problem is fullscreen doesnt work here on stackoverflow?).

  1. I am not sure what element should I make fullscreen, my wrapper div or documentElement?

  2. what element to attach scroll to (once you are in fullscreen)

document.querySelector('.fs-button').addEventListener('click', function() {

  var elem = document.querySelector('.wrapper')
  //var elem = document.documentElement;

  if (elem.requestFullscreen) {
    if (document.fullscreenElement) {
      document.exitFullscreen();
    } else {
      elem.requestFullscreen();
    }
  }

})

window.addEventListener('scroll', function(e) {
  console.log(e)
  
  //scroll container with wheel

}, true)
.video {
  width: 100%;
}

.content {
  margin-top: 50px;
}
<div class="wrapper">

  <div class="video-wrap">

    <video class="video" src="http://download.blender.org/peach/trailer/trailer_480p.mov" controls></video>

    <button class="fs-button">toggle fullscreen</button>

  </div>

  <div class="content">


    Why do we use it?
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).


    Where does it come from?
    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

    The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

    Where can I get some?
    There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

  </div>

</div>