how to get file input as dataURI, and then store it in a variable in Javascript? [duplicate]

so im just coding this little app and i have a form in which the user is prompted to input an image, i need to then get that image as dataURI and store that value in a variable for later use. Andy ideas how to do this?

I’ve tried the FileReader: readAsDataURL() method but i couldn’t get it stored in a variable. Im not a JavaScript genius so this might be a simple fix or an error on my part.

How to compute interpolation between more then 2 values?

Suppose you have 3 values [1, 3, 5] and itemsCount = 10 a number that describes how many resulting values the function should return, the result should be:

mainValues = [1, 5, 3]
itemsCount = 8
result = [1, 2, 3, 4, 5, 4, 3, 2]

so result is an array (of length=itemsCount) of numbers that are the interpolation between [1, 5, 3], as you can see, it’s circular.

I tried to write a function that do this but it’s not working well
Is there something already implemented? how can I fix my code?

function interpolateList(mainValues, itemsCount) {
  const mainValuesWithRepeatedFirst = [...mainValues, mainValues[0]]
  const itemsBetweenMainValues = Math.floor(itemsCount / (mainValuesWithRepeatedFirst.length - 1))

  const resultRaw = []
  for (let i = 1; i <= mainValuesWithRepeatedFirst.length - 1; i++) {
    const mainValueStart = mainValuesWithRepeatedFirst[i - 1]
    const mainValueEnd = mainValuesWithRepeatedFirst[i]
    const step = (mainValueEnd - mainValueStart) / (itemsBetweenMainValues - 1)
    const valuesRaw = _.range(mainValueStart, mainValueEnd + step, step)
    const values = [mainValueStart, ...valuesRaw.slice(1, -1), mainValueEnd]
    resultRaw.push(...values)
  }
  const differenceElements = itemsCount - resultRaw.length
  const result = differenceElements
    ? [..._.range(differenceElements).map((d) => resultRaw[0]), ...resultRaw]
    : resultRaw
  return result
}

const mainValues = [1, 5, 3]
const itemsCount = 8

const result = interpolateList(mainValues, itemsCount)
console.log(result); // expected result [1, 2, 3, 4, 5, 4, 3, 2]
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js" integrity="sha512-2V49R8ndaagCOnwmj8QnbT1Gz/rie17UouD9Re5WxbzRVUGoftCu5IuqqtAM9+UC3fwfHCSJR1hkzNQh/2wdtg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Get RegEx range results in Javascript

I wanted to use javascript to get the results in ranges. Something like matching a simple URL, and once it matches it shows in what range is in (in the red circle)

enter image description here

I tried something called .lastIndex, and had put it together like this.

const regex1 = new RegExp('(?:(?:https?|ftp|file)://|www.|ftp.)(?:([-A-Z0-9+&@#/%=~_|$?!:,.]*)|[-A-Z0-9+&@#/%=~_|$?!:,.])*(?:([-A-Z0-9+&@#/%=~_|$?!:,.]*)|[A-Z0-9+&@#/%=~_|$])');
const str1 = 'OH YES I DID https://www.example.com/';

regex1.test(str1);

console.log(regex1.lastIndex);
// Expected output: 13

regex1.test(str1);

console.log(regex1.lastIndex);
// Expected output: 36

I looked at the output console to both output are at 0. Any idea what I did wrong on this?

Web Assembly (WASM) errors in a Vite + Vue app using Realm Web SDK

I’m using MongoDB Realm / App Services to make a web front end for an existing iOS app.

The standard Realm Web SDK only permits authentication and backend functions, so I am trying to use the preview release of the Web Assembly version ([email protected]) so that I can use device sync and interact with a Realm object in the way I’m used to.

Details at: Get Started with Realm Web & Atlas Device Sync (Preview)

I am just using the basic app scaffold created by Vite, and then importing Realm in App.vue. I am not (yet) using Realm anywhere else in the code.

import Realm, { App } from "realm";

As advised in the Realm SDK documentation, for the Web Assembly version I had to enable top-level await in vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  esbuild: {
    supported: {
      'top-level-await': true
    },
  },
  optimizeDeps: {
    esbuildOptions: {
      supported: {
        "top-level-await": true
      },
    },
  },
})

