JS Start date system [closed]

I work for a college, and we have specific start dates for each program. Most programs have a monthly start date while others skip a few months.

I want to write a code whereby we can update the start dates and cut off dates yearly, and it will display the next two upcoming start dates.

My idea is to define start dates and cut off dates, get the current date, create arrays for each “set” of start dates and each “set” of cut off dates, then compare the current date to the cut off dates and create new variables from the start date arrays with only the next two upcoming start dates in it.

// Set start dates for each month - Update yearly:
const janStartDate = "January 29";
const febStartDate = "February 26";
const marStartDate = "March 25";
const aprStartDate = "April 29";
const mayStartDate = "May 27";
const junStartDate = "June 24";
const julStartDate = "July 29";
const augStartDate = "August 26";
const sepStartDate = "September 30";
const octStartDate = "October 28";
const novStartDate = "November 25";
const decStartDate = "December 16";

// Set cut off dates - Update yearly:
const janCut = new Date(2024, 0, 19);
const febCut = new Date(2024, 1, 16);
const marCut = new Date(2024, 2, 15);
const aprCut = new Date(2024, 3, 19);
const mayCut = new Date(2024, 4, 17);
const junCut = new Date(2024, 5, 14);
const julCut = new Date(2024, 6, 19);
const augCut = new Date(2024, 7, 16);
const sepCut = new Date(2024, 8, 20);
const octCut = new Date(2024, 9, 18);
const novCut = new Date(2024, 10, 15);
const decCut = new Date(2024, 11, 13);

// Get current date:
const currentDate = new Date();
const currentMonth = currentDate.getMonth();

// Create arrays of cut off dates:
const monthlyCutOffDates = [janCut, febCut, marCut, aprCut, mayCut, junCut, julCut, augCut, sepCut, octCut, novCut, decCut]
const phrmCutOffDates = [febCut, marCut, mayCut, junCut, augCut, sepCut, novCut, decCut]
const techCutOffDates = [janCut, marCut, aprCut, junCut, julCut, sepCut, octCut, decCut]
const pswCutOffDates = [janCut, febCut, marCut, aprCut, mayCut, junCut, julCut, augCut, sepCut, novCut, decCut]

// Create arrays of start dates:
const monthlySet = [janStartDate, febStartDate, marStartDate, aprStartDate, mayStartDate, junStartDate, julStartDate, augStartDate, sepStartDate, octStartDate, novStartDate, decStartDate];
const phrmSet = [febStartDate, marStartDate, mayStartDate, junStartDate, augStartDate, sepStartDate, novStartDate, decStartDate];
const techSet = [janStartDate, marStartDate, aprStartDate, junStartDate, julStartDate, sepStartDate, octStartDate, decStartDate];
const pswSet = [janStartDate, febStartDate, marStartDate, aprStartDate, mayStartDate, junStartDate, julStartDate, augStartDate, sepStartDate, novStartDate, decStartDate];

// Limit the start date sets to only the two upcoming start dates:
let monthlyStartDatesToShow = [];
if (currentDate > monthlyCutOffDates[currentMonth]) {
    monthlyStartDatesToShow.push(monthlySet[(currentMonth + 1)]);
    monthlyStartDatesToShow.push(monthlySet[(currentMonth + 2)]);
}
else {
    monthlyStartDatesToShow.push(monthlySet[currentMonth]);
    monthlyStartDatesToShow.push(monthlySet[(currentMonth + 1)]);
}
let phrmStartDatesToShow = [];
if (currentDate > phrmCutOffDates[currentMonth]) {
    phrmStartDatesToShow.push(phrmSet[(currentMonth + 1)]);
    phrmStartDatesToShow.push(phrmSet[(currentMonth + 2)]);
}
else {
    phrmStartDatesToShow.push(phrmSet[currentMonth]);
    phrmStartDatesToShow.push(phrmSet[(currentMonth + 1)]);
}
let techStartDatesToShow = [];
if (currentDate > phrmCutOffDates[currentMonth]) {
    techStartDatesToShow.push(techSet[(currentMonth + 1)]);
    techStartDatesToShow.push(techSet[(currentMonth + 2)]);
}
else {
    techStartDatesToShow.push(techSet[currentMonth]);
    techStartDatesToShow.push(techSet[(currentMonth + 1)]);
}
let pswStartDatesToShow = [];
if (currentDate > pswCutOffDates[currentMonth]) {
    pswStartDatesToShow.push(pswSet[(currentMonth + 1)]);
    pswStartDatesToShow.push(pswSet[(currentMonth + 2)]);
}
else {
    pswStartDatesToShow.push(pswSet[currentMonth]);
    pswStartDatesToShow.push(pswSet[(currentMonth + 1)]);
}

