Why I’m getting res is not defined error using i81n for node JS express and cannot switch between languages?

I’m new to Node JS, I have problem with it using localization i18n for Node JS and express also I’m using ejs as my view engine..

My locals files like this:

en.json

{
   "test": "this is a test",
}

fr.json

{
   "test": "c'est un test",
}

My server.js simply like this:

const express = require('express');
const app = express();
const i18n = require('i18n');

i18n.configure({
    locales: ['en', 'fr'], 
    directory: __dirname + '/locales', 
    defaultLocale: 'en', 
    cookie: 'lang',
});

app.use(i18n.init);
app.set('view engine', 'ejs');

app.get('/', (req, res, next) => {
    res.render('index');
});

app.listen(3000);

My index.ejs is:

<!DOCTYPE html>
<html lang="<%= res.locale %>">

   <head>
      <meta charset="UTF-8">
      <title>Test App</title>
   </head>

   <body>
      <h1><%= res.__('test') %></h1>     
   </body>

</html>

Finally, my express server is properly running without localization.

Now after setting it up for localization and running it again I got those errors!

  1. res is not defined in <html lang="<%= res.locale %>">
  2. res is not defined in <h1><%= res.__('test') %></h1>

If I try to remove the res. it’s working however the language is not changing!

So how to rectify this problem and how can I hardcode shifting between the langauges like by changing defaultLocale: 'fr' or i18n.setLocale('fr') ?

How to mock node-cron job in jest

I have a node application typescript based where I am running a cron job. It is being called when the server starts.

I am writting UT’s for this file but I am unable to mock the node-cron module. Any leads will be very helpful.

import { Log, LoggerInterface } from '@emileap/node-logger';
import { RetryKafkaConsumerGroup } from '../lib/kafka';
import * as Cron from 'node-cron';
import { env } from '../env';
import { mask } from '../env/helpers';
import { SubscriberStatus, getSubscriberByStatus } from '../lib/utils';

export class SubscriberRetryCronLoader {
        public brokenSubscribers: {[key: string]: any };
        public cronJob: any;
    constructor(
        @Log(__filename) private log: LoggerInterface
    ) {}

    public async retryBrokenSubscribers(): Promise<any | undefined> {
        try {
            const subscribers = await getSubscriberByStatus(SubscriberStatus.CircuitBroken);
            this.brokenSubscribers = {};
            this.log.info(`No of broken subscribers found retry cron loader: ${subscribers.length}`);
            subscribers.forEach((subscriber) => {
                const { subscriberId, callbackUrl, callbackMethod, types, updatedAt, financialId, channelId } = subscriber;
                const cgConfig = {
                    id: `${subscriberId}$${updatedAt}`,
                    groupId: `${env.kafka.consumerGroupPrefix}${subscriberId}`,
                    topics: types,
                    subscriberId,
                    financialId,
                    channelId,
                    callbackUrl,
                    callbackMethod,
                };

                this.log.info(`Retrying broken subscriber: ${mask(cgConfig.subscriberId)}$${updatedAt}`);
                this.brokenSubscribers[cgConfig.id] = new RetryKafkaConsumerGroup(cgConfig);
            });
        } catch (error: any) {
            this.log.error('Failure while retrying broken subscribers', error);
        }
    }

    public async startCronProcess(): Promise<any | undefined> {
        this.cronJob = Cron.schedule('* * * * *', this.retryBrokenSubscribers.bind(this));
        await this.retryBrokenSubscribers();
    }

    public destroyCronJob(): any {
        this.cronJob.destroy();
    }
}

Google Apps script : Exceeded maximum execution time

