How to shuffle an array of items

In the following example an array of numbers is shuffled each time the document is refreshed. How do I apply the same function that shuffles the numbers to shuffle the blocks of color?

const points = [1, 2, 3, 4, 5, 6];
document.getElementById("numbers").innerHTML = points;

function myFunction() {
  for (let i = points.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    let k = points[i];
    points[i] = points[j];
    points[j] = k;
  }
  document.getElementById("numbers").innerHTML = points;
}
<!DOCTYPE html>
<html>

<body onload="myFunction()">

  <div id="numbers"></div>

  <br>

  <div id="colors">
    <div style="width:50px; height:50px; background-color:red; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:yellow; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:blue; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:orange; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:green; display:inline-block"></div>
    <div style="width:50px; height:50px; background-color:purple; display:inline-block"></div>
  </div>

</body>

</html>

Having trouble uploading images from react js to node js backend

My issue is that when I make the request in thunder client extension in vs code, it works, but in my code I tried but didn’t succeed, Image files seem to not upload.
I have tried multiple ways to resolve this issue but without success, using chat gpt didn’t help at all. Please consider helping.

product create route:
“/products”

    .post(auth, fileUpload(fileValidation.image).array('images', 5), catcher(controller.createProduct))

multer file for file validation:

import multer from "multer";
export const fileValidation = {
    image: ['image/png', 'image/jpeg', 'image/jpg', 'image/webp'],
    pdf: ['application/pdf']
}
function fileUpload(customValidation = []) {
    const storage = multer.diskStorage({})
    const fileFilter = ((req, file, cb) => {
        if (customValidation.includes(file.mimetype)) {
            cb(null, true);
        } else {
            cb("Invalid file format", false)
        }
    })

    return multer({ fileFilter, storage });
}

export default fileUpload;

Product create controller:

export const createProduct = async (req, res, next) => {
    const { name, price, salePrice, tax, description, category, stock, quantity, status } = req.body;
    const { files } = req;

    if (!name || !price || !description || !category || !stock || !quantity || !status || !files) {
        return next(
            new ResponseError(
                "Please provide correct data for the product",
                statusCodes.BAD_REQUEST
            )
        );
    }

    let images = [];
    const uploadPromises = files.map(async file => {
        const { path } = file;
        const { secure_url, public_id } = await cloudinary.uploader.upload(path, {
            folder: process.env.CLOUDINARY_PRODUCTS_FOLDER
        });
        images.push({ url: secure_url, public_id });
    });

    await Promise.all(uploadPromises);

    // Create a new object with only the required fields
    const productData = {
        name,
        price,
        description,
        category,
        stock,
        quantity,
        status,
        seller: req.user._id,
        images,
    };

    // Add optional fields if they are present in the request body
    if (tax) {
        productData.tax = tax;
    }

    if (salePrice) {
        productData.salePrice = salePrice;
    }

    const product = await Product.create(productData);
    res.status(statusCodes.OK).json({
        message: "Product successfully created",
        product
    });
};

Image dropzone code:

const [coverImages, setCoverImages] = useState([]);
  const [files, setFiles] = useState([]);

  const onDrop = useCallback(
    (acceptedFiles) => {
      const remainingSlots = 5 - coverImages.length;
      const filesToAdd = acceptedFiles.slice(0, remainingSlots);
      setFiles(files.concat(filesToAdd));
      updateProductData("images", [...files, ...filesToAdd]);

      filesToAdd.forEach((file) => {
        const reader = new FileReader();

        reader.onload = () => {
          setCoverImages((prevImages) => [...prevImages, reader.result]);
        };
        reader.readAsDataURL(file);
      });
    },
    [coverImages]
  );
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    multiple: true,
    onDrop: onDrop,
  });
//--------------------------------------------------
<MUI.Box
            {...getRootProps()}
            className="absolute w-full flex-col h-full flex items-center justify-center cursor-pointer gap-3"
          >
            <img
              src="/src/assets/draganddropareacloudimage-removebg-preview.png"
              width={150}
              height={100}
              className=""
              alt=""
            />
            <MUI.Typography
              variant="subtitle1"
              className="dark:text-white text-center"
            >
              drag and drop files or{" "}
              <span className="underline text-blue-500">click</span> to browse
              files
            </MUI.Typography>
          </MUI.Box>
          <input
            {...getInputProps()}
            type="file"
            multiple
            onChange={(e) => onDrop(e.target.files)}
            className="hidden"
          />
        </MUI.Box>

BTW using Material UI*

Product data object:

 const [productData, setProductData] = useState({
    name: "",
    price: "",
    description: "",
    category: "",
    stock: 0,
    quantity: 0,
    salePrice: 0,
    tax: 0,
    status: "Pending",
    images: [],
  });

