Vue useFileDialog returns null

I’m trying to use @vueuse/core to allow a user to a select a file in vue. At this point, I’d be happy with just having the method return the filepath so I can eventually process it. I’m following along here: (https://vueuse.org/core/useFileDialog/). When I click the link, a window pops up and prompts me to select a file. When I select a file, nothing happens and I’m presuming that the file is returning null. Any idea what’s wrong?

Here’s some of my code:

<script setup>
    import IconUpload from "./icons/IconUpload.vue"
    import { useFileDialog } from "@vueuse/core"; 
    const { files, open } = useFileDialog()
</script>

<template>
    <a href @click="open()"><IconUpload /></a>
    <template v-if="filesSelected">
        Files: {{ files }}
        <li v-for="file in files" :key="file.name">
            Files: {{ file.name }}
        </li>
    </template>
</template>

Not sure if it’s helpful, but I’m using @vueuse/core: ^10.9.0.

i want to compare one array object and array inside array using javascript [closed]

const input = [
  {
    port: "mohan",
    flag: true,
  },
  {
    port: "mohan",
    flag: true,
  },
  {
    port: "mohanshiva",
    flag: false,
  },
  {
    port: "mohanshivaa",
    flag: false,
  },
];

const input1 = [
  [
    {
      port: "mohan",
      flag: true,
    },
  ],
  [
    {
      port: "mohanshivaa",
      flag: false,
    },
    {
      port: "mohanshivaa",
      flag: false,
    },
  ],
];

these all my input my expected output will be like

[
  [
    {
      port: "mohan",
      flag: true,
    },
  ],
  [
    {
      port: "mohan",
      flag: true,
    },
  ],
  [],
  [
    {
      port: "mohanshivaa",
      flag: false,
    },
    {
      port: "mohanshivaa",
      flag: false,
    },
  ],
];

i have tried this but not able to build the correct format

const output = input1.map((subArray) => {
  return subArray.map((item) => {
    return input.filter(
      (obj) => obj.port === item.port && obj.flag === item.flag,
    );
  });
});

could anyone can give me a solution .

Multi-polygon objects in matter.js being “smushed” together?

I have a polygon that I’m trying to make into a Body in matter.js, but it’s concave so i’ve split it into multiple convex polygons as shown below:

multiple polygons forming one large shape

here is the point data, it’s very large

But when I try to add this into my matter.js world, like this:

import m from "matter-js";

const engine = m.Engine.create();
const render = m.Render.create({
    engine,
    canvas,
});
const ramp = m.Bodies.fromVertices(150, 70, /* point data */);
const rampConstraint = m.Constraint.create({
    bodyA: ramp,
    pointB: { x: 150, y: 70 },
    length: 0,
    stiffness: 0.7,
});
m.Composite.add(engine.world, [ramp, rampConstraint]);

m.Render.run(render);

setInterval(() => {
    requestAnimationFrame(() => {
        m.Engine.update(engine, delta);
    });
}, 1000 / 60);

The polygons come out all “smushed together” in the center of the object:

enter image description here

How can I fix this? I’ve tried manually creating all of the polygons as their own individual bodies and then using them as the parts for a body, and removing the point constraint, but neither seems to do anything.

How to get the Element in DocumentFragment

I want to get all elements that are in the selection.

const selection = window.getSelection();
const range = selection.getRangeAt(0);
const selectedNodes = [range.cloneContents().childNodes][0];

This code returns an array of Nodes inside the DocumentFragment.
The DocumentFragment is created from the text you are selecting.

The Elements that are being selected in this case are inside of a <div> with the tag ContentEditable.
The childNodes types are either text or element/span.
I want to get the element so I am able to do window.GetComputedStyle().

I tried to do:

selectedNodes.foreach(node => {
    console.log(node.parentNode);
});

All that came out was the DocumentFragment not the Element that I was wanting.
Also if I did node.parentElement it would return false.

React Native & Expo unable to link images present in the project

I have been working on a Yoga-oriented Fitness App for a React Native Project to be showcased at University, and the app structure is given below:

Fit/
├── screens/
│   ├── Login.js
│   ├── Signup.js
│   ├── Welcome.js
│   ├── onboarding.js
│   ├── home.js
│   ├── notifications.js
├── yoga_poses/
│   ├── Dhanur.js
│   ├── Pawan.js
│   ├── Shirsha.js
├── ayurvedic/
│   ├── Vaata.js
│   ├── Kapha.js
│   ├── Pitta.js
├── App.js

Now in accordance with this structure, in the file yoga_poses/Dhanur.js, we have this code:

import React from 'react';
import { SafeAreaView, StyleSheet, Image, Text, TouchableOpacity, Linking} from 'react-native';

// Define the image using require('path_to_image')
const dhanur_pic = require('Fit/assets/dhanuraasana.jpg');

//rest of the code

Note: All other files in the yoga_poses folder have this same problem and this same first few lines, only the yoga pose’s name changes.
None of the files in the yoga_poses folder seem to work. Nor do any files in “ayurvedic” folder works.
But the image does not link since the error is thrown:

Unable to resolve "Fit/assets/dhanuraasana.jpg" from "yoga_poses/Dhanur.js"

Could this be an Expo/Metro Builder problem instead of it being a React Native issue and if yes, then how to fix it?

Everything I tried until now:
The file and folder names are correct (I agree that they are quite long), I have re-checked the names twice as I write this question. I have tried using all sorts of file paths (i.e., both relative and absolute) in all different forms/syntax one can use to define the image except maybe the Image tag itself since if the linking does not work, then how can we be sure that the Image tag would work? I was honestly very tired for the past 2 days working on this issue.
I am really sorry if this was a long read but I wanted to make the problem as clear as possible to any reader.

How to change React state variable inside a while loop?

I am new to React and web dev in general. I managed to find a workaround for my issue but the issue itself still baffles me. I am hoping for an in depth explanation or pointers to where I can learn more about this, thanks!

const [score, setScore] = useState(0);
const drawCard = async()=>{
    while (score < 20){
        const card = await deal(); //deal function fetches cards from deckofcards api
        const value = card.value; //syntax isn't correct but say I access it's int value
        setScore(score=> score+ value); //or setScore(score + value); both didn't work
        //other code, add to my deck etc...
    }
}

When I tried debugging this I found that the score doesn’t update in the loop, I am guessing it has to do with the async nature or maybe some react event loop thing? Thanks for the help!

I managed to get this working by creating a temporary variable outside the while loop to store the value and then setScore the variable in one go and it works fine. But I am curious to why this doesn’t work.

POS Development for Odoo 17

I want to do some changes on POS Odoo 17 like restrict out of stock products selection, POS receipts etc.

May I know what has changed in Odoo 17 JS so that i can work on the developments. Because the POS modules for Odoo 16 are not working in Odoo 17. I have changed the XML files according to v17 but still cannot make it work. So I want to know what has changed in the JS part and how do I implement it.

I have tried searching about this but didn’t get any solution.
I have some modules for this development but it is Odoo 16, it is not working on Odoo 17.

each JS file has 3 files js es5js and es5minjs why

Haven’t too much experience with

fileName1.js
fileName1.es5.js
fileName1.es5.min.js 

so please bear with

I need to make changes to a number of js files on our mvc project.

So each JS file has the 3 files (above).

When I make a change to the orignial, do I need to also change this in the other 2?

Also, ive just been brought onto this project, but in the .cshtml file where the js file is being referenced, sometimes it will reference the fileName.js and other times it will ref the fileName.es5.min.js

Was this a mistake on the developers side, im assuming every ref should have been to the fileName.es5.min.js file??

I get what the es5.min.js does, its compressed with no white space to save loading time etc… but whats the point of the es5.min.js file?,

Making the change of the file mentioned solves my task, but the other 2 js files for that particular file wont have the update then

My question is Do I mannually need to change all 3 files? or for example when I change the orignial file, and somehow during the build the other 2 files get updated, or is there somewhere I drop in the main file and can get 3 outputted files? what do I do?

any advice appreciated thank you for replies

Most efficient way to slice a large concatenated array in Javascript?

I need to retrieve at most N elements from an API endpoint, but this endpoint is paginated, with no options to configure how many items I get per page. The elements are json objects.

The obvious solution is this:

let page = 1
let totalAmount = 0
let elements = []
while (totalAmount < N) {
  const pageElements = apiService.getElements(page)
  elements.push(...pageElements)
  totalAmount += pageElements.length
  page += 1
  //code for the case when N is bigger than all the elements in the API
}

elements = elements.slice(0, N)

But this is probably too inefficient when N is big, since slice makes a copy of the array in memory.

So, what I’m doing is, inside the while loop, checking if I’m in the last iteration, and if I am, I slice only that page:

if (totalAmount + pageElements.length > N) {
  pageElements= pageElements.slice(0, N - totalAmount)
}

Is there a way to make this even more efficiently? The second solution is probably efficient enough, but I really need to make this as good as possible.

Timeout not resetting for each Promise

I am trying to make it so each mapbox cell will download. I want it so every loop has 60 seconds to download the street and satelite maps. This seems to timeout every 60 seconds regardless of whether it is successfully constantly looping and downloading maps.
So it will loop and download correctly but timeout after 60 seconds every time, instead of first loop, allow 60 seconds, finishes, second loop restart and allow 60 seconds, finishes….
They take less than 10 seconds to download so it should never timeout. I am also logging to see them finish.

const downloads = bufferedCellBBoxes.map(async (cell, i) => {
    let timeoutResolved = false; // Flag to track if the timeout has already been resolved

    const timeoutPromise = new Promise((resolve) => {
      setTimeout(() => {
        if (!timeoutResolved) {
          resolve('timeout');
          timeoutResolved = true; // Set flag to true to indicate timeout has been resolved
        }
      }, 60000); // 60 seconds timeout
    });

    const satellitePromise = downloadMapTiles(
      'satellite',
      [
        [cell[2] as number, cell[3] as number],
        [cell[0] as number, cell[1] as number],
      ],
    );

    const streetPromise = downloadMapTiles(
      'street',
      [
        [cell[2] as number, cell[3] as number],
        [cell[0] as number, cell[1] as number],
      ],
    );

    return Promise.race([
      Promise.all([satellitePromise, streetPromise]),
      timeoutPromise,
    ])
      .then((result) => {
        // Check if the result is 'timeout', if so, cancel the ongoing processes
        if (result === 'timeout') {
          throw new Error('Timed out');
        }
        return result; // Return the resolved promise result
      })
      .catch((error) => {
        console.error('Error during tile download:', error);
        return Promise.reject(error);
      });
  });

Issues with Jest Testing in Quasar Template with Vue 3 and Vite

I’m creating a template to work with Quasar Framework, Vue 3, and Vite where the goal is to clone the project and develop the frontend without extensive configurations since everything should already be set up. So far, I’ve made decent progress. However, recently I implemented a security module (I know, better safe than sorry). When I tried running the tests, I encountered the following error:

Jest error

I’ve researched this issue, but nothing seems to work.

Here is my package.json:

{
  "name": "quasar-template",
  "private": true,
  "version": "1.6.4",
  "type": "module",
  "main": "index.html",
  "description": "This is a template for quickly working with Quasar and Vite - Vue 3. It includes features that assist in both individual and group workflows, such as Husky for Git hooks, Prettier for code formatting, and ESLint for code quality checks. Additionally, it provides testing capabilities with Jest, along with Axios for HTTP requests, Crypto-js for cryptography functionalities, and Jwt-decode for JWT decoding. It also integrates Pinia for state management and Vue-router for routing. The template utilizes Sass for styling and supports TypeScript. Furthermore, it implements lint-staged for staged linting, and vue-eslint-parser for parsing Vue files within ESLint. Notably, it supports internationalization throughout the app, facilitating efficient adaptation of content and user interface to different languages via tools like vue-i18n, thus extending the application's reach to a broader audience.",
  "keywords": [
    "Quasar",
    "Vite",
    "Vue 3",
    "Husky",
    "Prettier",
    "ESLint",
    "Jest",
    "Axios",
    "Crypto-js",
    "Jwt-decode",
    "Pinia",
    "Vue-router",
    "Babel",
    "Testing-library",
    "Sass",
    "TypeScript",
    "lint-staged",
    "vue-eslint-parser"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/Santiago1010/quasar-template.git"
  },
  "bugs": {
    "url": "https://github.com/Santiago1010/quasar-template/issues"
  },
  "author": {
    "name": "Santiago Correa Aguirre",
    "email": "[email protected]"
  },
  "license": "MIT",
  "scripts": {
    "build": "vite build",
    "dev": "vite",
    "format": "prettier --write .",
    "format:check": "prettier --check "{public,src}/**/*.{js,ts,vue,json,css}"",
    "format:write": "prettier --write "{public,src}/**/*.{js,ts,vue,json,css}"",
    "lint": "eslint .",
    "lint:check": "eslint "{public,src}/**/*.{js,ts,vue,json}"",
    "lint:fix": "eslint "{public,src}/**/*.{js,ts,vue,json}" --fix",
    "prepare": "husky || true",
    "preview": "vite preview",
    "test": "jest",
    "test:integrations": "jest ./src/testing/integration",
    "test:unit": "jest ./src/testing/unit"
  },
  "lint-staged": {
    "**/*.{js,ts,vue}": [
      "prettier --write --ignore-unknown",
      "eslint --fix",
      "git add"
    ]
  },
  "dependencies": {
    "@intlify/unplugin-vue-i18n": "^4.0.0",
    "@quasar/extras": "^1.16.9",
    "axios": "^1.6.8",
    "crypto-js": "^4.2.0",
    "jsonwebtoken": "^9.0.2",
    "jwt-decode": "^4.0.0",
    "pinia": "^2.1.7",
    "quasar": "^2.14.5",
    "vue": "^3.3.11",
    "vue-i18n": "^9.9.0",
    "vue-router": "^4.3.0"
  },
  "devDependencies": {
    "@babel/eslint-parser": "^7.23.10",
    "@babel/plugin-syntax-import-meta": "^7.10.4",
    "@babel/preset-env": "^7.24.4",
    "@quasar/vite-plugin": "^1.6.0",
    "@testing-library/vue": "^8.0.2",
    "@vitejs/plugin-vue": "^4.5.2",
    "@vue/test-utils": "^2.4.5",
    "@vue/vue3-jest": "^29.2.6",
    "babel-jest": "^29.7.0",
    "babel-plugin-transform-import-meta": "^2.2.1",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.1.3",
    "eslint-plugin-vue": "^9.23.0",
    "husky": "^9.0.11",
    "jest": "^29.7.0",
    "lint-staged": "^15.2.2",
    "prettier": "^3.2.5",
    "sass": "^1.33.0",
    "ts-jest": "^29.1.2",
    "vite": "^5.0.8",
    "vite-plugin-environment": "^1.1.3",
    "vue-eslint-parser": "^9.4.2"
  }
}

This is my ./jest.config.json:

{
  "transform": {
    "^.+\.vue$": "@vue/vue3-jest",
    "^.+\.js$": "babel-jest"
  },
  "testRegex": "(/__tests__/.*|(\.|/)(test|spec))\.(js|ts)$",
  "moduleFileExtensions": ["vue", "js"],
  "moduleNameMapper": {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  "coveragePathIgnorePatterns": ["/node_modules/", "/tests/"],
  "coverageReporters": ["text", "json-summary"],
  "testEnvironmentOptions": {
    "customExportConditions": ["node", "node-addons"]
  }
}

This is my ./babel.config.json:

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-syntax-import-meta",
    "babel-plugin-transform-import-meta"
  ],
  "env

": {
    "test": {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "node": "current"
            }
          }
        ]
      ]
    }
  }
}