When copying a range of cells from one Google spreadsheet to another, if the number of rows is more than 20,000, an error appears: Exceeded maximum execution time.

  `function copySheetData2LTP() {  
  var sourceFolderId_2LTP = 'Id_from';  
  var sourceFileName = getCurrentYearAndMonth();
  var sourceSheetName = 'from';  

  var targetFolderId_2LTP_repeat = 'Id_to';
  var targetFileName = getCurrentYearAndMonth();  
  var targetSheetName = 'to';  

  var sourceFolder = DriveApp.getFolderById(sourceFolderId_2LTP);  
  var sourceFileIterator = sourceFolder.getFilesByName(sourceFileName);  
  var sourceFileId = '';

  while (sourceFileIterator.hasNext()) {
    var sourceFile = sourceFileIterator.next();
    sourceFileId = sourceFile.getId();
    break;
  }

  var sourceSpreadsheet = SpreadsheetApp.openById(sourceFileId);   
  var sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);  

  var targetFolder = DriveApp.getFolderById(targetFolderId_2LTP_repeat);
  var targetFileIterator = targetFolder.getFilesByName(targetFileName);
  var targetFileId = '';
  while (targetFileIterator.hasNext()) {
      var targetFile = targetFileIterator.next();
      targetFileId = targetFile.getId();
      break;
  }  
 var startRow = 1;
 var numColumns = 10; // Вставить только первые 10 столбцов до J        
 var batchSize = 50000; // Количество строк, обрабатываемых за одну операцию

 var sourceSpreadsheet = SpreadsheetApp.openById(sourceFileId);   
 var sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);  
 var numRows = sourceSheet.getLastRow();

 var targetSpreadsheet = SpreadsheetApp.openById(targetFileId);
 var targetSheet = targetSpreadsheet.getSheetByName(targetSheetName);
 clearSheet(targetSheet);

 for (var startBatchRow = startRow; startBatchRow <= numRows; startBatchRow += batchSize) {
 var endBatchRow = Math.min(startBatchRow + batchSize - 1, numRows); 

 var rangeToCopy = sourceSheet.getRange(startBatchRow, 1, endBatchRow - startBatchRow + 1, numColumns);
 var sourceValues = rangeToCopy.getValues();

 var targetRange = targetSheet.getRange(startBatchRow, 1, endBatchRow - startBatchRow + 1,         numColumns);
 targetRange.setValues(sourceValues);
  }
}` 

The script execution time is 5 minutes, after which an error appears

How to stop a button from being clicked again when I press the enter key after clicking it

<body>
    <button id="aButton">A button</button>

    <script>
        document.querySelector("#aButton").addEventListener("click", () => {
            console.log("Button clicked!");
        })
    </script>
</body>

I have a simple button that logs “Button clicked!” to the console when it is clicked. If I click that button and then press the enter key, the button is clicked again and the “Button clicked!” message is logged to the console a second time. How can I stop that? I don’t want the button to be clicked via the enter key, because I will be using the enter key for other purposes.

Is Promise.allSettled() response array sequence is same as promise array [duplicate]

I’m trying to call an api multiple times for different parameters. So I use Promise.allSettled something like this :

const allPromises = orderEligibleTxA?.map(async (transactionAccountId: string) => {
  return updateBulkEntitlementV2(transactionAccountId);
  });
const bulkReactivateResponse = await Promise.allSettled(allPromises);

I can see that the order of bulkReactivateResponse is same as the order of the promise array. But I’m not sure if order of the response will always be same as order of the promise array

How to make Custom Marquee in our react native app?

I need to make Marquee for our react-native app. I already tried many third party library. But all the library contains only one direction i.e. right-to-left, but I want to make marquee for both directions. Below is my code, I also tried react-native-reanimated library for making custom marquee, but not works. Please help

// Marquee.js file
import React, { useRef, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Animated, {
  useSharedValue,
  withSpring,
  useAnimatedStyle,
  useAnimatedScrollHandler,
} from 'react-native-reanimated';
 
const Marquee = ({ text, direction }) => {
  const scrollX = useSharedValue(0);
  const scrollRef = useRef(null);
 
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTo({ x: direction === 'left' ? 500 : -500, animated: false });
      scrollX.value = direction === 'left' ? 500 : -500;
      scrollRef.current.scrollTo({ x: 0, animated: true });
    }
  }, [direction]);
 
  const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event) => {
      scrollX.value = event.contentOffset.x;
    },
  });
 
  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: withSpring(scrollX.value, { stiffness: 50 }) }],
    };
  });
 
  return (
    <View style={styles.container}>
      <Animated.ScrollView
        ref={scrollRef}
        horizontal
        showsHorizontalScrollIndicator={false}
        onScroll={scrollHandler}
        scrollEventThrottle={16}
      >
        <Animated.View style={animatedStyle}>
          <Text style={styles.text}>{text}</Text>
        </Animated.View>
      </Animated.ScrollView>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
    width: '100%',
  },
  text: {
    fontSize: 16,
  },
});
 