// Assign start date sets to pages:
switch ({post_id}) {
    case 96:
        document.getElementById("start-date-1").innerHTML = phrmStartDatesToShow;
        break;
    case 1420:
        document.getElementById("start-date-1").innerHTML = pswStartDatesToShow;
        break;
    case 1411:
    case 1422:
        document.getElementById("start-date-1").innerHTML = techStartDatesToShow;
        break;
    default:
        document.getElementById("start-date-1").innerHTML = monthlyStartDatesToShow;
        break;
}

monthlyStartDatesToShow is working great, but the others are not. They either display only one date (which is incorrect, December), or neither.

How to generate GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET without a domain?

I would like to create a new Google API project for a nextJS webapp. I cannot understand how to get the API GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET without a domain.

I have to setup in the .env file

# Next Auth Google provider
GOOGLE_CLIENT_ID="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
GOOGLE_CLIENT_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

I tried looking for solutions but I cannot find the resources.Screenshot showing the options

Error in VS Code for not deploying express server

My vs code is not showing any links for running the express js server and there is no error in the code and every package is perfectly installed and previously it was running

I have done like every thing I could possibly think of like creating a new folder, downloading and enabling extensions and reinstalling vs code also

How to debug an unknown issue in GMaps JS API

A map editor implementation for Google Maps’ JS API suddenly stopped working.

I have a WordPress plugin with a backend that provides a “map editor” – the way it works is by rendering a GMap and providing an UI that allows you to place a marker on that map, retrieve the click location/coords and save it into the database. The frontend is pretty simple as well – it takes the markers and infowindow data from the db and renders the map.

The frontend is fine, however when a map is loaded through the editor – the map renders for a split second, like a flash, and then goes to “Oops! Something went wrong. – This page didn’t load Google Maps correctly. See the JavaScript console for technical details.”. I don’t identify any clues in the browser console.

How should I approach this?

API key and cloud settings are valid.

I tried loading a completely empty map – no markers or other config. Didn’t work. Frontend on the other hand loads fine and contains the same yellow warnings in the console.

P.S: this happened out of nowhere, there hasn’t been any updates or changes to the environment. The downside is that this is a vue.js implementation and the source files are unavailable, so I am stuck debugging output JS.

MathJax not rendering after refresh page

In order to understand how MathJax works, I have developed a very basic and simple html file (called test.html) with some MathJax equations:

<html>

    <!-- Module for rendering Markdown content -->
    <script type="module" src="https://md-block.verou.me/md-block.js"></script>

    <!-- Module for rendering mathematical equations -->
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

    <body>
        <md-block>

            Let's solve a simple second-order homogeneous linear differential equation with constant coefficients. One common example is:

            [
            y'' - 5y' + 6y = 0
            ]

            To solve this, we'll find the characteristic equation by assuming a solution of the form ( y = e^{rt} ), where ( r ) is a constant. The derivative terms ( y' ) and ( y'' ) become ( re^{rt} ) and ( r^2e^{rt} ) respectively, leading to the characteristic equation:

            [
            r^2 - 5r + 6 = 0
            ]

            This quadratic can be factored as:

            [
            (r - 2)(r - 3) = 0
            ]

            So, ( r_1 = 2 ) and ( r_2 = 3 ) are the roots. Therefore, the general solution of the differential equation is:

            [
            y(t) = c_1e^{2t} + c_2e^{3t}
            ]

            Here, ( c_1 ) and ( c_2 ) are constants determined by initial conditions, which are not given in this context. Thus, we have the general form of the solution.

        </md-block>
    </body>
</html>

Now, if I open with Google Chrome the test.html file, the equations render perfectly, but when I refresh the page using the refresh button of Chrome, the euqations are shown in their row form. I have to wait around a couple of minutes to have the equations properly rendered in MathJax format.