So this works without errors when I build and preview (vite build followed by vite preview).

However, when I do npm run dev (vite), the server starts as expected, but there are the following errors in the browser console:

Console errors

[Error] wasm streaming compile failed: TypeError: Unexpected response MIME type. Expected 'application/wasm'
    (anonymous function) (realm.js:726)
[Error] falling back to ArrayBuffer instantiation
    (anonymous function) (realm.js:727)
[Error] failed to asynchronously prepare wasm: CompileError: WebAssembly.Module doesn't parse at byte 0: module doesn't start with 'asm'
    (anonymous function) (realm.js:717)
[Error] Aborted(CompileError: WebAssembly.Module doesn't parse at byte 0: module doesn't start with 'asm')
    abort (realm.js:661)
    (anonymous function) (realm.js:718)

This doesn’t happen if I build and preview, so I hope it won’t actually be a problem, but I don’t understand what is going on here and I’m curious about how to fix it for working during the development process.

How to send PNG data response received from REST Api

I’m calling an API from Node.JS which results PNG data in response body, I’m getting response in encoded format (image attached below):

enter image description here

Now I need to send this PNG image as response in my API.

I’m able to save the image with below snippet:

const writer = fs.createWriteStream("testimage.png");

        const streamResponse = await axios({
          'method': 'GET',
          responseType: 'stream',
          'url': endPoint + requestRoute,
          'headers': {
            'Authorization': 'Bearer ' + _token 
          }
        });

        streamResponse.data.pipe(writer);

But I don’t want to save image in my server, I want to send the image received from external API on the fly as response in my API.

Example:

Api.getPNGImage = async function (_request, _respsonse) {

    var options = {
        'method': 'GET',
        'url': endPoint + requestRoute,

        'headers': {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + _token
         }
};
 request(options, function (error, response) {
        let image = response.body;
        _respsonse.send(image)
    });
}

I tried below approach, but base64 comes out invalid:
let str = "data:" + 'image/png' + ";base64," + Buffer.from(_responses.body).toString('base64');

Im having trouble with over flow problems on my website for mobile views, can someone please help me






