Proven Practices for Transferring Files Between Applications [closed]

I have a scenario where one app sends a list of links to files, then a web app receives them and displays to the user in the browser. The user can select one of these files, which will be sent to another app for further processing.

I am considering two approaches for implementing this transfer:

  1. Download the file on the web app side, save it in a javascript variable somehow, and then send it to the final app.
  2. Pass the file link to the server and let the server download the file itself.

I’m leaning towards the second option but have concerns about its security.

What would be the best practice for this kind of file transfer? Are there specific security implications or performance considerations I should be aware of for either approach?

Any advice or alternative suggestions would be greatly appreciated.


Details:

  • The service sends URLs to the files.
  • The web application receives them and displays as links to the user.
  • The user selects a file, and the selected file needs to be sent to another application for further processing.

Thank you!

Why can async code only be called by async code?

Could someone explain why async code needs to be called by async code in a few more words than this? I understand that async-await is just promises under the hood, so it makes sense that any code after an await is equivalent to a callback in then(). I also have an intuition for why internally the code after an await would need to close over anything before it, if it’s broken up into a separate callback. I don’t understand why it’s closures all the way back to main though?

So with callbacks, promises, async-await, and generators, you ultimately end up taking your asynchronous function and smearing it out into a bunch of closures that live over in the heap.
Your function passes the outermost one into the runtime. When the event loop or IO operation is done, it invokes that function and you pick up where you left off. But that means everything above you also has to return. You still have to unwind the whole stack.
This is where the “red functions can only be called by red functions” rule comes from. You have to closurify the entire callstack all the way back to main() or the event handler.

https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/

Trying to rewrite a token in ANTLR4 in two different ways depending on siblings. How do I do that without rewriting the same token twice?

AST

Target language JavaScript.

I have the pictured syntax tree. I want to rewrite

:d + 1 day

to

AddDay(:d, 1)

using an ANTLR4 listener. What’s the best approach here?

And also, if my listener already implements

enterHostVariable where it replaces :d with ? , how can I prevent it from doing that when this occurrence of :d has already been rewritten to AddDay(:d, 1) and I don’t want further changes?

Server side rendering Next.js (App Router) with async component with the pathname

I am using Next.js 14 with the App Router and Sanity CMS to manage a multilingual website (English, French, and Vietnamese). I have a language switcher in the Navbar that fetches data based on the selected language using an asynchronous function and GROQ requests from Sanity. However, I’ve noticed a delay in the state update when switching languages.

When I click on a language, the data fetch is triggered, but the state update seems delayed, causing a noticeable “data delay” in displaying the new translated content.It shows the previous data when I click a language. I’m trying to use async function with the pathname

enter image description here

Navigation Bar :

import NavigationItems from '@/components/core/NavigationItems';
import NavigationLanguages from '@/components/core/NavigationLanguages';
import { getData} from '@/sanity/sanity-utils';
import { headers } from 'next/headers';

const NavigationBar = async () => {
  const headersList = headers();
  const fullUrl = headersList.get('referer') || '';

  const segments = fullUrl.split('/');
  const languages = ['en', 'fr', 'vn'];
  const language = segments.find(segment => languages.includes(segment));
  const data= await getData(language);

  return (
    <nav className='flex justify-between container py-4 items-center'>
      <div className='flex flex-row gap-8'>
        <NavigationItems items={data} />
        <NavigationLanguages />
      </div>
    </nav>
  );
};

export default NavigationBar;

Snippet of the language buttons

        <ul className='grid p-4 gap-2'>
          <a href='/en'>
            <li className='text-sm text-center  rounded-md px-4 py-2 transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground text-center'>
              English
            </li>
          </a>
          <a href='/fr'>
            <li className='text-sm text-center  rounded-md px-4 py-2 transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground text-center'>
              Français
            </li>
          </a>
          <a href='/vn'>
            <li className='text-sm text-center  rounded-md py-2 transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground text-center'>
              Tiếng Việt
            </li>
          </a>
        </ul>

Close pop-up window opened by .click()

I have a pop window which is opened using this code run from console:

// Find all the "Activate" buttons on the page
var offerButtons = Array.from(document.getElementsByClassName("AvailableDealTile2__activation-status___jsguf")).filter(span => span.textContent === "Activate");
var index;
for (index = 0; index < offerButtons.length; ++index) {
    console.log("Clicking Activate button");
    offerButtons[index].click();
    // Wait 2seconds to be nice to WF servers :)
    await new Promise(r => setTimeout(r, 2000));
}
console.log("All done. Refresh and try again.");

How can I close that popup within that for loop?

I tried the following:

var daddy = window.self;
daddy.opener = window.self;
daddy.close();

but it did not work.

Display Data values on top of bar chart using angularJs

