Swap vs concatenation in javascript

In this example I am swapping first and last characters of a given string .
Which approach is more faster ? provided that the string length is 3 characters long .


function concatenation(string){

    let newString = string[2]+string[1]+string[0];
    console.log(newString);
}

function swap(string) {

    let array = string.split('');
    let last = array[2];
    let temp = array[0];
    array[0]=last;
    array[2] =temp;
    console.log(array.join(''));
}


swap("ABC");
concatenation("ABC");

How can I create a function that takes any number of tables as arguments? (Excel Script Lab)

I have this function in Excel Script Lab:

Libraries

https://appsforoffice.microsoft.com/lib/1/hosted/office.js
@types/office-js

[email protected]/dist/css/fabric.min.css
[email protected]/dist/css/fabric.components.min.css

[email protected]/client/core.min.js
@types/core-js

[email protected]
@types/[email protected]

Script:

/**
 * Create a list.
 * @customfunction
 * @param name string
 * @param args {string[]}
 */
function datatablex(display: string, ...args: string[]): any {
  const entity = {
    type: "Entity",
    text: display,
    properties: {
      Nombre: {
        type: "String",
        basicValue: display,
        propertyMetadata: {
          excludeFrom: {
            cardView: true
          }
        }
      }
    }
  };

  for (let i = 0; i < args[0].length; i += 2) {
    const name = args[0][i + 0];
    const value = args[0][i + 1];

    entity.properties[name] = {
      type: "String",
      basicValue: value
    };
  }
  return entity;
}

This function allows me to create a DataType: Entity with the parameters given in the function as arguments. Currently, this function takes a string which will be the displayed text in the cell, and then any number of arguments. These extra arguments always come in couples. The first is the name of the value and the second is the value itself. This repeats many times if you add many more parameters. Below is an image showing an example:

Current Example

My problem is that the extra arguments are currently strings and instead I want them to be tables (two dimensions each). I tried making changes in the function:

  • Replace the string[] with string[][] and even string[][][]
  • Replace the property “String” type to “Array” and basicValue to elements.
  • Replace the args[0][i + 0] stuff with more [].
    However, I couldn’t make it work. Sometimes it gives #Value! and others “Calc! depending on what I change. Below is an image explaining the imputs I want:

Example imputs

Below is an example of the output I want (I created it manually, not using the function cause obviously it doesn’t work)

Example output

Example when clicking one of the tables.

Example ouput inside

Refresh marker google maps on apache server

Can’t refresh marker only. Without refreshing whole google map. Location is sent every 10 seconds from esp32 to apache server. I just can’t refresh markers only. The only way to refresh marker position is to refresh whole map0 which is not my goal. I’d like to refresh only markers without reloading whole map or website.

Please HELP. =)

<?php foreach($rows as $row){ ?>


    var location = new google.maps.LatLng(<?php echo $row['lat']; ?>, <?php echo $row['lng']; ?>);
    function refreshMarker(){

// if marker exists and has a .setMap method, hide it
  function SetMarker(location, map) {
    //Remove previous Marker.
    if (marker == null) {
        marker.setMap(null);
    }
}
    //marker.setMap(map);
    var marker = new google.maps.Marker({
        position: location,
        icon: betw,
        title:"<?php echo $row['lat']; ?>, <?php echo $row['lng']; ?> , <?php echo $row['time']; ?> , <?php echo $row['altitude']; ?> m, <?php echo $row['speed']; ?> km/h, <?php echo $row['temperature']; ?> °C",
        map: map
    });
    
 setTimeout(refreshMarker, 1000);}
 refreshMarker();

            
<?php } ?>  

🔍 Need Suggestions for Beginner-Friendly Open Source Repositories

I’m a beginner in open source contributions and looking for beginner-friendly repositories where I can make meaningful contributions.
So far, I’ve contributed to freeCodeCamp and The Odin Project. Now, I’m hoping to work on projects where I can contribute more actively and improve my skills through real collaboration.

Languages I’m comfortable with:

  • JavaScript

  • TypeScript