`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>740 Madden</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" /></head>
    <link rel="stylesheet" href="ebookhome.css">
    <script defer src="app.js"></script>
</head>
<body>
    <header>
        <nav>
            <ul class='nav-bar'>
                <li class='logo'><a>740 Madden</a></li>
                <input type='checkbox' id='check' />
                <span class="menu">
                    <li><a href="">Ebook</a></li>
                    <li><a href="">Pro Tips</a></li>
                    <li><a href="">Memberships</a></li>
                    <li><a href="">Contact</a></li>
                    <li><a href="">FAQs</a></li>
                    <label for="check" class="close-menu"><i class="fas fa-times"></i></label>
                </span>
                <label for="check" class="open-menu"><i class="fas fa-bars"></i></label>
            </ul>
        </nav>
    </header>

    <!-- Our Team Section -->
    <section id="our-team">
        <h2>Our Team</h2>
        <div class="our-team.txt"></div>
        <p>Our team currently consists of SomeVersace who is 55th in the world, WIMBERLYBOY52 who is 51st in the world, Vohes who is 36th in the world, and Tuhmear who is 22nd in the world. SomeVersace and Tuhmear have both been playing Madden since Madden 19 where Sace introduced Tuhmear to Y-off Pats, better known as U-Trips, and ever since have been climbing their way to the top of the MCS Ladder. Vohes who popped off during COVID on Twitch, was not able to play due to age restrictions and later went on to qualify and play in a Madden championship worth $1 Million dollars. WIMBERLYBOY52 found success this year, and all 4 plan to Lab together in future Maddens.</p>
    </section>
    
    <!-- Ebooks Section -->
    <section id="ebooks">
        <h2>Current eBooks</h2>
        <div class="ebook-container">
                <!-- E-Book 1 -->
                <div class="ebook">
                    <iframe width="285" height="200" src="https://youtu.be/nYTrIcn4rjg?si=BU1aMy4-jt31igkn" title="pro-tips"
                     frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                     allowfullscreen></iframe>
                    <div class="ebook-details">
                        <h3>The GR8 BOOK of Knowledge</h3>
                        <p>by SomeVersace</p>
                    </div>
                </div>
                <!-- E-Book 2 -->
                <div class="ebook">
                    <iframe width="285" height="200" src="https://youtu.be/nYTrIcn4rjg?si=BU1aMy4-jt31igkn" title="pro-tips"
                     frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                     allowfullscreen></iframe>
                    <div class="ebook-details">
                        <h3>The GR8 BOOK of Knowledge</h3>
                        <p>by SomeVersace</p>
                    </div>
                </div>
                <!-- E-Book 3 -->
                <div class="ebook">
                    <iframe width="285" height="200" src="https://youtu.be/nYTrIcn4rjg?si=BU1aMy4-jt31igkn" title="pro-tips"
                     frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                     allowfullscreen></iframe>
                    <div class="ebook-details">
                        <h3>The GR8 BOOK of Knowledge</h3>
                        <p>by SomeVersace</p>
                    </div>
                </div>
                <!-- E-Book 4 -->
                <div class="ebook">
                    <iframe width="285" height="200" src="https://youtu.be/nYTrIcn4rjg?si=BU1aMy4-jt31igkn" title="pro-tips"
                     frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                     allowfullscreen></iframe>
                    <div class="ebook-details">
                        <h3>The GR8 BOOK of Knowledge</h3>
                        <p>by SomeVersace</p>
                    </div>
                </div>
            <div class="ebook">
                <iframe width="285" height="200" src="https://youtu.be/nYTrIcn4rjg?si=BU1aMy4-jt31igkn" title="pro-tips"
                 frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                 allowfullscreen></iframe>
                <div class="ebook-details">
                    <h3>The GR8 BOOK of Knowledge</h3>
                    <p>by SomeVersace</p>
                </div>
            </div>
        </div>
    </section>
<html>`

Please someone help i will post the css in a comment underneath this code
I tried everything I know to try as a beginner maybe I took on too big of a project for myself, sorry in advance but Im sure someone has more knowledge of what to do than me
Im looking for someone to make the ebooks when not on desktop in a column instead of a row like they are displayed on desktop and make it 100% of the viwport width -10px on the left and right side please.

Render video from js into html

I’m new here and have a question. How can I render the webcam video from JavaScript into HTML? I want to scan QR-Codes in my browser and while scanning there should be the video from the camera for better user experience (easier to find the qr-code). For scanning the QR-Codes, I use Instascan. My code looks something like this:

HTML:

<div class="video-container">
   <div class="overlay-box">
      <video id="preview"></video>
   </div>
</div>

JavaScript:

let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });

// When starting scanning, activate via css
document.getElementById("preview").style.display = "block";

// When stopping scanning, deactivate via css
document.getElementById("preview").style.display = "none";

I tried without the css stuff, but that was not a problem. It should be a problem with the scanner ig…

Expecting: that it render it into the html file that I can see the camera output while scanning

Thanks for every help!
PS: If it’s an important information (idk); its inside a Django project

socket io cluster with namespace and adapter

I am using socket io with multiple processes on node with cluster and the cluster adapter.

I have multiple namespaces, so I figured that I have to call use() (to register a middleware) for every namespace.

like:

io.of("/orders").use(...)

Now I’m asking myself, do I need to create multiple adapters, too? And register it on all namespaces, like:

io.of(namespace).adapter(createAdapter());

Or can I create one adapter and register that one on all namespaces? Or can I just call

io.adapter(createAdapter());

once? I believe the last one just uses the admin namespace?

I’ve created one adapter and added it to all namespaces, but I’m not sure if this is needed.

Flask : Handle Submit Event

