Force ReactJS routes index to reevaluate before redirecting on login

I wish to conditionally include authenticated routes on the routing index of my ReactJS application based on whether a token exists in the user’s local storage. However, for this to work, the routes must be reevaluated on login before redirecting.

Here is the ideal usage scenario:

When the user logs in (handled by the handleLogin function), a token is set in the browser’s local storage, then the user is redirected to "/dashboard".

The ternary operator in router conditionally includes private pages in the accepted routes, intended for letting authenticated users into their dashboard, for instance.

The problem:

It appears that the routes are not updated between the time the token is set and the time the user is redirected. This means that, after a user logs in, they are met with an error because the dashboard is not a valid path yet (even though it should be).

Relevant code snippets:

In LoginPage.jsx:

const handleLogin = () => {
  console.log(
    `Sending login request to ${process.env.REACT_APP_API_URL}/api/auth`,
  );

  fetch(`${process.env.REACT_APP_API_URL}/api/auth`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ email, password }),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.message === "success") {
        // the login was successful
        setToken(data.token);
        console.log("successful login");
        navigate("/dashboard");
        // window.alert("The login was successful");
        // get value of token using useAuth
      } else {
        window.alert(
          `The login failed with the following error:nn${data.error}`,
        );
      }
    })
    .catch((error) => {
      console.error("Could not login: ", error);
      window.alert("An error occurred while trying to login.");
    });
};

In index.jsx:

const Routes = () => {
  const { token } = useAuth();
  const [ isAuthenticated, setIsAuthenticated ] = useState(!!token);

  useEffect(() => {
    setIsAuthenticated(!!token);
  }, [token])

  // route configurations go here

  const routesAuthenticated = [
    {
      path: "/",
      element: <ProtectedRoute />,
      children: [
        {
          path: "/",
          element: <UserDashboardPage />
        },
        {
          path: "/dashboard",
          element: <UserDashboardPage />
        },
        {
          path: "/logout",
          element: <LogoutPage />
        },
      ]
    }
  ];

  const routesUnauthenticated = [
    {
      path: "/",
      element: <LandingPage />
    },
    {
      path: "/login",
      element: <LoginPage />
    },
    {
      path: "/about",
      element: <AboutPage />
    },
    {
      path: "/ipsum",
      element: <IpsumPage />
    }
  ];

  // decide which routes are available to user based on authentication status
  const router = createBrowserRouter([
    // we use the ... operator to combine these arrays into one
    ...routesUnauthenticated,
    ...(isAuthenticated ? routesAuthenticated : [])
  ]);

  // provide configuration using RouterProvider
  return <RouterProvider router={router} />;
};

Attempted fix:

I tried to use the following code to force the routes to reload on login

useEffect(() => {
  setIsAuthenticated(!!token);
}, [token])

Unfortunately, this does not guarantee that the routes are reloaded before handleLogin redirects the user to their dashboard.

My local variable is not being changed with watch in Vue.js + primevue

I have a parent component and a child component. I created a local variable in the child component to copy the parent’s variable and be able to change its value. The problem is that in some circumstances the local variable does not have its value changed to the value of the parent variable, even using watch.

// Child component:

<script setup>

const props = defineProps({
    document: Object,
    documentsSelected: Array,
    requestsSelected: Array,
    visibleAndSelectableRequests: Array,
    allRequestsSelected: Boolean
});

const emit = defineEmits([
    'toggleSelectAllRequests',
    'update:requestsSelected'
]);

const localRequestsSelected = ref([...props.requestsSelected]);

watch(props.requestsSelected, (newValue) => {
    localRequestsSelected.value = [...newValue];
}, {immediate: true});

const toggleRequestsSelection = (request) => {
    emit('update:requestsSelected', request);
}

const toggleSelectAllRequests = () => {
    emit('toggleSelectAllRequests');
}
</script>
<template>
    <Button
        v-if="visibleAndSelectableRequests.length !== 0"
        :label="allRequestsSelected ? 'Uncheck all' : 'Select all'"
        @click.stop="toggleSelectAllRequests"
    ></Button>

    <div v-for="request of document.requests">
        <Checkbox
            v-model="localRequestsSelected"
            :key="request.id"
            :value="request"
            @click.stop="toggleRequestsSelection(request)"
        />
    </div>
</template>

Parent component:

<script setup>
const requestSelected = ref([]);

