How to listen to connection errors in Action Cable?

// Create WebSocket connection
const socket = new WebSocket("ws://localhost:8080");

// Listen for possible errors
socket.addEventListener("error", (event) => {
  console.log("WebSocket error: ", event);
});

In this way I connect to Action Cable server:

import { createConsumer } from '@rails/actioncable'

export default createConsumer()

How to listen to connection errors in a similar way?

Is there a way to interop between C# and JS? [closed]

I am planning on making extensions for Turbowarp that will allow you to write actual code in various languages and use them for your projects.

The GitHub repo for what I’m working on is here.

I want to make C# one of the languages you can do this with but I can’t find any GitHub projects that could allow for this.

I already found one I could use for Lua, Python, Ruby, and Rust, but figuring that C# and C++ are used mainly for games, I find it pretty important to include them.

Django Select2 Autocomplete: How to Pass Extra Parameter (argId) to the View?

I’m using Django with django-autocomplete-light and Select2 to create an autocomplete field. The Select2 field is dynamically added to the page when another field is selected. It fetches data from a Django autocomplete view, and everything works fine.

Now, I need to filter the queryset in my autocomplete view based on an extra parameter (argId). However, I’m not sure how to pass this parameter correctly.

JavaScript (Select2 Initialization)

function getElement(argId) {
  let elementSelect = $("<select></select>");
  let elementDiv = $(`<div id='element_id' style='text-align: center'></div>`);
  elementDiv.append(elementSelect);

  $(elementSelect).select2({
      ajax: {
          url: "/myautocomplete/class",
          data: function (params) {
              return {
                  q: params.term,  // Search term
                  arg_id: argId    // Pass extra parameter
              };
          },
          processResults: function (data) {
              return {
                  results: data.results  // Ensure correct format
              };
          }
      },
      placeholder: "Element...",
      minimumInputLength: 3
  });

  return elementDiv; 

}

Django Autocomplete View

class ElementAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView):

      def get_queryset(self):
          qs = MyModel.objects.filter(...)

I want to pass argId from JavaScript to the Django view so that the queryset is filtered accordingly. However, I am not sure if my approach is correct or how to achieve this.

Appreciate any suggestions or improvements. Thanks!

How to share Redux state between microfrontends in different modules?

We have 3 separate development teams, each responsible for a different module of a large monolithic React application. We’re now migrating to a microfrontend architecture, where each module is exposed as a separate standalone application, consumed by a host application that we don’t control.

Important context:

The host app is completely separate — it’s not part of our codebase.

Previously, all modules shared a single Redux store with reducers like: ui, settings, translations, user.

After splitting the app into microfrontends, each module now independently fetches settings, user, etc., causing duplicated network requests and inconsistent state.

Question:
What’s the best way to share state (or data) between microfrontends, given that:

Only one of them may initially load the data

Others should be able to access the data if it’s already loaded

We considered exporting the store outside and having all microfrontends subscribe to it, but then the shared store might initialize too early, even when no frontend is mounted, and make requests preemptively.

Any best practices or patterns for this setup?
We’re open to solutions like shared singleton stores, global event buses, custom loaders, etc.
Appreciate any input or real-world experience!

How to track breakpoints which are added during debugging proces

I am developing a visual studio code plugin and I am trying to keep track of the breakpoints which have been set/triggered. Right now I am able to track all the breakpoints which have been set before the debugger runs. However when the user adds a breakpoint during the debug proces I cannot track it.

I log the breakpoint by iterating through the breakpoints and setting them based on index in an array. When onDidSendMessage gets triggered I retrieve the message.body.hitBreakpointIds and that way I can retrieve the correct index from my array in which I have set them. However this same approach does not work when I try to add breakpoints during the debugprocess. Is there a way to achieve this?

My code:

