Modular approach to dynamically extending class behavior in JavaScript without modifying the original class

I’m trying to create independent modules in JavaScript where I can add new functionality without modifying the original class.
My simplified version:

class adminMenu extends contextMenu {
    handleContextMenu(event) {
        if (fileManager.WindowElement.classList.contains('visible')){
            return;
        }
        super.handleContextMenu?.(event);
        this.showOptions();
    }
}

//and in other file:
class fileManager {
    show() {}
    hide() {}

}

And if I don’t include fileManager in a particular project, parts of adminMenu become useless. This doesn’t seem ideal because it results in redundant or unnecessary code when I don’t need certain functionality.

What I want is to structure my modules so that when I include a file (e.g., containing fileManager), it can modify how adminMenu.handleContextMenu() behaves without modifying adminMenu directly.

It seems like there must be a cleaner, more modular approach. For example, in GSAP, after importing a module, we can simply do:gsap.registerPlugin(moduleName); but I’m unsure how to implement something like this in my case.

paypal oncomplete handler example

i want setup a paypal donation button in my website,
about oncomplete: there is no example anywhere.
could u tell me how to get that data after payment and how to send the custom message immitted by user (cm) to a PHP script?

   <body>
     <div id="paypal-donate-button-container"></div>
    
      <script>
       PayPal.Donation.Button({
           env: 'sandbox',
           hosted_button_id: 'YOUR_SANDBOX_HOSTED_BUTTON_ID',
           // business: 'YOUR_EMAIL_OR_PAYERID',
           image: {
               src: 'https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif',
               title: 'PayPal - The safer, easier way to pay online!',
               alt: 'Donate with PayPal button'
           },
           onComplete: function (params) {
               // Your onComplete handler
           },
       }).render('#paypal-donate-button-container');
    </script>
    </body>
  • tx Transaction ID for the transaction
  • st Transaction status
  • amt Transaction amount
  • cc Currency code
  • cm Custom message
  • item_number Purpose configured for the transaction
  • item_name Program
    selected by the donor during the transaction

js multiple loop – time deduction

I have an array of “shift times” and “absence times”, and I’m trying to to subtract the absence time from the corresponding shift time via nested loop, to return the available shift times minus any absence time.

For example

  • there’s an absence that starts at 09:00 and finishes at 09:30 and
  • the first shift time starts at 08:00 and finishes at 10:00.

The code subtracts the absence from the shift time and returns these two items:

  1. starts at 08:00 and finishes at 09:00
  2. starts at 09:30 and finishes at 10:00

I wonder if there is a simpler way to subtract the absences from the shifts times, but I’ve been trying to do so without success.

Also, my code does not returns the correct output. At this moment, the code retrurns:

[
  { start_time: '08:00', finish_time: '09:00' },
  { start_time: '09:30', finish_time: '10:00' },
  { start_time: '10:30', finish_time: '11:00' },
  { start_time: '12:30', finish_time: '16:00' },
  { start_time: '17:00', finish_time: '17:30' }
]

but the results should look like this:

[
  { start_time: '08:00', finish_time: '09:00' },
  { start_time: '09:30', finish_time: '10:00' },
  { start_time: '10:30', finish_time: '11:00' },
  { start_time: '12:30', finish_time: '16:00' },
  { start_time: '17:00', finish_time: '17:30' },
  { start_time: '19:00', finish_time: '20:00' }
]

My code is here:

const arranged_shifts = [{
    'start_time'  : '08:00',
    'finish_time' : '10:00'
},
{
    'start_time'  : '10:30',
    'finish_time' : '16:00'
},
{
    'start_time'  : '17:00',
    'finish_time' : '18:00'
},
{
    'start_time'  : '19:00',
    'finish_time' : '20:00'
}];

const absences = [{
    'start_time'  : '09:00',
    'finish_time' : '09:30'
},
{
    'start_time'  : '11:00',
    'finish_time' : '12:30'
},
{
    'start_time'  : '17:30',
    'finish_time' : '18:00'
}
];

const available_times = [],
         add_time        = (start_time, finish_time) => {
    available_times.push({
        'start_time'  : start_time,
        'finish_time' : finish_time
    });
};

const get_time_difference = (a_time, b_time) => {
    return Date.parse('1970/01/01 ' + a_time) - Date.parse('1970/01/01 ' + b_time);
};