const toggleRequests = (request) => {
    if (requestSelected.value.includes(request)) {
        requestSelected.value = requestSelected.value.filter(
            (el) => el !== request
        );
    } else {
        requestSelected.value = [...requestSelected.value, request];
    }
}

const toggleSelectAllRequests = () => {
    if (allRequestsSelected.value) {
        requestSelected.value = [];
    } else {
        requestSelected.value = [...visibleAndSelectableRequests.value];
    }

    allRequestsSelected.value = !allRequestsSelected.value;
}
</script>
<template>
    <CardDocument
        v-for="document of documents"
        :key="document.p01_sequencial"
        :document="document"
        :requestsSelected="requestsSelected"
        :visibleAndSelectableRequests="visibleAndSelectableRequests"
        :allRequestsSelected="allRequestsSelected"
        @toggleSelectAllRequests="toggleSelectAllRequests"
        @update:requestsSelected="toggleRequests"
    />
</template>

The strangest thing is that when I click directly on the Checkbox, the value of the parent variable and the child variable change correctly. However, when I click the select or deselect all button, the value of the parent variable changes, while localRequestsSelected is not updated. This prevents the Checkbox from changing. Can someone help me with this? Am I doing something wrong?

How do I access vite `base` config in app?

I recently used the base config API in my Vite app for deployment reasons:

// vite.config.js
export default defineConfig({
    plugins: [vue()],
    base: "/f2e/",
});

The file structure, in a nutshell, looks like this:

app
╞-public
|  └-foobar.jpg
└-src
   └-App.vue

As you see, there’s an image in my app, using:

<!-- src.App.vue -->
<template>
    <img src="/foobar.jpg" />
</template>

Not surprisingly, the <img /> element is broken since the path is incorrect:

In /foobar.jpg

The server is configured with a public base URL of /f2e/ – did you mean to visit /f2e/foobar.jpg instead?

I know that we can use /f2e/foobar.jpg to fix the path, but, are there any APIs built in Vite that can access the base config? Just something like:

<!-- src.App.vue -->
<template>
    <img :src="locdBasePath() + '/foobar.jpg'" />
</template>

Because I don’t think attaching the /f2e/ path in an app is a good practice, and refactoring all paths takes a lot of effect.

Have read Configuring Vite but nothing useful for my situation.

Automating the logging hours process in Jira

I want to create an utility where it will logs the hours automatically by taking a input from an excel.

Real problem starts here:
It should choose the current date matching in the excel and it needs to find whether story is inprogress or not if it is not in Inprogress it should not log hours in that story

I need some insights from you guys

Node.js server running on Terminal but not loading on browser

I am trying to achieve a proxy server using node.js where my proxy server is running on the terminal as

Proxy server running on http://0.0.0.0:3000

but over the browser, it’s not working. I am using AWS EC2 and earlier when I faced an issue with Flask App I added custom TCP in AWS -> Security Group -> Inbound rules and it worked however this one is not working with that either. following is the code:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// Proxy configuration
app.use('/', createProxyMiddleware({
  target: 'https://target-website.com', // Replace with the actual target website URL
  changeOrigin: true,
  selfHandleResponse: true,
  onProxyRes: (proxyRes, req, res) => {
    let body = Buffer.from('');
    proxyRes.on('data', (chunk) => {
      body = Buffer.concat([body, chunk]);
    });
    proxyRes.on('end', () => {
      let content = body.toString();
      
      // Modify the HTML content to autofill and submit the login form
      content = content.replace('</body>', `
        <script>
          document.getElementById('amember-login').value = 'yourUsername';
          document.getElementById('amember-pass').value = 'yourPassword';
          document.getElementById('submit').click();
        </script>
      </body>`);

      res.send(content);
    });
  },
}));

