google.accounts.id.initialize callback not firing

I’m trying to setup the ability for the Authenticated User to manage the OAuth accounts they have linked. Here’s the code I’m using in my Angular Component:

linkGoogle(): void {
    debugger; // this pauses 1st
    const googleAuthButton = document.createElement('div');
    googleAuthButton.setAttribute('id', 'google-button');

    // Inject Google button dynamically
    document.body.appendChild(googleAuthButton);

    const client = google.accounts.id;
    client.initialize({
      client_id: environment.googleClientId,
      callback: (response: any) => {
        const idToken = response.credential;
        console.log('Google Sign-In callback triggered:', response);
        debugger; // this never pauses
        // Use the new CustomerService method
        this.customerService.linkGoogleAccount(idToken).subscribe({
          next: () => {
            this.snackBar.open('Google account linked successfully!', 'Close', {
              duration: 3000,
            });
            document.body.removeChild(googleAuthButton); // Cleanup
            this.authService.initializeAuth().subscribe(); // Refresh current user
          },
          error: (err) => {
            console.error('Error linking Google account:', err);
            this.snackBar.open('Failed to link Google account.', 'Close', {
              duration: 3000,
            });
          },
        });
      },
      auto_select: false,
      cancel_on_tap_outside: true,
    });
    console.log('Client initialized:', client);
    client.prompt();
  }

When I invoke this function I can see the debugger; statements pause but not the one that I have set inside the defined callback function.

I expect the callback method to be invoked so I can see the token and manage the linked account.

Why does my line of code to detect pausing video with Javascript for chrome extension not work?

console.log(alert('WORKING'))
var videoElement = document.getElementsByClassName('video-stream')[0];;videoElement.addEventListener('pause', function(){ alert('paused!'); })

I know python but am trying to learn java script. Im practicing by working on a Chrome extension but I’m already stuck.

The first line works I get popup when I open youtube in my chrome browser. But the next line does not. When I pause the video I do not get a popup. But if I copy the same line it into the console in chrome it does work. I will get a popup when I pause. Thanks!

Drag and drop in IOS webview

I have a IOS webview where I inject the following javascript. For some reason, drag and drop still doesn’t work.

Here’s my javascript

let dragScript = """
    const dragItems = document.querySelectorAll('.drag-item');
              const dropZones = document.querySelectorAll('.drop-zone');

              let draggedItem = null;

              dragItems.forEach(item => {
                  item.addEventListener('dragstart', () => {
                      draggedItem = item;
                  });

                  item.addEventListener('dragend', () => {
                      draggedItem = null;
                  });
              });

              dropZones.forEach(zone => {
                  zone.addEventListener('dragover', e => {
                      e.preventDefault();
                  });

                  zone.addEventListener('drop', () => {
                      if (zone.children.length === 0) {
                          zone.appendChild(draggedItem);
                      }
                  });
              });

              function checkAnswers() {
                  dropZones.forEach(zone => {
                      const answer = zone.querySelector('.drag-item');
                      if (answer && answer.dataset.answer === zone.dataset.correct) {
                          zone.classList.add('correct');
                          zone.classList.remove('wrong');
                      } else {
                          zone.classList.add('wrong');
                          zone.classList.remove('correct');
                      }
                  });
              }
"""
webView.evaluateJavaScript(dragScript) { _, error in
    if let error = error {
        print("Error injecting drag script: (error.localizedDescription)")
    }
}

Here’s the html

   <div class="quiz-container">
        <div class="drag-items">
            <div class="drag-item" draggable="true" data-answer="1776">1776</div>
            <div class="drag-item" draggable="true" data-answer="George Washington">George Washington</div>
            <div class="drag-item" draggable="true" data-answer="Boston Tea Party">Boston Tea Party</div>
            <div class="drag-item" draggable="true" data-answer="Treaty of Paris">Treaty of Paris</div>
        </div>

        <div class="drop-zones">
            <div class="drop-zone" data-correct="1776">Year the Declaration of Independence was signed:</div>
            <div class="drop-zone" data-correct="George Washington">Leader of the Continental Army:</div>
            <div class="drop-zone" data-correct="Boston Tea Party">Event where colonists protested by dumping tea:</div>
            <div class="drop-zone" data-correct="Treaty of Paris">Agreement that ended the American Revolution:</div>
        </div>
    </div>

Can someone help? Thanks!

Too many video tags causes problems with page speeds

