javascript: All device data is read into the object

When I write javascript, I want to read all the data of the device into the object, but only the last one is read.
I would like to ask how I can read all the data in the device into obj, thank you.

let data = [
      {
          "bind": "82218018295591013",
          "account": "admin",
          "password": "0000",
          "devices": [
              {
                  "ip": "192.168.0.88",
                  "brand_name": "UNIVIEW",
                  "name": "UNIVIEW"
              }
          ]
      },
      {
          "bind": "94907378021478863",
          "account": "admin",
          "password": "0000",
          "devices": [
              {
                  "ip": "192.168.0.88",
                  "brand_name": "UNIVIEW",
                  "name": "UNIVIEW"
              },
              {
                  "ip": "192.168.0.89",
                  "brand_name": "hisharp",
                  "name": "hisharp"
              }
          ]
      }
  ]
  
  let obj = {};
  
  function getObj() {
      for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < data[i].devices.length; j++) {
              obj.devices = data[i].devices[j];
          }
      }

      return obj;
  }

  console.log('obj :>> ', obj);
  getObj();

set GoogleMap widget gesturehandling to “greedy” on flutter

I’m working on a flutter web application and I’m using GoogleMap widget.
There are several interaction modes (gestureHandling) that google makes available in the JavaScript version (Interaction doc).

By default, the map is in “greedy” mode, but when I resize the internet browser, it goes into “cooperative” mode … and at this time, when I want to zoom on my map, I have to maintain CTRL key and i dont’t like it at all.

It show me : “Use ctrl + scroll to zoom the map”.

So in my project I want to set the map in the “greedy” interaction mode, but the GoogleMap widget doesn’t have any parameter for doing it.

I found an alternative solution which consists of going through JavaScript to programmatically press the CTRL button when there is an action of the wheel on the map.

<!-- In web/index.html -->
<!-- ... -->
<head>
  <!-- ... -->
  <script src="script.js" defer></script>
  <!-- ... -->
</head>
<!-- ... -->
// In web/script.js
function initScrollListener(id) {
    try {
        var map = document.getElementById('plugins.flutter.io/google_maps_' + id);
        map.addEventListener('wheel', wheelEvent, true);
    } catch (error) {
        console.error(error);
    }
}

function wheelEvent(event) {
    Object.defineProperty(event, 'ctrlKey', { value: true });
}
// In lib/main.dart (or anywhere in your project)
import 'dart:js' as js;
import 'package:flutter/foundation.dart';

//... in my widget ...//
@override
  Widget build(BuildContext context) {
    return GoogleMap(
      //...//
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
        if(kIsWeb) js.context.callMethod('initMap', [controller.mapId]);
      },
    );
  }
//...//

It works pretty well, but I’m not too confident about this solution.

I’m now trying to find a way to retrieve the google.maps.Map instance, and attempt to manualy set the “greedy” interaction mode onto it.

If you have any suggest ^^
Thanks !

Three.js How do I define variables and/or positions after a gsap position change

Basically, what im trying to do is, that I have three cubes, and on each click they switch positions. This works fine when done once. Now, I added 3 Lines in the end of the function called “rotWorld” like this:

var i1 = i3;
var i2 = i1;
var i3 = i2;

but i get errors all the time. How can I define the switches positions as new initial positions, to that the next time I click on the trigger, the objects will move again, making a full circle at 3 clicks?

Heres a fiddle:
https://jsfiddle.net/ung8qapd/1/

Passing data from a class component to a functional component

My class component which has the data and adding it to the <PointsLayer component:

import React, {Component} from 'react';

export class EventsMap extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        const data = this.props.data;
        console.log("data in events map", data)
....
....
...
                <PointsLayer data={data}/>

export default injectIntl(EventsMap);

Trying to receive it inside my PointsLayer component which is a functional component:

import { useState, useEffect } from 'react';
import { loadModules } from 'esri-loader';
import multipoint from "@arcgis/core/geometry/Multipoint";