Update products function

const updateProductData = (field, value) => {
    setProductData({ ...productData, [field]: value });
  };

form handle submit:

const handleSubmit = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    for (const key in productData) {
      if (key === "images") {
        for (let i = 0; i < productData.images.length; i++) {
          formData.append("images", productData.images[i]);
        }
        continue;
      }
      formData.append(key, productData[key]);
    }
    const formKeys = Array.from(formData.keys());
    console.log(formKeys);
    const formDataValues = Array.from(formData.values());
    console.log(formDataValues);
    createProduct(formData);
  };
const createProduct = async (data) => {
    // setLoadingToCreateProduct(true);
    console.log(data);
    try {
      const res = await axios.post("/products", data);
      if (res) {
        console.log(res.data);
      }
    } catch (error) {
      console.log(error);
    } finally {
      // setLoadingToCreateProduct(false);
    }
  };

When Ienter code here run the code in thunder client it works, but here it isn’t

Chrome log

Thunder Client extension log

problem of the ability to search in multiple selections

i use a html template with searchable selects
when i use tow or more select in same page search ability only work for first select
my codepen:
text

    $('select.TemplateSelectElement').each(function (i, select) {
        if (!$(this).next().hasClass('dropdown-select')) {
            $(this).after('<div class="dropdown-select wide ' + ($(this).attr('class') || '') + '" tabindex="0"><span class="current"></span><div class="list"><ul></ul></div></div>');
            var dropdown = $(this).next();
            var options = $(select).find('option');
            var selected = $(this).find('option:selected');
            dropdown.find('.current').html(selected.data('display-text') || selected.text());
            options.each(function (j, o) {
                var display = $(o).data('display-text') || '';
                dropdown.find('ul').append('<li class="option ' + ($(o).is(':selected') ? 'selected' : '') + '" data-value="' + $(o).val() + '" data-display-text="' + display + '">' + $(o).text() + '</li>');
            });
        }
    });
    $('.dropdown-select ul').before('<div class="dd-search"><input id="txtSearchValue" autocomplete="off" onkeyup="filter()" class="dd-searchbox" type="text"></div>');




function filter() {
     var valThis = $('#txtSearchValue').val();
    $('.dropdown-select ul > li').each(function () {
        var text = $(this).text();
        (text.toLowerCase().indexOf(valThis.toLowerCase()) > -1) ? $(this).show() : $(this).hide();
    });
 };

Merging Audio and MP4 using JavaScript

I am to make a website, which you would say yes and no to some questions, and it would give you an output in a video. Its meant to be different videoes with lots lf different sounds, which i have to merge in JS. Im trying to learn a bit of ffmpeg, but some videoes it will put Sound on, and some not. How would you tackle this assignment?

I tried ffmpeg but didnt get the resultat i needed

why not working blob/arrayBuffer on react native?

I am sending a request for an mp3 file. But there is a difference between node.js and react native.

Node.js/React Native Code:

fetch(url).then(async response => {
    console.log(await response.arrayBuffer());
});

Node.JS Response Log

ArrayBuffer {
  [Uint8Contents]: <ff fb 90 c4 00 bb ... 13692 more bytes>,
  byteLength: 13792
}

React Native Response Log:

[]

Even though it is the same code, the outputs are different. I couldn’t understand the reason. What should I do to get like pure nodejs output in React native?

How to upload files to a page using razor jivescript/c#

in my post, when clicking the create button it doesn’t save the file I uploaded and it still shows the error Unable to access this site

