Update a class when the extanded super class setter is used

I have an issue with the data within an extension class does not change when I change data within the super class.

This might be an XY issue or caused by the fact that I’m still not used to using class. I already read into mixin, but I don’t see yet how it would help me.

As an example:

I have a class “container” with the methods: height, depth, width, and volume. The defaults are set within the constructor by a settings file. height, width, and depth can be changed through setters, while the volume is always calculated. A container always exists; it can also exist without a product.

I also have a class with products that have a quantity and density. There is actually more to it, but to simplify it, I am limiting it to this in the example.
Basically, I call the extension class product that can only exist within a container. it calculates the quantity based on the densityand the volume of the super class.

That is the part that works fine.
The issue now is that the container size might change, and therefore also the volume. Which means the quantity of the product should change too, but it doesn’t. The extended class does not recognize an update of the super class data.

How can I make it work?

class Container {
  #height;
  #depth;
  #width;
  
  constructor() {
    this.#height = 10;
    this.#depth = 10;
    this.#width = 10;
  }
  
  set width(length) {
    this.#width = length;
  }
  
  get volume() {
    return this.#width * this.#height * this.#depth;
  }
}

class Product extends Container {
  #density;
  
  constructor(volume) {
    super(volume);
    this.#density = 4;
  }
  
  get quantity() {
    return this.volume * this.#density;
  }
}



const container = new Container();
const product = new Product();

// expectin 4,000 - true
console.log(product.quantity);

// expecting 6,000 - false
container.width = 15;
console.log(product.quantity);

Nextjs with Jest – unexpected token export

I have a Next.js project with typescript.

  1. It’s a page router instead of app router
  2. No babel config file(.babelrc etc) in the project

The error occurs when I run npm test. jost seems to be one of the package used by auth0.

XXXX/node_modules/jose/dist/browser/index.js:1
    export { compactDecrypt } from './jwe/compact/decrypt.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

I tried below 2 solutions, but it gave me the same error.

jest.config.ts

import type { Config } from 'jest';
import nextJest from 'next/jest.js';

const createJestConfig = nextJest({
  dir: './',
});

const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  roots: ['<rootDir>/tests/unit'],
  // Solution 1
  transformIgnorePatterns: [
     "/!node_modules\/jose/"
  ],
  // Solution 2
  moduleNameMapper: {
    "^jose$": "jose"
  }
};

export default createJestConfig(config);

package.json

{
  ...,
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "next": "^15.2.5",
    "react-dom": "^18.2.0",
    "auth0": "^4.4.0",
    ...
  },
  "devDependencies": {
    "@testing-library/dom": "^10.4.1",
    "@testing-library/jest-dom": "^6.8.0",
    "@testing-library/react": "^16.3.0",
    "@types/jest": "^30.0.0",
    "@types/react": "^18.3.20",
    "@types/react-dom": "^18.3.6",
    "jest": "^30.1.3",
    "jest-environment-jsdom": "^30.1.2",
    "node-mocks-http": "^1.17.2",
    "ts-jest": "^29.4.1",
    "ts-node": "^10.9.2",
    "typescript": "^5.8.3"
  }
}

api.test.ts

import handler from '@pages/api/users';
import { createMocks, createRequest, createResponse } from 'node-mocks-http';

  it('returns 405 on non-POST', async () => {
    const { req, res } = createMocks({
        method: 'GET',
      });
  
      await handler(req, res);
      ...
  });

what is middleware in backend dev? [closed]

Can you briefly explain what is middleware and how it works?
and what is the use of next function parameter and how it works.

I know a little bit about middleware that it works in between the client and the server but i don’t know how

I am learning backend dev and I am stuck at the concept of next and middleware.

Getting 404 from Clerk Sign Up or Sign In redirection