If you know any good repositories (with good documentation, beginner-friendly issues, or active maintainers), I’d love your suggestions.

TradingView Lightweight Chart crosshair tooltip time

type here

I am creating a algo trading platform which uses tradingView lightweight chart. I have now run into a issue wherein all the time shown on x axis is correctly being displayed in IST and the tooltip correctly shows date as per IST but shows the time in UTC.

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }

  const utcDate = new Date(param.time * 1000);
  const istTime = new Date(utcDate.getTime() + (5.5 * 3600 * 1000));
  const day = String(istTime.getDate()).padStart(2, '0');
  const month = istTime.toLocaleString('en-IN', { month: 'short' });
  const year = istTime.getFullYear();
  const hours = String(istTime.getHours()).padStart(2, '0');
  const minutes = String(istTime.getMinutes()).padStart(2, '0');
  const seconds = String(istTime.getSeconds()).padStart(2, '0');

  div.textContent = `${day}-${month}-${year} ${hours}:${minutes}:${seconds}`;
});

and

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }

  const date = new Date(param.time * 1000);
  const options = {
    timeZone: 'Asia/Kolkata',
    year: 'numeric', month: 'short', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
  };
  const istString = date.toLocaleString('en-IN', options);

  div.textContent = istString;
});

and

chart.subscribeCrosshairMove(param => {
  const div = document.getElementById('crosshairTimeDisplay');
  if (!param.time) {
    div.textContent = '';
    return;
  }

  const date = new Date(param.time * 1000);
  const formatter = new Intl.DateTimeFormat('en-IN', {
    timeZone: 'Asia/Kolkata',
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });

  div.textContent = formatter.format(date);
});

Puppeteer-extra, TimeoutError doesn’t seem to exist

This is a followup question to this one, which resolves a missing definition of TimeoutError in my puppeteer code. Thing is, I want to use puppeteer-extra, and despite being a lightweight wrapper for puppeteer it seems to be causing a difficulty in getting hold of TimeoutError. Here’s an SSCCE that should demonstrate the problem; I get TypeError: Right-hand side of 'instanceof' is not an object. My package.json states version 23.7.1 (I have no idea what version of puppeteer-extra I’m running as I don’t know where to look).

const puppeteer = require("puppeteer-extra");

let browser;
(async () => {
  const stealthPlugin = require('puppeteer-extra-plugin-stealth');
  puppeteer.use(stealthPlugin());

  browser = await puppeteer.launch();
  const [page] = await browser.pages();

  try {
    await page.goto("https://www.example.com", {timeout: 1}); // short timeout to force a throw
  }
  catch (err) {
    if (err instanceof puppeteer.TimeoutError) {
      console.log("caught timeout error", err);
    }
    else {
      console.log("caught non-timeout error", err);
    }
  }
})()
  .catch(err => console.log(err))
  .finally(() => browser?.close());
  

(I’m using console.log() instead of console.error() because my client code can’t get hold of anything in the error stream)

Grateful thanks for any help resolving this!

Verification Email not saving to runtime/mail folder

I recently installed a fresh install of linux with a LAMP stack (w/php8). I installed composer2. I created an advanced-app using the instructions provided on the Yii site. Ran init file (production). Made the DB, etc. So basically, a clean/default install of everything.

When I try to “Sign Up” in the frontend, the DB table gets the record, but the email isn’t saved into the runtime/mail folder. Actually NO ‘mail’ folder is created. I even tried to add it manually, no luck.

The common/config/main-local.php:

        'mailer' => [
            'class' => yiisymfonymailerMailer::class,
            'viewPath' => '@common/mail',
        ]

Everything I see, says that saving to a file is the default and this should work.

Do I need to add. 'useFileTransport' => true, or should it be working?

I’m thinking “maybe” a permissions problem. App was created from terminal with root access. I have chown to wwwrun:www, but still no luck.

C HTTP SERVER PHP INTEGRATION [closed]

