NodeJS Fork Balancer

I have read one of the article long back for solving high memory usage task in a separate child process. Based on the article I have implemented the same and latency has been reduced. But currently facing an wired issue.

Problem Statement: Fastify server – Browser will make a request to fastify server and in fastify I need to make 100+ parallel axios api calls to the downstream(Dont ask why Im dng- currently we have some challenges) and Ill return the response to the browser once all the api call are success. The latency issue arises due to these parallel API calls, particularly when there’s a higher TPS (transactions per second) to the Fastify server.

Solution: In an attempt to mitigate the latency issue, I endeavored to offload the logic for parallel calls to a child process using NodeJS’s Fork functionality. As expected, this reduced latency. However, the current issue I’m facing is that when there are numerous parallel requests to my server, approximately 60% of these requests receive incorrect responses.

enter image description here

Implementation:
ForkBalancer.js

import { ChildProcess, fork } from 'child_process';

const requestLimit = 0;

interface forkResponse {
  kill: boolean;
  string?: string;
}

class ForkBalancer {
path: string;
forks: number;
maxRAM?: number;
args?: Array<string>;

private activeFork: number;
private resolvers = new Map();
private renderers: Array<ChildProcess>;

constructor({ path = '', forks = 5, maxRAM = 250, args = [] }) {
    this.activeFork = 0;
    this.forks = forks;
    this.maxRAM = maxRAM;
    this.path = path;
    this.args = args;
    this.renderers = Array.from({ length: forks }, () => this.createFork());
}

public getFromRenderer(params: any): Promise<forkResponse> {
    const { resolvers, maxRAM, activeFork, restartFork, renderers } = this;
    const renderer = renderers[activeFork];

    return new Promise(function(resolve, reject) {
        try {
            renderer.once('message', (res: any) => {
                resolvers.delete(params.request.url);
                resolve(res);

                if (res.kill) restartFork();
            });

            if (!resolvers.has(params.request.url)) {
                renderer.setMaxListeners(requestLimit);
                resolvers.set(params.request.url, resolve);
                renderer.send({ ...params, maxRAM });
            }
        } catch (error) {
            resolvers.delete(params.request.url);
            reject(error);
        }
    });
}

private createFork = () => {
    const { path, args } = this;
    return fork(path, args);
};

private restartFork = () => {
    const { activeFork, renderers, next, createFork } = this;
    const renderer = renderers[activeFork];
    next();
    renderer.kill();
    this.renderers[activeFork] = createFork();
};

private next = () => {
    const { activeFork, forks } = this;
    if (activeFork === forks - 1) {
        this.activeFork = 0;
    } else {
        this.activeFork++;
    }
};
}
export default ForkBalancer; 

ParalllelAPI.js

import axiosInstance, { AxiosRequestConfig } from 'axios';

const maxRAM = 128
process.on('message', async (params: any) => {
  const { totalPages, offset: offsetProps = 0, PAGE_SIZE_LIMIT, request, body, testId, url } = params;
  const requests = [];
 for (let offset = offsetProps; offset <= totalPages; offset++) {
   requests.push(
      axiosInstance.post(
    `API_URL/search/v2?page=${offset}&limit=${PAGE_SIZE_LIMIT}`,
    body,
    {
      headers: {
        accept: 'application/json',
        authorization: `${request.token?.token_type} ${request.token?.access_token}`,
      }
    },
  )
);
}
const results = await Promise.allSettled(requests);

const list: any = [];
let isPartialFailed = false;
results.forEach((result) => {
if (result.status === 'fulfilled') {
  const quotesListData = result.value?.data?.quotes;
  if (Array.isArray(quotesListData)) {
    list.push(...quotesListData);
  }
} else {
  isPartialFailed = true;
}
});
const { heapUsed } = process.memoryUsage();

if (process.send) {
  process.send({
  key: request.url,
  list,
  url: request.url,
  testId,
  isPartialFailed,
  kill: heapUsed > maxRAM * 1024 * 1024,
 });
}
});

Implementation:

import path from 'path';
import ForkBalancer from './forkBalancer';