[HttpPost]
public async Task<IActionResult> Create([Bind("ID,Inicio,Vencimento,ImovelId,LocatarioId,Ativo,ContratoPdf")] Contratos contratos, IFormFile arquivo)
{
    if (ModelState.IsValid)
    {
        try
        {
            if (arquivo != null && arquivo.Length > 0)
            {
                string diretorioDestino = @"C:CodeRazor PagesLRAdministraLRAdministraArquivo";
                if (!Directory.Exists(diretorioDestino))
                {
                    Directory.CreateDirectory(diretorioDestino);
                }
                string nomeArquivo = Path.GetFileName(arquivo.FileName);
                string caminhoCompleto = Path.Combine(diretorioDestino, nomeArquivo);

                using (var stream = new FileStream(caminhoCompleto, FileMode.Create))
                {
                    await arquivo.CopyToAsync(stream);
                }
                contratos.ContratoPdf = nomeArquivo;
            }

Tips for Integrating the Google Geolocation API on 4G Devices

I’m starting a project that involves integrating Google’s Geolocation API into 4G devices. I’ve already decided to use Google’s API, but I’m looking for advice on implementation to ensure the best possible user experience.

Technical Challenges: Can anyone share insights into specific technical challenges that may arise when integrating the Google Geolocation API on 4G devices? I’m thinking about issues like battery consumption, data usage, and location accuracy.

Documentation and Resources: Although I have accessed the official documentation, I would like to know if there are any recommended guides, tutorials or external resources that can complement the official material, especially those focused on optimizing for 4G mobile devices.

Practical Examples: It would be awesome if someone could share code examples or reference projects that demonstrate successful integration of the Google Geolocation API into mobile applications. I’m particularly interested in examples that deal with efficiency and performance issues.

Privacy and Security: Given that we will be dealing with sensitive location data, what are the best practices to ensure user privacy and security? Are there any specific Google API settings or coding practices I should adopt?

I still don’t know where to start

React Native – storage – No Firebase App ‘[DEFAULT]’ has been created

I initialise my application this way and it work perfectly well as i can use the authentification.

import { initializeApp} from "firebase/app";
import { initializeAuth, getReactNativePersistence } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
import { getAnalytics } from "firebase/analytics";
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { requestTrackingPermissionsAsync } from "expo-tracking-transparency";
import { Settings } from "react-native-fbsdk-next";

const firebaseConfig = {
  apiKey: "",
  authDomain: "-..",
  projectId: "-",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

However, when i try to use the firebase storage with this function

import storage from '@react-native-firebase/storage'

export const UploadFile = async(file_uri,name,bucket) => {
    return new Promise((resolve, reject) => {
        try{

            const parts = file_uri.split(/[/\]/)
            const basename = parts[parts.length - 1]

            if(bucket){
                bucket = firebase.app().storage('gs://'+bucket+'.appspot.com').ref(basename)
            }else{
                bucket = storage().ref(basename)
            }

            bucket.putFile(file_uri)
            resolve(bucket)
        }catch(error){
            console.log('Error when uploading the file '+error)
            reject(error)
        }
    });
}

I get the error

No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()

for the line bucket = storage().ref(basename).
I tried to pass it app as argument as it’s a possible argument but it didn’t work either.
I tried other solution found on stackoverflow, github, reddit, etc without success either

Thank you for your help

Is Map a set of keys (JavaScript the Definitive Guide – David Flanagan) or a set of key-value pairs (MDN)?

Hi guys I’ve been learning about Map in JavaScript and how we can use it instead of object in some practical situations.

In my learning journey I’ve found in JavaScript the Definitive Guide – David Flanagan that he mentions Map are, quote:

Remember, though, that a map is a set of keys, each of which has an associated value. This is not quite the same as a set of key/value pairs. If you call set() with a key that already exists in the map, you will change the value associated with that key, not add a new key/value mapping

But then I go to MDN and they’re saying the opposite, so what do I follow or believe?, also, isn’t there like an official technical definitio for this?, I have to check out EcmaScript 6…

Note: at the moment of writing this post I’ve found in the official ES6 documentation that indeed MDN is right, Map are a set of key/value pairs… Why did I spent my money on David Flanagan smh

enter image description here

Anyway I’ll leave the question open in case there is something I’m missing, thank you in advance.

How can I select all and active button when I open the page in React though useState?

I have a react app. I listed some items in the ItemList Page. What I really want to do is to select all and active button. However, I couldn’t do that.

When I firstly open the page and select all , delete button isn’t active but all items are selected.

When I navigate the another page and return to previous page and select all, delete button is active.

Where is the problem? How can I fix it?

Here is the code shown below

export default function ItemList() {
  const [selectAllCheckbox, setSelectAllCheckbox] = useState(false);
  const [selectedCheckbox, setSelectedCheckbox] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [items, setItems] = useState([]);


useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const result = await response.json();
        setItems(result.items);

        setSelectAllCheckbox((prevState) => prevState || false);
      } catch (error) {
        throw(error.message);
      }
    };

   fetchData();

    return () => {
      setSelectedRows([]);
      setSelectedCheckbox(false);
    };
  }, [url]);



  useEffect(() => {
    if (checkAllRef.current) {
      checkAllRef.current.checked = selectAllCheckbox;
    }
  }, [selectAllCheckbox]);

  const handleCheckAll = () => {
    const updatedItems = items.map((item) => ({
      ...item,
      selected: !selectAllCheckbox,
    }));
    setItems(updatedItems);

    const updatedRows = !selectAllCheckbox
      ? items.map((item) => item.metadata.name)
      : [];

    setSelectedRows(updatedRows);
    setSelectAllCheckbox(!selectAllCheckbox);
  };


    const handleRowSelection = (name) => {
    const updatedItems= items.map((item) => {
      if (item.metadata.name === name) {
        return { ...item, selected: !item.selected };
      }
      return item;
    });
    setItems(updatedItems);
    setSelectedRows(
      updatedItems
        .filter((item) => item.selected)
        .map((item) => item.metadata.name)
    );
    setSelectAllCheckbox(updatedItems.every((item) => item.selected));
  };

{rest part of the code}

return (
    <>
 {rest part of the code}
 <button
        className="btn btn-danger"
        disabled={!(selectAllCheckbox || selectedRows.length > 0)}
        onClick={handleDeleteRows}
 >
    Delete
 </button>

 <input
     type="checkbox"
     className="js-check-all align-middle"
     ref={checkAllRef}
     checked={selectAllCheckbox}
     onChange={handleCheckAll}
  />
  {rest part of the code}
<>
)

How can I fix it ?

How to re-render the page while using router.push() in Next.JS 14 app directory?

When I navigate between pages using router.push() in the app directory (Next.JS 14), the page which is rendered is the cached version of that page (the page(s) to which I nagivate using router.push() is/are server component(s) and not client component(s)).

It does not re-render the page, i.e. instead of fetching the data again from the server and then rendering the page, it renders the cached version of that page.

My requirement is such that whenever I navigate using router.push(), the page should be re-rendered without using any cached version of that page.

I’ve tried various methods to address this, including setting export const dynamic = "force-dynamic" and export const revalidate = 0, but none of them have resolved the issue for me.

Could anyone offer insights or suggestions on how to ensure that pages re-render without using cached versions when navigating using router.push() in Next.js 14? Thanks in advance for your help.

javascript how to make each iteration wait for previous [closed]

I want my code to wait for each iteration to end before starting the next one.

mainmain() returns “done!” when its finished. it is supposed to constantly do main() until delchecker says to stop.

code:

    async function deleteitem(item){
        let itemid = item["id"]
        setInterval(async() => {
            await sendreq(itemid,item["type"])
        }, 4000);
        setInterval(async() => {
            if(await delchecker(superagent,itemid)){
                console.log("done!")
                return
            }
        }, 30000);
    }

    const items = [
        {id:1,type:"wig"},
        {id:2,type:"bag"},
        {id:3,type:"bag"},
        {id:4,type:"shoe"}]
    async function main(items){
        for (const item of items){
            console.log("hey hey hey")
            let stuff = await deleteitem(item)
            console.log(stuff)
        }
    }
    main(items)

current output:

hey hey hey
hey hey hey
hey hey hey
hey hey hey

desired output:

hey hey hey 
done! 
hey hey hey 
done! 
hey hey hey 
done! 
hey hey hey 
done!

web audio api, AudioContext dont play on channel 3. Channels 4 and above do not work correctly

A 5.1 audio system is connected via hdmi. The operating system processes it correctly, I can test each individual speaker and get the expected result.
enter image description here

I need to use JS to send audio to specific channels (speakers). Below is the code. The number of channels and other nuances work correctly.

  let source;
  const AudioContext = window.AudioContext || window.webkitAudioContext;
  const audioCtx = new AudioContext();

  const audioUrl = "1.mp3";
  const audioResp = await fetch(audioUrl);

  const arrayBuffer = await audioResp.arrayBuffer();
  const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);

  let channelCount = audioCtx.destination.maxChannelCount;
  let audioChannelCount = audioBuffer.numberOfChannels;

  const splitter = audioCtx.createChannelSplitter(channelCount);
  const merger = audioCtx.createChannelMerger(channelCount);

  source = audioCtx.createBufferSource();
  source.buffer = audioBuffer;
  source.connect(splitter);

  const test = splitter.connect(merger, 0, 0);
  const test2 = splitter.connect(merger, 0, 3);

  merger.connect(audioCtx.destination);

  source?.start();

If I’m writing splitter.connect(merger, 0, 0); or splitter.connect(merger, 0, 1); the audio is played correctly on the left or right speaker. But if I write splitter.connect(merger, 0, 3); it doesn’t play at all. But if I specify channel 4 or 5, I get the same result as if I specify 0 or 1. All other columns are always silent. How do I get through to them? I need to be able to send a certain audio file to a certain channel.

Tauri and Vite, Import binding name not found

I’m trying to create a database adapter for WatermelonDB for Tauri (using vite). I’ve followed the instructions to compile watermelondb and then symbolically link it into my Tauri project.

However, when the app starts I get a blank screen, the following error:

[Error] SyntaxError: Importing binding name 'tableSchema' is not found.

Given that adding an importing watermelondb normally works, I’m guessing this has to do with some transpilation issue.

I’ve scoured the internet for this type of error (which I’ve never seen before in my development years) and haven’t found much info besides some suggestion it might have to do with the module system being used.

Has anyone faced an issue like this before? Any ideas?