import * as vscode from 'vscode';
import { Session } from "./../models/Session";
import { Breakpoint } from "./../models/Breakpoint";
import { Event } from "./../models/Event";
import { Log } from "./../models/Log";
import { BREAKPOINT, LOG, SESSION } from './../enum/event_enum';
import { getSnapshotWith, insertBp, insertEvent, insertSnapshot } from './../dbHelper/insert';
import { isEmptyObject } from './../helpers/isEmpty';
import { snapshot } from './snapshot';
import { Snapshot } from './../models/Snapshot';

interface IDebugSessionMonitor {
    startMonitoring(): void;
}

export class DebugSessionMonitor implements IDebugSessionMonitor {
    private map: Record<any, any> = {};
    private isRunning = false;
    private deletedSession: string | null = null;

    constructor() {
        this.startMonitoring();
    }

    public startMonitoring(): void {
        vscode.debug.onDidStartDebugSession(this.handleStartDebugSession.bind(this));
        vscode.debug.registerDebugAdapterTrackerFactory('*', {
            createDebugAdapterTracker: this.createDebugAdapterTracker.bind(this)
        });
        vscode.debug.onDidChangeBreakpoints(this.procesBreakpointDuringDebug.bind(this));
        vscode.debug.onDidTerminateDebugSession(this.handleTerminateDebugSession.bind(this));
    }

    private async handleStartDebugSession(session: vscode.DebugSession): Promise<void> {
        if (this.isRunning) {
            this.isRunning = false;
            return;
        }

        this.initializeSession();
        const ss = await this.createSession();
        await this.processBreakpoints(session, ss);
        this.captureSnapshots(ss);
        await this.finalizeSession(session, ss);
    }

    private initializeSession(): void {
        this.deletedSession = null;
        this.isRunning = true;
    }

    private async createSession(): Promise<any> {
        let ss = await Session.create({});
        await Event.create({ session_id: ss.session_id, type: SESSION.START });
        return ss;
    }

    private async processBreakpoints(session: vscode.DebugSession, ss: any): Promise<void> {
        for (const [index, breakpoint] of vscode.debug.breakpoints.entries()) {
            if (breakpoint instanceof vscode.SourceBreakpoint) {
                console.log(index);
                let bp = await insertBp(breakpoint, session.id, this.map);
                await insertEvent(BREAKPOINT.SET, { breakpoint_id: bp.breakpoint_id, session_id: ss.session_id });
                this.map[index] = bp.breakpoint_id;
            }
        }
    }

    private async captureSnapshots(ss: any): Promise<void> {
        let snapAllFiles = await snapshot(false);
        await insertSnapshot(snapAllFiles);

        let snapActiveFile = await snapshot(true);
        let af: any[] | typeof Snapshot | null = await insertSnapshot(snapActiveFile);

        if (!af || af.length === 0) {
            af = await getSnapshotWith({ hash: snapActiveFile[0].hash });
        } else {
            af = af[0];
        }

        let ev = await Event.findOne({where: { session_id: ss.session_id, type: SESSION.START }});
        ev.snapshot_id = af.snapshot_id;
        await ev.save();
    }

    private async finalizeSession(session: vscode.DebugSession, ss: any): Promise<void> {
        this.map["id"] = ss.session_id;
        ss.is_debug = !session.configuration?.noDebug;
        await ss.save();
    }

    private createDebugAdapterTracker(session: vscode.DebugSession) {
        return {
            onDidSendMessage: this.handleDebugAdapterMessage.bind(this),
            onError: (error: any) => console.error("Debug Adapter Error:", error),
            onExit: (code: any, signal: any) => console.log(`Debug Adapter closed: code=${code}, signal=${signal}`)
        };
    }

    private async handleDebugAdapterMessage(message: any): Promise<void> {
        try {
            if (isEmptyObject(this.map)) return;

            if (message.type === 'event' && message.event === 'output') {
                await this.processDebugOutput(message);
            }

            if (message.type === 'event' && message.event === 'stopped' && message.body.reason === 'breakpoint') {
                await this.processBreakpointHit(message);
            }
        } catch (err) {
            console.log("Error during breakpoint processing:", err);
        }
    }