I m actually making an http server in C.
It started just for fun, then I’ve set up the epoll system, the post request handler with the data parser all from scratch.
Now my concern is how to handle php code in my server using FastCGI.
Can someone explain the process?

Google TTS stealing the first few ms of a script – but not the way I would think

I’ve built a PHP service that calls Google Cloud Text-to-Speech and writes the audioContent (base64-decoded) directly to an MP3 file. When I prepend a hard-coded phrase (e.g. “Ein Moment der Ruhe…”m which is the same phrase that laters apears as the dynamic text) it comes through perfectly–no words lost–but as soon as my dynamic text begins, the first 1–2 words are always faded in or cut. So they are not the first words anymore but are still “faded in”.

I’ve tried adding an SSML in the beginning or in between, but the same issue persists whenever I play back the MP3 that Google returns.

I’m on shared hosting so I’d prefer to consume Google’s MP3 directly instead of running a conversion pipeline myself. What else can I try to guarantee the very first syllable of dynamic text isn’t lost?

namespace AppServices;

class GoogleTtsService extends TtsService
{
    private const API_URL = 'https://texttospeech.googleapis.com/v1/text:synthesize';

    public function synthesize(string $text, array $options, string $outputPath, string $apiKey): bool
    {
        $breakMs      = defined('TTS_INITIAL_BREAK_MS') ? TTS_INITIAL_BREAK_MS : 100;
        // This hard-coded phrase plays fine
        $ssml = '<speak>'
              . 'Ein Moment der Ruhe...'
              . '<break time="'. $breakMs .'ms"/>'
              . htmlspecialchars($text, ENT_QUOTES|ENT_XML1, 'UTF-8') // this never plays fine
              . '</speak>';

        $payload = [
            'input'       => ['ssml' => $ssml],
            'voice'       => [
                'languageCode' => $options['language'] ?? 'de-DE',
                'name'         => $options['voice']    ?? 'de-DE-Standard-A'
            ],
            'audioConfig' => [
                'audioEncoding'   => 'MP3',
                'speakingRate'    => $options['speed']  ?? 1.0
            ]
        ];

        $response = $this->postJson(self::API_URL . '?key=' . urlencode($apiKey), $payload);
        if (empty($response['audioContent'])) {
            return false;
        }

        $audioData = base64_decode($response['audioContent']);
        return file_put_contents($outputPath, $audioData) !== false;
    }
}

Relevant debug log:

[28-Jun-2025 00:15:21] TTS chunk for job 311: text length=4159
[28-Jun-2025 00:15:21] SSML sent (first 100 chars): 
   <speak>Ein Moment der Ruhe...<break time="100ms"/>Ein Moment der Ruhe am Morgen. Ein bewu…

How to avoid stale closures inside useEffect with setInterval in React?

I’m trying to use setInterval inside a useEffect hook in a React functional component to perform a repeated task (like updating a counter or fetching data periodically). However, the callback inside setInterval seems to use stale state — it’s not accessing the most recent value of my state variable.

Even though the state updates correctly, the interval callback always logs the initial state instead of the updated one. This leads to unexpected behavior in my app.

import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      console.log('Current count:', count); // This always logs 0
      setCount(prev => prev + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return <div>{count}</div>;
}

In this, console.log(count) always logs 0, even though the UI shows the count increasing.

What I tried

  • Moving setInterval outside the useEffect (not possible because I need lifecycle management).

  • Including count in the dependency array — but that causes multiple intervals to be created.

  • Using useRef to store the latest state — seems promising, but not sure how to implement it correctly.

What I want to know

  • Why does this stale closure issue happen in useEffect?

  • What’s the correct and efficient way to ensure that the interval callback always has access to the latest state?

  • Is useRef the right approach? Are there other React best practices to handle this?

Why in D365 Handler of properties Im getting the following error formContext.getAttribute is not a function?

I have the following TypeScript function. It’s successfully hiding the test1 field on form load, as I’m calling the function on load and passing the execution context in a Dynamics CRM form.