// Start the proxy server
app.listen(3000, () => {
  console.log('Proxy server running on http://localhost:3000');
});
`

Magnifying Glass Effect – part 2

After I got this sample working, thanks to help from a few people, I wondered about doing it in a way that allows it to be responsive and to also include any filters added to the source image. I came up with this:

// The magnification factor; an integer greater than 1
const zoom = 3; 
// The radius of the glass (as a percentage of the image's width)
// a number between 1 and 100, inclusive
const radius = 25;

const container = document.querySelector('.container');
const glass = document.querySelector('.glass');
const { style } = glass;
style.setProperty('--zoom', zoom);

// Add the magnified image as a clone
// This way it'll include any filter applied to the original image
const img = container.querySelector('img').cloneNode();
glass.append(img);

container.addEventListener('mousemove', (e) => {
  // ISSUE: The diameter of the glass is, as the magnification gets bigger, smaller than expected
  const clipPath = `${radius / zoom}% at ${e.offsetX * zoom}px ${e.offsetY * zoom}px`;
  
  style.setProperty('--clip-path', clipPath);
  style.setProperty('--left', `${(zoom - 1 ) * -e.offsetX}px`)
  style.setProperty('--top', `${(zoom - 1 ) * -e.offsetY}px`)
});
.container {
  position: absolute;
  width: 40%;
  height: fit-content;
  left: 8%;
  top: 20%;
  border: 1px dashed grey;
  overflow: hidden;
  cursor: none;

  &> img {
    width: 100%; 
    height: auto; 
    display: block;
  }

  &:hover .glass {
    opacity: 1;
  }

  .glass {
    position: absolute;
    left: var(--left);
    top:  var(--top);
    width: 100%;
    height: auto;
    clip-path: circle(var(--clip-path));
    pointer-events: none;
    transition: opacity 0.2s;
    opacity: 0;

    img {
      width: calc(var(--zoom) * 100%);
      display: block;
    }
  }
}
<div class="container">
  <img src="https://i.sstatic.net/Z4aOFrum.jpg" alt="bg">
  <div class="glass"></div>
</div>

The issue that I can’t work out how it’s happening (and so I can’t fix) is that when the zoom factor is 2 the displayed radius of the glass matches the value I set – for example, if I set the radius to 25 the glass displays at 50% of the source image – but if I increase the zoom the glass displays smaller than expected even though the magnified image is larger (and so the glass size should match.)

Migration Material UI V3 V4 webpack Error

I have the following error when i tried to migrate material ui v4 with react and webpack is a visual error and i try a lot of things like uninstall node_modules change babel version use github similar issues i also comment a line of the file /@material-ui/core/es/TextField/TextField.js and it works but i don’t want touch node_modules folder can you give me posible solutions

ERROR in ./node_modules/@material-ui/core/es/TextField/TextField.js 112:46
Module parse failed: Unexpected token (112:46)
You may need an appropriate loader to handle this file type.
| 
|     if (label) {
>       const displayRequired = InputLabelProps?.required ?? required;
|       InputMore.label = /*#__PURE__*/React.createElement(React.Fragment, null, label, displayRequired && 'u00a0*');
|     }

webpack config

/**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path')
const webpack = require('webpack')
const env = require('../../env.json')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')

// Remove this line once the following warning goes away (it was meant for webpack loader authors not users):
// 'DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic,
// see https://github.com/webpack/loader-utils/issues/56 parseQuery() will be replaced with getOptions()
// in the next major version of loader-utils.'
process.noDeprecation = true

module.exports = options => ({
    mode: options.mode,
    entry: options.entry,
    output: Object.assign(
        {
            // Compile into js/build.js
            path: path.resolve(process.cwd(), 'build'),
            publicPath: '/',
        },
        options.output,
    ), // Merge with env dependent settings
    optimization: options.optimization,
    module: {
        rules: [

            // START EXPERIMENTAL REMOVE IF DIDN'T WORK
            {
                test: /.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    query: {
                        plugins: [
                            [
                                require('babel-plugin-transform-imports'),
                                {
                                    '@material-ui/core': {
                                        transform: function (importName, matches) {
                                            return '@material-ui/core/es/' + importName
                                        },
                                        preventFullImport: true,
                                    },
                                    '@material-ui/icons': {
                                        transform: function (importName, matches) {
                                            return '@material-ui/icons/' + importName
                                        },
                                        preventFullImport: true,
                                    },
                                },
                            ],

                        ],
                    },
                },
            },
            // END EXPERIMENTAL
            {
                test: /.(js|jsx)$/, // Transform all .js files required somewhere with Babel
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: options.babelQuery,
                },
            },
            {
                // Preprocess our own .css files
                // This is the place to add your own loaders (e.g. sass/less etc.)
                // for a list of loaders, see https://webpack.js.org/loaders/#styling
                test: /.css$/,
                exclude: /node_modules/,
                use: ['style-loader', 'css-loader'],
            },
            {
                // Preprocess 3rd party .css files located in node_modules
                test: /.css$/,
                include: /node_modules/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /.(eot|otf|ttf|woff|woff2)$/,
                use: 'file-loader',
            },
            {
                test: /.svg$/,
                use: [
                    {
                        loader: 'svg-url-loader',
                        options: {
                            // Inline files smaller than 10 kB
                            limit: 10 * 1024,
                            noquotes: true,
                        },
                    },
                ],
            },
            {
                test: /.(jpg|png|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            // Inline files smaller than 10 kB
                            limit: 10 * 1024,
                        },
                    },
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: {
                                enabled: false,
                                // NOTE: mozjpeg is disabled as it causes errors in some Linux environments
                                // Try enabling it in your environment by switching the config to:
                                // enabled: true,
                                // progressive: true,
                            },
                            gifsicle: {
                                interlaced: false,
                            },
                            optipng: {
                                optimizationLevel: 7,
                            },
                            pngquant: {
                                quality: '65-90',
                                speed: 4,
                            },
                        },
                    },
                ],
            },
            {
                test: /.html$/,
                use: 'html-loader',
            },
            {
                test: /.(mp4|webm)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                    },
                },
            },
            {
                test: /.tsx?$/,
                loader: 'ts-loader',
                options: {
                    // disable type checker - we will use it in fork plugin
                    transpileOnly: true,
                },
            },
        ],
    },
    plugins: options.plugins.concat([
        new ForkTsCheckerWebpackPlugin(),
        // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
        // inside your code for any environment checks; Terser will automatically
        // drop any unreachable code.
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV),
                ...env,
                API_DOMAIN: JSON.stringify(env['API_DOMAIN']),
                APP_DOMAIN: JSON.stringify(env['APP_DOMAIN']),
                WS_URL: JSON.stringify(env['WS_URL']),
                WS_KEY: JSON.stringify(env['WS_KEY'])
            },
        }),
    ]),
    resolve: {
        modules: ['node_modules', 'app'],
        extensions: ['.js', '.jsx', '.react.js', '.ts', '.tsx'],
        mainFields: ['browser', 'jsnext:main', 'main'],
    },
    devtool: options.devtool,
    target: 'web', // Make web variables accessible to webpack, e.g. window
    performance: options.performance || {},
})

babel config

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                modules: false,
            },
        ],
        '@babel/preset-react',
    ],
    plugins: ['styled-components', '@babel/plugin-proposal-class-properties', '@babel/plugin-syntax-dynamic-import'],
    env: {
        production: {
            only: ['app'],
            plugins: [
                'lodash',
                'transform-react-remove-prop-types',
                '@babel/plugin-transform-react-inline-elements',
                '@babel/plugin-transform-react-constant-elements',
            ],
        },
        test: {
            plugins: ['@babel/plugin-transform-modules-commonjs', 'dynamic-import-node'],
        },
    },
}

How to resolve this?

axiosClient.post() dose not pass the resolved then callback

axiosClient.put() an .post() dose not pass to resolve callback (then ).
I work with laravel and react ,
I want to save data with put an post and navigate to an othher page by navigate(“members”) route
here is details

my view component :

export default function UserForm() {
  const navigate = useNavigate();
  let {id} = useParams();
  const onSubmit = ev => {
    ev.preventDefault()
    //console.log(user)
    if (user.id) {
      axiosClient.put(`/users/${user.id}`, user).then((data) => {
          setNotification('User was successfully updated')
          **navigate('/members')**
        })
        .catch(err => {
          const response = err.response;
          if (response && response.status === 422) {
            setErrors(response.data.errors)
          }
        })
    } else {
        
      axiosClient.post(`/users`, user)
        .then((data) => {
          setNotification('User was successfully created')
          **navigate('/members')**
        })
        .catch(err => {
          const response = err.response;
          if (response && response.status === 422) {
            setErrors(response.data.errors)
          }
        })
    }
  }

and It can’t execute navigate to ‘/members’

this is my axiosClient :

import axios from "axios"
import { UseStateContext } from "./context/ContextProvider";
const axiosClient =axios.create({
    baseURL:`http://127.0.0.1:8000/api`
})
axiosClient.interceptors.request.use((conf)=>{
    const token = localStorage.getItem("ACCESS_TOKEN")
    conf.headers.Authorization=`Bearer ${token}`;
    return conf;
});
axiosClient.interceptors.response.use((resp)=>{
    return resp
},
(error)=>{
    const {resp}=error;
    if(resp.status === 401){
        localStorage.removeItem("ACCESS_TOKEN");
    } else if (response.status === 404) {
        //Show not found
      }
    throw error;
}
);

