Tempus Dominus minDate being enforced unintendedly when page loads

In my $(document).ready I have the following:

$('.mydatepicker').datetimepicker('minDate', someDate);

From the database I am receiving a date which is before the someDate.

The Tempus Dominus datetimepicker is annoying me with the behavior of automatically enforcing that minDate I set, but I want it to only enforce it when it is the user who explicitly interacts to change selected date.

Is there any way to make it behave as I described?

two digit only allowed before decimal and after decimal point in javascript

I am use an input field in html and use Javascript function.That input field accept two digit only allowed before decimal and after decimal point in javascript.And that input field not more than 4 digit before decimal and after decimal point.

1.05———-accept
12.05———-accept
12.78———-accept
122.45 ———-not accept
122..45———-not accept
122.789———not accept

try that
1.05———-accept
12.05———-accept
12.78———-accept
122.45 ———-not accept
122..45———-not accept
122.789———not accept

How can I add an infinite scrolling in my MUI DataGrid?

Basically, I have this component and I have to add it an infinite scrolling. I’ve read MUI DataGrid but couldn’t apply anything successfully.
I’m using GraphQL to fetch the data and i was using arrows to move to the next page but I have removed them.
I’m fetching 100 styles on each page.
Could anyone help me?

This is the component:

return (
    <>
      <StyledForm sx={{ height: 'calc(100vh - 72px)', p: 0, pt: 0, position: 'relative' }}>
        <DataGrid
          rows={tableRows}
          columns={columns}
          loading={isStylesLoading || !tableRows}
          localeText={localeText}
          rowCount={totalCount}
          getRowClassName={(params: GridRowParams): string => {
                const isPinnedRow = params.row.id.includes('pinned');
                return `${classes.row} ${isPinnedRow ? classes.pinnedRow : ''}`;
          }}
          rowHeight={64}
          paginationMode="server"
          pageSize={size}
          classes={{
                root: classes.root,
                columnHeaders: classes.columnHeaders,
                columnHeaderTitle: classes.columnHeaderTitle,
                cell: classes.cell,
                columnSeparator: classes.columnSeparator,
                footerContainer: classes.footerContainer,
          }}
          components={{
                LoadingOverlay,
                // eslint-disable-next-line react/no-unstable-nested-components
                Pagination: () => null,
          }}
          componentsProps={{
                row: {
                  onMouseEnter: handleRowMouseEnter,
                  onMouseLeave: handleRowMouseLeave,
                },
          }}
          disableSelectionOnClick
          disableColumnMenu
          onCellClick={handleCellClick}
        />
      </StyledForm>
      <StyleDialogDrawer isEdit={isEdit} />
    </>
  );
};

Why NodeJS doesn’t parse the incoming HTML form data by default

I want to know the underlying reason, why it’s not the part of NodeJS built-in API to parse incoming form-data, as it’s the very basic need of almost any web app.

I’ve tried searching the blog and asking the Ai tools like gpt, but still unable to understand at a very basic level, what’s the underlying cause.
All I came to know is that, NodeJS team left the choice up to the developer to choose their own parsing middleware.

Using an api to change the currency of another api

Im making a website that uses an api to show bitcoin and ethereum prices, but the prices are in USD whilst i want them to be in Euros. here is the current code:


<div class="text-center">
    <h1 class="display-4">Crypto priser</h1>
    <div id="output"></div>
</div>


<script>
    const apiUrl = 'http://api.coinlayer.com/api/live?access_key=';

    const outputElement = document.getElementById('output');

    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('noe gikk galt');
            }
            return response.json();
        })
        .then(data => {
            const Bitcoin = data.rates.BTC;
            const Ethereum = data.rates.ETH;


            outputElement.innerHTML = `<p>Bitcoin: ${Bitcoin}</p><p>Ethereum: ${Ethereum}</p>`;
        })
       
</script>

I want to add an api that translates 1 dollar into euroes automatically but im unsure how to do that without the use of chatGPT.
https://api.freecurrencyapi.com/v1/latest?apikey=&currencies=EUR%2CNOK

I removed the apikey from both the api links for obvious reasons.

I’ve tried multiple things, none that worked. (I don’t even remember what i tried sorry) Also im new to coding so sorry if the code seems bad

How to darken a MaterialUI Avatar component image and put text on it

I’m using the Avatar component from Material UI. I’am also using Tailwind
I can simply put the src with the image url and it works