And this is my ./vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '@quasar/vite-plugin'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import EnvironmentPlugin from 'vite-plugin-environment'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    host: true,
    port: 5173,
    watch: {
      usePolling: true,
    },
  },

  plugins: [
    vue({
      template: { transformAssetUrls },
    }),

    VueI18nPlugin({
      include: './src/config/i18n',
    }),

    quasar({
      sassVariables: './public/styles/sass/quasar-variables.sass',
    }),

    EnvironmentPlugin('all'),
  ],
})

Any help would be greatly appreciated.

Function not executing despite being called; JavaScript

For one of my programming classes, we were tasked to solve a problem using Java Script. I decided to make an inches-to-centimeter unit converter, but I’ve run into a problem. When running the program, one of the requirements is that you must call another function within a function. I did so, but the other function being called is not executing. The function in question is “unitConversion”.

I also tried calling the function outside the other function, but it doesnt work either way. Here’s the code:

// UNIT CONVERTER THAT ALLOWS USER TO CONVERT VALUES FROM 
// INCHES TO CENTIMETERS & VICE-VERSA

userConversionInput();

// Conversion rate from inches to centimeters
function inchesToCentimeters(){ 
    return inches * 2.54;
}

// Conversion rate from centimeters to inches
function centimetersToInches(){ 
    return centimeters / 2.54;
}