export default axiosClient;

I try to debugg and it’s run the axiosClient.post(/users, user) save data in database and jumpe to axiosClient and so on…. without return to resolve then callback

plizzz any help

thank you

Implementing Many-to-Many Relationship Between Projects and Questions in Razor Pages

Button
Button

When I want to add a question to my project in the project section, I want to be redirected to the questionFilter.cshtml page with the project’s ID. After that, I want to add and save the questions I click on with buttons related to this project ID. There is a many-to-many relationship between projects and questions. Is there anyone who can help me with this? Also, I am using Razor Pages with OnPost and OnGet methods, and I am using LINQ.
I could only write the button click part right now. I couldn’t figure out what to write in the onpost and onget part.

@section scripts
{
</script>
    // An array to hold the IDs of the selected questions
    let selectedQuestions = [];

    function addQuestion(questionId, button) {
        // Check the current class of the button
        if (button.classList.contains('btn-outline-primary')) {
            // Button selected, add ID and make button red
            selectedQuestions.push(questionId);
            button.classList.remove('btn-outline-primary');
            button.classList.add('btn-danger');
            console.log('Selected Question ID:', questionId);
        } else {
            // Button not selected, remove ID and revert button
            selectedQuestions = selectedQuestions.filter(id => id !== questionId);
            button.classList.remove('btn-danger');
            button.classList.add('btn-outline-primary');
            console.log('Removed from question, ID:', questionId);
        }

        // You can perform other operations here if necessary
        // To add a hidden input, use the following code:
        const form = document.getElementById('questionForm');
        let hiddenInput = document.querySelector(`input[name='SelectedQuestionIds'][value='${questionId}']`);
        if (hiddenInput) {
            form.removeChild(hiddenInput); // Remove if exists
        } else {
            hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'SelectedQuestionIds';
            hiddenInput.value = questionId;
            form.appendChild(hiddenInput); // Add new hidden input
        }
    }

</script>
}
<div class="col-md-9">
    <!-- Question Table -->
    <div class="card">        
        <div class="card-body">
            <div class="d-flex justify-content-between">
                <div>
                    <h5 class="card-title">Questions</h5>
                </div>
            </div>
            <!-- Select Questions Form -->
            <h2>Select Questions</h2>
            <form method="post" id="questionForm" asp-page-handler="OnPostAddSelectedQuestions">
                <div class="table-responsive mt-2" style="max-height: 500px; overflow-y: auto;">
                    @if (!Model.questions.Any())
                    {
                        <p>No Questions Added Yet.</p>
                    }
                    else
                    {
                        <div class="row" id="questionsContainer">
                            <!-- Show the first 20 questions -->
                            @for (int i = 0; i < Math.Min(20, Model.questions.Count()); i++)
                            {
                                var q = Model.questions[i];
                                <div class="col-md-6 mb-3">
                                    <div class="card">
                                        <div class="card-body">
                                            <!-- Question image -->
                                            <div style="padding: 10px;">
                                                <img src="@($"{Url.Content("/Upload/")}{q.FilePath}")" alt="Question Image" style="width: 100%; height: auto; object-fit: cover;" />
                                            </div>
                                            <!-- Button for each question -->
                                            <button type="button" onclick="addQuestion('@q.Id', this)" class="btn btn-outline-primary">Add Question</button>
                                        </div>
                                    </div>
                                </div>
                            }
                        </div>
                    }
                </div>
                <div>
                    <button type="submit" class="btn btn-primary mb-3" style="float: right;">Add Selected Questions</button>
                </div>
            </form>
        </div>
    </div>