// App.js File 
import React from 'react';
import { View, StyleSheet } from 'react-native';
import Marquee from './Marquee';
 
const App = () => {
  return (
    <View style={styles.container}>
      <Marquee text="This is a left-to-right marquee" direction="left" />
      <Marquee text="This is a right-to-left marquee" direction="right" />
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;

Discord bot 3rd party API OAuth2 integration

I’m working on a Discord bot that is supposed to return, via the Canvas LMS API, lists of user courses, assignment notifications, etc. The easiest way to do this is probably asking the user to provide their canvas authentication token through the bot, but that’s obviously against who knows how many terms of services lmao.

I’m somewhat familiar with OAuth2 workflow but am very confused about how to implement one with the discord bot as my app and the canvas class details as my protected resource. I’m also confused on how to implement an OAuth2 workflow without a user or web interface, as a discord bot is more of a CLI-type thing. Also very confused regarding the redirect_uri for canvas when there is no web interface or website for the authentication process.

Tried the OAuth2 workflow by attempting a Canvas GET request, using this endpoint:
https:///login/oauth2/auth?client_id=XXX&response_type=code&redirect_uri=https://example.com/oauth_complete&state=YYY&scope=<value_1>%20<value_2>%20<value_n>
via Postman. Endpoint info can be found here: https://canvas.instructure.com/doc/api/file.oauth_endpoints.html#get-login-oauth2-auth

Not sure what to put for client_id as canvas only lets me create an access token. Also confused on what to put for redirect_uri because my app isn’t web based.

Any help is greatly appreciated. Thanks!

ASSERTION ERROR: token must be defined [Expected=> null != undefined <=Actual]

While running my project in local server its working perfectly without error but when i build it and open on beta i start to get this error can anyone help me with this and below is the error message i am getting in console (https://i.stack.imgur.com/G4XkR.png)

i have searched online but i didnt got exactly anything related to my error.One post on reddit its says by updating angular version solved the issue and the version that i am using is angular 14

How to overwrite global variables in Jmeter

I am trying to execute a jmx file in such a way if the Report_Status goes to false it should overwrite initially declared global variable value as well
heres my code

var Status = WDS.vars.get("ReportStatus");
WDS.log.info("Original ReportStatus: " + Status);
Status = "fail";
WDS.vars.put("ReportStatus", Status);
WDS.log.info("Updated ReportStatus: " + 
WDS.vars.get("ReportStatus"));

it is updating in log.info but it is not overwritng in user defied variables below

Please view image for clear understanding

What is the best library way to control frames of an animated logo?

So I’m making an animated logo for a website of the name in neon lights. I wanted it to start off, the letters turn on one at a time, one letter vibrate, and then have certain sections of frames I can choose at random with javascript that all continue repeating on timers etc of letters periodically flickering.

I’ve done something similar using PNG sprite sheets sheets and Javascript and I see that is the answer in all the other posts like this, but I was just wondering if anyone has come up with a way of controlling frames of GIF like this.

I wouldn’t ask but the most recent question about this was from 10 years ago and I think it’s crazy that we haven’t come up with a solution for something like this yet. Is sprite sheet still the best way to go? I was thinking of using video / mp4 but I want it to support transparent background.

I’ve looked at all the other posts on here but they were all from 10+ years ago.

Phaser3 preFX addGlow doesn’t work with scaling

I’m trying to use Phaser3 .. currently tried 3.70 and the 3.80 beta with no avail.
If I try to use someSprite.preFX.addGLow() it works when there is no scaling, but
if I use scaling the sprites completely disappear.

Config that doesn’t work:

    const config = {
    type: Phaser.AUTO,
    backgroundColor: '#000000',
    scale: {
        mode: Phaser.Scale.RESIZE,
        width: 640,
        height: 960,
        min: {
            width: 320,
            height: 480
        },
        max: {
            width: 1400,
            height: 1200
        }
    },
    scene: [ BGScene, GameScene, UIScene ],
    fx: { // Glow FX settings... 
        glow: {
            distance: 32,
            quality: 0.1
        }
    },
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 300 },
            debug: false
        }
    }
};