const forkBalancer = new ForkBalancer({
 path: path.resolve(__dirname, './ParallelAPI'),
});

const handler = async (req, res) => {
  const { body } = req.body;
  const { testId } = req.query;
  const response = await forkBalancer.getFromRenderer({
    request: { 
      token: request.token,
      url: request.url 
    },
    testId,
    PAGE_SIZE_LIMIT: 50,
    body,
    totalPages: 100
  });
  return res.send(response);
 }

 fastify.post('/getAllItems', handler);

Creating a toggle/switch to show/hide divs

I would like to be able to click the toggle UI element (checkbox), and have it show/hide one or the other div.

The current CSS (below) is just some styling; and I can’t change my basic DIV HTML structure.

input[type="checkbox"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  -webkit-tap-highlight-color: transparent;
  cursor: pointer; }
  input[type="checkbox"]:focus {
    outline: 0; }

.toggle {
  height: 32px;
  width: 52px;
  border-radius: 16px;
  display: inline-block;
  position: relative;
  margin: 0;
  border: 2px solid #474755;
  background: linear-gradient(180deg, #2D2F39 0%, #1F2027 100%);
  transition: all .2s ease; }
  .toggle:after {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: white;
    box-shadow: 0 1px 2px rgba(44, 44, 44, 0.2);
    transition: all 0.2s cubic-bezier(0.5, 0.1, 0.75, 1.35); }
  .toggle:checked {
    border-color: #654FEC; }
    .toggle:checked:after {
      transform: translatex(20px); }
<div id="a">...</div>
<div id="b">...</div>
<div id="c">
  <div>
    <div>
      <input type="checkbox" class="toggle" checked>
    </div>
  </div>
</div>
<div id="d">...</div>
<div id="content-one">Content one</div>
<div id="content-two">Content two</div>
<div id="e">...</div>
</div>

EDIT:

I also wanted to share a simpler version that ChatGPT (Bing Chat) provided (did nothing, LOL):

  #content-two {
    display: none;
  }
  .toggle:checked ~ #content-two {
    display: normal;
  }
  .toggle:checked ~ #content-one {
    display: none;
  }
<div id="a">...</div>
<div id="b">...</div>
<div id="c">
  <div>
    <div>
      <input type="checkbox" class="toggle" checked>
    </div>
  </div>
</div>
<div id="d">...</div>
<div id="content-one">Content one</div>
<div id="content-two">Content two</div>
<div id="e">...</div>

Having fun with crypto-js

I have the following code in typescript

 const chunkRead = (c: ArrayBuffer) => {
   fileChunks.push(chunk);
   const wordArray = CryptoJS.lib.WordArray.create(c);
   md5.update(wordArray);
 };

I get the error Argument of type ‘ArrayBuffer’ is not assignable to parameter of type ‘number[]’ on the line where I try to call CryptoJS.lib.WordArray.create(chunk). I’m trying to upload a large file in parts to a server. Can someone please help?

mwc-textfield input pattern not working for backslash or vertical bar