I’m using Clerk Sign In and Sign Up components in my Next.js app. When a user signs up for the first time, everything works fine. However, if the user tries to sign up again (for example, using a Google account that already exists), Clerk treats it as a sign in and lets the user proceed, but the redirection breaks and I get a 404 in my Next.js app. The same issue happens with sign in: the user can sign in with a Google account (but not with regular email + password), and Clerk treats it as a new user. In that case, it doesn’t trigger the user.created event in my backend, which is a problem. Basically, I would like to prevent Clerk from allowing (1) a sign up attempt with an already existing user, and (2) a sign in attempt with an unregistered user. I already tried configuring the force redirect environment variables and passing them as props to the components, but it does not work. Everything works fine when the user signs up as a new user and when they sign in as an existing user.

Safari fails to play MP4 video from Strapi backend (works in Chrome, CORS issues)

I’m serving MP4 video files from a Strapi backend, and they play fine in Chrome but fail in Safari.

In Chrome:
The video loads and plays without issues.

In Safari:
I see this error in the console:

Unhandled Promise Rejection: AbortError: The operation was aborted.

What I’ve tried so far:

  1. tried to adjust cors in strapi middlewares.js

{
  name: 'strapi::cors',
  config: {
    origin: ['http://localhost:3000'], or //origin: ['*'],
    methods: ['GET', 'HEAD', 'OPTIONS'],
    headers: ['Content-Type', 'Authorization', 'Range'],
    exposeHeaders: ['Content-Length', 'Content-Range'],
    credentials: false,
    keepHeaderOnError: true,
  },
}

  1. added playsinline and muted attributes to video tag
  2. added ?ngsw-bypass=true as a query string in the mp4 url
  3. replaced native video tag with react-player VideoPlayer

But obviously nothing helped

code below:


'use client';
// imports...

export const VideoComponent: FC<VideoComponentProps> = ({
    video,
    poster,
    isVideoOnGrid,
    maxWidthMobile,
    maxWidthDesktop,
}) => {
    const videoRef = useRef<HTMLVideoElement>(null);
    const [isPlaying, setIsPlaying] = useState(false);
    const data = video.data.attributes;
    const posterData = poster?.data?.attributes;
    const src = data.url ? getAssetUrlPrefix() + data.url : '';

    useEffect(() => {
        const videoElement = videoRef.current;
        if (!videoElement) return;

        const handlePlay = () => setIsPlaying(true);
        const handlePause = () => setIsPlaying(false);

        videoElement.addEventListener('play', handlePlay);
        videoElement.addEventListener('pause', handlePause);

        return () => {
            videoElement.removeEventListener('play', handlePlay);
            videoElement.removeEventListener('pause', handlePause);
        };
    }, []);

    const togglePlay = () => {
        if (videoRef.current) {
            if (isPlaying) {
                videoRef.current.pause();
            } else {
                videoRef.current.play();
            }
            setIsPlaying(!isPlaying);
        }
    };
    return (
        <div>
            <video
                controls
                crossOrigin="anonymous"
                muted
                onCanPlayThrough={() => console.log('Video can play through')}
                onError={(e) => console.error('Video Error:', e)}
                playsInline
                preload="auto"
                ref={videoRef}
                width="100%"
                poster={`${posterData?.url ? getAssetUrlPrefix() + posterData.url : ''}`}
            >
                <source src={src} type={`${data.mime ? data.mime : 'video/mp4'}`} />
                Your browser does not support the video tag.
            </video>
            <Button
                className={`${isPlaying ? styles.isPlaying : ''}`}
                kind="primary"
                renderIcon={isPlaying ? Pause : Play}
                iconDescription={isPlaying ? 'Pausieren' : 'Abspielen'}
                hasIconOnly
                onClick={togglePlay}
            />
        </div>
    );
};

What can I try next?

Django + SimpleJWT: Access tokens sometimes expire immediately (“credentials not provided”) when calling multiple endpoints

I’m building a Vue 3 frontend (deployed on Vercel at example.com) with a Django REST Framework backend (deployed on Railway at api.example.com).

Authentication uses JWT access/refresh tokens stored in HttpOnly cookies (access, refresh).

Access token lifetime = 30 minutes

Refresh token lifetime = 1 day