</div>

How do I hide the “Built with Zendesk” logo in the messaging Web Widget?

The Zendesk Web Widget for messaging includes a “Built by Zendesk” logo at the bottom beneath the message composer. This is not consistent with my web application’s brand.

This badge shows up even if I’m a paying customer, all the way up to the Suite Professional $115/agent/month plan. How do I get rid of this without having to upgrade to the most expensive Enterprise level plan?

screenshot of the web widget

Polling using java script

I am working on an application where I am loading an iframe that contains the third-party payment. I am receiving a callback response on either of the functions onTransactionSuccess or onTransactionFailure. Still, in some random cases, I do not receive any response if the payment is a success. I want to start polling to retrieve the transaction status but I am stuck as when payment is made it shows payment is a success and now you can close the windows on which the user can close the tab and I cannot prevent it from keeping track of the polling. Below is my code I am trying to start the polling on the backend using an ajax call and when the page loads it start polling.

<%@ page title="GravityPaymentsDlg" language="vb" autoeventwireup="false" codebehind="GravityPaymentsDlg.aspx.vb" inherits="AspenWebConnector.CustomerPortal.GravityPaymentsDlg" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Gravity Payment</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Author" content="Charter Software, Inc." />
    <meta http-equiv="Copyright" content="2017 Charter Software, Inc." />
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Cache-control" content="no-cache" />
    <meta name="ROBOTS" content="NOINDEX,NOFOLLOW" />
    <meta name="Distribution" content="global" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
        .iframeContainer {
            width: 500px;
            z-index: 10000;
            position: absolute;
            top: 0;
            background-color: #fff;
            display: none
        }

        .headerRow {
            width: 100%;
            height: 40px;
            text-align: right;
            font-size: 2em;
            border-bottom: 2px solid #d3d3d3
        }

        .closeBtn {
            margin-right: 10px;
            cursor: pointer
        }

        #iframeDiv {
            height: 450px;
        }

            #iframeDiv.ach {
                height: 600px
            }

        .iframeStyles {
            width: 100%;
            height: 100%;
            border: none
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }

        .box {
            padding: 20px;
            background-color: #ffffff;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
    </style>
    <link rel="stylesheet" href="../JQuery/jquery.mobile-1.4.1/jquery.mobile-1.4.1.min.css" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <asp:Literal ID="chargeitproAssetUrl" runat="server"></asp:Literal>

</head>
<body>

    <div class="iframeContainer" id="gravityPayment" style="width: 100% !important;">
        <%--  <div class="headerRow"><span id="closeBtn" class="closeBtn">×</span></div>--%>
        <div id="iframeDiv"></div>

        <!--Payment Processing -->
        <div id="payment-response-failed" class="iframeStyles" style="display: none;">
            <div class="container">
                <div class="box">
                    Payment response not received. Please try again.
                </div>
            </div>

        </div>
    </div>

    <script>
        var iframe = document.createElement("iframe");
        iframe.id = 'cip-hosted-urlpage';
        iframe.style.display = 'none';
        iframe.classList.add("iframeStyles");
        $("#iframeDiv").append(iframe);
        var externalTransId = ''
        var transactionExecuted = false


        window.onload = function () {
            // set up event listener on Pay With Card button
            function StartTransaction() {
                //e.preventDefault();
                //var transToken = getUrlVars()["transactionToken"];

                var urlParams = getUrlVars();
                var transToken = urlParams["transactionToken"];
                externalTransId = urlParams["externalTransId"];

                var urlPage = emergepayUrlPage.init({
                    // (optional) Callback function that gets called after a successful transaction
                    onTransactionSuccess: function (approvalData) {
                        transactionExecuted = true
                        clearTimeout(pollingTimeout);
                        postCallbackCPResponse("true", approvalData);

                    },
                    // (optional) Callback function that gets called after a failure occurs during the transaction (such as a declined card)
                    onTransactionFailure: function (failureData) {
                        transactionExecuted = true
                        clearTimeout(pollingTimeout);
                        postCallbackCPResponse("false", failureData);
                    }
                });
                // set the source of the iframe to the emergepay page.

                iframe.src = urlPage.getUrl(transToken);
                iframe.style.display = 'block';
                $(".iframeContainer").show();

                var pollingTimeout = setTimeout(function () {
                    if (!transactionExecuted) {
                        startServerPolling();
                    }
                }, 3000);

            }

            // Read a page's GET URL variables and return them as an associative array.
            function getUrlVars() {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            }

            $("#closeBtn").on('click', function (e) {
                e.preventDefault();
                $(".iframeContainer").hide();
            });
            // Post response message from Callback function

            function postCallbackCPResponse(approved, callbackResponse) {
                var postData = {
                    isApproved: approved,
                    transactionResponse: callbackResponse
                };
                var responseData = JSON.stringify(postData);
                $.ajax({
                    url: 'GravityPayments.aspx/ProcessResponse',
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ data: responseData }),
                    success: function (response) {
                        if (response.d.success) {
                            window.opener.location.href = "Payments_Success.aspx";
                        } else {
                            alert(response.d.message)
                            window.opener.location.href = "MainMenu.aspx";
                        }
                        window.close();
                    },
                    error: function (xhr, status, error) {
                        console.error('Error sending data to server:', error);
                    }
                });

            }

            function startServerPolling() {
                $.ajax({
                    url: 'GravityPayments.aspx/StartPolling',
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ externalTransactionId: externalTransId }),
                    success: function (response) {
                        if (response.d) {
                            console.log("Server-side polling started successfully.");
                        } else {
                            console.error("Failed to start server-side polling.");
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Error starting server-side polling:', error);
                    }
                });
            }

            StartTransaction();
        }
    </script>