I am trying to add a pattern to a mwc-textfield input to filter a file name. My pattern seems to be valid js regex and seems to work on a html input but does not as a pattern on a mwc-textfield. I have two problems:

  1. | or gives Pattern attribute value ^[^|/:*"<>]+$ is not a valid regular expression: ect... but \| works which confuses me
  2. \ never actually seems to match no matter what I try.

Example: https://codesandbox.io/p/sandbox/fervent-field-jjpvjz

Regex: ^[^|\/:*&quot;&lt;&gt;]+$

Can anyone explain this weirdness or what I’m doing wrong?
Thanks!

React App calling JavaScript function from embedded webpage

I am working on a React App based on this example: https://github.com/facebook/create-react-app#creating-an-app

I embedded an HTML viewer in this app which calls a HTML5 page that embeds some JavaScript functions. Now I am trying to call one of the JavaScript function when clicking on a button defined in TypeScript.

Function declaration in HTML page:

function sendMessage(str)
 {
     theRenderArea.sendMessage(str);
 }


Function definition in JavaScript embedded in the HTML page

this.sendMessage = function(b) {
   if (this.isConnected()) {
      b = {
            type: "command",
            message: b.toString()
      };
      var a = new h;
      this.websocket.send(a.encode(b))
   }
};

TypeScript viewer object opening HTML page:

function Viewer() {
    return (
        <>
            <div id="loaderGroup" style={{"display": "none"}}><div id="loader"></div><div id="loaderText">Network calibration</div></div>
            <div id="TheDiv"></div>
        </>
    )
}

export default Viewer

Button definition in React app:

<Button 
    style={{color: selected ? "#6A89FF": "#5B5C5D"}}
    onClick={changeColor}>
    Interact
  </Button>

I tried this suggestion: Call external Javascript function from react typescript components

But couldn’t get it to work.

JsonRpcProvider broadcasted sending function

Would you please give me advice on what is a method to broadcast my signed TX into the network? Can find any %send% method for provider instance

Here is my code snippet:

export async function signAndBroadcast(address, rawTransaction, jrpcUrl, key) {
    const provider = new ethers.JsonRpcProvider(jrpcUrl)
    expect( await checkBalance(address, provider)).toBe(true)
    // Initialize a new Wallet instance
    const wallet = new ethers.Wallet(key, provider);
    // Parse the raw transaction
    const tx = ethers.Transaction.from(rawTransaction);
    tx.nonce = await provider.getTransactionCount(wallet.address)
    const { name, chainId } = await provider.getNetwork()
    tx.chainId = chainId
    tx.value = ethers.parseUnits('32', 'ether')
    tx.gasLimit = 1000000
    tx.gasPrice = undefined
    tx.type = 2
    // Sign the transaction
    const signedTransaction = await wallet.signTransaction(tx);
    console.log("TX signed: " + signedTransaction)
    // Send the signed transaction
    const transactionResponse = await provider.sendTransaction(signedTransaction) // no function sendTransaction

    transactionResponse
        .then((transactionResponse) => {
            console.log('Transaction broadcasted, transaction hash:', transactionResponse.hash);
        })
        .catch((error) => {
            console.error('Error:', error);
        }).finally(() => {
            console.log('Finished')
        });
}

Thank you in advance!

I want to scroll down a page of CRM D365 form which is inside a container but cant locate it using selenium with python

syntax of layout of container: < div class = formContainer fill-width fill-height layout-container layout-vertical role=”region” data-dyn-bind=”
attr: { ‘aria-label’: $dyn.format(‘{0}: {1}’, $dyn.value($data.FormCaption), $dyn.value($data.ParentTitleFields)) },
sizing: { width: $dyn.layout.Size.available, height: $dyn.layout.Size.available },
layout: { arrangeMethod: $dyn.layout.ArrangeMethod.vertical }”

I tried using javascript executor for pycharm but this didnt work : self.driver.execute_script(“window.scrollTo(0,document.body.scrollHeight);”)

Convert text to number JavaScript

I am trying to convert text (E.g. Hello) to a number (E.g. 0805121215).
I have looked up many sources, but none of them have worked.

I have tried:
https://dev.to/sanchithasr/7-ways-to-convert-a-string-to-number-in-javascript-4l
and
thttps://www.geeksforgeeks.org/convert-a-string-to-an-integer-in-javascript/
I tried a few more sources but they all say that text outputs as NaN. I would like it to convert to a number, I don’t want Not a Number.

Here is an example of what I want to happen:
https://scratch.mit.edu/projects/948090655/

How to get the ID token in trigger functions of AWS Cognito?

In the lambda trigger functions of AWS Cognito, say Post confirmation trigger or Post authentication trigger, I would like to get the ID token, such that I could query some other services on behalf of the user.

Is that possible and if so, how?

It would be terrific if you could also provide a small example in Javascript and/or Python.

How to execute a script after an external asynchronous script in header tag completes execution?

With Webflow native custom code editor, I added to my website an external script made by Finsweet inside the <head> tag, as they instruct to do.

I want to make some changes in the page with my own script after the execution of Finsweet’s one but I’m limited by my knowledge in asynchrous JavaScript and use of JavaScript in HTML code.

Here is what it looks like:

<!-- [Attributes by Finsweet] CMS Slider -->
<script async src="https://cdn.jsdelivr.net/npm/@finsweet/attributes-cmsslider@1/cmsslider.js"></script>
<script>
  // my own script
</script>

Putting my own script before the closing </body> tag is still not enough to allow the external script to fully execute.

I want a clean solution that avoids using a timer, knowing that I’m also limited by Webflow’s environment.

How can I clone a text that’s inside a and paste it in the same ?

I’m trying to create a function that would copy the <p> text and paste it within the same div (duplication) on click.

I’ve tried a couple of methods, none of them worked, unfortunately.

function duplicate() {
  let clone = document.querySelector('.header p').cloneNode(true);
  document.querySelector('.header').appendChild(clone);
}
<div class='header'>
  <p onclick="duplicate();">Text</p>
</div>

How to display my result in fraction form instead of decimal form when converting from degree to radians

I used the math.js library to be able to create a calculator which converts any number from radian to degree or vice versa. The calculations work perfectly, but the problem comes when trying to display the result from degrees to radians. For exampple, If I place 360 degrees to calculate to radians it returns 6.28, instead of 2π. From radians to degrees it displays the result perfectly because it doesn’t need to give me the result in fraction form plus a pi sign. Is there a way to convert my answer into fraction form and add the pi sign to it ?

my Html :

         <section id="Radian/Deegree_Converter">
            <h3 id="Radian/DegreeTitle">Radian-Degree Converter</h3>
            <input type="text" placeholder="Number" id="placeDegRadNumber">
               <span>=</span>
               <input type="text" placeholder="Result" id="displayDegRadResult">

               <select id="assignDegRadUnit">
                  <option value="choseDegrees">Degrees</option>
                  <option value="choseRadians">Radians</option>
               </select>

               <select id="convertToDegRadUnit">
                  <option value="choseDegrees">Degrees</option>
                  <option value="choseRadians">Radians</option>
               </select>
               <button id="piButton">π</button>

               <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.1.0/math.min.js"></script>
         </section>

my Javascript :

//RadianDegree Converter---------------------------------------------------------------------------------------   


    const numberInput = document.getElementById('placeDegRadNumber');
    const resultInput = document.getElementById('displayDegRadResult');
    const assignUnitSelect = document.getElementById('assignDegRadUnit');
    const convertToUnitSelect = document.getElementById('convertToDegRadUnit');
    const piButton = document.getElementById('piButton');

    piButton.addEventListener('click', function () {
        numberInput.value += 'π';
        convertUnits(); // Trigger conversion when π is added
    });

    numberInput.addEventListener('input', convertUnits);
    assignUnitSelect.addEventListener('change', convertUnits);
    convertToUnitSelect.addEventListener('change', convertUnits);

    function convertUnits() {
        const inputValue = math.evaluate(numberInput.value.replace(/π/g, 'pi')) || 0;
        const assignUnit = assignUnitSelect.value;
        const convertToUnit = convertToUnitSelect.value;
    
        let result;
    
        if (assignUnit === 'choseDegrees' && convertToUnit === 'choseRadians') {
            result = math.format(math.unit(inputValue, 'deg').to('rad'), { fraction: 'ratio' });
        } else if (assignUnit === 'choseRadians' && convertToUnit === 'choseDegrees') {
            result = math.format(math.unit(inputValue, 'rad').to('deg'), { fraction: 'ratio' });
        } else {
            result = inputValue;
        }
    
        // Remove the unit label from the result and update the input field
        resultInput.value = Number(result.replace(/[^d.-]/g, '')).toFixed(2);    
    }

I tried adding a string with the π sign to be added when displaying the result in a fraction form, but it didnt work

Parent triggering function defined in Child, React Native

Good afternoon,

I have a react native project. I currently have 3 major UI components:

A timeline which consists of a user defined number of channels, which have a fluctuating number of events (Think gantt chart or audio editors). I want a button defined in the timeline to call a function defined in the child channel object, change some parameters as defined in the child function, and re-render.

const TIMELINE = ({ }) => {
  const router = useRouter();
  const [allChannels, setChannels] = useState([]);

  const addChannel = () => {
    const newChannel = <Channel onRef = {ref => (this.child=ref)} key={allChannels.length}/>;
    setChannels([...allChannels, newChannel]);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.welcomeMessage}>Timeline</Text>
      {
        allChannels.map((item)=>{
          return item
        })
      }
      <Pressable style={styles.searchBtn} onPress={()=>addChannel(allChannels, setChannels)}>
        <Image
          source={icons.add}
          resizeMode='contain'
          style={styles.searchBtnImage}
        />
      </Pressable>
      <Pressable style={styles.Btn} onPress={()=>updateEvents(allChannels, setChannels)}>
        <Image
          source={icons.search}
          resizeMode='contain'
          style={styles.searchBtnImage}
        />
      </Pressable>
  );
};