sdf import React, { useState } from ‘react’; const WellText3 = () => { const [text, setText] = useState(”); const [undoStack, setUndoStack] = useState([]); const [redoStack, setRedoStack] = useState([]); const handleChange = (event) => { const newText = event.target.value; setText(newText); setUndoStack([…undoStack, newText]); }; const handleUndo = () => { if (undoStack.length > 1) { const currentText = undoStack.pop(); setRedoStack([…redoStack, currentText]); setText(undoStack[undoStack.length – 1]); setUndoStack([…undoStack]); } }; const handleRedo = () => { if (redoStack.length > 0) { const nextText = redoStack.pop(); setUndoStack([…undoStack, text]); setText(nextText); setRedoStack([…redoStack]); } }; return ( <div> <textarea value={text} onChange={handleChange} /> <button onClick={handleUndo} disabled={undoStack.length <= 1}>Undo</button> <button onClick={handleRedo} disabled={redoStack.length === 0}>Redo</button> </div> ); }; export default WellText3; dfsdfs s

How to Download Blob video from Flutter inAppWebView

I am trying to download a video file from a website which records your video and lets you download them using blob. the websites shows saved to download but nothing happens.

heres my code:

// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:path_provider/path_provider.dart';

class MyWebsite extends StatefulWidget {
  const MyWebsite({super.key});

  @override
  State<MyWebsite> createState() {
    return _MyWebsiteState();
  }
}

class _MyWebsiteState extends State<MyWebsite> {
  late InAppWebViewController inAppWebViewController;

  @override
  Widget build(context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Optimised Surveillance'),
      ),
      body: Stack(
        children: [
          InAppWebView(
            initialUrlRequest: URLRequest(
              url: WebUri("https://watchtower-ai.vercel.app/"),
            ),
            initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
              useOnDownloadStart: true,
            )),
            onWebViewCreated: (InAppWebViewController controller) {
              inAppWebViewController = controller;
            },
            androidOnPermissionRequest: (controller, origin, resources) async {
              return PermissionRequestResponse(
                  resources: resources,
                  action: PermissionRequestResponseAction.GRANT);
            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url.toString(),
                savedDir: (await getExternalStorageDirectory())!.path,
                showNotification: true,
                openFileFromNotification: true
              );
            },
          ),
        ],
      ),
    );
  }
}

The url is being printed like this one:

I/flutter (14502): onDownloadStart blob:https://watchtower-ai.vercel.app/ae18d63a-88dd-4c5c-a6cb-fd89ad64aeec

VS Code screenshot

Can someone help me please?

Communicate safely between head script and body script (if possible)

I have a bundle script that loads my app in the body.
I wrote a script in the head of my site in order to harden some JS functionalities related to my web app.
I load 3rd party scripts between those scripts (between the hardening script in head and the app script in body).

I need to get some data in the head and to be able to give it to the app script in the body.
Is there any safe (client side) way to communicate between each other? I don’t want that 3rd party scripts to be able to get that data.

I don’t want to add server side communications since it will cost me in performance until site is loaded.
I cannot move any code from the places it suppose to be.

Thanks in advance.

I’ve tried custom messaging with crypto but this can still be copied from 3rd party script in the middle.

I can’t figure out what’s going on. I add an object to the array, it is added, but the old data copies the values from the new object

I can’t figure out what’s going on. I add an object to the array, it is added, but the old data copies the values from the new object. This is the first time I’ve encountered this.

Here is the code

      var news = []
      var next
      if(cart === null){
        next = 0
      }else {
        next = cart.length
      }
      switch(type){
        case 'horizontal':
          config['0']['type'] = type
          config['0']['id'] = next
          config['0'].idImg = selectSvg
          if(cart === null || cart === undefined || cart.length < 1){
            news.push(config)
            setCountCart(news.length)
            localStorage.setItem('cart-tagstyle', JSON.stringify(news))
            setCart(news)
          }else {
            var news = cart.slice()
            console.log(news);
            news.push(config)
            console.log(news);
            setCountCart(news.length)
            localStorage.setItem('cart-tagstyle', JSON.stringify(news))
            setCart(news)
          }
          break;

I tried it without push, according to the following index, the same thing. I searched the Internet, it didn’t help. I’ve been suffering for the second day