Do you know what could be the reason and how should I edit this file in order to have a properly working code?

Strapi (v4.x): Difficulty Refreshing Expired JWT Token Due to Lack of User ID

I’m facing an issue with refreshing an expired JWT token in my application. The problem is that when a token expires, I can no longer retrieve the user’s ID because the token is invalid, and I need the user’s ID to generate a new token.

Here’s a brief overview of the situation:

  1. Problem Description: When a user’s JWT token expires, I cannot
    extract the user’s ID from the expired token because the
    verification process fails due to the token’s expiration. Without
    the user ID, I can’t issue a new JWT token.

  2. Current Approach: I’m using the following approach to verify the
    token and issue a new token:

 plugin.controllers.auth.refreshToken = async (ctx) => {
    const params = _.assign(ctx.request.body);

    try {
      const { id } = await strapi.plugins[
        "users-permissions"
      ].services.jwt.verify(params.jwt); // Problem retrieving user id, if token expires.

      const RAW_SQL = `SELECT id FROM up_users WHERE id = ${id}`;

      const entriesResult = await strapi.db.connection.raw(RAW_SQL);
      const rows = entriesResult.rows;

      if (_.size(rows) === 1) {
        const user = _.first(rows);

        ctx.send({
          jwt: strapi.plugins["users-permissions"].services.jwt.issue({
            id: user.id,
          }),
        });
      }
    } catch (e) {
      return ctx.badRequest(null, "Invalid token");
    }
  };

aes256 dbms_crypto output mismatches with crypto-js

I am trying to match PLSQL dbms_crypto with Javascript crypto-js. I want to encrypt in JS and decrypt in PLSQL, but for testing, I am encrypting in both to see if I can get the encrypted value to match.

I followed this as much as I could but I am still stuck.

dbms_crypto output mismatches with crypto-js

PLSQL

    FUNCTION cl_encrypt (p_string VARCHAR2, p_key VARCHAR2)
        RETURN VARCHAR2
    AS
        lv_whats_my_name    VARCHAR2 (100) := 'cl_utilities.cl_encrypt';
        v_encrypted_raw     RAW (32000);
        v_key               RAW (320);
        v_encryption_type   PLS_INTEGER := DBMS_CRYPTO.encrypt_aes256 + DBMS_CRYPTO.chain_cbc + DBMS_CRYPTO.pad_pkcs5;
    BEGIN
        v_key   := RAWTOHEX (UTL_I18N.string_to_raw (p_key, 'AL32UTF8'));
        v_encrypted_raw   :=
            DBMS_CRYPTO.encrypt (src => UTL_I18N.string_to_raw (p_string, 'AL32UTF8'), typ => v_encryption_type, key => v_key,iv=>utl_raw.cast_to_raw(1));

       RETURN UTL_RAW.cast_to_varchar2 (UTL_ENCODE.base64_encode (v_encrypted_raw));

    END;

Javascript

const CryptoJS = require('crypto-js');

const key = 'some key phrase to 0129034676438'
const message = 'bob is your uncle'
var encrypted = CryptoJS.AES.encrypt(
    message,
   CryptoJS.enc.Base64.parse( Buffer.from(key).toString('hex')),
    { iv: CryptoJS.enc.Utf8.parse(1), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });

console.log("encrypted vaule :: " + encrypted );