absences_loop : for (const absence of absences){
    shift_loop : for (const arranged_shift of arranged_shifts){
        const start_time_difference  = get_time_difference(arranged_shift.start_time, absence.start_time),
                    finish_time_difference = get_time_difference(arranged_shift.finish_time, absence.finish_time);

        if (start_time_difference === 0 && finish_time_difference > 0){
            add_time(absence.finish_time, arranged_shift.finish_time);
    }
        else if (start_time_difference < 0 && finish_time_difference > 0){
            add_time(arranged_shift.start_time, absence.start_time);
            add_time(absence.finish_time, arranged_shift.finish_time)
        }
        else if (finish_time_difference === 0 && start_time_difference < 0){
            add_time(arranged_shift.start_time, absence.start_time);
        }
  }
}

console.log(available_times);

EWS on OVH Hosted Exchange

I am trying to use EWS API to set OOF on a webmail account hosted on OVH (Hosted) Exchange.

I am getting 401 status code every time whereas my email and password are good.

When trying here : https://testconnectivity.microsoft.com/tests/EwsTask/input
It works well with the same credentials when I check “Ignored SSl”

Any idea please ?

Here is my code

import {
  ExchangeService,
  ExchangeVersion,
  Uri,
  OofSettings,
  TimeWindow,
  OofReply,
  WebCredentials,
  DateTime,
} from 'ews-javascript-api';

function createExchangeService(username: string, password: string) {
  const exch = new ExchangeService(ExchangeVersion.Exchange2016);
  exch.Credentials = new WebCredentials(username, password);
  exch.Url = new Uri(`https://${process.env.MAIL_HOST}/EWS/Exchange.asmx`);
  return exch;
}

try {
    const exch = createExchangeService(username, password);

    const oofSettings = await exch.GetUserOofSettings(username);
    res.json({
      status: oofSettings.State,
      internalReplyMessage: oofSettings.InternalReply?.Message || '',
      externalReplyMessage: oofSettings.ExternalReply?.Message || '',
      externalAudience: oofSettings.ExternalAudience,
      scheduledStartDateTime: oofSettings.Duration?.StartTime,
      scheduledEndDateTime: oofSettings.Duration?.EndTime,
    });
  } catch (err: any) {
    console.error('Error getting OOF settings', err);
  }

Thank you

Request variable doesn’t work if uses environment variables in .http in Visual Studio 2022

Can someone check if this is a visual studio error or if I made a mistake somewhere?

Desired scenario: first request in each of .http files is login request.
Other requests consume the token from the login request variable.

http-client.env.json:

{
  "$shared": {
      "login": "<login>",
      "pass": "<pass>" 
  },
  "local": {
    "host": "<url:localhost>"
  },
  "dev": {
    "host": "<url:dev>"
  }
}

MyRequests.http:

### Run Login before next queries. 
// @name login
POST {{host}}/api/auth/login HTTP/1.1
Content-Type: application/json

{
    "Login": "{{login}}", 
    "Password": "{{pass}}"
}

### GET current-user
GET {{host}}/api/todos
Authorization: Bearer {{login.response.body.$.token}}

Error:

(2,25): error HTTP0012: Unable to evaluate expression 'login.response.body.$.token'.

Everything works if I use constants directly in the .http file for login-password instead of environment variables.

In general, the goal is to store the login and password in a separate file that is not under source control, but without using like Azure or others.

Date validation between 2 form dates entered in rules for json

So I have a web form that compares a date of loss to different other dates for validation. Most work such as the lessThan and greater than. However, one that will not work is equal. When it says that the DateOfLoss (DOL) cannot be less than the effective date it also includes the actual effective date. For our purposes, the DOL Can be the same as the effective date so I tried the following:

{
  "name": "dateofloss-can-be-equal-to-effective-date",
  "conditions": {
    "all": [
      {
        "fact": "DateOfLoss",
        "operator": "equal",
        "value": {
          "value": {

            "fact": "EffectiveDate"
          }
        }
  }
    ]
  },
  "event": {
    "type": "date-of-loss-can-be-equal-to-effective-date",
    "params": {
      "message": "The Date of Loss can be equal to the policy effective date.",
      "instructions": ""
    }
  }
},