</body>
</html>

Here I want to show the user the div which contains the message “Payment response not received..” when I didn’t receive any response from third party.

Can someone look into my hackerrank code and suggest why test case not passing [closed]

You are analyzing the market trend of amazon stocks. An AWS service
model returned array of integers, PnL (Profit and loss) for your
portfolio representing the ith month, you will either gain or lose
PnL[i]. All reported PnL values are positive representing gains.

As part of analysis you will perform the following operations in PnL
array any number of times:

  • Choose any month i(0<=i<=n) and multiply PnL[i] by -1

  • find maximum number of months you can afford to face a loss, i.e.
    having a negative PnL, such that the cumulative PnL for each of the n
    months remains strictly positive i.e. remains greater than 0

note :- the cumulative PnL for the ith month is defined as the sum of
PnL from the starting month upto the ith month.For example the
cumulative PnL for the PnL= [3,-2,5,-6,1] is [3,1,6,0,1]

write a javascript code such that function description

getMaxNgetaivePnL has parameters int PnL[n]: an
array of integers

Input format for custom testing:-

  • the first line contains an integer, n, the number of elements in PnL

  • each line i of the n subsequent lines (where 0<=i<=n) contains an
    integer, PnL[i]

function getMaxNegativePnL(PnL) {
  let n = PnL.length;
  let totalSum = PnL.reduce((acc, val) => acc + val, 0);
  let minPrefixSum = 0;
  let currentPrefixSum = 0;
  let negativeCount = 0;

  for (let i = 0; i < n; i++) {
    currentPrefixSum += PnL[i];
    minPrefixSum = Math.min(minPrefixSum, currentPrefixSum);
  }

  for (let i = 0; i < n; i++) {
    if (totalSum - 2 * PnL[i] > 0) {
      totalSum -= 2 * PnL[i];
      negativeCount++;
    }
  }

  return negativeCount;
}