I am trying to dispay a barchart using chartjs and angularjs by getting data from database i am succesful in doing it but when i hover on the bar then the values are displayed i want the values to be displayed on top of Bar.

My angularjs code-

  $scope.labelsFamilyAge = [" 60 to 64", " 65 to 70", " 71 to 75"," 76 to 80", "81 to 85", "86 to 90", "91 to 95","96 to 100", "100"];

         $scope.get_data = [];
              $scope.GET_Data = function () {
                 $scope.getdata = [];
                   var GetRc = new Object();
                   var httprequest = $http({
                     method: 'POST',
                 url: API_URL + GetDBdata,
                        data: GetRc
               }).then(function (data) {
                   $scope.get_data = data.data.Data[0];
                  angular.forEach($scope.get_data, function (values) {
                $scope.getdaata.push(values);
                    $scope.totaldata += values;
                       })
                      $scope.ctrloptions = {
                       legend: {
                         display: true,
                      position: "bottom"
                     },
                    tooltipEvents: [],
                     showTooltips: true,
                     tooltipCaretSize: 0,
                  onAnimationComplete: function () {
                     this.showTooltip(this.segments, true);
                    }, }; }); }

   my HTML-   <canvas  id="bardata" class="chart chart-bar" chart-data="getdaata"                       
    chart-option="ctrloptions" chart-labels="labelsFamilyAge"></canvas>

My data is displayed when i hover on particular bar but i want it to be displayed on top of the bar chart like this.