And when we try DateOfLoss Cannot be greaterThan the Expiration date it does Not include the ExpirationDate in the error and it needs to. I tried equal with this one also and it does not work. What am I missing? This is new to me and I have tried to figure this out. Thanks in advance.

{
  "name": "dateofloss-cannot-be-same-as-expiration-date",
  "conditions": {
    "all": [
      {
        "fact": "DateOfLoss",
        "operator": "equal",
        "value": {
          "fact": "ExpirationDate"
        }
      }
    ]
  },
  "event": {
    "type": "date-of-loss-cannot-be-same-as-expiration-date",
    "params": {
      "message": "The Date of Loss cannot be the same as the policy expiration date.",
      "instructions": ""
    }
  }
},

SSE (server side event) went CSE (Client Server Event) – loop sse.php working only with curl

around 2017 I wrote a SSE (PHP) script and the javascipt code. Worked fine with PHP-5 + HTTP/1 and the firefox of that era.

Same code now it does not work with Firefox-140 esr or latest Chrome with PHP-8.2 + HTTP/2. I have time-out after 60 seconds.

Also tried the simplest SSE example from lucidar.me, zip. If I remove the while loop something that I think it’s bad, it’s working. In that case the JavaScript makes requests every 5 seconds. I think this defeats the purpose of SSE.

The code with while works fine with curl but not with browsers.

My implementation and the rational of SSE is that the server decides when to send the data, not the client. Right?

It changed something in JavaScript I guess, in browsers, or I miss something? It’s the HTTP/2 the problem?

The code works with curl like that (while version)

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache, no-transform');
header('X-Accel-Buffering: no');
header('Access-Control-Allow-Origin: *');
set_time_limit(0);
@ini_set('zlib.output_compression', 0);
@ob_implicit_flush(true);

// Loop until the client close the stream
while (true) {

  // Echo time
  $time = date('r');
  echo "data: The server time is: {$time}nn";
 
  // Flush buffer (force sending data to client)
  @ob_flush();
  flush();

  // Wait 2 seconds for the next message / event
  sleep(2);
}
?>

Get incident report on Access-Contro-lAllow-Origin violation

I am trying some things out regarding the reporting API. I have set up a simple HTML page that registers a ReportingObserver like so:

const reportObserver = new ReportingObserver((reports) => alert(JSON.stringify(reports)),
                                             { buffered: true });
reportObserver.observe();

This page also contains an image tag like this:

<img src="https://other.mydomain/image.png">

This page is requested by the browser as https://main.mydomain/test.html. The CSP headers of this page are set such that the request to the image is not blocked. For this the Content-Security-Policy header of the HTML page contains img-src 'self' https://other.mydomain/.

Now I block the loading of the image with the following headers returned by the image:

Access-Control-Allow-Origin: https://other.mydomain/
Cross-Origin-Resource-Policy: same-origin

The browser reports that the image cannot be loaded since the origins do not match, which is correct. However, nothing is reported via the ReportingObserver in the web page.

I also tried to have the violation report sent to an endpoint on my server. For this, the response for the image also contains the following headers:

Report-To: {"group":"default","max_age":10886400,"endpoints":[{"url":"https://main.mydomain/reports"}]}
Reporting-Endpoints: default=https://main.mydomain/reports

But nothing is being posted to this endpoint regarding this violation.

I am testing this using Google Chrome, starting it from the command line with the command line option --short-reporting-delay to make sure that reports are sent quickly after an incident occurs. In the test webpage I also generate other violations and those are being sent to the reporting endpoint and are also caught by the ReportingObserver.

Is it actually possibly to have a report generated when there is a mismatch in origin upon a request? If it is possible, what am I missing?

getCSRFToken is not defined error, JavaScript