// Custom testing input
const PnL = [3, 2, 5, 6, 1];
console.log(getMaxNegativePnL(PnL)); // Expected output: Depends on input

const PnL2 = [3, 2, 1, 4, 5, 6];
console.log(getMaxNegativePnL(PnL2)); // Expected output: Depends on input

expected output was 2 ours was 3

For example, the input [3, 2, 5, 6, 1] should produce a count of 2, because only the array values 2 and 1 can be made negative and yet the cumulative sum of the array(up to and including that element) remains above zero.

API call in js to return image

I am working on js web app and it is my first time working on any js app. After calling an API web app is not showing any image on overlay screen but the API is returning an image.

Html code

<input type="file" id="imageUpload" accept="image/*">
                <button id="uploadButton">Upload Image</button>
    <button id="openOverlayButton">Open Overlay</button>

    <div id="overlay" style="display: none;">
        <button id="closeOverlayButton">×</button>
        <div id="overlayContainer">
            <canvas id="renderCanvas"></canvas>
            <img id="overlayImage" src="" alt="Processed Image Overlay">
                        <div id="imageUploadContainer">
                
            </div>
            <div id="cameraControls">
                <div class="slider-container">
                    <span class="slider-label">Rotation</span>
                    <input type="range" id="rotationSlider" class="camera-slider" min="0" max="360" value="0" step="1">
                </div>
            </div>
        </div>
    </div>

I asked GPT to write code and this is what it returned:

js code