Cookies are set with: HttpOnly; Secure; SameSite=None; Domain=.example.com

Django timezone settings:

LANGUAGE_CODE = “en-us”

TIME_ZONE = “Africa/Lagos”

USE_I18N = True

USE_TZ = True

The problem

When the frontend calls multiple API endpoints simultaneously (e.g. 5 requests fired together), some succeed but others fail with:

401 Unauthorized

{“detail”:”Authentication credentials were not provided.”}

In the failing requests I can see the cookies are sent:

cookie: access=…; refresh=…

But SimpleJWT still rejects the access token, sometimes immediately after login.

It looks like the exp claim in the access token is already in the past when Django validates it.

What I’ve tried

Verified cookies are set with correct domain and withCredentials: true.

Implemented an Axios response interceptor with refresh token retry.

Ensured CookieJWTAuthentication checks both Authorization header and access cookie.

Flask application: Forgot Password route is not working

I am creating an authentication system and i want to send reset request using MailerSend API, the code has no errors. The entry point for the application is in app.py file. The structure of the data is correct also. The project folder includes login.html and login.js which holds both the login and the forgot password pages. Entry point for the application is on app.py

The code doesn’t even log the console out with print() used to

authentication.py

import secrets
import bcrypt
import sqlite3
import datetime
from flask import Blueprint, jsonify, request,session
from mailersend import MailerSendClient, EmailBuilder
import secrets

auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')

# creatin mail sender client
mailer = MailerSendClient(api_key='mlsn.cc7po0a13bghjgjg061960a92b85e0676e762384ba8097993cc02ac8783052849baba75d')

def get_db_connection():
    # Get database connection to the cyber-shield-linkguard database
    conn = sqlite3.connect('cyber-shield-linkguard.db')

    # return dictionary data structure from the columns of the database
    # e.g instead of column id data[2] use data['password']
    conn.row_factory = sqlite3.Row
    return conn

@auth_bp.route('/forgot-password', methods=['POST'])
def forgot_password():
    try:
        data = request.get_json()
        email = data.get('email', '').strip().lower()

        if not email:
            print('No email provided')
            return jsonify({'error': 'Email is required'}), 400
        try:
            conn = get_db_connection()
            cursor = conn.cursor()

            # Check if user exists
            cursor.execute('SELECT id FROM users WHERE email = ?', (email,))
            user = cursor.fetchone()
            print(f'Entries found: {user}')

            if not user:
                
                conn.close()
                print('Email not found in database')
                return jsonify({'error': 'Email not found'}), 404

            #generate token 
            token = secrets.token_urlsafe(32)
            print(f'Generated token: {token}')
            
            cursor.execute('''INSERT INTO password_reset_tokens (email, token, is_used) VALUES (?, ?, 0)''', (email, token))

            conn.commit()
            conn.close()

            reset_link = f'http://localhost:5000/reset-password?token={token}'
            print(f'Reset link: {reset_link}')


            mail_msg = EmailBuilder().from_email("[email protected]","theArchive").to_many([{"email":email}]).subject("Password Reset Request").html(f"<p>Click <a href='{reset_link}'>here</a> to reset your password.</p>").text(f"Use the following link to reset your password: {reset_link}").build()

            try:
                response = mailer.emails.send(mail_msg)
                print(f'Email sent successsfully: {response.json()}')

                print(f'Password reset link sent to {email}: {reset_link}')
                return jsonify({'message': 'Password reset link sent'}), 200
            except Exception as e:
                print(f'Error sending email: {e}')
                return jsonify({'error': str(e)}), 500
            
            

        except sqlite3.Error as e:
            print(f"Database error: {e}")
            return jsonify({'error': 'Database error occurred'}), 500
    except Exception as e:
        print(f"Forgot password error: {e}")
        return jsonify({'error': 'Failed to process request'}), 500
    

Is possible to skip one scroll context for a position sticky element?

There is a way in css to specify relative to which scroll context a position sticky element should be floating?