    private async processDebugOutput(message: any): Promise<void> {
        const output = message.body.output;
        if (!output.includes("js-debug/")) {
            const logs = await Log.create({ stream: LOG.OUTPUT, output });
            await Event.create({ log_id: logs.log_id, session_id: this.map["id"], type: SESSION.LOG });
        }
    }

    private async processBreakpointHit(message: any): Promise<void> {
        console.log(message.body.breakpoints);
        const activeSession = vscode.debug.activeDebugSession;
        const breakpointIds = message.body.hitBreakpointIds || [];

        console.log(`Breakpoint triggered in session: ${activeSession?.name}`);
        console.log(`BREAKPOINT TRIGGERED IDs: ${breakpointIds}`);

        if (breakpointIds.length > 0) {
            for (const breakpointId of breakpointIds) {
                let bpId = this.map[breakpointId];
                if (bpId !== undefined) {
                    await Event.create({ breakpoint_id: bpId, session_id: this.map["id"], type: BREAKPOINT.TRIGGER });
                }
            }
        } else {
            await this.handleFallbackBreakpoint(message);
        }
    }

    private async procesBreakpointDuringDebug(session: vscode.DebugSession) : Promise<void> {
               //this is where I fail and have no idea how to tackle this problem
  
     }

    private async handleFallbackBreakpoint(message: any): Promise<void> {
        const stackTrace = await vscode.debug.activeDebugSession?.customRequest('stackTrace', { threadId: message.body.threadId });
        if (stackTrace && stackTrace.stackFrames.length > 0) {
            const frame = stackTrace.stackFrames[0];
            console.log(`Fallback: breakpoint at ${frame.source?.path}:${frame.line}`);
        }
    }

    private async handleTerminateDebugSession(session: vscode.DebugSession): Promise<void> {
        let sessionId = this.map.id;
        if (sessionId && this.deletedSession === null) {
            this.deletedSession = session.id;
            await Event.create({ session_id: sessionId, type: SESSION.END });
        }
        this.map = {};
    }
}

How to Query Facebook Page Posts for an External Partner?

I have already created a Facebook App and selected the Other option during setup. My goal is to fetch posts from a Facebook Page owned by an external partner (not my own page) using the Facebook Graph API.

Could you give me any guidance how to do it?

Since I don’t own the page, how should the external partner authorize my app so I can obtain a valid Page Access Token?

What is the correct process for them to authenticate my app and grant access to their page?

After authentication, how do I correctly retrieve the Page Access Token to query /page_id/posts?

Are there any additional app configurations or API calls required?

Thanks for any help!

Google Pay Invalid token id error with stripe gateway

I’m integrating Google Pay with Stripe in my webshop. The integration works perfectly in test mode, but when I switch to production, I get Invalid token id from stripe

My javascript code: ( I successfully retrieve the Google Pay token and send it to my backend )

let paymentToken = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);
let transactionInfo = await getGoogleTransactionInfo();

let response = await fetch('/stripe/processGooglePayPayment', {
   method: 'POST',
   headers: {
       'Content-Type': 'application/json',
       'Accept': 'application/json',
   },
   body: JSON.stringify({
        token: paymentToken.id,
        totalPrice: transactionInfo.totalPrice,
        currencyCode: transactionInfo.currencyCode,
   })
});

My backend code:

 Stripe::setApiKey(config('shop.stripe_keys.stripe_secret_key'));

 $googlePayToken = $request->input('token');
 $totalPrice = $request->input('totalPrice');
 $currencyCode = $request->input('currencyCode');

 $paymentMethod = PaymentMethod::create([
    'type' => 'card',
    'card' => [
        'token' => "$googlePayToken", // Invalid token id
    ],
 ]);

I ensure that both of Stripe and Google Pay is in production, Google Pay environment variable is set to PRODUCTION, I pass the merchantID too, and I use the live secret key to initialize Stripe.