I have a webpage that loads a bunch of videos (21) and loads more videos with Ajax as the user scrolls down the webpage. This is no problem as I use preload=“none” on my video tag. The problem arises when I play multiple videos and load their metadata. Is there a way to unload the metadata of a video after it’s been played? I tried setting preload=“none” and than video.load() but it bugs up the rest of the JavaScript on the page.

red line under import react-dom/client while having dev-dependency @types/react-dom installed

This is the first time doing een project react + typescript. When I run the script it does work and shows up in my browser. The only thing I don’t understand is when I “import {createRoot} from “react-dom/client””, there is a red line under react-dom/client which I want to remove. I suppose it had to do with that I had to install @types/react-dom so I did and it shows in my devDependencies. I also put the ts-loader behind my babel-loader in de webpack.config.js but it still didn’t work. I also tried to remove the package.json and do npm install again but still get the same result with the red line under it. Does someone know what I am missing or doing wrong? Many thanks in advance!

enter image description here

enter image description here

enter image description here

Sequelize Associations Error: “Product is not associated to CartItem” while eager loading relationships


I’m working on a Node.js project using Sequelize, and I’m encountering an error when trying to fetch associated data with eager loading. Here’s the error:

Error fetching cart items: EagerLoadingError [SequelizeEagerLoadingError]: Product is not associated to CartItem!

Here’s the relevant part of my setup:

CartItem Model

const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const { CART_ITEM_STATUS } = require("../constants");