Bar chart with data on top](https://i.sstatic.net/IxyQLX1W.png)

     I tried with changing chart-options but it didnt work.

     Please provide suggestion how can i achive this.`

React Router doesn’t work properly in React / Vite Project

I want to build a react app with vite. “npm run dev” works fine but when I want to build it and open the index.html in the new /dist folder I am coming to an empty /index.html side with no errors in the console. I tried to change the paths but that did not work. It has to be the react-router because everything else works fine. But I don’t know the exact problem and I am not able to finde it out.
I hope you can help me.

PS: Down below you find the relevant code. If you need more information please ask.

Picture of the page

Folder-Structure

Dist folder

enter image description here

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/img/djServiceLandLogo.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

package.json

{
  "homepage": "https://www.enian-gashi.xyz/",
  "name": "dj-service-land-production",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@gsap/react": "^2.1.1",
    "@vitejs/plugin-vue-jsx": "^3.1.0",
    "gsap": "^3.12.5",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^5.2.1",
    "react-router": "^6.23.1",
    "react-router-dom": "^6.23.1"
  },
  "devDependencies": {
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.19",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "postcss": "^8.4.38",
    "tailwindcss": "^3.4.3",
    "vite": "^5.2.0"
  }
}

vite.config.js

import { resolve } from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
  base: "",
  plugins: [react()],
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, "index.html"),
      },
    },
  },
});

main.jsx

import React from "react";
import ReactDOM from "react-dom/client";
import App from "/src/App.jsx";
import { BrowserRouter } from "react-router-dom";
import "./index.css";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

App.jsx

import "./App.css";
import React from "react";
import { Routes, Route } from "react-router-dom";
import Event from "./pages/Event";
import Hochzeit from "./pages/Hochzeit";
import Terminanfrage from "./pages/Terminanfrage";
import AboutMe from "./pages/AboutMe";
import Impressum from "./pages/Impressum";
import Datenschutz from "./pages/Datenschutz";
import MissMatch from "./pages/MissMatch";

function App() {
  return (
    <>
      <Routes>
        <Route index path="/" element={<Event />} />
        <Route path="Hochzeit" element={<Hochzeit />} />
        <Route path="Terminanfrage" element={<Terminanfrage />} />
        <Route path="AboutMe" element={<AboutMe />} />
        <Route path="Impressum" element={<Impressum />} />
        <Route path="Datenschutz" element={<Datenschutz />} />
      </Routes>
    </>
  );
}

export default App;

dist index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="./img/djServiceLandLogo.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
    <script type="module" crossorigin src="./assets/main-mOYYtr3v.js"></script>
    <link rel="stylesheet" crossorigin href="./assets/main-B4zcMpNs.css">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Error requiring GLPK.js in React “GLPK is not a function”

I am trying to build a web app that involves solving an integer linear program (basically, I am doing constrained group assignment). In order to solve this ILP, I am trying to use the javascript porting of the GLPK library that is in npm. I installed it by doing npm i glpk.js Then, I imported the package in my function as

const foo = async () => {
     const GLPK = require('glpk.js');
     const glpk = GLPK();
     ...
}

and this gave the error

Uncaught (in promise) TypeError: GLPK is not a function

Because of the “(in promise)” part, I also tried to await the require, but this gave the same error.

Angular notify parent of child input changes

I have a parent component with a data object, which I pass the same object into two child components (all components are onpush strategy). Each of these child components have a form that update the properties they responsible for. Since I am mutating the Input data directly, the parent object is up to date immediately.

I want to refactor the child components to receive a clone of the data object, so I follow best practices by not mutating the input. I set up Output events in each child to update the parent of the properties that should be changed.

The problem is I do not know the correct time to emit the children output. I have a submit button on the parent, calling submitForm(). How can I then get the updated values from the children? I can only think of creating some kind of input for the children that lets them know its’s time to update the parent, but that feels wrong.

Why classList contains returns false after calling appendChild on a div element with JavaScript

I have a checkers project that I am trying to debug, I am using this logic to move pieces around. I play around with the CSS properties to remove pieces from previous boxes and add them to target boxes. Suppose player taps cell A which contains a gold piece then I use this code to check if the cell contains a gold piece

 if (event.target.classList.contains('gold-piece'));

This method returns true before that piece is moved but returns false on the newly tapped cell where the gold piece was moved. This is the logic am using to remove the gold-piece CSS style property from the original cell and add it to the new cell to create the illusion of a checkers move

 if (lastcell != null) {
     console.log("previous tapped cell is not null");
     //get the cell that was previously tapped
     //make sure the rows and the columns have a difference of 1
     let x1 = lastcell[0]; let y1 = lastcell[1];
     if (col < y1) {
         //it is a move towards the left
         if ((y1 - col) == 1 && (row - x1) == 1) {
             //the move is valid
             let original = getTableCell(table, x1, y1);
             let child = original.querySelector("div.gold-piece");;
             if (child != null) {
                 original.removeChild(child);
             }
             //move the piece to the target cell
             let target = getTableCell(table, row, col);
             const div = document.createElement("div");
             div.classList.add("gold-piece");
             target.appendChild(div);
             B = true;
             A = false;
         } else {
             console.log("the move is not valid");
             A = true;
             B = false;
             //clear the dictionary after a move
             lastTappedA = {}
         }
     } else {
         //it is a move towards the right
         if ((col - y1) == 1 && (row - x1) == 1) {
             //the move is valid
             let original = getTableCell(table, x1, y1);
             let child = original.querySelector("div.gold-piece");;
             if (child != null) {
                 original.removeChild(child);
             }
             //move the piece to the target cell
             let target = getTableCell(table, row, col);
             const div = document.createElement("div");
             div.classList.add("gold-piece");
             target.appendChild(div);
             B = true;
             A = false;
             lastTappedA = {}
         } else {
             console.log("the move is not valid");
             A = true;
             B = false;
         }
     }

 }

I programmatically create a child div element and then I add the gold piece style to it and then append it to the target cell, then I remove the the gold piece from the original cell using removeChild but when I tap on the new cell where the gold piece was added then the line event.target.classList.contains('gold-piece') returns false despite that cell having a gold-piece element.

I expected the new cell where the gold piece using the element.appendChild() method to return true, instead it is returning false, why is this and how can I resolve the issue?

Google Enterprise ReCaptcha v3 always returning score of 0.9

I’ve integrated Enterprise reCAPTCHA v3 with my HTML and JavaScript contact form. To ensure its effectiveness, I’m attempting to automate testing with Selenium to verify if the reCAPTCHA accurately identifies bots. However, after submitting 100 contact forms, the reCAPTCHA consistently returns a score of 0.9, indicating that it’s likely a human interaction. This outcome seems unexpected and contrary to the intended functionality.

What could be causing this discrepancy? Has anyone encountered a similar issue with Enterprise reCAPTCHA v3 and Selenium automation? Any insights or suggestions on how to troubleshoot and resolve this problem would be greatly appreciated.

`function onClick(e) {
    e.preventDefault(); // Prevents the default form submission behavior
    const captchaTokens = document.querySelectorAll(".form__recaptcha");
    for (let captchaToken = 0; captchaToken < captchaTokens.length; captchaToken++) {
        const element = captchaTokens[captchaToken];
        grecaptcha.enterprise.ready(async () => { // Ensures the reCAPTCHA library is fully loaded
          const token = await grecaptcha.enterprise.execute('6Le-Ia0p********NLj***LTVR******bJC1uF', {action: 'Testing__contact_form'}); // Executes reCAPTCHA with a specific action ('LOGIN')
          element.value = token;
        //   MY FETCH CALL RUN HERE
        });
        
    }
  }
onClick(event)`

This is my frontend code,
I expecting 0.0 to 0.3 when selenium automation hit the contact form

Dashboard:57 Uncaught SyntaxError: Unexpected end of input with Charts.Js

I’m trying to create a chart that has both a bar dataset and a line dataset. When I load the page, the model populates correctly as far as I can see, but the chart doesn’t show up and the only errors or clues I have are Dashboard:57 Uncaught SyntaxError: Unexpected end of input and in the debug output: Exception thrown: ‘System.FormatException’ in System.Private.CoreLib.dll . I’m not sure the second error is related but thought it might help. My code for the chart is as follows:

<div id="chartContainer" style="width: 100%; height: 150px;">
    <canvas id="ticketCountChart" width="1100" height="180"></canvas>
</div>

<script>
        var ctx = document.getElementById('ticketCountChart').getContext('2d');

        var newTicketData = @Model.DashboardMetrics.HourlyTicketData;
        var resolveddData = @Model.DashboardMetrics.HourlyResolvedTicketsData;

        var labels = newTicketData.map(item => item.Hour);

        var lineBarChart = new Chart(ctx, {
            type: 'bar',
            data: {
                datasets: [
                    {
                        type: 'line',
                        label: 'New Tickets',
                        data: newTicketData.map(item => item.NewTicketsCount),
                        borderColor: 'rgba(75, 192, 192, 1)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        fill: true
                    },
                    {
                        type: 'bar',
                        label: 'Resolved Tickets',
                        data: resolvedData.map(item => item.ResolvedTicketsCount),
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Hour'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Number of Tickets'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: 'Tickets Overview (Last 24 Hours)'
                    },
                    legend: {
                        display: true,
                        position: 'bottom'
                    },
                    tooltip: {
                        callbacks: {
                            label: function (tooltipItem) {
                                var label = tooltipItem.dataset.label || '';
                                var value = tooltipItem.raw;
                                return label + ': ' + value;
                            }
                        }
                    }
            }
        });
    });
</script>

I’ve tried parsing the data to get rid of any leading zeroes and ensuring the data points are being accessed as ints, but that hasn’t had any effect. Triple-checked all the options, missing parentheses etc but can’t see anything wrong

How to stop adding more input values after a certain length has reached?

I’m creating a football lineup creator where the user can select between a keeper, defender, 3 different types of midfielders, and a forward, with each position having a maximum number (this seems to be working well). However, I want the user not to be able to add more players to the lineup when they’ve added 11 players.

My code as of now is:

const [error, setError] = useState(null);
const [homeTeam, setHomeTeam] = useState(
    localStorage.getItem("homeTeam") === null
        ? {
          squad: {
            gk: null,
            df: [],
            cdm: [],
            cm: [],
            cam: [],
            fw: []
          },
          style: {
            color: `#${state.homeTeamColor}`,
            numberColor: `#${state.homeTeamNumberColor}`,
            nameColor: `#${state.nameColor}`
          }
        }
        : JSON.parse(localStorage.getItem("homeTeam"))
    );