<div class="main">
  <div class="row">
    <div class="cell">(0, 0)</div> <!-- I want this to be sticky -->
    <div class="cell">(0, 1)</div>
    <div class="cell">(0, 2)</div>
    ...
    <div class="subtable">
      <div class="somtehing">
        <div class="row">
          <div class="cell">(0, 0)</div> <!-- I also want this one to be sticky to the .main tag -->
          <div class="cell">(0, 1)</div>
          <div class="cell">(0, 2)</div>
          ...

check this codepen example

The first column of the nested table rows, despite of how many tags deep is inside the DOM tree always uses the .main div as it’s scroll context because is its the first one that it found going up in the tree.

// this makes the subtables less annoying enforcing a scroll
// but makes the sticky to be relative to .subtable
.subtable
  height: 100px
  overflow-y: auto

check this other codepen example

If I enforce a height and a scroll-y auto to the .subtable div, then the stickyness of the cells in the subtable are applied to this scroll context since is the first one they found in their way up.

I would like to ignore that first one scroll context and tell to the sticky columns to be aware of the second scroll context in their way up of the tree. Or maybe to specify directly to which tag is supoused to listen.

How to reuse common localization texts for a specific domain in JSON files?

I have multiple JSON files for localization in my Next.js/React project. Some texts and phrases are shared within a specific domain, like product or order.

I don’t want to put these texts into a global commonText.json because:

  • It would become too large and messy.
  • These texts are only relevant to a specific domain.

I also don’t want to duplicate them in each JSON file for the pages of that domain.

My idea is to create a separate JSON file for each domain, e.g., OrderCommonText.json, define the shared texts there, and then reference or import them where needed.

Question:
What is the best way to structure and reuse domain-specific common texts in JSON for localization?
Is there a better approach than creating a separate JSON per domain?

I tried creating separate JSON files for each domain (like OrderCommonText.json) and importing or merging them in the page files.

I expected to be able to reuse the shared texts across multiple pages without duplicating them, and keep the localization files organized per domain.

Currently, the solution works with manual imports and merges, but I am looking for a cleaner, more scalable approach that might work directly with JSON or some preprocessing, ideally also compatible with client-side rendering in Next.js.

Why is my filter returning all data values?

I’m accessing a firestore db via vanilla js. The filter I’ve setup is returning all values in the db instead of the single matching value.
Here is a screenshot of the filtered data item:
Screenshot showing title stored as string vs a number.

Here is my code:

import { initializeApp } from 'firebase/app'
import {
    getFirestore, collection, getDocs,
    addDoc, deleteDoc, doc,
    onSnapshot,
    query, where
} from 'firebase/firestore'

const firebaseConfig = {
    // data removed for posting
}

initializeApp(firebaseConfig)
const db = getFirestore()
const colRef = collection(db, 'books')
// query
const q = query(colRef, where("title", "==", "1984"))

// real time data collection listener
onSnapshot(q, (snapshot) => {
    let books = []
    snapshot.docs.forEach((doc) => {
        books.push({ ...doc.data(), id: doc.id })
    })
    console.log(books)
})

Any feedback is greatly appreciated! Thank you.

A bundle.js exported from Canvas LMS runs on local machine but all the links cannot be found on remote machine

I have a bundle.js file that Canvas generated for a course export. Browsing the index.html:

<body onunload="function noop(){}">
  <div id="app">
  </div>
  <script src="viewer/course-data.js"></script>
  <script src="viewer/bundle.js"></script>
</body>

Works perfectly navigating around all the links on my local machine. But when posted up on a webserver, it gives 404 no page found. The bundle.js is very convoluted and over 2 Million characters long, and I don’t know if there is something in there that could be preventing it from running remotely.

I have tried running it on my machine from Firefox and it works fine on Windows 11:
file:///C:

But when running remotely, it will load the index.html page, but all the links are broken.

Get parent’s data attribute in jQuery

A topic already discussed in several previous questions…but I’m not able to figured out to fix it.
In my page there is a pictures gallery, dynamically appended after an AJAX call. Each picture has a menu, the user can click on eah menu item.
When the user click on item menu I need to get a data attribute of the UL container.
Below the html menu code, appended in DOM by the jQuery script:

<ul class="dropdown-menu dropdown-menu-end picture-menu" data-imgid="${data.pictures[i].imgid}">
    <li>
    ${(() => {
        if (data.pictures[i].status == '1'){
        return `<a href="javascript:void(0);" class="dropdown-item unpublish-item-btn"><i class="ri-camera-off-line align-bottom me-2 text-muted"></i> Unpublish</a>`
        } else {
        return `<a href="javascript:void(0);" class="dropdown-item publish-item-btn"><i class="ri-camera-line align-bottom me-2 text-muted"></i> Publish</a>`
        }
    })()}
    </li>
    <li>
    ${(() => {
        if (data.pictures[i].listed == '1'){
        return `<a href="javascript:void(0);" class="dropdown-item delist-item-btn"><i class="ri-chat-delete-line align-bottom me-2 text-muted"></i> Delist</a>`
        } else {
        return `<a href="javascript:void(0);" class="dropdown-item list-item-btn"><i class="ri-chat-new-line align-bottom me-2 text-muted"></i> List</a>`
        }
    })()}
    </li>
    <li>
        <a href="javascript:void(0);" class="dropdown-item download-item-btn">
            <i class="ri-file-download-line align-bottom me-2 text-muted"></i> Download
        </a>
    </li>
    <li>
        <a href="javascript:void(0);" class="dropdown-item move-item-btn">
            <i class="ri-drag-move-2-line align-bottom me-2 text-muted"></i> Move
        </a>
    </li>   
    <li>
        <a href="javascript:void(0);" class="dropdown-item delete-item-btn">
            <i class="ri-delete-bin-line align-bottom me-2 text-muted"></i> Delete
        </a>
    </li>
</ul>

Below the code in jQuery file to get the UL data-imgid attribute when the user click on the LI anchor item:

$("body").on("click",".dropdown-item",function(e){
    e.preventDefault;
    
    $(this).closest('ul.dropdown-menu').css({"color":"red", "border":"2px solid red"});
    let imgid = $(this).parents('ul.picture-menu').data('imgid');
    console.log(`Pictur imgid is ${imgid}`);
    
});

I’m not able to get the imgid data…I always get undefined.
I did some test…for example using the following code:

$(this).parents('ul.dropdown-menu').css({"color":"red", "border":"2px solid red"});

I correctly see the border red sorroundng the menu…so I’m not able to understand why the attribute is not correctly grabbed.
enter image description here

Any help to fix the issue? Thanks a lot

Assistance regarding Python projects [closed]

Hello I am new to stack Overflow, I am a beginner and started to learn python, i need assistance in Pytho project. Could you please help me out where to start and suggest me some topics which can improve my knowledge.

I had gained knowledge and devloped some basic projects like Calc, Todo list, now need some assitance with Flask and Django

Mouse Event Propagation in SvelteUI

My Svelte app (SvelteUI) displays a series of elements in grid rows. When you click on a row, it expands using the CSS display property. Some rows have controls that are visible whether or not the row is expanded — buttons, sliders, etc. The issue arises when a mousedown occurs on a control and mouseup occurs outside the control (clicking on a button and releasing outside the button). The button properly ignores the event, but the event causes the containing row to expand/collapse (which I don’t want). I know this is a common issue with mouse events, but with SvelteUI there is a wrinkle because of the way it handles click events. This is also exacerbated by the structure of the app. If someone can point me to a dup that actually has an answer that works, I will happily delete this question.

An MRE is tough because of the size of the proprietary project, but here’s the gist.

buttonGroup.svelte
<script lang='ts'>
    import {Button, Group} from '@svelteuidev/core';  // SvelteUI `<Button>` not html `<button>`
</script>