I searched for the solution in Stripe and Google Pay documentations, but I can’t find anything related to this, anyone who is faced with this error too?

Any help would be appreciate!

Cross-origin request on PHP APi

I have cross-origin request from client side to the PHP Api. I founded that at the response request part some cookies couldn’t be able set on the client side.
At the PHP Api side i have code:

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");
$names    = ClearTextData($_POST['names']);
$to = "some";
$subject = "some";
$message = "some";
$headers = "some";
$emailResult = mail($to, $subject, $message, implode("rn", $headers), " [email protected]");

sometimes mail() PHP function didn’t work. Could bad context of not settings headers influence on the mail() PHP function?

When i’ve changed to same-origin request everything working. mail() function work.
whats wrong with the mail() function on the cross-origin request?

WooCommerce: How to Add Content Below Single Product Gallery [duplicate]

I want to add a custom content module below the product gallery on the WooCommerce product detail page. I found a solution on Google from this website:

https://www.businessbloomer.com/woocommerce-add-content-below-the-single-product-page-images/

However, this solution only works for the desktop version. When switching to the mobile version, the display position of the custom content module changes and ends up below the “Add to Cart” button.

How can I fix this issue?

Digital Ocean Managed MySql DB can not connet via PHP project hosted on Bigirock Server [duplicate]

I have domain and hosing in bigrock linux shared server.
Digital Ocean Managed MySql DB successfully connect via Navicat for Mysql but when i use these credentials in my php project its not working showing error

Basically i am trying to connect Digital Ocean MySQL DB with php project which is hosted on Bigrock shared linux server.

Code i Have Used

<?php
ini_set('display_errors', 1); 
$servername = "db-mysql-db.ondigitalocean.com"; // CHANGED FOR SEQURITY
$username = "repo_Jyoti"; // CHANGED FOR SEQURITY
$password = "AVNbJQM";  // CHANGED FOR SEQURITY
$dbname = "repo_Jyoti"; // CHANGED FOR SEQURITY
$port = "27850"; // CHANGED FOR SEQURITY
    $options = array(
                  PDO::ATTR_PERSISTENT    => true,
                  PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
              );
   
    $dsn = 'mysql:host=' . $servername . ';port=' . $port. ';dbname=' . $dbname;    // Create a new PDO instanace
    try{
        $dbh = new PDO($dsn, $username, $password, $options);
       
         echo "Connected successfully";
    }
    // Catch any errors
    catch(PDOException $e){
        echo "Connection failed: " . $e->getMessage();
    }    
?>

ERROR : Connection failed: SQLSTATE[HY000] [2002] Connection refused


if you want to see the errors by yourself please visit
https://wapi.rentdekhoo.com/bbsapi/repo_Offline/testconn.php

Hide Subtitles option in fullscreen mode on iOS – video.js library

How can I disable subtitles option in video.js player when using fullscreen mode on iOS devices?
Subtitles are not enable in config, I’ve added these options to video.js

  nativeAudioTracks: false,
  nativeVideoTracks: false,
  nativeTextTracks: false,
  textTrackSettings: false,
  preloadTextTracks: false,

Subtitles option is not showing up on standard view, but only on iOS fullscreen. A i can see Fullscreen video is controlled by iOS software, but is it possible to disable this option somehow?

iOS fullscreen Screenshot

Trying to add query parameters to a URL but params.set not doing anything, [closed]

I am trying to add a query search parameter onto a URL, it is getting all the parts but not putting them together. The alerts are just my debugging.

let barcode = "123";
alert(barcode); // correctly shows the numerical version of the barcode
const url = new URL("https://example.com/library/search.by.code.php");
const params = new URLSearchParams(url.search);

alert(url); // shows the url correctly
params.set('code', barcode);
params.toString();
alert(params); // correctly shows "code=67862323" 
alert(url); // still shows url without parameters

Using jest fake timers to advance when testing cache ttl