function handleImageUpload() {
    const file = imageUpload.files[0];
    if (file) {
        const formData = new FormData();
        formData.append('image', file);

        // Make an API request
        fetch('http://127.0.0.1:5000/segment', {
            method: 'POST',
            body: formData,
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json(); // Parse the JSON response
        })
        .then(data => {
            // Get the base64 encoded image
            const imageBase64 = data.image;

            // Show the overlay
            const overlay = document.getElementById('overlay');
            overlay.style.display = 'block';

            // Show the processed image in the img element
            const processedImage = document.getElementById('processedImage');
            processedImage.src = `data:image/jpeg;base64,${imageBase64}`; // Use the correct MIME type
            processedImage.style.display = 'block'; // Make sure the image is displayed

            // Optionally, hide the canvas if it's not needed
            const renderCanvas = document.getElementById('renderCanvas');
            renderCanvas.style.display = 'none';

            // Optionally hide the overlay image (if applicable)
            document.getElementById('overlayImage').style.display = 'none';
        })
        .catch(error => {
            console.error('Error during API call:', error);
        });
    } else {
        alert('Please upload an image');
    }
}

// Attach the event listener to the upload button
uploadButton.addEventListener('click', handleImageUpload);

// Add event listener to close the overlay
document.getElementById('closeOverlayButton').addEventListener('click', () => {
    document.getElementById('overlay').style.display = 'none';
});

and flask API reponse.

return jsonify({
            'image': image_base64,
            'angle': float(angle)
        })   

How do I create a scroll which is similar to this?

I am trying to create a similar scroll like this.

Now I have created a structure in reactjs but I am not able to figure the left side scroll when right side is sticky without using any library.

.project-section {
  height: 400vh;
  position: relative;
  background-color: lightcoral; 
}

.project-heading {
  display: flex;
  background-color: lightblue;
  font-size: var(--font-size-heading);
}

.project-heading-text {
  font-family: Campton-Font-Bold;
  font-size: var(--font-size-heading);
}

.project-header {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
  width: 100%;
  height: 300vh;
  background-color: lightsalmon;
}

.project-container-text {
  display: flex;
  flex-direction: column;
  width: 50%;
  justify-content: center; /* or space-around */
  align-items: center; /* Ensure this has a value, like 'center' */
  height: 300vh;
  border: 1px solid blue;
}

.project-text {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  border: 1px solid yellow;
}

.project-container-images {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 50%;
  height: 300vh;
  border: 1px solid green;
  top: 0;
  bottom: 0;
  z-index: 1000;
  position: relative;
}

.project-image {
  display: flex;
  justify-content: center;
  align-content: center;
  width: 100%;
  height: 100vh;
  border: 1px solid black;
  flex-wrap: wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
<section class="project-section" style="top: 0px;"><div class="project-heading"><span class="project-heading-text">Projects</span></div><div class="project-header"><div class="project-container-text"><span class="project-text">Text 1</span><span class="project-text">Text 2</span><span class="project-text">Text 3</span></div><div class="project-container-images" style="position: initial; top: 0px;"><span class="project-image">image1</span></div></div></section>

Functionality:

  • The Project headline should stick on top.
  • The Right side should also stick on top.
  • The Left side should be able to scroll and the text 1 and text 2 and text 3 should appear one by one while rest of the part should be sticky.

Bonus Question: As given in the link above, for reference, please let me know how to work on the image stack scrolling?

PS: cannot provide the github repo as it is a private project.

Note: I am using it in a react.js project.

How to smoothly transition between absolute and fixed positions on a navbar during scroll?

I’m trying to implement a navbar that switches from position: absolute to position: fixed when the user scrolls down more than 160 pixels. My goal is to have a smooth transition between these two states, but I’m struggling to make it work as I expect.

Currently, the change between absolute and fixed happens abruptly, and I can’t seem to make the transition feel smooth, since CSS doesn’t allow animating the position property.

Here’s what I’ve tried so far:

.navbar-absolute {
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 999;
    transition: all 0.5s ease;
    background-color: rgba(255, 255, 255, 0.76); /* Semi-transparent background */
    box-shadow: none;
    opacity: 0.9;
}

.navbar-fixed {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 999;
    background-color: rgb(255, 255, 255); /* Solid white background */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); /* Shadow when scrolling */
    opacity: 1;
}

JS:

let lastScrollTop = 0;
const navbar = document.querySelector('.navbar');

window.addEventListener('scroll', function () {
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollTop === 0) {
        navbar.classList.remove('navbar-fixed');
        navbar.classList.add('navbar-sticky');
    } else if (scrollTop > 160 && scrollTop > lastScrollTop) {
        navbar.classList.remove('navbar-sticky');
        navbar.classList.add('navbar-fixed');
    }
});