and this is the attempt to add glow to the sprite

    this.player = this.physics.add.sprite(100, 800, 'dude');

    this.player.preFX.setPadding(32);
    const fx = this.player.preFX.addGlow();

    this.tweens.add({
        targets: fx,
        outerStrength: 10,
        yoyo: true,
        loop: -1,
        ease: 'sine.inout'
    });

any suggestions what’s wrong? If I use postFX it does render, but the Phaser examples I saw (without scaling) had suggested preFX.

How to grow/shrink widely a container’s width based on scroll till it reaches top of the screen?

My code is working at some extent like for medium screens it looks good, but for bigger screens like 1920*1080, I can see much gap at left and right side even Im very close to the top of the screen. When top reaches, it suddenly fills the right and left gap. For small screens like small laptops and tabs, I can see the container’s width occupies 100% width before even reaching top of the screen. Below is my implemented code, please suggest some solution.

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

const Template = () => {
const [scrollPercentage, setScrollPercentage] = useState(0);
const [isAtTop, setIsAtTop] = useState(false);

const isMobileView = window.innerWidth < 768;

const handleScroll = () => {
const scrollPosition = window.scrollY;
const percentage = (scrollPosition / window.innerHeight) * 100;
setScrollPercentage(percentage);

const expandableContainerTop = document.querySelector(".expandable-         container").getBoundingClientRect().top;
setIsAtTop(expandableContainerTop <= 0);
};

useEffect(() => {
window.addEventListener("scroll", handleScroll);

return () => {
  window.removeEventListener("scroll", handleScroll);
};
}, []);

useEffect(() => {
if (isAtTop) {
  alert("Media container reached the top of the screen!");
}
}, [isAtTop]);

const calculateWidth = () => {
const baseWidth = isMobileView ? 100 : 80;
const maxScrollPercentage = 20;
const dynamicWidth = isAtTop ? 100 : baseWidth + Math.min(scrollPercentage * 0.3,                                                               maxScrollPercentage);
return `${dynamicWidth}vw`;
};

return (
<div className="shoaib-rebrand">
  <section className={`one-col-container column-container is-expandable`}>
    <div
      style={{
        marginBottom: "200px",
        background: "linear-gradient(to top, #FFF 0%, #FFF 10%, #2A5B6C 10%, #2A5B6C 100%)",
      }}
    >
      <div
        className={`${isFluid ? "fluid-container" : "container"} pt-${topPadding} pb-$.  {bottomPadding}`}
        style={{ maxWidth: "100%" }}
      >
        <div className="row justify-content-md-center">
          <div className={`col-${isMobileView ? 12 : col}`}>
            <div className="text-center pb-6 pt-6 inverse-color">
              <h1> This is the header title</h1>
              <p>
                There are many variations of passages of Lorem Ipsum
                available, but the majority have suffered alteration in some
                form, by injected humour, or randomised words which don't
                look even slightly believable.
              </p>
            </div>
          </div>

          {isExpandable && (
            <div
              className={`expandable-container col-${expandableCol} ${scrollPercentage}`}
              style={{
                width: calculateWidth(),
              }}
            >
              <div style={{ backgroundColor: "lightgray", height: "100%" }}></div>
            </div>
          )}
        </div>
      </div>
    </div>
    <div
      className="expandable-container"
      style={{
        backgroundColor: "lightgray",
        marginTop: "100px",
        height: "1000px",
        width: "100%",
      }}
    ></div>
   </section>
   </div>
);
};

export default Template;

Trying to understand p-queue concurrency

So I’m trying to use p-queue under nodejs to spin up a bunch of API calls; however, I don’t want them to get to out of control and bring down the server. So the through was that I would set the concurrency to only run a few at a time. But it didn’t work out that way and I’m trying to understand why.

If there is no concurrency restriction my counter passes to my function as expected.

