Error: No response is returned from route handler ‘

I think i am handling the case if an exception is thrown just fine but still I keep getting an error Error: No response is returned from route handler ‘C:UsersayanOneDriveDesktopappswebappapifollowupsroute.ts’. Ensure you return a Response or a NextResponse in all branches of your handler.

I expected a response from this api after successful execution or just an exception rather than no response is returned error

/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import type { NextApiResponse } from "next";

 

export async function GET(res: NextApiResponse){

    try {

    const cohere_api_key = "";

    const followups = [
        {
            ques : "What other creative ways can ChatGPT be integrated into everyday objects?"
        },
        {
            ques: "How can AI be used to enhance education and learning experiences beyond exam assistance?"
        },
        {
            ques: "What are the potential ethical considerations of using AI-powered tools like this eraser during exams?"
        }

    ]

    console.log("###########Cohere is called");
    const promises = followups.map((item)=>(
        fetch('https://api.cohere.ai/v1/chat', {

        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${cohere_api_key}`, // Replace YOUR_API_KEY with your actual API key
        },
        body: JSON.stringify({
            message: `You are a smart blogger who write detailed blogs on a given topic, write a blog on topic: "${item.ques}"`,
            connectors: [{ id: 'web-search' }],
        }),
    }) 
    )

    )

    console.log("###########resolving promises")

    Promise.all(promises)
    .then((response)=>{
        console.log("all promises resolved", response);
        return Promise.all(response.map((res)=> res.json()));
    })
    .then((res)=>{
        console.log("/////response", res);
        const result = followups.map((followup , index) => ({
            question : followup.ques,
            content : res[index].text
        }))

        console.log("our final result set" ,result)

        return Response.json(result);

    })
    .catch((error) => {
        console.log("error",error)
        return res.status(500).json({ message: 'Internal server error' })
    })

} catch (error) {
    return res.status(500).json({ message: 'Internal server error' })
        
}
  } 

Edit multiple records in textfile by using javascript

so i need to edit VIN data in text file i have code to edit one data. but i need code to edit multiple VIN data in text file
i created VIN data and stored in VIN array now i want code to modify multiple vin’s
this how text file data looks and VIN is EB6A9EBHD96FA5MDH

L|10071887|1564|EB6A9EBHD96FA5MDH|Jeep|Wrangler JK|
L|10071887|1564|EB6A9EBHD96FA5MDH|Jeep|Wrangler JK|
L|10071887|1564|EB6A9EBHD96FA5MDH|Jeep|Wrangler JK|

below is the code can someone please help me with this? iam expecting modification in code to edit multiple vin data in text file


`return new Promise((resolve, reject) => {

let filePath = fileSourcePath+fileName;

const fs = require("fs");
var data = fs.readFileSync(filePath, "utf8");

function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}

console.log("before editing : ", data)
let field=[Vin];
let startPos=[716]
let endPos=[733]
let i;
let replaceValues;
console.log("lenght:",field.length)
for(i=0; i<field.length; i++) {
replaceValues=replaceRange(data,startPos[i],endPos[i],field[i]); // for .txt file
data = replaceValues

    }
    
    console.log(data);
    
    fs.writeFile(filePath, data, (err) => {
        if (err) console.log(err);
        console.log("file edited Successfully!");
        resolve();
    });

});`

Angular16 MongoDB Multiple Parameters on Http Post

I need to pass two parameters to my end point, along with the request so that would make it three and only two are allowed per my http post request. I tried the HttpParams but that does not work in my case. The situation is when product is chosen a size must be chosen as well. It works when I add url plus end point and append the Id. I then add Id to my end point, I have already tested it, product is added to cart. There are different sizes for each product so a size must me chosen. Once I get the issue with the parameter figured out I will update the item by Id this is the reason I need both parameters. I can’t append the size and Id I will get an error.

I Need figure out the best approach to get both. Everything I had tried does not work.

Can someone point me in the right direction: Code snippet below:

cart Service:

     addProductToCart(product:Product, _id:String, size:String):Observable<Product>{


     return this.http.post<Product>(this.rootUrl + '/getProducts/addtocart' + _id, 
     {product})

   }

api:

        router.post('/getProducts/addtocart:_id',   async(req, res)=> {
      .......
        }) //this works

update service:

         UpdateCart(product:Product, _id:String, size:String):Observable<Product>{

          alert("Service update cart")


       return this.http.post<Product>(this.rootUrl + '/getProducts/updatecart/' + _id + 
        size, {product})


        }

api end point:

        router.post('/getProducts/updatecart/:_id/:size', async(req,res)=>{  
 
        const _id = req.params.id;
        const size = req.params.size;

       }); //The above does not work gives me an error
  
    

How can I construct a variable in JavaScript based on another variables value? And How can I reassign it’s value and perform methods on that variable? [duplicate]

I want to be able to basically do this

let x = 1;
let `arr${x}`;

if ((i = 0)) `arr${x}` = [];
`arr${x}`.push(words);
console.log(`arr${x}`);

I have tried using eval()

let x = 1;
eval(`let arr${x}`);

if ((i = 0)) eval(`arr${x} = [];`);
eval(`arr${x}.push(${words})`);
console.log(eval(`arr${x}`));

But it’s giving an error:
Uncaught ReferenceError: arr1 is not defined
In this line: eval(arr${x}.push(${words}));

Any way to hide or obfuscate the “pattern” attribute in an Angular reactive form’s HTML source?

I have a requirement on a project I’m working in which the Angular “pattern” directive works great and checks all the boxes but one. The only issue is that pattern is readily viewable in the HTML source.

For example, I have a series of mat-input controls in a form. Before the user can submit the form, they must enter a known value in a few of the fields. I’ve marked up these fields with the “key” value using the pattern attribute.

In this case, I need the user to enter the value specified in the pattern of input but not cheat by peeking at the pattern in the html source of the input.

Any ideas of how I may achieve this with the pattern attribute? This is not sensitive data, so I don’t need a high degree of obfuscation. I just need to make it so its not worth the time to try to find the pattern from the html source.

<input pattern="Some Secret Value" />

If user enters “Some Secret Value”, the input is valid.

MediaRecorder not Initializing Correctly for Real-time Audio Broadcasting

I’m working on a project where I need to implement real-time audio broadcasting from an admin to multiple users. While researching, I found examples using WebRTC and Socket.IO
My current setup involves an admin streaming audio from their microphone to a server, which then broadcasts the audio to connected users in real-time. However, I’m encountering issues with the WebRTC and Socket.IO approach, and I’m open to exploring other options too.

Here’s a version of the client-side code I’m using for the admin:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Broadcasting</title>
</head>
<body>
    <h1>Admin Broadcasting</h1>
    <button id="startBroadcastBtn">Start Broadcasting</button>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const startBroadcastBtn = document.getElementById('startBroadcastBtn');
        const socket = io('ws://localhost:9000');
        let mediaRecorder;

        startBroadcastBtn.addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                console.log('MediaStream object:', stream);
                const audioTracks = stream.getAudioTracks();
                console.log('Audio tracks:', audioTracks);
                if (audioTracks.length > 0) {
                    console.log('Audio track inside stream:', audioTracks[0]);
                    mediaRecorder = new MediaRecorder(stream);
                    console.log('MediaRecorder object:', mediaRecorder);
                    mediaRecorder.ondataavailable = (event) => {
                        console.log('Audio chunk captured:', event);
                        if (event.data.size > 0) {
                          console.log('Audio chunk captured:', event.data);
                          socket.emit('admin-audio-chunk', event.data);
                        }
                    };
                    mediaRecorder.start();
                } else {
                    console.error('No audio tracks available');
                }
            } catch (error) {
                console.error('Error accessing media devices:', error);
            }
        });
    </script>
</body>
</html>

On the server side, I’m using Node.js with Socket.IO for handling client connections and broadcasting audio streams.

The MediaRecorder object seems to be created, but the ondataavailable event is not triggering when audio chunks are available. As a result, no audio data is being sent to the server for broadcasting.

I’ve checked the browser compatibility and permissions for accessing the microphone, but I’m still unable to figure out why the MediaRecorder object is not initializing correctly.

Can anyone help me identify what might be causing this issue and how to resolve it? Any suggestions or insights would be greatly appreciated.

Thank you!

Best way to share css across packages in lerna with monorepos

Currently i have bootstrapped a lerna monorepo with multiple apps, the structure is like this

--node_modules
--packages   
     --app1 (a react app bootstrapped with tsdx)  
     --app2 (a typescript app bootstrapped with tsdx)
     --app3 (another react app bootstrapped with tsdx)  
--lerna.json
--yarn.lock
--package.json

Now i have some style related files (.scss , mixins etc) that i need to share between the three apps.

question is whats the best way to do this ?

1.is it possible to put it as files in a seperate folder and these packages can access it ?

2.Do i need to create it as a app ?

3.Any specific tweaks in the webpack i need to add ?

JavaScript Audio Streaming: CHUNK_DEMUXER_ERROR_APPEND_FAILED: RunSegmentParserLoop: stream parsing failed

Please I am building a chatbot and the Audio format is WebM Opus … I am using a websocket to stream the audio chunks (after the response as been synthesized to speech) to my client js where I then append it to the source buffer. The issue is the first speech response I send after synthesis playback smoothly but when I try to append to source buffer for the next response I get the error : CHUNK_DEMUXER_ERROR_APPEND_FAILED: RunSegmentParserLoop: stream parsing failed……. Note I have tried doing source buffer remove(0, Infinity) after first audio chunks even did audio element.buffered.end(0).

///////////////////////////// Speech response /////////////////////////////

// Create a new MediaSource instance
var mediaSource = new MediaSource();
// Create an audio element
const audioElement = document.createElement('audio');
var updating = false;
var pendingAppendData = [];
var sourceBuffer;

let buffer = new Uint8Array([]);

async function websocketMessageHandler(event) {

  if (event.data.maxByteLength != 1 ) {
    // // Append new data to the buffer
    buffer = new Uint8Array([...buffer, ...new Uint8Array(event.data)]);

    if (buffer.length >= 512) {
      pendingAppendData.push(new Uint16Array(buffer.slice(0, 512).buffer));
      buffer = buffer.slice(512, buffer.length);

      appendData(); // Append the new data to the SourceBuffer
      if (audioElement.paused) audioElement.play();
    }

  } else {
    if (new Uint8Array(event.data)[0] == ControlMessagesEnum.END_AI_RESPONSE[0]){
      // pendingAppendData.push(new Uint16Array(buffer.buffer));
      // appendData();
      buffer = new Uint8Array([]);

    } else if (new Uint8Array(event.data)[0] == ControlMessagesEnum.START_AI_RESPONSE[0]){
        if (audioElement.currentTime != 0) {
          updating = true;
          audioElement.pause();
          audioElement.currentTime = 0;
          sourceBuffer.abort();
          sourceBuffer.remove(0, Infinity);
          // audioElement.buffered.start(0);
          audioElement.buffered.end(0);
          updating = false;
        }
    }
  }
}


// # add on message to ws.
function addOnWebsocketMessageCallback(external_function){
 // change websocket callback to include external function.
  async function on_websocket_message (event){
    external_function(event);
    await websocketMessageHandler(event);
  }
  ws.onmessage = on_websocket_message;
}

// Set the MediaSource object as the source for the audio element
audioElement.src = URL.createObjectURL(mediaSource);
audioElement.onerror = (err)=>console.error(err.target.error);

// Listen for the 'sourceopen' event to create and initialize the SourceBuffer
mediaSource.addEventListener('sourceopen', function(){
  console.log('source is open')
  if (!sourceBuffer) {
  sourceBuffer = mediaSource.addSourceBuffer('audio/webm; codecs="opus"');
  sourceBuffer.mode = 'sequence';
  this.onsourceclose = ()=>console.log('them don close me oooo');
  }
});

// Function to append data to the SourceBuffer
function appendData(){
  if (updating || pendingAppendData.length === 0) {
    return;
  }

  updating = true;
  const data = pendingAppendData.shift();

  sourceBuffer.addEventListener('updateend', ()=>{
    updating = false;
    appendData(); // Recursively call appendData to process the next chunk
  }, {once: true});

  sourceBuffer.appendBuffer(data);
}

The python code :

audio_format = "Webm24khz16bitMonoOpus"

@app.websocket("/voice_chat")

async def voice_chat(websocket: WebSocket):

    # print(websocket.headers)

    await websocket.accept()



    try:

        transcription = ""


        # for text to speech

        speech_synthesizer =TTS(text_to_speech_config, audio_format)


        async def finished_speaking(_):

            nonlocal transcription

            print(f"nnFull transcription from session: {transcription}")

            user_chat, ai_response = await conversation_handler_forAudio.chat(transcription)

            print("response .... ", ai_response)



            async def send_audio_stream(evt):

                print('sent audio bytes')

                await websocket.send_bytes(evt.result.audio_data)



            async def start_synthesis(_):

                await websocket.send_bytes(bytes([2])) // control byte to signal speech stream start



            async def end_synthesis(_):

                await websocket.send_bytes(bytes([3])) // control byte to signal speech stream end

 

            speech_synthesizer.onstarted(start_synthesis)

            speech_synthesizer.onsynthesizing(send_audio_stream)

            speech_synthesizer.oncompleted(end_synthesis)



           speech_synthesizer.start_speaking(str(ai_response.extracted_response))


I am expecting to be able to append the next audio chunks directly to source buffer because low latency is crucial. I don’t want to create a new media source on every set of chunks.

Unit test using sinon js

I’m writing unit test for a JS class via sinon and here is the sample. I would like to know whether what ever I wrote is appropriate. Reason, I am not using stub/mock as what mentioned in different tutorial on the Internet.


//let someGlobalVariable
class Topics  {

  constructor() {}
  
  isValidTopic(topics, requiredTopic) {
    let topicFound = false;
    requiredTopic.filter((topic) => {
      if (topics.includes(requiredTopic.topicId)) {
        topicFound = true;
      }
    });
    return topicFound;
  }
}

module.exports = Topics;


it('isValidTopic should return false', () => {
    const topics = [
      { topicId: 'topic 1' },
      { topicId: 'topic 2' }
    ];
    const requiredTopic = ['topic 9'];

    const topicsInstance = new Topics();
    const isValid = topicsInstance.isValidTopic(topics, requiredTopic);
    sinon.assert.match(isValid, false);
  });

Also, there is a global variable ‘someGlobalVariable’ and we are using across this class (I did not mention in the above code) and I know its not good to use global variables and should be part of constructor as ‘this.someGlobalVariable’ but the code base is written in that way unfortunately and have little control to refactor.

So question, how to mock/stub this global variable ?

ffmpeg problem video duration of an hour and a half

When start record i call an api /start-record which does:

const ffmpeg = spawn("ffmpeg", [
        "-i",
        rtsp,
        "-c:v",
        "copy",
        "-an",
        "-f",
        "flv",
        `${filename}.flv`,
      ]);
ffmpegProcesses[rtsp] = {
        process: ffmpeg,
        filename,
      };

When stop the record i call an api /stop-record which does:

ffmpegProcesses[rtsp].process.kill("SIGKILL");
ffmpegProcesses[rtsp].process.on("exit", async () => {
   const ffmpeg = spawn("ffmpeg", [
          "-i",
          `${filename}.flv`,
          "-c:v",
          "libx264",
          "-preset",
          "fast",
          "-crf",
          "30",
          "-an",
          `${filename}.mp4`,
        ]);

    ffmpeg.on("exit", async () => {
        uploadToS3()
    })

})

If the recording is less than or equal to approximately 1 hour it works perfectly, but if the recording is 1 and a half hours it already breaks and it does not correctly generate the files, nor the flv nor the conversion to mp4

I hope my program works the same way it does for 1 hour recordings

How to add another class name to already exisiting class of a button on click event

I have a form that sends an email upon clicking a button. However, while the email is being sent, the button remains active, allowing users to click it multiple times, which interrupts the email-sending process. I want to add a ‘disabled’ class to the button as soon as it’s clicked. I attempted to achieve this with the following code, but it doesn’t work.

Please assist me with this problem.I tried the following codes

<div class="d-grid mt-3">
<button class="btn btn-primary" type="submit" name="authoriseUser" id="authoriseUser" onclick="disableBTN()">Enroll New Admin <i class="fas fa-sign-in-alt ms-1"></i></button>
</div>

// JS & Jquery Code that I Tried are in the following order

// First Attempt - didn't work
<script type="text/javascript">
    $(document).ready(function(){
        $("#authoriseUser").on('click',function(){
            $(this).removeClass('btn btn-primary')
            $(this).addClass('btn btn-primary disabled')
        });
    });
</script>

//Second Attenpt - didn't Work
<script type="text/javascript">
    $(document).ready(function(){
        $("#authoriseUser").on('click',function(){
            $(this).removeClass('btn btn-primary').addClass('btn btn-primary disabled');
        });
    });
</script>

//Third Attempt - Didn't Work
<script type="text/javascript">
    $(document).ready(function(){
        $("#authoriseUser").on('click', function(){
            $(this).addClass('disabled').attr('disabled', true); 
        });
    });
</script>