const PointsLayer = (props) => {
    const data = this.props.data;
    console.log("data in pointslayer", data);

The console.log in my “EventsMap” component shows the data but the console.log in the “PointsLayer” component is undefined. Is is possible to pass data from a class component to a functional component?

Sharp library doesn’t capture the padding area when creating a file output

I want to use the Sharp library to output a line graph SVG to a png. In the SVG the axis and legends are on top of the padding space of the SVG as overflow, shown in this picture.

When I use Sharp to process the SVG into an image file, the padding part is not captured as in output png shown in this picture.

const element = renderToString(svg);
sharp(Buffer.from(element))
.png()
.toFile("output.png", Object);

JSFiddle of line graph: https://jsfiddle.net/Lefsqo3j/14/

<svg overflow="visible" style="padding:24px 0px 24px 40px">
  {/*Grid lines*/}
        <svg role="img" viewBox="0 0 300 100" preserveAspectRatio="none">
            <svg viewBox="0 0 300 100" preserveAspectRatio="none">
                <line y1="0" y2="100" x1="0" x2="0" stroke-width="0.2" stroke="black"></line>
                <line y1="0" y2="100" x1="75" x2="75" stroke-width="0.2" stroke="black"></line>
                <line y1="0" y2="100" x1="150" x2="150" stroke-width="0.2" stroke="black"></line>
                <line y1="0" y2="100" x1="225" x2="225" stroke-width="0.2" stroke="black"></line>
                <line y1="0" y2="100" x1="300" x2="300" stroke-width="0.2" stroke="black"></line>
                <line x1="0" x2="300" y1="0" y2="0" stroke-width="0.2" stroke="black"></line>
                <line x1="0" x2="300" y1="25" y2="25" stroke-width="0.2" stroke="black"></line>
                <line x1="0" x2="300" y1="50" y2="50" stroke-width="0.2" stroke="black"></line>
                <line x1="0" x2="300" y1="75" y2="75" stroke-width="0.2" stroke="black"></line>
                <line x1="0" x2="300" y1="100" y2="100" stroke-width="0.2" stroke="black"></line>
            </svg>
        </svg>
  {/*Legend*/}
        <svg x="100%" overflow="visible">
            <text text-anchor="end" dy="-8px">
                <tspan fill="red"> ⬤</tspan>
                Line A<tspan fill="blue"> ⬤</tspan>
                Line B
            </text>
        </svg>
  {/*Date lines*/}
        <svg viewBox="0 0 300 100" preserveAspectRatio="none">
            <path
                d="M 0 75 M 0 75  L 75 50 L 150 15 L 225 67 L 300 67 L 300 67"
                stroke-width="3"
                stroke="red"
                fill="transparent"
                vector-effect="non-scaling-stroke"
            ></path>
            <path
                d="M 0 92 M 0 92  L 75 72 L 150 80 L 225 50 L 300 50 L 300 50"
                stroke-width="3"
                stroke="blue"
                fill="transparent"
            ></path>
        </svg>
        <svg overflow="visible">
    {/*Y Axis*/}
            <text x="0%" text-anchor="end" y="0%">
                40
            </text>
            <text x="0%" text-anchor="end" y="25%">
                30
            </text>
            <text x="0%" text-anchor="end" y="50%">
                20
            </text>
            <text x="0%" text-anchor="end" y="75%">
                10
            </text>
            <text x="0%" text-anchor="end" y="100%">
                0
            </text>
    {/*X Axis*/}
            <g style="transform: translateX(0%);">
                <text y="100%" dy="16px">
                    5
                </text>
            </g>
            <g style="transform: translateX(25%);">
                <text y="100%" dy="16px">
                    10
                </text>
            </g>
            <g style="transform: translateX(50%); ">
                <text y="100%" dy="16px">
                    15
                </text>
            </g>
            <g style="transform: translateX(75%); ">
                <text y="100%" dy="16px">
                    20
                </text>
            </g>
            <g text-anchor="end" style="transform: translateX(100%);">
                <text y="100%" dy="16px">
                    25
                </text>
            </g>
        </svg>
    </svg>

Is there a way for the padding area with the axis and legend to be captured in the output png together with the graph?
Thank you.

Animation slide in multi item carousel with youtube videos Bootstrap 5 and Angular

I need to make a multi item carousel with youtube videos, I found one example and made it work for me using bootstrap 5 carousel and cards, but the animation when de carousel slides is not fluid, the problem is the cards overlaps when the carousel slide, I tried to change the values on transform: translateX(%) but the animation is not that fluid, any advice on this?

This is the carosuel code, this displays 3 cards with the videos and the tittle in the bottom, as you can see I’m using iframe to call the youTube videos

<!--Carrusel videos-->
      <div class="col-lg-12 ms-2 mt-5">
        <div class="mx-auto my-auto justify-content-center">
          <div id="recipeCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner" role="listbox">
                <div class="carousel-item active">
                    <div class="col-md-4 me-2">
                      <div class="card">
                        <iframe src="https://www.youtube.com/embed/rf8vM_X1g9U" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      </div>
                      <div id="cardHeight" class="d-flex align-items-center text-center justify-content-center">
                        <p class="fs-5 fw-bold">Experiencia John Deere, Expo Agroalimentaria 2021</p>
                      </div> 
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-4 me-2">
                      <div class="card">
                        <iframe src="https://www.youtube.com/embed/3xq7z7WBOGU" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      </div>
                      <div id="cardHeight" class="d-flex text-center align-items-center justify-content-center">
                        <p  class="fs-5 fw-bold">Cosecha en la mira, Ensiladora 8300i</p>
                      </div> 
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-4 me-2">
                      <div class="card">
                        <iframe src="https://www.youtube.com/embed/9PBeqHEopLs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      </div>
                      <div id="cardHeight" class="d-flex align-items-center text-center justify-content-center">
                        <p class="p-2 mb-2 fs-5 fw-bold">Cosecha en la mira, CH570</p>
                      </div> 
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-4 me-2">
                      <div class="card">
                        <iframe src="https://www.youtube.com/embed/1jeHyrRskdk" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      </div>
                      <div id="cardHeight" class="d-flex align-items-center text-center justify-content-center">
                        <p class="p-2 mb-2 fs-5 fw-bold">"EL INGE" Arandas, Jalisco</p>
                      </div>  
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-4 me-2">
                      <div class="card">
                        <iframe src="https://www.youtube.com/embed/KauOtgNuzQQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                      </div>
                      <div id="cardHeight" class="d-flex align-items-center text-center justify-content-center">
                        <p class="p-2 mb-2 fs-5 fw-bold">"EL INGE" Ayotlán, Jalisco</p>
                      </div>  
                    </div>
                </div>
            </div>
            <a class="carousel-control-prev bg-transparent w-aut" href="#recipeCarousel" role="button" data-bs-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            </a>
            <a class="carousel-control-next bg-transparent w-aut" href="#recipeCarousel" role="button" data-bs-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
            </a>
          </div>
        </div>
      </div>
      <!--Carrusel videos-->

This is the CSS where i have the transform: translateX()%

#cardHeight {
  height: 80px;
}