<div>
    <Group>
        <Button on:click={() => {"do stuff"}>
            My Button
        </Button>
    </Group>
</div>
objectRows.svelte
<script lang='ts'>
  import Grid from '@svelteuidev/core';
  import buttonGroup from "./buttonGroup.svelte";
  import anotherGroup from "./anotherGroup.svelte";

  function toggleVisibility() {
    if (myElement.style.display === '') {
      myElement.style.display = 'none';
    } else {
      myElement.style.display = '';
    }
  }
</script>

<div>
    <Grid>
        <div class="list" on:click={() => {toggleVisibility(); open = !open}} on:keydown={() => ""}>
        <Grid.Col>
            Stuff
        </Grid.Col>
        <Grid.Col>
            <div id="controls">
                <div class="button-group">
                    <buttonGroup bind:deviceStore bind:objectStore />
                </div>
                <div class="another-group">
                    <anotherGroup bind:deviceStore bind:objectStore />
                </div>
                ...
            </div>
        </Grid.Col>
    </Grid>
</div>

So when I click on My Button and drag out before release, it toggles visibility of class list.

What I’ve Tried

  • Stop Propagation:
    SvelteUI does not honor stopPropagation when you try to use it on SvelteUI components — on:click|stopPropagation — doesn’t work, so I tried wrapping the Button in a div and tried to capture and stop propagation there. That didn’t work either.

  • Handling Mouse Events:
    I’ve tried adding a series of mouse event handlers to successive divs up the food chain. Didn’t work.

  • Ignoring Mouse Events:
    I’ve tried adding dummy functions to mouse events to have them go nowhere like on:mouseup={() => {}}. Didn’t work.

What I Think is Happening

I think the enclosing grid row is seeing the release event as a unique click event which is causing the visibility prop to toggle.

What I Want to Happen

I want to stop the mouse release event from causing

  • the parent grid row from expanding unless the mouse event originated there. Or,
  • anything to happen unless the mouse release event occurs within the button (control) SvelteUI component.

AnyChart candlestick data dissapearing at certain zooms

I am having an issue using anychart when loading large amounts of data into a stock (candlestick) chart and applying a zoom.

For example, loading ~60 hours of m1 data, the chart is loading showing no data, however if I expand and condense the zoomed area of the chart the data suddenly appears and disappears.

I have uploaded a vid showing the issue: https://imgur.com/a/4cdtrcD

the code that is responsible for drawing the chart:

const chart = anychart.stock();
    chart.background().fill("#131821");
    var table = anychart.data.table();
    var plot = chart.plot(0);

    this.chart = chart;
    this.plot = plot;

    plot.legend().enabled(false);

    table.addData(parsedJsonData.chart_data);
    var mapping = table.mapAs();

    mapping.addField('open', 1);
    mapping.addField('high', 2);
    mapping.addField('low', 3);
    mapping.addField('close', 4);
    mapping.addField('volume', 5);

    plot.candlestick(mapping);

    plot.yGrid().enabled(true);
    plot.yGrid().stroke({
        color: "rgba(255,255,255,0.125)", 
        thickness: 1,
        dash: "3 5"
    });
    plot.xGrid().enabled(true); 
    plot.xGrid().stroke({
        color: "rgba(255,255,255,0.125)",
        thickness: 1, 
        dash: "3 5"
    });
    
    // Minor grid lines
    plot.yMinorGrid().enabled(true);
    plot.yMinorGrid().stroke({
        color: "rgba(255,255,255,0.095)", 
        thickness: 1,
        dash: "1 3"
    });
    plot.xMinorGrid().enabled(true);
    plot.xMinorGrid().stroke({
        color: "rgba(255,255,255,0.095)",
        thickness: 1, 
        dash: "1 3"
    });

    chart.selectRange(parsedJsonData.zoom_start, parsedJsonData.zoom_end);

    chart.contextMenu().itemsFormatter(function(items) {
      delete items["save-data-as"];
      return items;
    });

    chart.title().fontColor("#000000").fontSize(16).fontFamily("Arial, sans-serif");

    document.querySelector(`#chart-container-${this.orderIdValue}`).innerHTML = '';

    chart.container(`chart-container-${this.orderIdValue}`);

    chart.draw();