<Avatar alt="Cindy Baker" src="https://mui.com/static/images/avatar/3.jpg" />

But I have a situation where I need to put an overlay on the image (make it darker) and need to put a white text like +5

https://stackblitz.com/edit/react-ohycv7?file=Demo.tsx

Right now it looks like this

enter image description here

I need it to look something like

enter image description here

How to download url file?

I just use a tag to achieve this, but my chrome browser just show the image not download.

        <a
          href="https://png.pngtree.com/png-vector/20221222/ourmid/pngtree-super-cute-cartoon-vector-bear-png-image_6504049.png"
          download="your-file-name.png"
        >
          Download File
        </a>

Why download is not working ?

How to write a function that will handle multiple onclick events which toggle the visibility of a field

Ive not been coding long and I am new to javascript. Im making a simple web page that will show and hide part of a sentence for the purposes of learning foreign language. Is there a way to write one function that when a button is clicked it shows and hides the field.

If I use document.getElementsByClassName() and iterate through each button and get an array of buttons, I don’t understand how I feed that array of buttons into one function tat performs the showing and hiding similar to this function below. (I know the below is using getElementById) but im trying to do the same thing but with document.getElementsByClassName().

const a = document.getElementById("button1").addEventListener( "click" , function(){
  if(document.getElementById("para1").style.visibility === "hidden"){
    document.getElementById("para1").style.visibility = "visible";
  }else{
    document.getElementById("para1").style.visibility ="hidden";
  }

Ive looked at the questions already on here but they seem very advanced for what i’m trying to do. I know this is simple stuff but any help would be appreciated.

Ive tried the above as explained but I just can’t seem to find an example of how to connect one function to multiple buttons.

what are different Lifecycle stages of NLP?

What are the different lifecycle stages of NLP?

I want brief explaination of NLP and its life cycle of NLP and its different life cycle The Natural Language API allows you to easily apply NLU to your applications. The natural language API uses machine learning to uncover the meaning & structure of text.API

EsModule JS Dynamic importing using Vite instead of Webpack?

I have a number of Laravel projects which use Webpack and ES5 Modules to create/provide separate JS files which can be imported only as and when required by a page. Some of my projects are quite complex and pages need their own specific javascript. These projects are not built using responsive engines like Vue, React or Livewire (although that is something I’ve moved towards more recently, preferring TALL stack solutions).

I use Webpack Mixins to add my separate JS files, following the naming convention of js/pages/[some page name here]/[some module name here].js:

  mix.js('resources/js/app.js', 'public/js')
     .js('resources/js/pages/some-page/some-module.js', 'public/js/pages/some-page/')

Each Laravel blade page includes a small JS script which holds an array of all the required JS pages that need to be used on that page (along with any global shared helper functions). Normally this is just one JS page, but more can be added.

document.js_arr = [
    {
        "file" : "pages/some-page/some-module.js",  //removed "js/" to make the reference smaller
        "shared" : "validateEmail,dateFormatting",  //two sample global function references I might need importing in to my local js file.
    }
];

After the webpage has loaded, my app.js checks for any requested JS import (using webpackChunkName and the [name] placeholder), imports it and handles any shared functionality requirements:

 if( undefined != document.js_arr){

        document.js_arr.forEach((js_object) => {
            import(
                /* webpackChunkName: "js/[name]" */
                /* webpackMode: 'eager' */
                './'+js_object["file"]
            )
            .then( module => {

                if(js_object["shared"]){

                    let shared_objects = js_object["shared"].split(',');
                    let objects = [];
                    shared_objects.forEach((shared_object) => {

                       if( eval(shared_object) ){
                        objects.push( eval(shared_object) );
                       }

                    });
                    if(objects.length > 0){
                        //Bind our local references to global shared functions
                        module.shareGlobalFunctions(...objects);
                    }
                }
                
                module.default();
            } )
            .catch(error => { console.log( error ); } );
        } );

    }

The solution I have actually works well enough. But more recent versions of Laravel suggest using Vite instead of Webpack.
I’m not as clued up with Vite. How would I go about setting up the same system to work with Vite? Are there similar processes as ChunkNames and placeholder references like [name] in Vite?

bing-translate-api language is not defined

Hei. im trying to create a telegram bot to translate. And here is the code:

const { Bot, InlineKeyboard, session } = require('grammy');
const axios = require('axios');
const { translate } = require('bing-translate-api');

const bot = new Bot("");
bot.use(session());


bot.command("start", async (ctx) => {
  ctx.session = ctx.session || {};
  ctx.session.language = ctx.session.language || ''; 

  if (!ctx.session.language) {
    // User has not selected a language yet
    const text = 'Assalamualaikum!nHi, nice to meet you! I am Ayakan. I can help you search for Surah. Select the button below to choose your language.';
    const buttonText = 'Select Language';
    const languageButton = { text: buttonText, callback_data: 'pilih_language' };
    const inlineKeyboard = new InlineKeyboard();
    inlineKeyboard.row(languageButton);
    await ctx.reply(text, { reply_markup: inlineKeyboard });
  } else {
    // User has already selected a language
    const defaultText = 'Assalamualaikum!nHi, nice to meet you! I am Ayakan. I can help you search for Surah. Select the button below to get started.';
    const defaultButtonText = 'Pilih Bahasa';

    let translatedText = defaultText;
    let translatedButtonText = defaultButtonText;

    if (ctx.session.language) {
      try {
        translatedText = await translate(defaultText, ctx.session.language);
        translatedButtonText = await translate(defaultButtonText, ctx.session.language);
      } catch (error) {
        console.error('Translation error:', error);
        // Handle translation error (fallback to default text)
      }
    }

    const inlineKeyboard = new InlineKeyboard();
    const languageButton = { text: translatedButtonText, callback_data: 'pilih_language' };
    inlineKeyboard.row(languageButton);
    await ctx.reply(translatedText, { reply_markup: inlineKeyboard });
  }
});


bot.callbackQuery('pilih_language', async (ctx) => {
  const inlineKeyboard = new InlineKeyboard();
  const languages = [
    { name: 'English', code: 'en' },
    { name: 'Indonesia', code: 'id' },
    { name: 'Chinese', code: 'zh-Hans' },
    { name: 'Japanese', code: 'ja' },
    { name: 'Korean', code: 'ko' }
  ];

  languages.forEach(language => {
    const languageButton = { text: language.name, callback_data: `language_${language.code}` };
    inlineKeyboard.row(languageButton);
  });

  await ctx.editMessageText('Select The Language:', { reply_markup: inlineKeyboard });
});


bot.callbackQuery(/language_(w+)/, async (ctx) => {
  ctx.session = ctx.session || {};
  ctx.session.language = ctx.match[1] || '';

  if (ctx.session.language) {
    const inlineKeyboard = new InlineKeyboard();
    const infoButton = { text: 'Back', callback_data: 'h' };
    await ctx.editMessageText(`Bahasa telah diubah menjadi ${ctx.session.language}.`, { reply_markup: inlineKeyboard.add(infoButton) });
  }
});


bot.callbackQuery("h", async (ctx) => {
  ctx.session = ctx.session || {};
  ctx.session.language = ctx.session.language || '';
  const text = 'Assalamualaikum!nHi, nice to meet you! I am Ayakan. I can help you search for Surah. Select the button below to get started';
  const buttonText = 'Pilih Bahasa';
  const translatedText = await translate(text, ctx.session.language);
  const translatedButtonText = await translate(buttonText, ctx.session.language);
  const inlineKeyboard = new InlineKeyboard();
  const languageButton = { text: translatedButtonText, callback_data: 'pilih_language' };
  inlineKeyboard.row(languageButton);
  await ctx.editMessageText(ctx.chat.id, translatedText, { reply_markup: inlineKeyboard });
});


bot.command('surah', async (ctx) => {
  try {
    ctx.session = ctx.session || {};
    const response = await axios.get(quranApiUrl);
    const surahList = response.data;
    let surahText = `List Surah:nn`;

    for (let i = 0; i < surahList.length; i++) {
      surahText += `${surahList[i].number}. ${surahList[i].name}n`;
    }

    const inlineKeyboard = new InlineKeyboard();
    const infoButton = { text: 'Info', url: 'https://t.me/Ayakaninfo' };
    inlineKeyboard.row(infoButton);

    await ctx.reply(surahText, { reply_markup: inlineKeyboard });
  } catch (error) {
    console.log(error);
    ctx.reply('Error retrieving surah list. Please try again later.');
  }
});

bot.callbackQuery(/surah_(d+)/, async (ctx) => {
  const surahNumber = ctx.match[1];
  ctx.session = ctx.session || {};
  console.log('Sending Surah:', surahNumber);

  try {
    const response = await axios.get(`${quranApiUrl}/${surahNumber}`);
    const surahData = response.data;
    const { ayahs } = surahData;
    const maxMessageLength = 4096;

    let message = ''; 

    for (const ayah of ayahs) {
      const translatedText = await translate(ayah.translation, ctx.session.language);
      const ayahText = `${ayah.number.inSurah}. ${ayah.arab}nn ${translatedText.translation}n`;

      // Check if adding the current ayah will exceed the maximum message length
      if ((message + ayahText).length > maxMessageLength) {
        // Send the current message
        ctx.reply(message);

        // Start a new message with the current ayah
        message = ayahText;
      } else {
        // Add the current ayah to the message
        message += ayahText;
      }
    }

    // Send the remaining message if there's any
    if (message.length > 0) {
      ctx.reply(message);
    }

  } catch (error) {
    console.log(error)
    ctx.reply('Error retrieving surah data. Please try again later.');
  }
});

bot.start();

im trying start the bot and select the language at the bot using the code i write before. language is already selected but then the bot giving error TypeError: Cannot read properties of undefined (reading 'language') at translate (C:UsersFarihdownloadsquranbotnode_modulesbing-translate-apisrcindex.js:327:26) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async C:UsersFarihdownloadsquranbotbot.js:86:26

I want the bot when the user already click the selected language. the bot will send the text with the language selected before. Sorry for my bad code because im new using nodejs. Thank you for the correcting my code 🙂

How to show shared screen to multiple participants peerjs?

I’m working on a web application that uses PeerJS for real-time communication. Initially, I was rendering video and name information for 2 participants simultaneously, and that was working well. However, I recently attempted to expand the application to accommodate 3 participants at the same time, and I’m encountering an issue when sharing screens.
Problem: When I initiate screen sharing, not all of the participants can see the shared screen. Although I have successfully rendered the video and name for the 3rd participant, but candidate’s shared screen is visible to only one interviewer.

`const generateRoom = (room,randomNum)=>{

room_id = "DELTA" + room + randomNum + "MEET";


console.log("generateRoom start--->")
peer = new Peer(room_id)
peer.on('open', (id) => {
getUserMediaScreen({ video: true, audio: true },
    (stream) => {
        // Success: Store the stream
        local_stream = stream;
        console.log('User media obtained successfully.');
    },
    (err) => {
        console.error('Error obtaining user media:', err);
         if (err.name === 'NotAllowedError') {
            console.log('User denied permission for media access.');
        } else if (err.name === 'NotFoundError') {
            console.log('Requested media devices not found.');
        } else {
            console.log('Other getUserMedia error:', err);
        }
    }
);

});

peer.on('call', (call) => {
    console.log(call);
    currentPeer = call;
    call.answer(local_stream);
    console.log(local_stream);
    call.on('stream', (stream) => {
      console.log(stream);
        var sharedproUserRoom =  "${Client}"
        if (sharedproUserRoom == "Client") {
          setTimeout(() => {
            setRemoteStream(stream)
          }, 1000);
        }
    })
   currentPeer = call;
   console.log("---> on call local_stream",local_stream)
})

peer.on('error', (err) => {
console.error('PeerJS error:', err);
$('#startScreenShare').show();
$('#stopScreenShare').hide();
$('#questionCodeBox').hide();
$('#modal-background').hide();
screenSharing = false;
if (!screenSharing) return;
let videoTrack = local_stream.getVideoTracks()[0];
if (peer && currentPeer) {
  let sender = currentPeer.peerConnection.getSenders().find(function (s) {
    return s.track.kind == videoTrack.kind;
  })
  sender.replaceTrack(videoTrack)
}
screenStream.getTracks().forEach(function (track) {
  track.stop();
});

   if(peer){
   peer.destroy();
 }
 
});


peer.on('close', () => {
  console.log("close function called >>>")
// Find and remove the user's ID from the participantsInRoom array
const index = participantsInRoom.indexOf(peer.id);
if (index !== -1) {
  participantsInRoom.splice(index, 1);
  }
});

console.log('generateRoom end>>')

}

function startScreenShare(room) {
let randomNumber = Math.floor((Math.random() * 100000) + 1);

stompClient.send(‘/app/application’, {}, JSON.stringify({ jobId : jobId, candidateId : candidateId, roomId:room,activity :”shareScreenstartedTrue”,randomNumber:randomNumber}))

joinRoom(room,randomNumber);

 if (screenSharing) {
   stopScreenSharing()
  }
 
  navigator.mediaDevices.getDisplayMedia({video:true}).then((stream) => {
    screenStream = stream;
    let videoTrack = screenStream.getVideoTracks()[0];
   
    // Check if the user is sharing the entire screen
    let displaySurface = videoTrack.getSettings().displaySurface;
    const url = window.location.href
    let segments = url.split('/');
    let jobId = segments[segments.length - 2];
    let candidateId = segments[segments.length - 1];
    if(displaySurface == 'window' || displaySurface== 'browser'){
     stompClient.send('/app/application', {}, JSON.stringify({jobId : jobId, candidateId : candidateId,userAlertMessage:displaySurface }))
    }
    if (displaySurface !== 'monitor') {
    screenSharing = true
    stopScreenSharing();
    $.notify("Please share entire screen!", { className: "failure" });
    return;
   }
    saveUserScreenSharedActivity(room,true);
   
    videoTrack.onended = () => {
      stopScreenSharing()
    }
    if(peer && currentPeer) {
      let sender = currentPeer.peerConnection.getSenders().find(function (s) {
        return s.track.kind == videoTrack.kind;
      })
     
      if (sender) {
      sender.replaceTrack(videoTrack)
      screenSharing = true
      setTimeout(() => {
        stompClient.send('/app/application', {}, JSON.stringify({ jobId : jobId, candidateId : candidateId, shareScreen: "true",activity :"shareScreenTrue" }))
      }, 1000);
      $('#stopScreenShare').show();
      $('#questionCodeBox').show();
      $('#startScreenShare').hide();
     }
      else {
                console.error("Sender not found for screen sharing.");
            }
    }

    // Share screen with all participants in the room
peer.on('open', (id) => {
  // Loop through all participants in the room and initiate screen sharing calls

  participantsInRoom.forEach((participantId) => {
    if (participantId !== id) {
      const screenSharingCall = peer.call(participantId, screenStream, { metadata: { type: 'screenshare' } });
      console.log("screen sharing call>>>-->>",scre)
      screenSharingCall.on('close', () => {
        // Handle screen sharing call closure
        console.log("screen sharing call closed.......", )
      });
    }
  });
});

   
    function setupPeerConnection() {
        // peerConnection = new RTCPeerConnection();
        currentPeer.peerConnection.oniceconnectionstatechange = handleICEConnectionStateChange;
        screenStream.getTracks().forEach(track => {
        currentPeer.peerConnection.addTrack(track, screenStream);
    });
  }


if (currentPeer.peerConnection.iceConnectionState === 'disconnected') {
$('#startScreenShare').show();
$('#stopScreenShare').hide();
$('#questionCodeBox').hide();
$('#modal-background').hide();
screenSharing = false;
if (!screenSharing) return;
let videoTrack = local_stream.getVideoTracks()[0];
if (peer && currentPeer) {
  let sender = currentPeer.peerConnection.getSenders().find(function (s) {
    return s.track.kind == videoTrack.kind;
  })
  sender.replaceTrack(videoTrack)
   setupPeerConnection();
}
screenStream.getTracks().forEach(function (track) {
  track.stop();
});
     }

  })

}`

Error screenshot:
console error screenshot

SharePoint Online Filter By URL

I am working with the SharePoint API and trying to filter search results based on specific URLs. Currently, I have the following search query:

http://www.test.com/_api/search/query?querytext=%27Hello%27&trimduplicates=false&sortlist=%27Write:descending%27&rowlimit=5000

I want to filter the results from the API based on the following URLs:

https://www.test.com/SiteTest
https://www.test.com/Divisions/Academy
https://www.test.com/Divisions/National

Is there a specific filter or URL parameter that I can use in the SharePoint API to achieve this? I appreciate any guidance or examples on how to implement this filtering logic.

How to stop this behaviour in Javascript [closed]

I was trying to make a functionality where I have number of buttons inside a div when ever I click a button it triggers removing and adding a class inside another div
CODE: –

tabContainer.addEventListener("click", function (e) {
   // e.target.preventDefault();

  // Removing active class
  cardContent.forEach((c) => c.classList.remove("card__content--activate"));
  tabBtn.forEach((b) => b.classList.remove("btn-active"));
  // Activate tab button
  e.target.classList.add("btn-active");

  // Activate content
  document
    .querySelector(`.card__content--${e.target.dataset.tab}`)
    .classList.add("card__content--activate");
});

enter image description here

Now the problem is when I click the space between the buttons the div below disappears how to control that?
enter image description here