How to know to understand dayJS

I have a date ‘08.06.2024’
08 – day
06- mounth
2024 – year
BUT DAYJS .But it sees it this way
08 – mounth
06 – day
2024 – year

How can I make him think otherwise?

Nothing helps meNothing helps meNothing helps meNothing helps meNothing helps meNothing helps meNothing helps meNothing helps meelps meNothing helps meelps meNothing helps me

React State isn’t updating inside an API callback

I am trying to update some state variables in my react app, the setstate method is called inside the API callback function. however the state doesn’t update

Every step in the code works fine except for the state update code inside the “.then” callback function of axios request.

here is the axios request code down below

  const [userOTP, setUserOTP] = useState(0)
  const [apiOTP, setApiOTP] = useState(0)

  const handlesubmit = (e) => {
    e.preventDefault();
    setIsPhoneNumberSubmitted(true)

    // Login API Call
    axios({
      url: loginRequestData.url,
      method: loginRequestData.method,
      params: loginRequestData.params
    })
    .then((response) => {
      setCurrentUid(response.data.uid)
      // get OTP for validation API call
      axios({
        url: `https://api-url.com?params`,
        method: OTPRequestData.method,
        params: OTPRequestData.params
      })
      .then((response) => {
        // console.log('GET OTP ____________', typeof(response.data.OTP))
        let otpFromAPI = response.data.OTP
        // problem below
        setApiOTP(otpFromAPI)
      })
      .catch(error => {
        console.error("Error is ____________", error)
      })
    })
    .catch(error => {
      console.error("Error is ____________", error)
    })
  }

I am controlling the OTP form submissions using the method below, when i checked with the state varibles, those persist the initial value itself.

  const handleOTPSubmit = (e) => {
    e.preventDefault()
    console.log(`userOTP: ${userOTP} & apiOTP: ${apiOTP}`)
    if(userOTP === apiOTP) {
      // setIsOTPcorrect(true)
      // navigate('/consultation-mode')
      console.log('Entered OTP is correct')
    } else {
      console.log('Entered OTP is incorrect :crossmark:')
    }
  }

the getOTPFromInput() is a method passed as prop to the otp input component

  const getOTPFromInput = (OTP) => {
    // the problem below
    setUserOTP(Number(OTP.join('')))
  }

mocking a dependency of a module with Jest not working as expected

Given the following files (a module and a test), using Typescript and jest can someone please explain why mocking the dependency function addOne doesn’t work?

// mocking.ts

export function addOne(num: number){
  return num + 1;
}

export function dependent(num: number){
  return addOne(num);
}





// mocking.test.ts

import { addOne, dependent } from "./mocking";
jest.mock('./mocking', () => ({
  ...jest.requireActual('./mocking'),
  addOne: jest.fn(),
}));
describe('mocking', () => {

  it('should mock addOne successfully', () => {
    const result = dependent(1);
    const mockAddOne =    jest.mocked(addOne).mockReturnValue(900);
    expect(mockAddOne).toHaveBeenCalled();
    expect(result).toBe(901);
  });

});

result:

`
Expected number of calls: >= 1
Received number of calls: 0

   9 |     const result = dependent(1);
  10 |     const mockAddOne = jest.mocked(addOne).mockReturnValue(900);
> 11 |     expect(mockAddOne).toHaveBeenCalled();
     |                        ^
  12 |     expect(result).toBe(901);
  13 |   });
  14 |

`

I’ve tried various ways of mocking the addOne function and the module but I can’t get it to work

When i set a v-for, props undefined

I’m doing a website of a League of Legends assist, and i have a component with five elements (one for each line). I had it setted without a v-for, and it worked perfect, but when i configured it with a v-for for future eficiency, it gives me a error of not getting the prop passed by the father.

If i remove the v-for it works perfectly.

Here is the code without the v-for:

<template>
    <div class="champsIconsSelection">
      <button class="champIconSelection" :class="{[lado]: true, picked: (this.rolePicked==='TOP'), setted: (this.champsPicked[0] !== 0)}" @click="pickRole('TOP')">
        <img :src="'/static/icons/'+ this.champsPicked[0] +'.jpg'" v-if="this.champsPicked[0] !== 0">
      </button>
      <button class="champIconSelection" :class="{[lado]: true, picked: (this.rolePicked==='JGL'), setted: (this.champsPicked[1] !== 0)}" @click="pickRole('JGL')">
        <img :src="'/static/icons/'+ this.champsPicked[1] +'.jpg'" v-if="this.champsPicked[1] !== 0">
      </button>
      <button class="champIconSelection" :class="{[lado]: true, picked: (this.rolePicked==='MID'), setted: (this.champsPicked[2] !== 0)}" @click="pickRole('MID')">
        <img :src="'/static/icons/'+ this.champsPicked[2] +'.jpg'" v-if="this.champsPicked[2] !== 0">
      </button>
      <button class="champIconSelection" :class="{[lado]: true, picked: (this.rolePicked==='ADC'), setted: (this.champsPicked[3] !== 0)}" @click="pickRole('ADC')">
        <img :src="'/static/icons/'+ this.champsPicked[3] +'.jpg'" v-if="this.champsPicked[3] !== 0">
      </button>
      <button class="champIconSelection" :class="{[lado]: true, picked: (this.rolePicked==='SUP'), setted: (this.champsPicked[4] !== 0)}" @click="pickRole('SUP')">
        <img :src="'/static/icons/'+ this.champsPicked[4] +'.jpg'" v-if="this.champsPicked[4] !== 0">
      </button>
    </div>
</template>

And here is with the v-for:

<template>
    <div class="champsIconsSelection">
      <div v-for="position in positions" v-bind:key="position.pos">
        <button class="champIconSelection"
                :class="{[lado]: true, picked: (this.rolePicked && this.rolePicked===position.role), setted: (this.champsPicked[position.pos] !== 0)}"
                @click="pickRole(position.role)">
          <img :src="'/static/icons/'+ this.champsPicked[position.pos] +'.jpg'" v-if="this.champsPicked[position.pos] !== 0">
        </button>
      </div>
    </div>
</template>

The rest of the component, in case it’s useful:

<script>
export default {
  name: 'champ_selector',
  props: ['lado', 'rolePicked', 'champsPicked'],
  data () {
    return {
      positions: [
        {
          'pos': 0,
          'role': 'TOP'
        },
        {
          'pos': 1,
          'role': 'JGL'
        },
        {
          'pos': 2,
          'role': 'MID'
        },
        {
          'pos': 3,
          'role': 'ADC'
        },
        {
          'pos': 4,
          'role': 'SUP'
        }
      ]
    }
  },
  methods: {
    pickRole (role) {
      this.$emit('pickRole', role)
    }
  }
}
</script>

This is the parent component:

<template>
  <main>
    <div id="champZone">
      <div id="blueChampSelect">
        <champSelect :lado="'blue'" :rolePicked="b_rolePicked" :champsPicked="b_champsPicked" @pickRole="pickRoleB"></champSelect>
      </div>
      <div id="champList">
        <champList @setChamp="setChamp"></champList>
      </div>
      <div id="redChampSelect">
        <champSelect :lado="'red'" :rolePicked="r_rolePicked" :champsPicked="r_champsPicked" @pickRole="pickRoleR"></champSelect>
      </div>
    </div>

    <dataZone></dataZone>
  </main>
</template>

<script>
import champList from './ChampList.vue'
import champSelect from './ChampSelect.vue'
import dataZone from './DataZone.vue'

export default {
  data () {
    return {
      b_rolePicked: '',
      r_rolePicked: '',
      b_champsPicked: [0, 0, 0, 0, 0],
      r_champsPicked: [0, 0, 0, 0, 0],
      roleDict: {'TOP': 0, 'JGL': 1, 'MID': 2, 'ADC': 3, 'SUP': 4}
    }
  },
  components: {
    champList,
    champSelect,
    dataZone
  }
}
</script>

I tried setting something in the variable passed throught the ‘rolePicked’ prop, but it didn’t work either.
It feels weird.