const updateEvents = (allChannels, setChannels) => {
  setChannels(allChannels => 
    allChannels.map(channel => {
      channel.child.updateChildEvents(2); //<<<<<<Error occurs here
      return channel;
    })
  );
};

As you can see, I store each channel object created in an array in the state variables of timeline. I then have a function that attempts to update the data stored in the events of each channel.

For reference, here is the Channel code as well:

class Channel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allEvents: [],
    };
  }
  updateChildEvents(scaleFactor) {
    this.state.allEvents = this.state.allEvents.map(event => ({
      ...event,
      width: event.width * scaleFactor,
    }));
  }

Unfortunately, this give me the error: “Cannot read properties of undefined (reading ‘updateChildEvents’)” when called on the button press

I have tried passing the ref to the child on creation, as suggested in this answer on SO Call child function from parent component in React Native but that also fails. I think the issue is actually how the Channel elements are stored in the state. Most examples and Stack Overflow answers I have found have a static number of children, and therefore static refs. Since I have a dynamic number of children (both Channels and Events), I think I need a better way to define my refs dyanmically as well.

So my first question: Is this the right approach? Should I define these as separate components, or should the timeline just contain all of the data (channels and channel events) in its state directly?

Otherwise, if this is the proper way to define everything (which is how I would go about this in object oriented projects I have built before outside of react native), what am I missing? Why does my current approach not work?