```
Key : 'some key phrase to 0129034676438'
message: 'bob is your uncle'
iv: 1

Plsql Encrypted value
UiJjrdgefVCcY1aJNuIt+oPPAPNOtnVTsE1g3sOwxiU= 

Javascript value
 
3UcXtyd9amnyjCYXKqi4ZrqB48ZerohDON80i1h4v2U=

Speech bubble not appearing every 30 seconds

I’m trying to create a speech bubble that appears every 30 seconds next to a floating button. I’ve added the necessary HTML, JavaScript, and CSS styles, but the speech bubble is not appearing as expected.

Here’s my code:

<div class="floating-button" style="
      position: fixed;
      bottom: 20px;
      right: 20px; /* Changed from left to right */
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background-color: #ff6347;
      box-shadow: 0 0 15px rgba(255, 99, 71, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      transition: box-shadow 0.3s ease;
      cursor: pointer;
    " onmouseover="this.style.boxShadow='0 0 25px rgba(255, 99, 71, 1)'" onmouseout="this.style.boxShadow='0 0 15px rgba(255, 99, 71, 0.6)'">
            <!-- Image Inside the Button -->
      <img src="https://files.oaiusercontent.com/file-U1rw4cb2Q4LKzu41EK5M5J6S?se=2024-09-04T17%3A08%3A10Z&sp=r&sv=2024-08-04&sr=b&rscc=max-age%3D604800%2C%20immutable%2C%20private&rscd=attachment%3B%20filename%3D69cadf7d-9e41-48cd-aa92-8361b108725b.webp&sig=PVKZ92cCPlN8LRuR0RcR/wTJvaA%2BOuSJ5Ew7UwPh/74%3D" alt="Button Image" style="
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 50%;
      ">
    </div>

<!-- Add a container for the speech bubble -->
<div class="speech-bubble-container" style="
  position: fixed;
  bottom: 80px;
  right: 20px;
"></div>

<script>
  // Get the speech bubble container
  const speechBubbleContainer = document.querySelector('.speech-bubble-container');

  // Function to create a speech bubble
  function createSpeechBubble(message) {
    const speechBubble = document.createElement('div');
    speechBubble.className = 'speech-bubble';
    speechBubble.textContent = message;
    speechBubble.style = `
      background-color: #fff;
      border-radius: 10px;
      padding: 10px;
      font-size: 16px;
      font-weight: bold;
      color: #333;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
      animation: fadeOut 2s forwards;
    `;
    speechBubbleContainer.appendChild(speechBubble);

    // Remove the speech bubble after 2 seconds
    setTimeout(() => {
      speechBubble.remove();
    }, 2000);
  }

  // Create a speech bubble every 30 seconds
  setInterval(() => {
    createSpeechBubble('Hi');
  }, 30000);
</script>

The speech bubble is not appearing every 30 seconds as expected. I’ve tried moving the CSS styles into the HTML code, but that didn’t work either.

Can anyone help me figure out what’s going wrong?

fetch() or axios keeps hanging even though Lambda function sent back a result after 10 mins

I have a Lambda function to run a large query that takes 10 minutes to finish and send a response. The function has no issue to eventually return a result. However, when I use fetch() or axios to get the response, it keeps hanging even after I verified that there’s already a result from Lambda in the CloudWatch log. But if I send a small query that only takes a few seconds to finish, fetch() or axios has no issue return the response. How can I fix this?

When I send 2 consecutive asynchronous messages to the database, the function works incorrectly. What can I use in this case?

When I send 2 consecutive asynchronous messages to the database, the function works incorrectly and prints incorrectly to my database. What can I use in this case? I am using AWS and when I use SQS, can I return the correctness messages in the database via SQS?

Even if I use it asynchronously, when I send two consecutive data to my function, it always prints the second one incorrectly. I hope you can help.

Creating a Typescript Project with Support for Web Workers?

I’m trying to create a Typescript project that supports web workers.

First I create a baseline that will compile typescript code like this.

mkdir ts
cd ts
npm init -y
npm i -D typescript
npm i -D @types/mocha

Add tsconfig.json.

{
  "compilerOptions": {
    "target": "es2021",
    "module": "es2020",
    "lib": ["es2021", "DOM", "DOM.Iterable"],
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitOverride": true,
    "types": ["mocha"]
  },
  "include": ["src/**/*.ts"],
  "exclude": []
}

Add some typescript (src/hello.component.ts).

/**
 *  @category WebComponent
 *
 * Hello World Web Component
 * that renders a greeting.
 */
export class HelloWorldComponent extends HTMLElement {
    static get observedAttributes() {
      return ['name'];
    }
  
    /**
     * The name to greet
     * @defaultValue World
     */
    name: string | null = 'World';
    something!: string;
    /**
     * Initializes the name property to `World`.
     */
    constructor() {
      super();
      //    this.name = 'World';
    }
  
    /**
     * Sets the component inner
     * html to the greeting.
     */
    connectedCallback() {
      this.textContent = `Hello ${this.name}!`;
    }
  
    //========================================
    // attribute change callback
    //========================================
    attributeChangedCallback(
      property: keyof HelloWorldComponent,
      oldValue: string | null,
      newValue: string | null
    ) {
      if (oldValue === newValue) return;
      switch (property) {
        case 'name':
          this.name = newValue;
          break;
        default:
          throw new Error(`Unhandled attribute: ${property}`);
      }
    }
  }
  customElements.define('hello-world', HelloWorldComponent);

And run tsc.

This compiles fine.

And the only step left to add web worker support is to add it to the lib compiler option like this.

"lib": ["es2021", "DOM", "DOM.Iterable", "WebWorker"],

And rerun tsc. However now it generates creates all these errors. Any ideas?

tsc
../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:3632:5 - error TS2374: Duplicate index signature for type 'number'.

3632     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:5234:5 - error TS2374: Duplicate index signature for type 'number'.

5234     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:5290:5 - error TS2374: Duplicate index signature for type 'number'.

5290     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:6471:5 - error TS2374: Duplicate index signature for type 'number'.

6471     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:8412:5 - error TS2374: Duplicate index signature for type 'number'.

8412     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:1234:5 - error TS2374: Duplicate index signature for type 'number'.

1234     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:1266:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSNumericValue' must be of type '{ new (): CSSNumericValue; prototype: CSSNumericValue; parse(cssText: string): CSSNumericValue; }', but here has type '{ new (): CSSNumericValue; prototype: CSSNumericValue; }'.

1266 declare var CSSNumericValue: {
                 ~~~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:3664:13
    3664 declare var CSSNumericValue: {
                     ~~~~~~~~~~~~~~~
    'CSSNumericValue' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:1355:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSStyleValue' must be of type '{ new (): CSSStyleValue; prototype: CSSStyleValue; parse(property: string, cssText: string): CSSStyleValue; parseAll(property: string, cssText: string): CSSStyleValue[]; }', but here has type '{ new (): CSSStyleValue; prototype: CSSStyleValue; }'.

1355 declare var CSSStyleValue: {
                 ~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:5189:13
    5189 declare var CSSStyleValue: {
                     ~~~~~~~~~~~~~
    'CSSStyleValue' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:1383:5 - error TS2374: Duplicate index signature for type 'number'.

1383     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:1424:5 - error TS2374: Duplicate index signature for type 'number'.

1424     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:2247:5 - error TS2374: Duplicate index signature for type 'number'.

2247     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:2763:5 - error TS2374: Duplicate index signature for type 'number'.

2763     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:3075:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'FormData' must be of type '{ new (form?: HTMLFormElement | undefined, submitter?: HTMLElement | null | undefined): FormData; prototype: FormData; }', but here has type '{ new (): FormData; prototype: FormData; }'.

3075 declare var FormData: {
                 ~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:8758:13
    8758 declare var FormData: {
                     ~~~~~~~~
    'FormData' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:4185:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'Notification' must be of type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback | undefined): Promise<...>; }', but here has type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; }'.

4185 declare var Notification: {
                 ~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:16699:13
    16699 declare var Notification: {
                      ~~~~~~~~~~~~
    'Notification' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:5693:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'URL' must be of type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob | MediaSource): string; revokeObjectURL(url: string): void; }', but here has type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob): string; revokeObjectURL(url: string): void; }'.

5693 declare var URL: {
                 ~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:22904:13
    22904 declare var URL: {
                      ~~~
    'URL' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9187:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessage' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9187 declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28270:13
    28270 declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~
    'onmessage' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9189:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessageerror' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9189 declare var onmessageerror: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28272:13
    28272 declare var onmessageerror: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~~~~~~
    'onmessageerror' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9216:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'location' must be of type 'Location', but here has type 'WorkerLocation'.

9216 declare var location: WorkerLocation;
                 ~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:27594:13
    27594 declare var location: Location;
                      ~~~~~~~~
    'location' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9222:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.

9222 declare var navigator: WorkerNavigator;
                 ~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:27611:13
    27611 declare var navigator: Navigator;
                      ~~~~~~~~~
    'navigator' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9224:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onerror' must be of type 'OnErrorEventHandler', but here has type '((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null'.

9224 declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null;
                 ~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:27967:13
    27967 declare var onerror: OnErrorEventHandler;
                      ~~~~~~~
    'onerror' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9226:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onlanguagechange' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9226 declare var onlanguagechange: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28268:13
    28268 declare var onlanguagechange: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~~~~~~~~
    'onlanguagechange' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9228:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onoffline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9228 declare var onoffline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28274:13
    28274 declare var onoffline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~
    'onoffline' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9230:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'ononline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9230 declare var ononline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28276:13
    28276 declare var ononline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~
    'ononline' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9231:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onrejectionhandled' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9231 declare var onrejectionhandled: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28284:13
    28284 declare var onrejectionhandled: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~
    'onrejectionhandled' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9232:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onunhandledrejection' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9232 declare var onunhandledrejection: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:28288:13
    28288 declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~~~
    'onunhandledrejection' was also declared here.

../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:9238:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'self' must be of type 'Window & typeof globalThis', but here has type 'WorkerGlobalScope & typeof globalThis'.

9238 declare var self: WorkerGlobalScope & typeof globalThis;
                 ~~~~

  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:27695:13
    27695 declare var self: Window & typeof globalThis;
                      ~~~~
    'self' was also declared here.


Found 28 errors in 2 files.

Errors  Files
     6  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.dom.d.ts:23
    22  ../../.nvm/versions/node/v20.15.0/lib/node_modules/typescript/lib/lib.webworker.d.ts:23

Why is this js file reloaded on each page change?

I have two page called first.html and second.html.

The template of the two page is the same except for first and second text. Is an example to understand an issue.

  • first.html:
<!doctype html>

<body hx-boost="true">
    First page!

    <a href="/second.html">Go to second page</a>

    <script src="https://unpkg.com/[email protected]"
        integrity="sha384-Y7hw+L/jvKeWIRRkqWYfPcvVxHzVzn5REgzbawhxAuQGwX1XWe70vji+VSeHOThJ"
        crossorigin="anonymous"></script>

    <script src="/test.js"></script>
</body>

</html>
  • second.html:
<!doctype html>

<body hx-boost="true">
    Second page!

    <a href="/first.html">Go to first page</a>

    <script src="https://unpkg.com/[email protected]"
        integrity="sha384-Y7hw+L/jvKeWIRRkqWYfPcvVxHzVzn5REgzbawhxAuQGwX1XWe70vji+VSeHOThJ"
        crossorigin="anonymous"></script>

    <script src="/test.js"></script>
</body>

</html>
  • test.js:
let players = 0;

If I launch a server and open the browser to http://localhost:3000/first.html and then I click on “Go to second page” link I can see in the console the error:

Uncaught SyntaxError: Identifier 'players' has already been declared (at test.js:1:1)

Why?

I expect it to be loaded just one time!

How can I fix?

How to decode or process a large byte string in Python? [closed]

I’m working with a large byte string in Python, and I’m having trouble understanding how to decode or process it. Here’s the byte string I’m working with:

data = b'nx18WV-mUKO4xoWKy9M4ZzRyNrP_x12xf9x0c03AFcWeA6A09jPzb5qrurdHl5kHgTGk8ejKJ8zjCb8T_3Ir0tyXoXOtGtRro9ozDjDA4Dgw764ek-W4IwO_3k-UpRTN9LWoevodR_A-efeORQF7orh8hgWkOHl4P1s_Dgou7Q4EfBMHGOIb_r5YnXWVU1JgK8EM06d36fvbVXLYX0K0ukY7wneTkn6RVAJ4GCFyjKTliz4_Hlsub3sGKxvYCCLzEpqfnu0M5VaLqB_6Rl2pTyxMjH5cBNrUgos0xBsZUut1z_8i3S0eByCGZuAdFiHlvFFvl3Nx-9aCA0oU70xLA8MrlTcMCdwz0mBwtUOeYf_IqB2WbUYmTL6N-CocD5d9c5Dlt3OL-chtfaol2d7Xv1TyX7JJcl6nphvtFbUtMYOSNf-2XNP7qsYAKYd1hFkRzLQw9AeBcYO0oaNnsMN8zZM5yJxCaaF3BHzFozqTVNubEW_V6dUQnh2qjsE0wi7ZEhKyHDqpN11UmXYlmgghfr2_6-KrPwRjvHjqr9TxkhqQ1eKgNS1EOdTjPZc6GorHwA8a9yVwSxvxQiCtMrCfdQL65hRKG5mRTH8pwFhx5dN7h8ZV3z1cPM-sdYka52q1LqZSGKd7Wru2yi4JbEmBixT7QShDNCzGeLudXHbQkwZpViwQedg1dj8Crjq4Q-pnBsjV3uLMJqgfZJwj68jCW2aXNcaEiXL314snTmo1__Y7QdeeXIC-8WTInCcRvcVajdwAIJY1vduiwQttQ1Mc-JV6kBNhLp6cA-4lpICFk1fOlh2582wSUIM0IHn_aOX8I5PnqtrSAoLUtw7Miivg_rath2gfd7yHZyYy0jaRZ_JM8XpmyKhu6BMmL5JNc02D13wOWW5fVZPmo5EX2qHuYXEEPW3zDYOU4BHeG95Hq0-4I9K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mEKIl0hrgRRAkggYRBAAs3RGOEaEY5ESACJAhqDYAAIABAIQQBCh0CAuKgRhDCiWEEAM0CgFJAIChUI0SjggEkiggIJkS0GxCoUpgJg8laRRBxQmE0EoDBYCUE0WAogFVXKgpA6UFxtgkEQYyAICFVRYihKRCEoIEk1LAwhGh+Ug9UYgEBSAuoKSiADQABACxFmhGABASDFcHJALBEABlFAjUlEBQgnIlPYlAsUQTICJBmZiAIgBYCIxcax01:W1tbNTAwNiw3Ml0sWzY0NjA3LDNdLFs0NTQ2NCwzXSxbMzU4MzcsMl1dXQ'

convert this string to be very useful.

Mongoose schema field wont update its values

In a Next.js project, I have the below Wallet schema :

const walletSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
      maxlength: 20,
    },
    user: { type: String, required: true },
    transactions_count: { type: Number, required: true, default: 0 },
    expenses_transactions_count: {
      type: Number,
      required: true,
      default: 0,
    },
    income_transactions_count: {
      type: Number,
      required: true,
      default: 0,
    },
    balance: { type: Number, required: true, default: 0 },
    expenses: { type: Number, required: true, default: 0 },
    income: { type: Number, required: true, default: 0 },
  },
  { timestamps: true, minimize: false }
)

walletSchema.index({ user: 1, title: 1 }, { unique: true })

walletSchema.plugin(uniqueValidator, {
  message: "{PATH} {VALUE} already exists.",
}) 

New doc is created by passing only the 2 non-defaulted values :

 const wallet = new WalletModel({ title, user })
 await wallet.save()

And the below Transaction schema :

const transactionSchema = new Schema(
  {
    wallet_id: { type: String, required: true },
    category_id: { type: String, required: true },
    user: { type: String, required: true },
    amount: { type: Number, required: true },
    type: { type: String, required: true },
    date: {
      type: String,
      default: moment().format("YYYY-MM-DD"),
      required: true,
    },
    description: { type: String, required: true },
  },
  { timestamps: true }
)

Which is created like so :

    const transaction = new TransactionModel(payload)
    await transaction.save()

I also have a pre(“save”) middleware on the Transaction where im trying to modify the Wallet field based on the incoming new Transaction document, like updating the income,expenses values, incrementing totals etc..

transactionSchema.pre("save", async function (next) {
  try {

     const wallet = await model("wallet").findOne({ _id: this.wallet_id })
      
      if(this.type === "expense"){
      wallet.balance: -= transaction.amount
      wallet.expenses: += transaction.amount
      //wallet.income: //not used here
      //wallet.income_transactions_count: //not used here
      wallet.expenses_transactions_count: expenses_transactions_count += 1
      wallet.transactions_count: number

     await wallet.save()
}

///the same for income type etc
...
    
    next()
  } catch (error: any) {
    next(error)
  }
})

For some very curious reason, the fields income_transactions_count,expenses_transactions_count and transactions_count sometimes change and sometimes dont.
The reason is that sometimes they have undefined values at the time i’m trying to modify them and the mind blowing thing is that when i log the value of wallet right after const wallet = await model... i get all the values without issues, but when i do the same thing inside the if statement, ONLY those 3 return undefined and not every time ! Sometimes they have their correct values as expected !