How to get consistent duration when using ScrollMagic `.on(‘progress’)` callback?

I am using this library https://github.com/janpaepke/ScrollMagic .
I create a ScrollMagic based animation of 4 elements fade in and out according to the Scene e.progress value. For example when e.progress > 0.3 && e.progress < 0.5 it makes this.cIndex = 1; which trigger first element fade out and the second one fade in.

I implement this by using progress callback of scrollMagic as code below.
Basically, this code works well, but there is one problem: this.cIndex may turns from 1 to 3 very quickly when user scroll too fast, as a result the animation duration of 4 elements is not consistent.

 new ScrollMagic.Scene({
    triggerElement: pinEl2,
    triggerHook: 'onLeave',
    duration: 1000,
  })
    .setPin(pinEl2)
    .on('progress', (e) => {
      const base = 0.3;
      const unit = (1 - base) / 4;
      if (e.progress <= base) {
        this.cIndex = 0;
      } else if (e.progress > base && e.progress <= base + unit) {
        this.cIndex = 1;
      } else if (e.progress > base + unit && e.progress <= base + unit * 2) {
        this.cIndex = 2;
      } else if (e.progress > base + unit * 2) {
        this.cIndex = 3;
      }
    })
    .addTo(this.controller);

ChartJS Stacked Bar- but always stay on 100% on y-axis

JSFiddle : https://jsfiddle.net/jze1kr6u/2/

    const data = [{"band_1_correct":"16","band_1_total":"20","band_2_correct":"15","band_2_total":"20","band_3_correct":"12","band_3_total":"20","band_4_correct":"15","band_4_total":"21","band_5_correct":"13","band_5_total":"19","band_6_correct":"0","band_6_total":"0"}];

 
 var correctCounts = [];
    var totalCounts = [];
    var difficultyLevels = [];

    var difficultyData = data[0]; // Access the first element of the array

    // Iterate over the difficulty levels
    for (var i = 1; i <= 6; i++) {
        var levelKey = 'band_' + i;
        difficultyLevels.push('Band ' + i);

        var correctCount = parseInt(difficultyData[levelKey + '_correct']);
        var totalCount = parseInt(difficultyData[levelKey + '_total']);

        if (totalCount === 0) {
            correctCounts.push(0); // Handle division by zero case
        } else {
            var correctPercentage = (correctCount / totalCount) * 100;
            correctCounts.push(correctPercentage.toFixed(2));
        }

        totalCounts.push(100); // Set total count to 100%
    }

    var ctx = document.getElementById('barChart1').getContext('2d');
    var barChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: difficultyLevels,
            datasets: [
                {
                    label: 'Correct',
                    data: correctCounts,
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    stack: 'combined' // Stack the bars
                },
                {
                    label: 'Total',
                    data: totalCounts,
                    backgroundColor: 'rgba(255, 99, 132, 0.5)',
                    stack: 'combined' // Stack the bars
                }
            ]
        },
        options: {
            scales: {
                x: {
                    beginAtZero: true
                },
                y: {
                    beginAtZero: true,
                    max: 100, // Set y-axis maximum to 100
                    stacked: true // Stack the bars
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            var label = context.dataset.label || '';
                            var value = context.parsed.y || 0;
                            if (label === 'Correct') {
                                return label + ': ' + value + '%';
                            } else {
                                return label + ': 100%';
                            }
                        }
                    }
                }
            }
        }
    });

Above is the working code of the chart, but What i wanted to do is, Y-Axis will be always 100%, so for example on Band 1 (the band_1_correct is 80%), so it will filled up 80% of band_1_total, instead of stacking up

Tried couple of method from other post such as adding : stacked: false, not helping the issue i am facing

Trying to fetch a-z-animals but getting 403 error

I’m trying to web scrape a-z-animals using node-fetch but I’m getting a 403 error that says I need to “Enable JavaScript and cookies to continue”, how do I fix this?

const fetch = require("node-fetch") await fetch("https://www.a-z-animals.com")

I used reqbin and got the same result:

<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>Just a moment...</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="robots" content="noindex,nofollow">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="/cdn-cgi/styles/challenges.css" rel="stylesheet">