// Asks the user for the values to convert
function userConversionInput(){ 
  var value = readInt("Enter a value to convert: ");
  var fromUnit = readLine("Enter the unit of measurement (Inches or Centimeters): ");
  var toUnit = readLine("Enter the unit of measurement to convert to (Inches or Centimeters): ");
  unitConversion();
}

// Actual conversion function

function unitConversion(value, fromUnit, toUnit){ 
    var convertedValue;
    
    if(fromUnit === 'inches' && toUnit === 'centimeters'){
        convertedValue = inchesToCentimeters(value);
        console.log(value + "in inches is equal to: " + convertedValue + "centimeters. ");
        
    } else if (fromUnit === 'centimeters' && toUnit === 'inches'){
        convertedValue = centimetersToInches(value);
        console.log(value + "in centimeters is equal to: " + convertedValue + "inches. ");
    }
}

Please Help!

In JS, checking if element.style.bottom is empty not working

I have an element <div class="my-thing"></div>

I need to programmatically toggle the bottom property in javascript, so I have a simple click event that calls a function with this if statement:

if(element.style.bottom === "") {
   //do something
}

if( element.style.bottom !== "") {
   //do something else
}

However both of these if statements trigger at the same time if I don’t have style set on my div. If I /do/ set style like style="bottom: 120px;" then the second statement gets triggered.

When it’s empty I need only the first if statement to trigger, not both.

I tried changing === "" to === null or === undefined or all 3 separated by ||, and the same thing still happens. I also tried !element.style.bottom. None worked.

When I do console.log(element.style.bottom) when it’s empty, I get <empty string> as a response in the console.

So how do I target a non-set property???

Find function by name in a complex object using dev tools

I’m importing a library in a project and I can’t find a method that I’m supposed to use.

The functions name is itDoesntMatterFunctionName().

Is there a search by function name in the chrome debugger tools that if I give it an object it will find it?

Example:

var myApp = new ComplexApplication();
console.find(myApp, "myFunctionName");

It’s entirely possible that this function is not exported by the module because note this error:

Uncaught SyntaxError: The requested module './lib/pixi/pixi.mjs' does not provide an export named 'getCanvasBoundingBox'

But it does find other classes / objects in the module.

Chrome debugger / Dev tools Filter box (does not find methods or properties on objects which is what I want):
enter image description here