However, I’m trying to achieve the following behaviour: when the testisCompleted field is changed to “Yes”, I want to show the header_process_test1date field. The issue I’m facing is that when the onChange event fires, I get an error saying: formContext.getAttribute is not a function

Could anyone help me understand why this is happening and how to fix it? Thanks in advance!

export function onContractPrepStage(executionContext: Xrm.Events.EventContext) {
    const formContext = executionContext.getFormContext();

    const testisCompleted = formContext.getAttribute("test1")?.getValue();
    const ctrl = formContext.getControl<Xrm.Controls.OptionSetControl>("header_process_test1date");

    if (testisCompleted) {
        ctrl?.setVisible(true);
    } else {
        ctrl?.setVisible(false);
    }
}

handleAuth is not a function with @auth0/nextjs-auth0 v4.x in Next.js App Router / Pages Router

I am trying to integrate Auth0 authentication in a Next.js project using the official @auth0/nextjs-auth0 package (v4.7.0).
I carefully followed both the official documentation and several community guides.
I tried both of these setups:

  1. Using the App Router, created src/app/api/auth/[…auth0]/route.ts.
  • Used the documented import:
    import { handleAuth } from '@auth0/nextjs-auth0'; export const GET = handleAuth(); export const POST = handleAuth();
  1. Result: Always get TypeError: handleAuth is not a function or Module ‘”@auth0/nextjs-auth0″‘ has no exported member ‘handleAuth’.

  2. Using the Pages Router; vreated /pages/api/auth/[…auth0].ts (and tried .js as well)

Tried both
import { handleAuth } and const { handleAuth } = require(...)

  1. Result:

If using import, Next.js throws “Module parse failed: ‘import’ and ‘export’ may appear only with ‘sourceType: module’”.

If using require, I get Module not found: ESM packages (@auth0/nextjs-auth0) need to be imported.

I also tried multiple package versions (e.g., 2.x, 4.7.0, 4.0.0), cleaning node_modules, deleting lock files, and using both JS and TS files, but always end up with either a 404, 500, or the above TypeErrors.

To be able to use Auth0’s handleAuth in either App Router or Pages Router as shown in the docs, and get a working authentication endpoint .

Why does Parcel intermittently fail to recognize modules or .env variables in my React project?

I’m using Parcel in a React project, and I’m running into frequent and inconsistent build issues.

The project works fine one moment, but after making a small change (like importing a hook or updating a file), Parcel suddenly throws errors such as:

Cannot find module ‘react’ – even though react is installed and present in node_modules

.env variables like process.env.BEARER_TOKEN return undefined, even though the exact same code was working before

Some examples:
I added useEffect from “react” and Parcel failed to recognize the react module, breaking the build

I used process.env.BEARER_TOKEN in my API call – initially it worked, then suddenly it broke and returned undefined; when I hardcoded the token, it worked again. But later, without any changes, process.env.BEARER_TOKEN started working fine again

Occasionally, Parcel fails to rebuild unless I:

Delete .parcel-cache

Delete and reinstall node_modules

My setup:
Parcel version: ^2.15.2

React version: 19.1.0

OS: Microsoft Windows [Version 10.0.26100.4351]

My .env file (at project root):

BEARER_TOKEN=yuJhbG… (no quotes or spaces) [this is just example token]

My API options in code:

export const API_OPTIONS = {
method: ‘GET’,
headers: {
accept: ‘application/json’,
Authorization: Bearer ${process.env.BEARER_TOKEN?.trim()},
},
};

What I’ve tried:
Restarting Parcel dev server (npx parcel index.html)

Deleting .parcel-cache

Reinstalling node_modules

Restarting my IDE (VS Code)

Confirmed .env is correctly formatted and at the root

Ensuring I’m not using stale cached tokens or module imports

My question:
Why is Parcel behaving so inconsistently with module resolution and .env variables?

Is this expected behavior? Is there a known issue with Parcel’s caching or environment variable injection?

How can I make my development environment more stable and predictable?

Any insights or best practices for working with Parcel in React projects would be appreciated!