// No concurrency
import PQueue from 'p-queue';
console.time('bunch-of-stuff');

var queue = new PQueue();

    for (var i = 1; i <= 5; i++) {
        console.log(i);
        queue.add(() => httpProcess(i));
    }

console.timeEnd('bunch-of-stuff');

function httpProcess(pageNumber) {  

    console.log('Done: ' + pageNumber);
}

Output:
1
Done: 1
2
Done: 2
3
Done: 3
4
Done: 4
5
Done: 5
bunch-of-stuff: 9.385ms

If I set a limiting concurrency value the number of sessions set by the concurrency work perfectly; however, all remaining receive the value of the counter after the count has finished.

// Set concurrency to 1
import PQueue from 'p-queue';
console.time('bunch-of-stuff');

var queue = new PQueue({concurrency: 2});

    for (var i = 1; i <= 5; i++) {
        console.log(i);
        queue.add(() => httpProcess(i));
    }

console.timeEnd('bunch-of-stuff');

function httpProcess(pageNumber) {  

    console.log('Done: ' + pageNumber);
}

Output:
1
Done: 1
2
Done: 2
3
4
5
bunch-of-stuff: 10.596ms
Done: 6
Done: 6
Done: 6

Help. Any thoughts would be appreciated. I’m just trying to understand why I loose my count on any number over and beyond the concurrency value.

Framer Motion apply two properties in one component

I know you can defintely apply one variant in tag but how can i apply two varient in single tag?


<Slider>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 512 512"
          onClick={decreaseIndex}
        >
          <path d="M512 256A256 256 0 1 0 0 256a256 256 0 1 0 512 0zM217.4 376.9L117.5 269.8c-3.5-3.8-5.5-8.7-5.5-13.8s2-10.1 5.5-13.8l99.9-107.1c4.2-4.5 10.1-7.1 16.3-7.1c12.3 0 22.3 10 22.3 22.3l0 57.7 96 0c17.7 0 32 14.3 32 32l0 32c0 17.7-14.3 32-32 32l-96 0 0 57.7c0 12.3-10 22.3-22.3 22.3c-6.2 0-12.1-2.6-16.3-7.1z" />
        </svg>
        <AnimatePresence initial={false} onExitComplete={toggleLeaving}>
          <Row
            variants={(rowFowardVariants, rowBackwardVariants)}
            initial={("Fhidden", "Bhidden")}
            animate={("Fvisible", "Bvisible")}
            exit={("Fexit", "Bexit")}
            transition={{ type: "tween", duration: 1 }}
            key={index}
          >
            {data.results
              .slice(offSet * index, offSet * index + offSet)
              .map((tv) => (
                <Box
                  key={tv.id}
                  bgphoto={makeImagePath(tv.poster_path, "w500")}
                ></Box>
              ))}
          </Row>
        </AnimatePresence>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 512 512"
          onClick={increaseIndex}
        >
          <path d="M0 256a256 256 0 1 0 512 0A256 256 0 1 0 0 256zM294.6 135.1l99.9 107.1c3.5 3.8 5.5 8.7 5.5 13.8s-2 10.1-5.5 13.8L294.6 376.9c-4.2 4.5-10.1 7.1-16.3 7.1C266 384 256 374 256 361.7l0-57.7-96 0c-17.7 0-32-14.3-32-32l0-32c0-17.7 14.3-32 32-32l96 0 0-57.7c0-12.3 10-22.3 22.3-22.3c6.2 0 12.1 2.6 16.3 7.1z" />
        </svg>
      </Slider>

const rowFowardVariants = {
  Fhidden: {
    x: window.innerWidth,
  },
  Fvisible: {
    x: 0,
  },
  Fexit: {
    x: -window.innerWidth,
  },
};

const rowBackwardVariants = {
  Bhidden: {
    x: -window.innerWidth,
  },
  Bvisible: {
    x: 0,
  },
  Bexit: {
    x: window.innerWidth,
  },
};

So I’m trying to create a backward and forward buttons with framer motion, how can I apply two framer motion properties in the Row tag? and is there any document about two properties in one component

I tried to [(“”,””)], but it won’t work