Thank you!

How to Check if The End Date is Bigger Than The Start Date Using Script in HTML?

i want to Check if The End Date Is Bigger Than The Start Date , i had add an HTML Code to Get the Date Entered, and also i have wrote this Script to Check the if the End Date is bigger Than the Start Date.

// Function to check if the DateFin is Bigger Than The DateDebut
document.getElementById('DateFin').addEventListener('change', function() {
  var dateDebut = document.getElementById('DateFin').value.trim();
  var dateFin = document.getElementById('DateFin').value.trim();

  if (isNaN(dateFin) || dateFin < dateDebut) {
    document.getElementById('error-message').innerText = "The End Date must be greater than or equal to the Start Date";
    document.getElementById('DateDebut').value = "";
    document.getElementById('DateFin').value = "";
  } else {
    document.getElementById('error-message').innerText = "";
  }
});
<div class="mb-3">
  <label for="datadebut" class="form-label text_color">Date de Début :</label>
  <input type="date" class="text_color btn_designBtn bold-border-label form-control" id="DateDebut" name="searchDateDebut" value="{{ $searchDateDebut ?? '' }}">
  <div></div>
</div>

<div class="mb-3">
  <label for="datafin" class="form-label text_color">Date de Fin :</label>
  <input type="text" class="text_color btn_designBtn bold-border-label form-control" id="DateFin" name="searchDateFin" placeholder="jj/mm/yyyy">
  <div id="error-message" style="color: red;"></div>
</div>

But When i try the write the full End Date the Script is executed directly whiout a finish write the year example : i try to write the : startDate = 15/01/2024
and when i write the endDate = 15/01/2 < Whiout finish the year > the Script is executed directly and i got the message Error :

document.getElementById('error-message').innerText = "The End Date must be greater than or equal to the Start Date";

Can You help me please ? i’m stake in this Scripts…

Find a solution for my question please