Android Camera Permission – significant drop in the number of devices your apps supports

We have a live React Native Android application on the Play Store. In a recent update, I need to add camera permissions to the mobile app. I am using this package for image cropping: https://github.com/ivpusic/react-native-image-crop-picker. After uploading the update to the Play Store, I received a warning: ‘This release will cause a significant drop in the number of devices your app supports on the following form factors: Car, Chromebook, Phone, Tablet. Devices not supporting camera hardware.’

The camera functionality is not mandatory in our app, but if a device has a camera, it should work. How can I achieve this?

<uses-permission android:name="android.permission.CAMERA"/>"

This line added for permission

sort array object by using set of collection in javascript

I have a very unique situation and i am trying to sort this complex data structure in javascript.

let data = [
    {
        "failureNo": 1,
        "rec": { "uniqId": "l-7fa-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 0
    },
    {
        "failureNo": 2,
        "rec": { "uniqId": "l-1577edb762f", "rotorId": "1.20.32" },
        "exceptionId": 1
    },
    {
        "failureNo": 2,
        "rec": { "uniqId": "l-85fa-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 1
    },
    {
        "failureNo": 3,
        "rec": { "uniqId": "l-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 2
    },
]

Here is my input above. User does some interaction in the UI and i get the below variable from that interaction. so checkedValues variable tells me that user has selected 2 entries using checkbox. 2 entries because the collection object below has value associated to it. for e.g for key 1 it has value as new Set([ "_com.smp.1905546540", "_com.smp.3345454545" ]),
key 2 has value as new Set([ "_com.smp.33343rf453" ]) 3rd checkbox is not selected and that value is {} in below data.

let checkedValues = new Map([
    [
        1,
        new Set([ "_com.smp.1905546540", "_com.smp.3345454545" ])
    ],
    [
        2,
        new Set([ "_com.smp.33343rf453" ])
    ],
    [
        0, 
        {}
    ],
])

So when checkbox with key 1 and 2 are selected, it is mapped to exceptionId in the data variable. This selection of 1 and 2 means we want the objects with exceptionId 1 and 2 to be sorted and shown first and then the rest.

So my final output should be as follows

let result = [
    {
        "failureNo": 2,
        "rec": { "uniqId": "l-1577edb762f", "rotorId": "1.20.32" },
        "exceptionId": 1
    },
    {
        "failureNo": 2,
        "rec": { "uniqId": "l-85fa-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 1
    },
    {
        "failureNo": 3,
        "rec": { "uniqId": "l-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 2
    },
    {
        "failureNo": 1,
        "rec": { "uniqId": "l-7fa-48eda0bb762f", "rotorId": "1.24.39" },
        "exceptionId": 0
    }
]

In order to achieve this sorting, i created a function as follows

export const sortData = (data, checkedValues) => {
    const dataCopy = [...data];
    return dataCopy.sort((a, b) => {
      const aValues = checkedValues.get(a?.exceptionId);
      const bValues = checkedValues.get(b?.exceptionId);
      const aChecked = aValues ? aValues.has(a?.value) : false;
      const bChecked = bValues ? bValues.has(b?.value) : false;
  
      if (aChecked && !bChecked) return -1;
      if (!aChecked && bChecked) return 1;
  
      return a.failureNo - b.failureNo;
    });
  };

There is no runtime error on this function but the problem is that it doesnot sort data at all. it just displays the data as output as it is without sorting anything. Can someone please let me know where i am going wrong.

How to disable line break because of enter, shift+enter, cntrl+enter in TIp tap editor

I am using Tip tap editor for my project, I am able to disable the action performed by Enter button for my editor, but I need help for disabling the action for my Shift+Enter click

const DisableEnter = Extension.create({
        addKeyboardShortcuts() {
          return {
            Enter: () => {
              console.log('Enter pressed');
              return true;
            },
            'Shift-Enter': () => {
              console.log('Shiftkey disabled');

              return true; 
            },
            D: () => {
              return true;
            },
          };
        },
      });

then I placed the DisableEnter in my extensions, I am able to disable the Enter, but I try for shift enter, it does not work, though it works to not allow D as well, what can I do, i want a similar action for ctrl Enter

but it works if I do like this:

editorProps: {
                
                handleDOMEvents: {
                    keydown: (_, event) => {
                        if (event.shiftKey === true) {
                            if(event.key=="Enter") {
                                return true;
                            } 
                        }
                    },
                },
            },

So my question is can I do it using the extensions or the only option is through the editor props?

Exporting multiple imported components for efficiency/readability?

I’m working with a project that makes many imports from a particular library, but importing from the dist rather than being more generic.

ie.

import {Header} from '@some-lib/.../.../dist/Header';
import {Footer} from '@some-lib/.../.../dist/Footer';
import {Column} from '@some-lib/.../.../dist/Column';
import {Button} from '@some-lib/.../.../dist/Button';
import {Radio} from '@some-lib/.../.../dist/Radio';

rather than

import {Header, Footer, Column, Button, Radio} from '@some-lib';

While I understand that this is done for greater efficiency and more specificity in what we import into each component, it really clogs up the file with a million imports at the top and doesn’t look all that attractive.

Would it be possible to perhaps have a separate file in which we can import all of the lib’s components from their respective dist locations and re-export them such that we can achieve a single line import, but with the benefits of performance of the multi-line?

For example:

// libImportExport.js
import {Header} from '@some-lib/.../.../dist/Header';
import {Footer} from '@some-lib/.../.../dist/Footer';
import {Column} from '@some-lib/.../.../dist/Column';
import {Button} from '@some-lib/.../.../dist/Button';
import {Radio} from '@some-lib/.../.../dist/Radio';

export {Header, Footer, Column, Button, Radio};

// MyComponent.jsx
import {Header, Footer, Column, Button, Radio} from './libImportExport';

...

Or is this a pointless effort to make?

whats the smallest way to store a html canvas image

I’m trying to make a pixel art animator thing where you can make pixel art but also animate it but the problem is I want the canvas to take up most of my screen with just a little bit of space below it (and it’s a square canvas so there will be a lot of space on the sides (for buttons to change the pixel size and color etc) but I just want it to take up most of the window vertically) but I ended up having to set it to like 600×600 or 800×800 pixels (for my large monitor) but that would make the data url take up a lot of space especially if I’m storing a bunch of them for an animation so is there any smaller way to store the canvas image data for each frame (without external/third party compression libraries/frameworks)?

I tried using a smaller canvas (hidden with display: none;) that whenever I drew a larger pixel (e.g. 32×32 pixels image) on the interactive canvas on screen it drew it on the respective pixel on the smaller (hidden) canvas but when I tried to get the image data from the smaller canvas and make a <img> from the smaller canvas data url and make the image bigger again it sometimes gets blurry between the pixels

I’m not able to see a button Yes and No

After 6 attempts I’m not getting the buttons rendered in the page. I tried to debug but i’m not understanding. Below is the code for the componenet and everything is working as expected except the button yes and no.

import { useNavigate } from "react-router-dom";
import {useRef} from "react";
function Game() {
    const p1Ref = useRef(null);
  const p2Ref = useRef(null);
  const p3Ref = useRef(null);
  const navigate = useNavigate();
  const inputRef = useRef(0);
  const handleInputChange = (event) => {
    inputRef.current.value = event.target.value;
  };
  let randomNumber = Math.floor(Math.random() * 100) + 1;
  let count = 0;
  
  let v3 = [];

  function calculate() {    
    if (count == 5) {
      p2Ref.current.innerHTML = "You lost";
      p3Ref.current.innerHTML = "Gameover";
      count = 0;
      v3 = [];
    } else if (inputRef.current.value === randomNumber) {
      p1Ref.current.innerHTML = "Your guess is right. The random number chosen is: " + randomNumber;
      p2Ref.current.innerHTML = "you have guessed in " + v3.length + " chances";
      p3Ref.current.innerHTML = "Gameover";
      count = 0;
      v3 = [];
    } else if (inputRef.current.value > randomNumber) {
      p1Ref.current.innerHTML = "your guess is high";
      v3[count] = inputRef.current.value;
      count = count + 1;
      p2Ref.current.innerHTML = "your guesses: " + v3.join(", ");
    } else {
      p1Ref.current.innerHTML = "your guess is low";
      v3[count] = inputRef.current.value;
      count = count + 1;
      p2Ref.current.innerHTML = "your guesses: " + v3.join(", ");
    }

    if (p3Ref.current.innerHTML === "Gameover") {
        console.log("im inside")
      return (
        <div>
          <button>
            Yes
          </button>
          <button onClick={() => navigate("/next")}>
            No
          </button>
        </div>
      );
    }
  }

  return (
    <div className="mad">
      <h1><b>Number guessing game</b></h1>
      <pre>
        <p id="p4">
          We have selected a random number between 1 and 100. See if you can guess it in 6 turns or fewer.
          <br />
          We&apos;ll tell you if your guess was too high or too low.
        </p>
      </pre>
      <div className="prompt1">
        Enter the prompt: <input type="number" required min="1" max="100" id="input1"  ref={inputRef} onChange={handleInputChange}></input>
        <button id="done" onClick={calculate}>submit</button>
      </div>
      <p ref={p1Ref}></p>
      <p ref={p2Ref}></p>
      <p ref={p3Ref}></p>
    </div>
  );
}

export default Game;

I’m not understanding why it’s not rendering as it’s going inside and priniting in i’m inside in console.

Run a Vite server within configureServer of another Vite server

Wondering if it’s possible to run a Vite server within another.

I’m trying to create a plugin that serves assets of another library in a monorepo. I can’t seem to get both running at the same time.

import { createServer } from 'vite';

const CONFIG_FILE = "...";

export default function viteMyServer() {
  return {
    name: 'vite-plugin-my-server',
    async configureServer(server) {
      const viteService = await createServer({
        configFile: CONFIG_FILE,
        appType: "custom",
        server: {
          middlewareMode: true,
        },
      });

      server.middlewares.use(viteService.middlewares.handle);
    }
  }
}

Why are chunks sent from Node.js using Sever-Sent Events / Chunked Transfer Encoding different in size when sent and received?

I am streaming some data using Node.js / Express.js Server-Sent Events:

app.get('/', async (req, res) => {
    // Implementaiton detail doesn't matter, writing some pieces over some period of time
    await getSomeAsyncData((chunk) => {
        console.log("Writing a chunk to client, size", chunk.length);
        res.write(chunk);
    });
    res.end();
}

On the client-side, I am using a simple fetch call:

// Fetching the endpoint above
const req = await fetch(`https://example.com/my-endpoint`);

let done = false;
while (!done) {
    let result = await req.body.getReader().read();
    done = result.done;
    if (result.value) {
        console.log("Received chunk of length", result.value.length);
    }
}

As a result, the full data (118708 bytes in this case) is sent, but the chunks are split in a different way, making them impossible to parse. The logs on the server side read:

Writing a chunk to client, size 36128
Writing a chunk to client, size 36200
Writing a chunk to client, size 33648
Writing a chunk to client, size 12732

And the logs on the client read:

Received chunk of length 68786
Received chunk of length 36864
Received chunk of length 12288
Received chunk of length 770

Are the messages not supposed to be sent in exactly the same way? Is there something that could be making them recombined and split differently?

Is it possible to detect (with CSS or JavaScript) whether Safari has compact tabs enabled?

If you’re not familiar, Safari on macOS and iPadOS supports compact tabs in Safari, which lets the top of the screen bleed up into the UI chrome, similar to how the top of a page bleeds into the status bar in PWA mode in iOS/iPadOS. Because I’m using the theme color to match the top of the page, I want to round the corners of my sidebar so it’s not just a flat edge.

Example of the look I’m going for (see the border radius atop the green sidebar):
screenshot of rounded corner

However, for normal tabs, it’d look better without this border radius.

I already use JS/CSS to scope this to just PWAs (detected with window.matchMedia && window.matchMedia('(display-mode: standalone)').matches), but I’m wondering if Apple has exposed a way to determine if the user has compact tabs enabled.

Since the feature isn’t on by default and it’s lesser-known, I wonder if this is possible and just isn’t documented because I am, in fact, the first person to care about this.

Below is the answer i get from ChatGPT. Is it right?

React’s logic of constantly trying to re-render comes from its internal rendering and error handling mechanisms. When a component throws a Promise (such as when Suspense is not wrapped in useSuspenseQuery), React does not recognize this situation and therefore treats it as an error. React tries to re-render the component to “fix” the error, but since there is no mechanism for handling Promise, the same Promise will be triggered every time it is rendered, thus entering an infinite loop. This is because the Suspense component catches and pauses rendering, causing React to render repeatedly

The library webcam-easy generates an error OverconstrainedError {message: “Invalid constraint”, constraint: “width”} on iOS 12.1 (Safari)

I use the library via cdn to access the device’s webcam. When I execute the following code, I get the error I specified in the question title. It is ejected through console.error in else block. Thus, the steps start() and then() are not completed successfully. Everything works fine on android and desktop. Are there any ways to solve this?

import checkPermissionState from "../helpers/checkPermissionState";
import takePicture from "../helpers/takePicture";

export default function goToPhoto() {
  $("#toPhotoStepBlock").on("click", async function () {

    const webcamElement = document.getElementById("webcam"),
      canvasElement = document.getElementById("canvas"),
      webcam = new Webcam(webcamElement, "user", canvasElement);

    webcam
      .start()
      .then((res) => {
        webcamElement.removeAttribute("controls");
      })
      .catch(err => {
        if (err.name === "NotAllowedError") {
          checkPermissionState();
        } else {
          console.error(err);
        }
      });
    takePicture(webcam);
  });
}

I haven’t tried anything, I don’t know how to solve this problem.

I don’t understand constructor function with object inside it

I am a Javascript novice, while doing a course, everything was going all right until I got to the “prototype chain” part of the course.
I am here to ask if someone can explain to me this exercise:

This is the exercise copied and pasted from the course:

The Shape function will take two arguments: x and y. Store these values in an object position on the instance (this).

For reference see this example. The tests will invoke Shape with the new keyword, creating an object and setting it to this within the function.

The position should have keys x and y containing the corresponding values:

const shape = new Shape(5, 10);

console.log(shape.position.x) // 5
console.log(shape.position.y) // 10

Notice that position is an object with two keys x and y!


The example is clear, I understand it:

function Car(make, model) {
    this.make = make;
    this.model = model;
}

const car = new Car('Toyota', 'Camry');
const car2 = new Car('Honda', 'Civic');

console.log(car.make) // Toyota
console.log(car2.model) // Civic

But the exercise wants me to store x , y in the object position in the function Shape:

My solution (wrong):

function Shape(x, y) {
    // store x and y in this.position
    const position = {
        this.x = x
        this.y = y
    }


}

the original exercise:

// Our Shape "Constructor"
function Shape(x, y) {
    // store x and y in this.position
}

module.exports = Shape;

Can someone explain to me what is wrong with my code? I know I can peek and see the correct solution to this exercise, but since I don’t understand it, I feel that I can’t move forwards.
Thank you for your help.

Lightningchart js, use different sampling rate in Medical Dashboard

Currently I have ECG, Pulse rate, Respiratory Rate and NIBP to show in LightningChart JS Medical Dashboard which used a global sampling rate which is common to all channels [ecg,pulseRate,respRate,nibp]. But the sampling rate would change for each channel. ECG and Pulse Rate will have 256, and Respiratory rate will have 128.

I tried below but didn’t work, as it now becomes 128 samples/second to all the channels.

Code:

 const SAMPLE_RATE_NEW = 128;

Below is the function i used with my changes.

    let tSamplePos = window.performance.now();
    let tSamplePosNew = window.performance.now();
    let iSampleX = 0;

    const addData = () => {
      const tNow = window.performance.now();
      const seriesNewPoints = seriesList.map((_) => []);
      while (tNow > tSamplePos) {
        const x = tSamplePos;
        const xNew = tSamplePosNew;
        for (let i = 0; i < seriesList.length; i += 1) {
          const channel = channels[i];
          const dataSet = channel.dataSet;
          const sample = dataSet[iSampleX % dataSet.length];
           if (i !== 2) {
             // @ts-ignore
             seriesNewPoints[i].push({ x, y: sample });
           } else {
             // @ts-ignore
             seriesNewPoints[i].push({ xNew, y: sample });
           }
          // // @ts-ignore
          //seriesNewPoints[i].push({ x, y: sample });
          if (channel.name === "Electrocardiogram") {
            updateBpm(sample);
          }
        }
        tSamplePos += 1000 / SAMPLE_RATE;
        tSamplePosNew += 1000 / SAMPLE_RATE_NEW;

        iSampleX += 1;
      }

How do i get different sampling rates in different channel?
I am using this medical dashboard Online Medical Dashboard

Entire Code can be found above.

I have tried multiple different solution but none of them worked. Need guidance on how to do it.

I tried using different sampling rate and push the data inside array, but i am not getting different sampling rates. Why I want this? The charts formed are different in different devices(laptop/desktop). And since this is a medical application, so its very urgent.