This is the part of the code in the Django + JavaScript Todo App that is responsible for deleting a note. I need a csrftoken for this, but the JS is showing me an error in the console. What did I do wrong and how can I fix it?

    Uncaught ReferenceError: getCSRFToken is not defined
    at HTMLButtonElement.<anonymous> (main.js:100:30)
    const delUrl = document.body.dataset.delNoteUrl;
  
    deleteBtn.addEventListener("click", (e) => {
      e.preventDefault();
  
      if (e.target.classList.contains("delete-btn")) {
        const parentLi = e.target.closest(".todo__note");
        const noteId = parentLi.getAttribute("data-id");

        fetch(`${delUrl}/${noteId}`, {
            method: "POST",
            headers: {
              "X-CSRFToken": getCSRFToken(),
            },
          })
            .then((response) => response.json())
            .then((data) => {
              if (data.status == "success") {
                parentLi.remove();
              }
            });
      }
    });```

Here is HTML, if need.

<ul class="todo__list">
  {% for note in notes %}
  <li class="todo__note flex" data-id="{{ note.id }}">
    <div>
      <input type="checkbox" />
      <span>{{ note.text }}</span>
    </div>
    <div class="delete__edit">
      <button class="edit-btn" id="editBtn">
        <img src="{% static 'images/edit.svg' %}" alt="" />
      </button>
      <button class="delete-btn" id="deleteBtn">
        <img src="{% static 'images/delete.svg' %}" alt="" />
      </button>
    </div>
  </li>
  {% endfor %}
</ul>

How to use Theia Sticky Sidebar without Jquery

I am using the theia sticky sidebar, but this is Jquery Dependend plugin. But it also have a vanilla JS version in CDN. But not working without Jquery. How can I use it without Jquery? and will get same functionality. I tried in many ways, but it always requires Jquery. But I do not want to use Jquery, cause my website is without Jquery Dependency.

Here is my approach.

$(document).ready(function() {
  $('.leftSidebar, .content, .rightSidebar')
    .theiaStickySidebar({
      additionalMarginTop: 30
    });
});
.content {
  width: 50%;
  float: left;
  position: relative;
}

.leftSidebar {
  width: 25%;
  float: left;
  padding: 0 30px 0 0;
  position: relative;
}

.rightSidebar {
  width: 25%;
  float: right;
  padding: 0 0 0 30px;
  position: relative;
}
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/theia-sticky-sidebar.min.js"></script>
<div class="header">
  <div class="wrapper wrapperThreeColumns">
    <div class="leftSidebar">
      <div class="theiaStickySidebar">
        <div class="box">
          <h2>Left Sidebar</h2>

          <p>
            Gloriatur neglegentur ea mel. Eu pro option moderatius, elitr nonumy molestiae
            ad nam.
          </p>
        </div>
      </div>
    </div>

    <div class="content box">
      <div class="theiaStickySidebar">
        <h2>Content</h2>

        <p>
          Lorem ipsum dolor sit amet, ei vix dicit possim. Pro principes urbanitas ei, his no
          omittam inimicus, qui apeirian honestatis philosophia ei.
        </p>
      </div>
    </div>

    <div class="rightSidebar">
      <div class="theiaStickySidebar">
        <div class="box">
          <h2>Right Sidebar</h2>

          <p>
            Decore aliquando has in, mel exerci inermis an. Phaedrum consequat cum ex, harum
            legere ad qui.
          </p>
        </div>
      </div>
    </div>
  </div>

How to set options to an object

In an JS web application (OpenLayers) I have implemented a search function in a map:

var selectCtrl = new Select({

source: vectorSource,
caseLabel:'Test',
property: $(".options select").val()
});
map.addControl (selectCtrl);

That works fine as you can see:
Implemented Search

The documentation says that one can add Conditions to that search.
It says the following:
Documentation

But I don’t get how to use the syntax.
I try e.g.

selectCtrl.addCondition("attr:fid","op:=","val:9");

…but that has no influence. No entries are made then in the search.
A new condition is implemented then, but without attributes (like “fid=9”).
How do I have to set the addCondition(options) function?

Javascript: How to set options to an object

In an JS-web-application (OpenLayers) I have implemented a search-function in a map:

var selectCtrl = new Select({

source: vectorSource,
caseLabel:'Test',
property: $(".options select").val()
});
map.addControl (selectCtrl);

That works fine as you can see:
Implemented Search

The documentation says that one can add Conditions to that search.
It says the following:
Documentation

But I don`t get how to use the syntax.
I try e.g.

selectCtrl.addCondition("attr:fid","op:=","val:9");

…but that has no influence. No entries are made then in the search.
A new condition is implemented then, but without attributes (like “fid=9”).
Could anybody help me and give me a hint how I have to set the addCondition(options) function?