I am using a ttl cache library to cache my data and let it expire after a certain duration.

import TTLCache from '@isaacs/ttlcache';

const DATA_KEY = 'barks';

const dataCache = new TTLCache({ ttl: 60_000, checkAgeOnGet: true, max: 1 });

export const getCachedData = async (): Promise<string> => {
    if (!dataCache.has(DATA_KEY)) {
        dataCache.set(DATA_KEY, 'new-item');
    }

    console.log('remainingTTL', dataCache.getRemainingTTL(DATA_KEY));

    return dataCache.get(DATA_KEY);
};

I want to test what happens after the ttl expires, thus the need to use the jest fake timers but I cannot get the timer to advance beyond the ttl expiry:

jest.useFakeTimers();

describe('ttlCaching', () => {
    test('Return undefined when ttl has expired', async () => {
        expect(await getCachedData()).toEqual('new-item');

        jest.advanceTimersByTime(100_000);

        expect(await getCachedData()).toEqual(undefined);
    });
});

When logging the ttl, the ttl has not expired yet I am advancing the timers.

I try to open the npm start file on my Windows OS computer and nothing happens [closed]

The service requires determining and fixing an issue preventing a cryptocurrency website from starting up, particularly while executing the ‘npm start’ command on Windows. Additionally, the website requires continuous troubleshooting and maintenance service. Note that the issue might be related to the website’s code or its functionality. The website is not yet hosted and the service does not involve hosting it. There’s a necessity to examine the provided site files.

I try to open the npm start file on my Windows OS computer and nothing happens, but on my friend’s MacOs computer everything works!

Nothing happening all

Select multiple options in dropdown list and add to url

I would like that I can choose brand 1 and brand 2 and brand 3.
Is it possible that I can choose multipe options from a dropdown list without pressing “strg”? Just by clicking? Like a checkbox listed as a dropdown menu? And that the option values are just joined in the url: brand1,2,3

<form action="" method="GET" id="myForm">
    <select name="channel" id="0" onChange="changeURL()">
        <option value="" selected disabled>Choose Channel</option>
        <option value="facebook-ads">Facebook ads</option>
        <option value="instagram-ads">Instagram ads</option>
    </select>
    <select name="brand" id="1" onChange="changeURL()">
        <option value="" selected disabled>Choose Brand</option>
        <option value="brand-1">brand 1</option>
        <option value="brand-2">brand 2</option>
        <option value="brand-3">brand 3</option>
    </select>
</form>
<p id="test"></p>
<script>
// Initialize the filters array
var filters = [];

// Initialize filters with any pre-selected values on page load
document.addEventListener("DOMContentLoaded", function() {
    // Get all select elements
    var selects = document.querySelectorAll('select');
    
    // Initialize the filters array with the correct size
    filters = new Array(selects.length).fill("");
    
    // Check for any pre-selected options
    selects.forEach(function(select) {
        if (select.selectedIndex > 0) { // If something is selected (not the disabled option)
            filters[select.id] = select.value;
        }
    });
    
    // Update URL on initial load
    changeURL();
});

function changeURL() {
    var yourUrl = "https://yourdomain.com"; // Base URL
    var queryParams = [];
    
    // Update the current changed value
    var selects = document.querySelectorAll('select');
    selects.forEach(function(select) {
        filters[select.id] = select.value;
    });
    
    // Build query parameters, only including valid values
    selects.forEach(function(select) {
        var paramName = select.name;
        var paramValue = filters[select.id];
        
        // Only add to URL if there's a valid value
        if (paramValue && paramValue !== "" && paramValue !== "undefined") {
            queryParams.push(paramName + "=" + paramValue);
        }
    });
    
    // Add the query string if we have parameters
    if (queryParams.length > 0) {
        yourUrl += "?" + queryParams.join("&");
    }
    
    // Display the result
    document.getElementById("test").innerHTML = yourUrl;
}
</script>

Thank you in advance for your help!