</head>

<body class="no-js">
    <div class="main-wrapper" role="main">
        <div class="main-content">
            <noscript>
            <div id="challenge-error-title">
                <div class="h2">
                    <span class="icon-wrapper">
                        <div class="heading-icon warning-icon"></div>
                    </span>
                    <span id="challenge-error-text">
                        Enable JavaScript and cookies to continue
                    </span>
                </div>
            </div>
        </noscript>
            <div id="trk_jschal_js" style="display:none;background-image:url('/cdn-cgi/images/trace/managed/nojs/transparent.gif?ray=7d3fd55a9f20c425')"></div>
            <form id="challenge-form" action="/?__cf_chl_f_tk=9AqesBTIJLb0a3FMrhs.mNeDl1PmeyrmejA0lWutgGc-1686213661-0-gaNycGzNCqU" method="POST" enctype="application/x-www-form-urlencoded">
                <input type="hidden" name="md" value="T8sY2HeCtL0_v6nqNPblDxVYSHRenzTXrfgJbBY2eNw-1686213661-0-AY9LXiyF8Ro1iKhVNq20bsXN4g7l_s0-gnasONdWzl-WMM54798xmgGwDZkfZ9whLw7YbQDiOR6hDotQUajnN7BeYST5k6S4Jxw2ubsNHUOoIY8zM6iMa39dKTdgKQIqgKJ2750gg2m6_jGrmHozkY7k5E5WHyQpNFORlcnYkXW4H853JkLNAseof2FSHcIDU-y0tKiBQEavdKYqctIzRLNlHHugHLWdEv7SRLcVWKMZsCMJfHedUDgWFgwmkgSq1X7BdgCm9mK_9z2ToWdD-X1NEBhT57ciX2yG-86A7l_mSUInIwRTNqLozXPPm2-v9GCZcrhxapm1HEGYv6IwP7SEQnEV_UZ75qhJjy61sH2R0_stfxf6qaU7eNKIPXI_12Bv3STMJHToF1oUSndDmFgzC71TeWCwkgO6LUCJLyuPtsX8JehtZH6JPvh24Np6ZiLYSjfJYOA5GNGACiObNO5kfDy8XCJ4_2imgX_rmXLboFjpAgjQy24JUXr1lNuOrXPyaAAzM_U5-3k51jWuZtVClEdz4nZTG0sw1xFl-qlHDycH0k9KP2Qx8h3ZxV3P4DjOc1jFrdxcnaJ1Eh_33fWfJAXJOjHkM9aOb0uNsg0wFQn6XSmw-_G6vM-ihYxcZpy8o4lSRp9lI0ikbpEFqbnSgpw5NjMZqOGP8XbZwddJCbLh1HNOybmkGhZnk8dM9LSyVyeMhsye0VuWmxzrSGH96d5UC-H9HZRExC_XClSjlclUwbAzCIC96klSEORKr-YM0EgJSttikwc4knRbRaXB_eNOB-AKAGldOAgBYTLbRYsnW8gDlSx4Zq8nopIUAU4GbOvlgvXan3L5MbT7zTINMOv7qPsfbeCEnUEGnqzIAgZBM8DwB6N85_Xa0kl1NW88OmO3lW0Io5MWj_bDo-Iza3sO6VPmmIuhrfR6IIJzqEAzSuoudCyY96Lp1Ox4cT_TpOmbbJs4MqzW-3Rihhq1GCXWREFXgBzobBj-3ig5Aq_MPTX_CsOgePQ5HZRuFYRAEYcqyhguyNg7vfKI46BfAAjpj-uylUAFncr79Q-yWbdccwEkZSsE1pHFqxfKBT7Ktg1hoVOrHjhiXE9iQRfCe5XjUgtDWD4Co5rAxkxeoT6XkoMG9IAobcuKzpUGCq4HtqfukA2UKcEbgyZdUTbFjvnsygkqHCMO7-yAFIexPnh7WK6gkaNH8GRdMXPH5uQ4hic7a8e1-2QxkZEkkZuesE6h9WpD42EHTVk4Ww7rEqeqPe2GL-VMaewf3ZmPrFLa9zv370c_wJ7Zq5CwcHTfcPD-5qWA6eDEqCWoo3XnCLInoBOWCSta7HAXNw0Iau8a5BWh16ro_1Iqjh2uO-tydPY5aAlXqElEZirea3AqEGy2V2uWkQFNY6l1WXGJ1gqhwmTwzxspZPZHoHOheJpUN3EsNlytV9PpSlpHwFjlSBimwnvSI_pn6psoFEUVMgtAN5cLufWH2MPLcuheJPbVeJw4WVAJuBPCHp3t0mz9VM72CHZljQGrYZmZ3UhVkvKMJE60xGegTsccrhIm0U9ZNb4erkP7MO8iogpjk4b4ktjNf1rK0unpm3RXNUYEmmJr2s9KWlVtq9bp46vPWT7TLdsWSXvQjiN926iEKyn_Ilq51aM2i3fj3rhEE4SzkE6EuhPiWNK1SlDre9n0wl4aFkUopCiSIfz5HJrVhl1KPQI8_ZnIf0mBVwz3brDKu4qvIQIUGd-uNWN1lfZbaBgWKdZndBjIx6hML3tA20lFthKmHXSKBr9bQ1r-JaKTwGc8CGfuiKTW7AhgyRSqJMHH4FLt1oPb3ebRxupfwL_bJlN6eVb5kQqzlnyVLGsOUQekefsG-zJfPtYZ5TX48LfeCx10_eb6S2fyNxbQc0pOOnL3Ucu_oPASmlg69bPxgDowy7770JtaRBrB1itahEy4mkx8v-kCxqOp-LjU8xFAQqFbmwzGeaLLu7QFyAiq3tqfud1hBYxMSemQWI0dFTuk6NMk2w5l0q9D-jkXdIMBQnMGcY4EMIXAnCvIl5Y6cV54z6v3SsA9orwpgl5GKxxi5eCUSdQI88lzlYY4qpaZ_g3w_pkBNUEorLhsPSV3Ztl77wXsLH7D4HulsFKxpqwRG8X6okN3uOmqt5icNO9j2FBEn4fON6bYSZky_-RQgu4E2L7c-NGejtQbV4KcJzKjnQB78npbZb2x8En1FLIGM_F4AaSfcvPgLFSyWOZKFlHVccAG-pAjU_zee20cOE0bTKZooCLO1qOU8gG4g8nUht4IJy-E-1zSnUTaLqlCO3XQKGug2djKMrDz1lJQ_wjqDehLM9mMWK4cHCg_xpI24dd3hBasu-4Z0h4ttaZRPcDD8iiFu2w6go0u6Q8RNvO8kYIHUA4B8HGOe-AvnoUHqnHIHjgvrXlXtX_-MDFBS_XTNeAcXd1IdXlawnN3e1BcsQyTmFFf_pf471cJS7ifSTWGcDNFjspJyt5jQZ4ioRcetNVE2FFvyU-rxOacv9W8NvZZl6sMWWn_NLFOlKrN8JBnwPpkPTXHDO8f5G_MmGCQcO4ZjO5k_iRLLKiY5DApGDwOsH7BYc7_e7WDn1HHWdSZlDDH8l523s0wBNvf3ZthBjcRuBb2Smd4B6mBdd_Sv6Cc4ZYozYr57UdG3ejS">
            </form>
        </div>
    </div>
    <script>
        (function() {
            window._cf_chl_opt = {
                cvId: '2',
                cZone: 'a-z-animals.com',
                cType: 'managed',
                cNounce: '79302',
                cRay: '7d3fd55a9f20c425',
                cHash: 'e5fabc89c0759bb',
                cUPMDTk: "/?__cf_chl_tk=9AqesBTIJLb0a3FMrhs.mNeDl1PmeyrmejA0lWutgGc-1686213661-0-gaNycGzNCqU",
                cFPWv: 'b',
                cTTimeMs: '1000',
                cMTimeMs: '0',
                cTplV: 5,
                cTplB: 'cf',
                cK: "",
                cRq: {
                    ru: 'aHR0cHM6Ly9hLXotYW5pbWFscy5jb20v',
                    ra: 'TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExMy4wLjAuMCBTYWZhcmkvNTM3LjM2IFgtTWlkZGxldG9uLzE=',
                    rm: 'R0VU',
                    d: '3LxDxIzNrb9/fnBOnbT2rOljR6/F1n4zAiEiAvWIgmSf8OQvZHOUOd0f7+TqvTY+mPb4fbssU5tnj3xOqV0iR3HmFTbJCJfmk4bixqDjSOPuBqKDnyJl2V219HtW8Yq+ajCobbUAuVdcpGf3Rxvbmr+5Q5QXfhMUHigBL6OjvCLXQ3w1bQu+Ds4Gr5N6Wp1pmAuw0C4PbO862hd5SjynUXaMs2oJxGzgfugtRrKUVd6UqdzE2xJa9cC5WPNci+hadJyEw0AqKBe18Amex4dCs0H1Eixuy+z+ltB1icJM49sTYXnpuU4YoqPwm5XAMQojmI/wyr+pYaSOYK2yIE/+Q2AyfIspx5IeDphx09iCWMZpxEu3oVUbkyoc9xGRFkdoCK4L5ShH3R8l7wqVXp7m2PCYQIoKrYkz8e/gBUhVbxSADnyvl9uB33DqyfjlkmW2cSSkbNvwkIqBA5KusVXwnDdflyAvjxloMYWsnF41HcKEcUZ6WfsXx81lnPfl/2+0joqkKogMdtLXmWGftmN0oqzEW0H4CoIKXtz4RYM4FcILoJ/s/R415Amh0l7px5C8Ddcbxz/FJTFxHAxFJXjCs3QuwAdoXqrNSEvPAzZ2pO1CWhHuCfSja+dE3DW/v+/C',
                    t: 'MTY4NjIxMzY2MS44NTMwMDA=',
                    cT: Math.floor(Date.now() / 1000),
                    m: 'LDOguUJ5vPB/XftJH3ZlytwszCeRu13n8x930/iN4lc=',
                    i1: 'EezHxn/NAqXiqD4lKBR7Uw==',
                    i2: 'aA6jZUtqp35Qi7T5R0LNAg==',
                    zh: 'O5n2TQTOKmSdzbZJ3v5g6pGOsfcv8Cju0RHpZMkxPQ0=',
                    uh: 'CQto/H/0vbU8R+8P1UgFYdNmj/SlB6bS/mJU8aHsKfg=',
                    hh: 'EvpKtqjHM6twb5PDiA1pNbu4YpGP91kpyeLzmLtqCsM=',
                }
            };
            var trkjs = document.createElement('img');
            trkjs.setAttribute('src', '/cdn-cgi/images/trace/managed/js/transparent.gif?ray=7d3fd55a9f20c425');
            trkjs.setAttribute('alt', '');
            trkjs.setAttribute('style', 'display: none');
            document.body.appendChild(trkjs);
            var cpo = document.createElement('script');
            cpo.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/managed/v1?ray=7d3fd55a9f20c425';
            window._cf_chl_opt.cOgUHash = location.hash === '' && location.href.indexOf('#') !== -1 ? '#' : location.hash;
            window._cf_chl_opt.cOgUQuery = location.search === '' && location.href.slice(0, location.href.length - window._cf_chl_opt.cOgUHash.length).indexOf('?') !== -1 ? '?' : location.search;
            if (window.history && window.history.replaceState) {
                var ogU = location.pathname + window._cf_chl_opt.cOgUQuery + window._cf_chl_opt.cOgUHash;
                history.replaceState(null, null, "/?__cf_chl_rt_tk=9AqesBTIJLb0a3FMrhs.mNeDl1PmeyrmejA0lWutgGc-1686213661-0-gaNycGzNCqU" + window._cf_chl_opt.cOgUHash);
                cpo.onload = function() {
                    history.replaceState(null, null, ogU);
                };
            }
            document.getElementsByTagName('head')[0].appendChild(cpo);
        }());
    </script>