Dimensions.get(‘window’).height doesn’t include StatusBar.currentHeight when the Status Bar is translucent

I set the StatusBar to translucent in order to draw the app’s content under the status bar (on Android 14 and earlier — Android 15 enforces edge-to-edge design by default).

According to the React Native documentation:

For Android, the window dimensions will exclude the size used by the status bar (if not translucent) and bottom navigation bar.

https://reactnative.dev/docs/dimensions#get

However, in my tests, the window height still excludes the status bar area, even though the status bar is set to translucent using the translucent prop of StatusBar.

Is this a bug, or is there something I’m missing?

My test was using this App.tsx file on a dummy react native project and run on an Android device.

To test, please install react-native-safe-area-context.

App.tsx

import React from 'react';
import { Dimensions, StatusBar, StyleSheet, Text, useColorScheme, View, } from 'react-native';
import { SafeAreaProvider, SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

const ContentView = () => {

  const insets = useSafeAreaInsets();

  const heightPercentage = (percentage: number) => (Dimensions.get('window').height - insets.top - insets.bottom) * percentage / 100;

  const widthPercentage = (percentage: number) => (Dimensions.get('window').width - insets.left - insets.right) * percentage / 100;

  const CustomStatusBar = (): React.JSX.Element => {
    return <View style={{ height: insets.top, width: widthPercentage(100), backgroundColor: 'red' }}>
      <SafeAreaView>
        <StatusBar barStyle='dark-content' translucent backgroundColor='transparent' />
      </SafeAreaView>
    </View>
  };

  const BottomBar = (): React.JSX.Element => {
    return <View style={{ height: insets.bottom, width: widthPercentage(100), backgroundColor: 'red' }} />
  }

  const LeftBar = (): React.JSX.Element => {
    return <View style={{ height: heightPercentage(100), width: insets.left, backgroundColor: 'red' }} />
  }

  const RightBar = (): React.JSX.Element => {
    return <View style={{ height: heightPercentage(100), width: insets.right, backgroundColor: 'red' }} />
  }

  return (
    <View style={{ flex: 1, backgroundColor: 'red' }}>
      <CustomStatusBar />

      {/* content */}
      <View style={{ flexDirection: 'row', height: heightPercentage(100), width: widthPercentage(100) }}>
        <LeftBar />

        {/* content */}
        <View style={{
          backgroundColor: 'green',
          height: heightPercentage(100),
          width: widthPercentage(70),
          justifyContent: 'center',
          paddingLeft: widthPercentage(2)
        }}>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>top: {insets.top}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>right: {insets.right}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>bottom: {insets.bottom}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>left: {insets.left}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>StatusBar's height: {StatusBar.currentHeight}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>window's heihgt: {Dimensions.get('window').height}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>screen's heihgt: {Dimensions.get('screen').height}</Text>
          <Text style={{ color: 'white', fontSize: heightPercentage(2) }}>heightPercentage(100): {heightPercentage(100)}</Text>
        </View>

        <RightBar />
      </View>

      <BottomBar />
    </View>
  );
}

function App(): React.JSX.Element {
  return (
    <SafeAreaProvider style={{ flex: 1 }}>
      <ContentView />
    </SafeAreaProvider>
  );
}



export default App;

How to stream Twilio media audio into n8n webhook for real-time transcription?

I am working on a workflow to transcribe live audio from a Twilio call using Deepgram via n8n. What I’ve done so far:

1.Set up Twilio to stream call audio using <Stream> with a WebSocket proxy.

2. My proxy forwards media.payload as base64 audio to my n8n webhook.

3. Using a Function node in n8n to decode base64 and send to Deepgram for transcription.
The problem:
My Decode Caller Audio node in n8n does not output any data, and Deepgram receives nothing.

Question:

• Is there something wrong with how I decode the Twilio media.payload in n8n?

• How should I properly decode and forward Twilio’s streamed base64 audio to Deepgram in a way it accepts for transcription?

Here is the relevant code in my n8n Function node:

const base64Audio = $json.base64Audio;
if (!base64Audio) {
  throw new Error('base64Audio missing');
}
const buffer = Buffer.from(base64Audio, 'base64');
return [{
  binary: {
    audio: {
      data: buffer,
      mimeType: 'audio/mulaw',
      fileName: 'caller.wav'
    }
  }
}];