const addPlayer = () => {
    //const i = 0;
    //while (homeTeam.squad.length < 11 && i < homeTeam.squad.length) {
    setError(null);
    if (playerName === "") {
      setError("Player Name required!");
    }
    //if (homeTeam.squad.length === 11) {
    //  setError("squad is full!");
    //}
    else {
      let playerObj = {
        id: nanoid(),
        number: number,
        name: playerName,
        color:
          playerTeam === "homeTeam"
            ? `#${state.homeTeamColor}`
            : `#${state.awayTeamColor}`,
        numberColor:
          playerTeam === "homeTeam"
            ? `#${state.homeTeamNumberColor}`
            : `#${state.awayTeamNumberColor}`,
        namecolor: `#${state.nameColor}`
      };
      if (playerTeam === "homeTeam") {
        if (playerPosition === "gk") {
          if (homeTeam.squad.gk !== null) {
            setError("goal keeper is full!");
          } else {
            playerObj.onClick = () =>
              playerRemove("homeTeam", "gk", playerObj.id);
            setHomeTeam((homeTeam) => ({
              ...homeTeam,
              squad: { ...homeTeam.squad, gk: playerObj }
            }));
          }
        } else if (playerPosition === "df") {
          if (homeTeam.squad.df.length === 5) {
            setError("defence is full!");
          } else {
            playerObj.onClick = () =>
              playerRemove("homeTeam", "df", playerObj.id);
            setHomeTeam((homeTeam) => ({
              ...homeTeam,
              squad: {
                ...homeTeam.squad,
                df: [...homeTeam.squad.df, playerObj]
              }
            }));
          }
    }
 //CODE IS REPEATED BUT FOR DIFFERENT POSITIONS WHICH I DIDN'T ADD
      }
    }
//}
    setNumber(number + 1); 
  };

The commented code is what I attempted to do. I tried to wrap the whole code in a while loop and that prevented me from adding any players, and when I implemented an if loop with the condition of if (homeTeam.squad.length === 11) {
setError(“squad if ull”)
}
this adds players without any name being inputted.