const CartItem = sequelize.define(
  "CartItem",
  {
    productId: {
      type: DataTypes.INTEGER,
      references: {
        model: "Products",
        key: "id",
      },
      allowNull: false,
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    purchasePrice: {
      type: DataTypes.FLOAT,
      defaultValue: 0,
    },
    status: {
      type: DataTypes.ENUM(
        CART_ITEM_STATUS.Not_processed,
        CART_ITEM_STATUS.Processing,
        CART_ITEM_STATUS.Shipped,
        CART_ITEM_STATUS.Delivered,
        CART_ITEM_STATUS.Cancelled
      ),
      defaultValue: CART_ITEM_STATUS.Not_processed,
    },
  },
  {
    tableName: "cart_items",
    timestamps: false,
  }
);

module.exports = CartItem;

Product Model

const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const CartItem = require("./cartitem");

const Product = sequelize.define(
  "Product",
  {
    id: {
      type: DataTypes.STRING(64),
      primaryKey: true,
      defaultValue: () => {
        return crypto.createHash("sha256").update(uuidv4()).digest("hex");
      },
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
  },
  {
    tableName: "products",
    timestamps: false,
  }
);

Product.hasMany(CartItem, {
  foreignKey: "productId",
  as: "items",
});

CartItem.belongsTo(Product, {
  foreignKey: "productId",
  as: "product",
});

module.exports = Product;

Setup DB

CartItem.belongsTo(Product, { foreignKey: "productId", as: "product" });
Product.hasMany(CartItem, { foreignKey: "productId", as: "cartItems" });

await sequelize.sync({ alter: true });

Query

const cartItems = await CartItem.findAll({
  include: [{ model: Product, as: "product" }],
});

Despite defining associations properly, the error persists. What might be causing this issue, and how can I fix it?


CSS 3D Dice: Visually make dice land on different number [closed]

I am taking two different dice codepens, a d20 dice roll here: https://codepen.io/vicentemundim/pen/nXNvBw, and swirling polyhedron dice here: https://codepen.io/vcurd/pen/RwaQPrb. My goal is to have all the polyhedron dice shapes from that second codepen but roll them on a click, I’m starting with a d8. I’ve got the d8 shape with numbers on it, and it rolls – but I can’t seem to get the dice to land on a different number. Behind the scenes the data-side attribute changes to a different roll, but visually the dice lands on the side with 2 facing up and 7 facing down.

This is my codepen: https://codepen.io/bookluvr416/pen/qEWymxX. Mostly the html and css are from the swirling polyhedron dice, the js is from the dice roll. Some additions to the css from the dice roll codepen. I’ve never played with animations before, this is for a pet project I want to do.

Can anyone help me? I’m not sure what I’ve done wrong or how to fix it. I’ve studied the dice roll animation code, and I’ve tried building the html/css like that one is with using classes and step counters to set the numbers of the sides – and I still ended up having the same problem that visually the dice lands in the same spot.

Failing to implement StPageFlip

I am trying to use this js for a webpage. I have downloaded the javascript through npm (“page-flip.browser.js”), I then copied the code (html/scss/js from the demo page.

I am not sure what I am doing wrong but nothing is showing up aside from the buttons (from the html demo), I have a very fundamental understanding with html/css but this is my first time using npm/node modules so I might have missed something incredibly obvious.

<script src="{path/to/scripts}/page-flip.browser.js"></script> was added at the top of asset/cafe-flip.js so the broswer flip.js should have been imported to the page-flip.js, which then both are mentioned in the html.

HTML:

<body>
 <div>
   codes here are a direct copy of the demo
 </div>
     <script src="asset/page-flip.browser.js"></script>
     <script src="asset/cafe-flip.js"></script> //this is the js from the demo

</body>

Getting bold math expresion when converting MathJax to png and adding to jsPDF

I am using MathJax to render math expresion in the text and want to convert it to pdf. But when I open pdf the expresion is like bold or it looks like two expresions are overlaped. (below is my code)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MathJax to PDF</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
    <div id="math-container" style="font-size: 20px;">
        This is some text with MathJax: (E = mc^2)
    </div>
    <button onclick="generatePDF()">Generate PDF</button>

    <script>
        async function generatePDF() {
            const mathContainer = document.getElementById("math-container");
            
            // Step 1: Render MathJax in the container
            await MathJax.typesetPromise([mathContainer]);

            // Step 2: Remove the raw LaTeX source (e.g., (E = mc^2)) after rendering
            // MathJax inserts the rendered output in an element with class 'mjx-chtml'
            const renderedMath = mathContainer.querySelector('.mjx-chtml');
            if (renderedMath) {
                // Clear the container and only append the rendered output
                mathContainer.innerHTML = ''; 
                mathContainer.appendChild(renderedMath); // Keep only the rendered content
            }

            // Step 3: Convert the container to an image using html2canvas
            const canvas = await html2canvas(mathContainer, {
                backgroundColor: "#ffffff", // Set background color to white for clarity
                scale: 2, // Higher scale for better resolution
            });
            const imgData = canvas.toDataURL("image/png");

            // Step 4: Add the image to the PDF using jsPDF
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF();
            pdf.text("MathJax in PDF Example", 10, 10);
            pdf.addImage(imgData, "PNG", 10, 20, 180, canvas.height / canvas.width * 180); // Scale to fit
            pdf.save("mathjax_fixed.pdf");
        }
    </script>
</body>
</html>

How can I fix this problem?

How to Scrape and Convert F1 Website Data into JSON Using Node.js and ScraperAPI?

const express = require("express");
const request = require("request-promise");

const app = express();
const PORT = process.env.PORT || 5000;

const generateApiKey= (apiKey) => `http://api.scraperapi.com?api_key=${apiKey}&autoparse=true`

app.use(express.json());

app.get("/f1", async (req, res) => {
  const {apiKey}=req.query;
  try {
   
    const response = await request(`${generateApiKey}&url=https://www.formula1.com/en/teams/ferrari`);
    
    res.json(JSON.parse(response));
  } catch (error) {
    console.error("Error fetching data:", error);
    res.status(500).send(`${error}`);
  }
});

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

I am trying to create an API that scrapes data from the Formula 1 website (e.g., team pages) and returns it in JSON format using Node.js and ScraperAPI. My current approach is to use request-promise with ScraperAPI to fetch the page, but I’m encountering issues where the data is not being parsed correctly into JSON for some reason
This what I get instead of JSON format with the data
Picture with what I get in return

IntersectionObserver rootMargin is not working on mobile device

I’m using the IntersectionObserver API to load additional content when the page scrolls close to 1000px from the bottom. It works fine and loads content on desktop, but on mobile screens, the content only loads when it reaches to the end of the footer.Basically rootMargin is being ignored on mobile device.

Here’s my current code:


let is_loading = false;
let has_more_content = true;

const loader_element = document.querySelector("container.home column#container_contents > p#loading");
    
const observer = new IntersectionObserver(async (entries) => { if(entries[0].isIntersecting && !is_loading && has_more_content) await load_more_content(); },
        { root: null, rootMargin: "0px 0px 1000px 0px", threshold: 0.1 }
    );
observer.observe(loader_element);

On mobile, I want the content to load earlier, before it reaches the footer. How can I adjust my implementation to achieve this? Any suggestions or solutions would be greatly appreciated!

How to implement Github Oauth with state?

I have two Python routes which allow my frontend on React to authorize with Github Oauth. It happens like that:

  • Frontend user goes to BACKEND_URL/api/v1/oauth/github from page FRONTEND_URL/login
  • Backend returns redirect to https://github.com/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=FRONTEND_URL/login?app=github&scope=user:email
  • Frontend redirects to Github and gets code in FRONTEND_URL/login?app=github&code=CODE
  • Then useEffect fetches BACKEND_URL/api/v1/oauth/github/access?code=CODE and gets access token

I am new to Oauth, do I have correct implementation? I’m asking because now I am trying to add state to Oauth requests. But how can I do that?

Frontend code:

useEffect(() => {
    const code = searchParams.get("code");
    const app = searchParams.get("app");
    if (!code || !app) {
      return;
    }
    axios.get(`${BACKEND_URL}/api/v1/oauth/${app}/access?code=${code}`);
}, []);

<Link to={`${BACKEND_URL}/api/v1/oauth/github`}>Login with GitHub</Link>

Backend code:

@app.get('/api/v1/oauth/github')
def github():
    return RedirectResponse("https://github.com/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=FRONTEND_URL/login?app=github&scope=user:email", status_code=307)


@app.get('/api/v1/oauth/github/access')
def github_access(code: str):
    r = requests.post(f"https://github.com/login/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&code={code}")
    ...
    return "token"

Tried to find out answer in chat gpt. But it suggested using variant below. But it looks strange. Is it a good practice?

state_storage = {}

@app.get('/api/v1/oauth/github')
def github():
    state = str(uuid.uuid4())
    state_storage[state] = True
    return RedirectResponse("https://github.com/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=FRONTEND_URL/login?app=github&scope=user:email", status_code=307)

@app.get('/api/v1/oauth/github/access')
def github_access(code: str):
    if state not in state_storage:
        raise HTTPException(status_code=400)
    
    del state_storage[state]
    
    r = requests.post(f"https://github.com/login/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&code={code}")
    ...
    return "token"

Socket.io code snippet explained (JavaScript setTimeout and function.apply)

I have two questions regarding the following socket.io code snippet:

const withTimeout = (onSuccess, onTimeout, timeout) => {
  let called = false;

  const timer = setTimeout(() => {
    if (called) return;
    called = true;
    onTimeout();
  }, timeout);

  return (...args) => {
    if (called) return;
    called = true;
    clearTimeout(timer);
    onSuccess.apply(this, args);
  };
}

socket.emit("hello", 1, 2, withTimeout(() => {
  console.log("success!");
}, () => {
  console.log("timeout!");
}, 1000));

Question 1: withTimeout returns a callback that we (the server) emit to the client. If the client does not call the emitted callback before the timer runs out, we should get “timeout” printed on our (server) console, right? Eventually, the client will call our callback but “success” is never printed since the client lost the race. My question here is, why don’t we need to call clearTimeout(timer) but instantly return (due to if (called) return;)? We only call clearTimeout if the client wins the race but not when the client loses the race. Won’t be “timeout” be printed every timeout milliseconds? Or does this only happen as long as the client does not call the callback, but when the callback is called by our client the scope gets destroyed anyways (socket.emit function finished executing) and therefore our timer gets destroyed as well?

Question 2: What is onSuccess.apply(this, args); making for a difference? Why not just calling onSuccess(args) directly here? Is it because of where the console.log should happen (with onSuccess.apply(this, args); making it log to the server’s console and onSuccess(args) making it log to the client’s console)?

I have to admit that are kind of basic JS concept questions but I never really had experienced them in practice (i only remember them from a book i read a while ago) to fully understand them until (hopefully) now

Pure HTML Stepper Changing the color of the line

I have a pure html stepper. It works if the ‘active’ class is in the 2nd, 3rd and so on element. But I have a problem if the ‘active’ class is only in the 1st class. How do I make it if the ‘active’ class is in the first class, then no line is colored? If only the first stepper has active, then no line should be changing color, only the color before the stepper with the active class should be colored. Appreciated all the help I can get.

Below is the screenshot:
enter image description here

HTML:

<div class="wrapper">
              <ol class="stepper">
                <li class="stepper-item active" data-step="1">
                  <h3 class="stepper-title">Step 1</h3>
                  <p class="stepper-desc">Authentication started</p>
                </li>
                <li class="stepper-item active" data-step="2">
                  <h3 class="stepper-title">Step 2</h3>
                  <p class="stepper-desc">Authentication successful</p>
                </li>
                <li class="stepper-item active" data-step="3">
                  <h3 class="stepper-title">Step 3</h3>
                  <p class="stepper-desc">Authorization complete</p>
                </li>
                <li class="stepper-item" data-step="4">
                  <h3 class="stepper-title">Step 4</h3>
                  <p class="stepper-desc">Finalizing process</p>
                </li>
                <li class="stepper-item" data-step="5">
                  <h3 class="stepper-title">Step 5</h3>
                  <p class="stepper-desc">Process complete</p>
                </li>
              </ol>
            </div>

CSS:

:root {
  --circle-size: clamp(1.5rem, 5vw, 3rem);
  --spacing: clamp(0.25rem, 2vw, 0.5rem);
}

.stepper {
  display: flex;
}

.stepper-item {
  display: flex;
  flex-direction: column;
  flex: 1;
  text-align: center;

  &::before {
    --size: 3rem;
    content: "";
    display: block;
    width: var(--circle-size);
    height: var(--circle-size);
    border-radius: 50%;
    border: 0.4rem solid green;
    background-color: transparent;
    opacity: 0.5;
    margin: 0 auto 1rem;
  }

  &:not(:last-child) {
    &::after {
      content: "";
      position: relative;
      top: calc(var(--circle-size) / 2);
      width: calc(100% - var(--circle-size) - calc(var(--spacing) * 2));
      left: calc(50% + calc(var(--circle-size) / 2 + var(--spacing)));
      height: 2px;
      background-color: #448b62;
      order: -1;
    }
  }
}

.stepper-title {
  font-weight: bold;
  font-size: clamp(1rem, 4vw, 1.25rem);
  margin-bottom: 0.5rem;
  color: #448b62;
}

.stepper-desc {
  color: grey;
  font-size: clamp(0.85rem, 2vw, 1rem);
  padding-left: var(--spacing);
  padding-right: var(--spacing);
}

/*** Non-demo CSS ***/

.wrapper {
  max-width: 100%;
  margin: 2rem auto 0;
}

*,
*:before,
*:after {
  box-sizing: border-box;
}

.stepper-item::before {
  --size: 3rem;
  content: attr(data-step); /* Use a custom attribute for step number */
  display: flex;
  align-items: center;
  justify-content: center;
  width: var(--circle-size);
  height: var(--circle-size);
  border-radius: 50%;
  border: 4% solid rgb(0, 64, 255);
  opacity: 0.5;
  margin: 0 auto 1rem;
  font-weight: bold;
  font-size: 1.25rem;
  color: #448b62;
    /* Font customization */
  font-family: 'Poppins', sans-serif; /* Change to any desired font */
  font-weight: 700; /* Bold */
  font-size: 1.5rem; /* Adjust size */
  letter-spacing: 0.05rem; /* Optional spacing */
}

.stepper-item.active::before {
  opacity: 1;
  border: 0.4rem solid red;
  color: red;
}

.stepper-item.active .stepper-title {
  color: red;
}

.stepper-item.active:is(:first-child):after {
  background-color: red;
  opacity: 1;
}

/* Style the line between consecutive active items */
.stepper-item.active + .active:before {
  opacity: 1;
}

.stepper-item:not(:last-child)::after {
  content: "";
  position: relative;
  top: calc(var(--circle-size) / 2);
  width: calc(100% - var(--circle-size) - calc(var(--spacing) * 2));
  left: calc(50% + calc(var(--circle-size) / 2 + var(--spacing)));
  height: 2px;
  background-color: #448b62;
  opacity: 0.5;
  order: -1;
}

/* Color line red only when current item is active AND next item is active */
.stepper-item:not(:first-child).active:not(:last-child):has(+ .active)::after {
  background-color: red;
  opacity: 1;
}

/* Special case for first item - only color if next is active */
.stepper-item:first-child.active:has(+ .active)::after {
  background-color: rgb(255, 0, 0);
  opacity: 1;
}

Why isn’t this String.match() matching? [closed]

I have a match() function in Apps Script set up like this:

else if (desc.match(/.*ENTERPRISE.*/i))

With this earlier in the code:

let desc = row[3];

And I have a line in a spreadsheet like this:

enter image description here

Cell D of the line contains the text

Direct debit ENTERPRISE FUND

It’s not matching anything earlier in the if chain, as I’d be able to see it performing the wrong action. I’ve reread the script and cell to ensure I’m not getting mixed up about the spelling.. I’ve tried swapping /.*ENTERPRISE.*/i for ".*ENTERPRISE.*" in case it’s something about the regex. Why is it not picking it up?