</body>

Screenshot

I used to be able to web scrape this website with no issues until maybe a month ago now, not sure if I should be providing extra headers with my request?

How to restrict unauthorized member to access the URL and redirect to some admin login page

I have couple login page.

laptopsearch.jsp

productsearch.jsp

gmailsearch.jsp

Same logic applied in every pages.

If anyone try to access this page then redirect to admin login (adminlogin.jsp).

$(document).ready(

function() {

let paramsString = (new URL(document.location).searchParams);

let searchParams = new URLSearchParams(paramsString);

var someVarName = localStorage.getItem("someVarKey");

if (!searchParams.has("rwUrl") & someVarName == null) {

var someVarName = "false";

localStorage.setItem("someVarKey", someVarName);

window.location.replace("http://localhost:8080/adminlogin.jsp");

location();

else {

if (icount == 0 & searchParams.has("tester")) {

incrementCount();

window.location.replace("http://localhost:8080/login? rwUrl=variable");

location();

}

}

});

Issue: 1. on accessing any xxxsearch.jsp page it redirecting to adminlogin.jsp while login in adminlogin.jsp and click on hyperlink redirect to xxxsearch.jsp page but when click on search button on xxxxsearch.jsp page it redirect to adminlogin.jsp dashboard.

Issue 2. Once we logout from adminlogin.jsp, if we try to access xxxsearch.jsp page its accessible to everyone not redirecting to adminlogin.jsp page.

Expectation:

1. On click on search button should not redirect to adminlogin.jsp dashboard once we login.

2. Once we logout from adminlogin.jsp page in that case other xxxsearch.jsp page should not be accessibe it should redirect to adminlogin.jsp page.

Kindly help on it.

Thanks in advance.

Can’t figure out how to properly use easing function

I really need help to figure out on how to use these easing functions I found on this helpful website: https://spicyyoghurt.com/tools/easing-functions

I know what the values that the function needs means, I created a function in one of my classes that helps me get the current time (t) to pass it to the function afterwards:

getEaseTimeVar()
{
    var timeStamp = performance.now();
    this.#secondsPassed = (timeStamp - this.#oldTimeStamp) / 1000;
    this.#oldTimeStamp = timeStamp;

    return timeStamp;
}

(EXPLANATION)
This function works, but only if it is called at the beginning of the code execution. For example, if I want to fade something in (value from 0 to 1) using a linear easing function and call it at the beginning of code execution, it would increase and even go beyond 1, which is fine, that’s normal. However, if I want to do the same thing, but I want it to start say 5 seconds after code execution, it will not start at 0, but jump to a larger value.

(PROBLEM)
This is because I think I am not getting the time at which the animation starts, but from the start of all code execution, and I am struggling to understand how to do this while still maintaining a simple function to use the easing animation.

Thank you in advance for your help.

Showing holiday events on fullcalendar v3 as in easemytrip mobile view calendar

mobile view calendar from easemytrip.com

I am using fullcalendar v3 in my project. I want to show holidays on the calendar, as shown on attached image marked in red square box.

It should show following as:


  1. on the top – it will show total holidays of each month
  2. it should number 1,2,3 like badge on dates which has holidays for each month
  3. at the bottom of the month it should describe the badge with the holiday name for each month

Ajax response 404

I’m trying to make a ajax call to delete and get a new page in response. But facing 404 error.

<c:forEach items="${listLocation}" var="location">
<tr>
  <td>${location.id}</td>
  <td>${location.code}</td>
  <td>${location.name}</td>
  <td>${location.type}</td>
  <td><a href="deleteLocation?id=${location.id}" id="locID" onclick="return deleteRecord('${location.id}');">Delete</a></td>
</tr>
</c:forEach>

Ajax call

function deleteRecord(locId) 
    {
        let contextURL = 'http://localhost:8080/LocationWeb/LocCon/deleteLocation/'
        let parmURL = contextURL + locId;
        var xhr = new XMLHttpRequest();
        xhr.open("DELETE", parmURL);
        xhr.send();
        xhr.onload = function() 
        {
            if (xhr.status != 200) 
            {
                console.log('ERROR');
            }
            else
            {
              listAllPageCall();
            }
        };
        xhr.onerror = function()
        {
          console.log('NO CONNECTION');
        };
    }
    
    function listAllPageCall() 
    {
        let parmURL = 'http://localhost:8080/LocationWeb/LocCon/listAllLocations/'
        var xhr = new XMLHttpRequest();
        xhr.open("GET", parmURL);
        xhr.send();
        xhr.onload = function() 
        {
            if (xhr.status != 200) 
            {
                console.log('ERROR');
            }
            else
            {
                console.log('Called');
            }
        };
        xhr.onerror = function()
        {
          console.log('NO CONNECTION');
        };
    }

Spring Boot code flow

This is to call the webpage to be displayed

@GetMapping("/listAllLocations")
public String displayLocations(ModelMap resModMap)
{
    List<Location> listLocation = locationService.getAllLocation();
    resModMap.addAttribute("listLocation", listLocation);
    return "displayAllLocations";
}

This is to delete and call the webpage like above one. Both response are same. But still getting the white lable error 404

@DeleteMapping("/deleteLocation/{id}")
public String deleteLocation(@PathVariable int id, ModelMap resModMap)
{
    //Location location = locationService.getLocationByID(id);
    Location location = new Location();
    location.setId(id);
    locationService.deleteLocation(location);
    List<Location> listLocation = locationService.getAllLocation();
    resModMap.addAttribute("listLocation", listLocation);
    return "displayAllLocations";
}

Delete is happening. Only the page is not getting displayed on response. Please help me.

how to create chrome extension for google translate?

I want create chrome extension for translate page to my language.

My solution didn’t work:

function google_translate_api(){
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
  document.body.appendChild(script);
}
function tElement(){
  var gt = document.createElement('div');
  gt.setAttribute("id", "google_translate_element");
  document.body.appendChild(gt);
}
function googleTranslateElementInit() {
  new google.translate.TranslateElement(
    {pageLanguage: 'en'},
    'google_translate_element'
  );
}
chrome.action.onClicked.addListener(async (tab) => {
  if (tab.url || tab.url) {
    const prevState = await chrome.action.getBadgeText({ tabId: tab.id });
    const nextState = prevState === 'ON' ? 'OFF' : 'ON'
    await chrome.action.setBadgeText({
      tabId: tab.id,
      text: nextState,
    });
chrome.runtime.onInstalled.addListener(() => {
    chrome.action.setBadgeText({
      text: "OFF",
    });
  });
  function changeHtmlLangFr(){
    document.documentElement.setAttribute('lang','fr')
    tElement()
    google_translate_api()
  }
  function changeHtmlLangEn(){
    document.documentElement.setAttribute('lang','en')
    tElement()
    google_translate_api()
  }
 if (nextState === "ON") 
 {
      await chrome.scripting.executeScript({
        target : {tabId : tab.id},
        func : changeHtmlLangFr,
      });
    } 
    else if (nextState === "OFF") 
    {
      await chrome.scripting.executeScript({
        target : {tabId : tab.id},
        func : changeHtmlLangEn,
      });
    }
  }
});

I want the entire page to be translated into French by running this extension. and in the manifest.json file there is a suggested_key that to run this extension.

Is there a solution to make this extension? Help me please.

cursor_div wont follow the cursor when I scroll to the bottom

When Im at the top of the page. The curose_div will follow the cursor perfectly. But when I start scrolling to the bottom the cursor_div position will not follow correctly.

Heres my code

<div id="cursor"</div></div id="cursor_border"></div>

`var cursor = $(‘#cursor’);
var cursor_border = $(‘#cursor_border’);

$(document).mousemove(function(e){
    console.log(e.pageY + ' and '+ e.pageX ) ;

    
    var x = e.pageX;
    var y = e.pageY;
    cursor.css("left",x+'px');
    cursor.css("top",y+'px');
    
    cursor_border.css("left",x+'px');
    cursor_border.css("top",y+'px');`