@media only screen and (min-width: 768px) {
  iframe{
    height: 24em;
  }
  .card{
    width: 100%;
  }
}

@media (max-width: 767px) {
  .carousel-inner .carousel-item > div {
      display: none;
  }
  .carousel-inner .carousel-item > div:first-child {
      display: block;
  }
}

.carousel-inner .carousel-item.active,
.carousel-inner .carousel-item-next,
.carousel-inner .carousel-item-prev {
  display: flex;
}

/* medium and up screens */
@media (min-width: 768px) {
  
  .carousel-inner .carousel-item-end.active,
  .carousel-inner .carousel-item-next {
    transform: translateX(33%);
  }
  
  .carousel-inner .carousel-item-start.active, 
  .carousel-inner .carousel-item-prev {
    transform: translateX(-33%);
  }
}

.carousel-inner .carousel-item-end,
.carousel-inner .carousel-item-start { 
transform: translateX(0);
}

An finally the JS for the carousel

  let items = document.querySelectorAll('.carousel .carousel-item')

  items.forEach((el) => {
    const minPerSlide = 3
    let next = el.nextElementSibling
    for (var i=1; i<minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})

I’ll leave an image of my project to show you how this carousel is displayed in my project
carousel-image

Catching async errors with context referenced to originating sync function

In the code below the error is never caught:

const fn = () => {
  try {
    setTimeout(() => { throw new Error('An exception is raised') }, 10)
  } catch (error) {
    console.error({ error })
  }
}
fn()

The following is a solution:

const fn2 = () => {
  const errorFn = (error) => console.error({ error })
  setTimeout(() => {
    try {
      throw new Error('An exception is raised')
    } catch (e) { errorFn(e) }
  }, 10)
}
fn2()

The downside to this solutions is that it has to be implement in the function within setTimeout. That’s fine if one controls the code, but if users are supplying the code and calling setTimeout and don’t implement appropriate error handling, it could bring down one’s server!

Another solution is process.on('uncaughtException,... but that loses the context of the originating sync call that initiated the async function. Unless there is some clever way to supply that context?

Are there any other ways to catch async errors with context to the originating sync code?

Could one set a default error handler for a particular async branch – that’s catches all unhandled errors that may occur in that async branch?

Having trouble with java script

I’m starting to learn how to make a website using HTML,css, and js. When I try to open my html file on google chrome to see if my js function is working it says “Uncaught ReferenceError”. I than went to sources and realized that my javascript file isn’t there. I’m not sure what I am doing wrong and why my js file isn’t in sources.

Thank you for the help!

How to make a message appear once email is submitted using React and CSS

I am using React and have built an email form. I currently have this class: <div className="msg">Message has been sent</div> but only want it to appear when the message has successfully sent. So only when the following resolves as status: true. How can I target this using only React/CSS?

  .post('/api/email', values)
  .then((res) => {
    console.log("Server responded")
    setValues({
      name: "",
      email: "",
      message: "",
      status: true
    })
    .catch(err => {
      console.log(err);
      window.alert("Email not sent")
    });```


Order or sort multiple arrays by indexs of matched strings in another array using lodash or JS

I am trying to have my arrays sorted by the indexes of strings in another array.

I am getting back the following:

const matchtoThisArray:

['11006', '10240', '10142', '10309', '10367', '10724', '10741', '10362', '10919', '11115', '10590', '10179', '18510', '10051']

if there is a match in one of my arrays, the output will be in that position.

My default output starts with this below, which is at index 0. My desired output is that it would at the end since “10051” is at the end in the “matchThisArray”

     0: Array(36)
        0: {TMSId: 'EP009285440323', rootId: '21253358', time: '17:00', dur: 'PT00H30M', prgSvcId: '10051', …}
        1: {TMSId: 'EP035579760050', rootId: '21253391', time: '17:30', dur: 'PT00H30M', prgSvcId: '10051', …}
        2: {TMSId: 'EP033168400060', rootId: '21166708', time: '18:00', dur: 'PT01H00M', prgSvcId: '10051', …}

1: Array(24)
0: {TMSId: 'EP014781492754', rootId: '21041927', time: '16:00', dur: 'PT01H00M', prgSvcId: '10142', …}
1: {TMSId: 'EP006062994294', rootId: '21041931', time: '17:00', dur: 'PT01H00M', prgSvcId: '10142', …}
2: {TMSId: 'EP041682710002', rootId: '21418098', time: '18:00', dur: 'PT01H00M', prgSvcId: '10142', …}

Filtering method that does not work:

const criteria = ['11006', '10240', '10142', '10309', '10367', '10724', '10741', '10362', '10919', '11115', '10590', '10179', '18510', '10051']
      
    const filterPrgs = resultSchedules.map((rows) => {
            return rows.map((column) => {
              return column;
            });
          });
          const filtered = filterPrgs.filter((obj) => {
           return criteria.indexOf(obj.prgSvcId) >= 0;
          });

Got a somewhat original task concerning a nickname generator function

Luckily this is a purely JS task and I also have a full instruction for it, which kinda simplifies solving it. I imagined how I can create something that is needed, but even after searching everywhere I couldn’t figure it out. This “odd” one made me write a question to our friendly programmer team!

I would be grateful if you can write a working code for the task below and it surely could be an achievement. You know that otherwise it may throw some unexpected errors. I include it in details to get rid of any uncertainty :

Write a function, nicknameGenerator that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.

If the 3rd letter is a consonant, return the first 3 letters.

nickname("Robert") //=> "Rob"
nickname("Kimberly") //=> "Kim"
nickname("Samantha") //=> "Sam"

If the 3rd letter is a vowel, return the first 4 letters.

nickname("Jeannie") //=> "Jean"
nickname("Douglas") //=> "Doug"
nickname("Gregory") //=> "Greg"

If the string is less than 4 characters, return “Error: Name too short”.

Notes:

Vowels are “aeiou”, so discount the letter “y”.
Input will always be a string.
Input will always have the first letter capitalised and the rest lowercase (e.g. Sam).
The input can be modified

Create an object from function inputs using ES6 destructuring

I’m trying to learn destructuring to create an object from function inputs. I’d do it like this normally:

  const createContact = (name, email, phone) => {
    const newContact = {
      name: name,
      email: email,
      phone: phone
    };
    console.log(newContact);
  };

  createContact("virge", "[email protected]", "1234555555");

But when I try to assign these values using destructuring I get an error “Identifier ‘name’ has already been declared.”

  const createContact = (name, email, phone) => {
    const { name, email, phone } = newContact;
    console.log(newContact);
  };

  createContact("virge", "[email protected]", "1234555555");

How can I fix this?

Check if class type extends another class? [duplicate]

I’m having a hard time to express my problem, take this following code for exemple.

class Foo {}

class Bar extends Foo {}

const myFct = (bar: typeof Bar) => {
    if(bar instanceof Foo) { 
        // I want to check if Bar extends Foo 
        // bar is not an instance so instanceof won't do it
    }

}

How I can check the class Bar extends Foo from a typeof ?