Why do I get undefined when trying to get a dynamically added data attribute?

I’m trying to get the value for data-tab-id based on the class .tab-btn.active | however, the result keeps returning undefined.

This is where I add the data attribute

$navigation.find(".tab-btn").each(function(i, ele) {
        $(ele).attr("data-tab-id", i);
    });

This is where I retrieve it

var autoSwitch = setInterval(function() {

    //Get maximum # of tabs
    maxTabs = $(".tab-btn").length;
                        
    //Get the currently active button
    pastActiveBtn = $(".tab-btn").find(".active");
    pastId = pastActiveBtn.data('tabId'); //I have also tried tab-id; also 'undefined'

    console.log(pastId); //OUTPUT = undefined

});

If anyone knows why I am getting this, I’d appreciate it.

How can I use REGEXEXTRACT to return the text after the nth instance of a word in Google Sheets?

I’m rather new to regex and I need some advice for how to tackle a particular problem. Apologies for any breaches in etiquette/terminology, I have only very basic knowledge of coding.

Let’s say I have the following string in Cell A1 of spreadsheet “Test”:

Activity: Simon Says

Handout: Wordsearch

Activity: Musical Chairs

Handout: Crossword

Activity: Four Corners

Handout: Color by Number

I can use the following formula to return the first activity, “Simon Says” in another cell:
=REGEXREPLACE(REGEXEXTRACT(Test!A1, ("Activity:(.+)")),"d* - ","")

My question is, what regex can I use to return the second activity, which is to say, “Musical Chairs”? And the third?

Thank you to any who answer.

How to implement efficient data pagination in a web application?

I’m developing a web application that displays a large amount of data on a single page. To improve user experience and performance efficiency, I’m looking to implement data pagination. What are the best practices for efficiently implementing data pagination in a web application? I’m interested in methods both on the client-side and server-side, as well as performance and scalability considerations. I appreciate any advice or recommendations you can offer. Thank you!

DIV in flexbox adds unknown space below if it has no text inside

I have two identical div structures, left and right. Both has two rows with x number of divs inside each row.

Both has display=flex for parent div (class box) and display=inline-flex for inner div (class rowa).

There is only one difference, left structure doesn’t have any content inside div in first row which seems to be adding space below that div even though they all have fixed size. See picture below with arrow point to extra space.

enter image description here

If I add text inside first div on left, space goes away and div works as expected.

enter image description here

here’s link to code : https://stackblitz.com/edit/angular-html2canvas-uk7uzt?file=src%2Fapp%2Fapp.component.html

If someone can explain the issue that would be really appreciated.

Thanks

How to capture the coordinates of a click with JavaScript?

I am working on a web project and I need to capture the coordinates (x,y) at which a click is made on the page. I am using JavaScript and would like to know if there is a way to achieve this easily.

I’ve tried searching the JavaScript event documentation, but haven’t found a clear solution. Could anyone guide me on how to do it?

Firebase custom token in NodeJS (fastify framework)

I would like to create a custom token from my fastify server.

Now, I am reading the following, exceptionally poor, guide:
https://firebase.google.com/docs/auth/admin/create-custom-tokens

They have this (incomplete in my opinion) example:

const uid = 'some-uid';

getAuth()
  .createCustomToken(uid)
  .then((customToken) => {
    // Send token back to client
  })
  .catch((error) => {
    console.log('Error creating custom token:', error);
  });

The first thing I do not understand is where the method getAuth() comes from. There is zero explanation in the official documentation.
My guess would be that it comes from the firebase-admin. However I do not understand how to use it.

The second non-sense thing, related to the above is when I created a project in firebase console I got the following:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "api_key",
  authDomain: "xyz",
  projectId: "xyz",
  storageBucket: "xyz",
  messagingSenderId: "000",
  appId: "0xyz",
  measurementId: "xyz0"
};

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

However I do not understand how to use it in the firebase-admin.

Even if I do the following:

const admin = require('firebase-admin');
admin.initializeApp(firebaseConfig);

I get the message:

errorInfo: {
code: ‘auth/invalid-credential’,
message: ‘Failed to determine service account. Make sure to initialize the SDK with a service account credential. Alternatively
specify a service account with iam.serviceAccounts.signBlob
permission. Original error: Error: Error while making request:
getaddrinfo ENOTFOUND metadata. Error code: ENOTFOUND’ },
codePrefix: ‘auth’

Any help would be much appreciated as I have wasted a lot of time due to the incompleteness of the firebase documentation.

How to center a please help me?

How to center a

I want my to be centered. please help me I am writing more here because apparently I don’t have 200 characters ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

Spotify API Throwing Errors

I’m doing Codecademy’s Jammming project and it has been way above the level of what we’ve been taught so far. What I could use some input on is the error’s I’m getting when trying to save the name of the playlist I’m trying to create. I will include the Spotify API call and the App.js function that are both providing me errors.

// Spotify API Call

import React from 'react';

let userAccessToken = '';

const clientID = '**redacted**';
const redirectURI = `http://localhost:3000/`;

const Spotify = {
  getAccessToken() {
    // First check
    if (userAccessToken) return userAccessToken;

    const token = window.location.href.match(/access_token=([^&]*)/);
    const expiry = window.location.href.match(/expires_in=([^&]*)/);

    // Second check for the access token
    if (token && expiry) {
      // Setting values for token and expiration time
      const userAccessToken = token[1];
      const expiresIn = Number(expiry[1]);

      // Setting the access token to expire at the value for expiration time
      window.setTimeout(() => (userAccessToken = ''), expiresIn * 1000);
      window.history.pushState('Access token', null, '/');

      // Returning the access token
      return userAccessToken;
    }

    //Redirect
    const redirect = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
    window.location = redirect;
  },

  // Search method
  search(term) {
    const accessToken = Spotify.getAccessToken();
    return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
      headers: { Authorization: `Bearer ${accessToken}` },
    })
      .then((response) => response.json())
      .then((jsonResponse) => {
        if (!jsonResponse) {
          console.error('Response error!');
        }
        return jsonResponse.tracks.items.map((t) => ({
          id: t.id,
          name: t.name,
          artist: t.artists[0].name,
          album: t.album.name,
          uri: t.uri,
        }));
      }); // Second .then() statement
  }, // getAccessToken function

  savePlaylist(name, trackUris) {
    if (!name || !trackUris) {
      throw new Error('Please provide a name');
    } else {
      const aToken = Spotify.getAccessToken();
      const header = { Authorization: `Bearer ${aToken}` };
      let userId;
      return fetch('https://api.spotify.com/v1/me', { headers: header })
        .then((response) => response.json())
        .then((jsonResponse) => {
          userId = jsonResponse.id;
          let playlistId;
          return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
            headers: header,
            method: 'post',
            body: jsonResponse.stringify({ name: name }),
          })
            .then((response) => response.json())
            .then((jsonResponse) => {
              playlistId = jsonResponse.id;
              return fetch(
                `https://api.spotify.com/v1/playlists/${playlistId}/tracks`,
                {
                  headers: header,
                  method: 'post',
                  body: JSON.stringify({ uris: trackUris }),
                },
              );
            });
        });
    }
  },
}; // Spotify Initializer

export { Spotify };
// App.js Function

function savePlaylist(trackUris) {
  const TrackURIs = playlistTracks?.map((track) => track.uri);
  return Spotify.savePlaylist(playlistName, TrackURIs)
    .then(() => {
      setPlaylistName('New Playlist');
      setPlaylistTracks([]);
    })
    .catch((error) => {
      alert(error);
    });
}

I’ve tried throwing and catching an error, I’ve ran it with breakpoints, I’ve refactored the if/else statement

Why am i having wrong order of execution in my async code

I am having an error where my asynchronous code is running in the wrong order.

So as it seems the balance should run last but currently its running as soon as the TradingAlgorithm functions is called. The correct order should be for the change of position mode to happen and then to get the balance. I checked in higher parent functions if i had missed any async but it seemed that i had not.

// Imports
const ChangePositionMode = require("./OtherFunctions/ChangePositionMode");
const GetBalance = require("./SharedFunctions/GetBalance");

// Constants
const MINIMUM_USDT_BALANCE = 10;

// Trading Algorithm
const TradingAlgorithm = async (session) => {
  // Assign Values
  const id = session.id;
  const apiKey = session.api_key;
  const apiSecret = session.api_secret;
  const encryptedApiKey = session.encrypted_api_key;
  const encryptedApiSecret = session.encrypted_api_secret;
  const email = session.email;
  const fullIPs = session.full_ips;
  const isNew = session.is_new;
  const startBalance = session.start_balance;

  // Change Position Mode
  const changePositionModeResult = await ChangePositionMode(
    apiKey,
    apiSecret,
    fullIPs
  );

  // Validate Change Position Mode
  if (changePositionModeResult === false) {
    console.log("Position Mode Change Failed");
    return;
  }

  // Get Balance
  const balance = await GetBalance(apiKey, apiSecret, fullIPs);

  // Validate Balance
  if (balance === null || balance === undefined) {
    console.log("Balance Not Found");
    return;
  } else if (balance < MINIMUM_USDT_BALANCE) {
    console.log("Insufficient Balance");
    return;
  }
};

// Export
module.exports = TradingAlgorithm;

Logs:

Balance Not Found
Position Mode Already Set
Balance Details

Add input file field to FormlyFieldConfig

I’m building a form in my project and I have to add an image selection field, that is, an input field of type file. I searched a few places on the internet and couldn’t find my solution. Has anyone faced the same problem as me helping me?

I’m going to make my form’s config available here, but the part I want to add I put a very visible comment in the body.

One thing I left out is that the following error appears in the browser console:

ERROR Error: [Formly Error] The type "file" could not be found. Please make sure that it is registered through the FormlyModule declaration.

I would really like to thank anyone who can help me with this problem❤

OBS: Im using ng-matero template

`fields: FormlyFieldConfig[] = [

{

  fieldGroupClassName: 'row',

  fieldGroup: [

    {

      className: 'col-sm-6',

      type: 'input',

      key: 'name',

      templateOptions: {

        label: 'Nome',

        required: true,

      },

    },

    {

      className: 'col-sm-6',

      type: 'input',

      key: 'instagramURL',

      templateOptions: {

        label: 'URL do instagram',

        required: false,

      }

    },

  ],

},

{

  fieldGroupClassName: 'row',

  fieldGroup: [

    {

      className: 'col-sm-4',

      type: 'combobox',

      key: 'animalAge',

      templateOptions: {

        label: 'Idade',

        options: [

          { id: 0, name: 'BELOW_TWO_MONTHS', label: 'Menos que dois meses' },

          { id: 1, name: 'TWO_TO_SIX_MONTHS', label: 'De dois a seis meses' },

          { id: 2, name: 'SEVEN_TO_ELEVEN_MONTHS', label: 'De sete a onze meses' },

          { id: 3, name: 'ONE_YEARS', label: 'Um ano' },

          { id: 4, name: 'TWO_YEARS', label: 'Dois anos' },

          { id: 5, name: 'THREE_YEARS', label: 'Três anos' },

          { id: 6, name: 'FOUR_YEARS', label: 'Quatro anos' },

          { id: 7, name: 'FIVE_YEARS', label: 'Cinco anos' },

          { id: 8, name: 'MORE_SIX_YEARS', label: 'Mais de seis anos' },

        ],

        labelProp: 'label',

        valueProp: 'name',

        required: true,

      },

    },

    {

      className: 'col-sm-4',

      type: 'combobox',

      key: 'animalType',

      templateOptions: {

        label: 'Tipo',

        options: [

          { id: 0, name: 'DOG', label: 'Cachorro' },

          { id: 1, name: 'CAT', label: 'Gato' },

        ],



        labelProp: 'label',

        valueProp: 'name',

        required: true,

      },

    },

    {

      className: 'col-sm-4',

      type: 'combobox',

      key: 'size',

      templateOptions: {

        label: 'Tamanho',

        options: [

          { id: 0, name: 'SMALL', label: 'Pequeno' },

          { id: 1, name: 'AVERAGE', label: 'Médio' },

          { id: 2, name: 'BIG', label: 'Grande' },

        ],

        labelProp: 'label',

        valueProp: 'name',

        required: true,

      },

    },

  ],

},

{

  type: 'textarea',

  key: 'description',

  templateOptions: {

    label: 'Descrição',

    rows: 5

  },

},

{

//THIS IS THE FIELD I WANT TO ADD************************************************************************

  type: 'file',

  key: 'image',

  templateOptions: {

    label: 'Imagem do animal',

    accept: 'image/*',

    required: true,

  },

},

{

  fieldGroupClassName: 'row',

  fieldGroup: [

    {

      className: 'col-sm-6',

      type: 'input',

      key: 'race',

      templateOptions: {

        label: 'Raça',

        required: true,

      },

    },

    {

      className: 'col-sm-6',

      type: 'input',

      key: 'priority',

      templateOptions: {

        type: 'number',

        label: 'Prioridade',

        max: 10,

        min: 0,

        pattern: '\d{5}',

      },

    },

  ],

},

];`

I wanna add this field in my form at my project

How to Utilize Intel AMX or DSA Instructions in JavaScript or WebAssembly for High-Performance Computing Tasks?

Background:

I am working on a high-performance computing project that requires intensive matrix computations and data streaming operations. Given the potential performance benefits, I am interested in leveraging Intel’s Advanced Matrix Extensions (AMX) and Data Streaming Accelerator (DSA) instructions. My application is developed with a web-based interface, and the core computational work is implemented in JavaScript and WebAssembly. I aim to enhance my application’s performance by directly utilizing these hardware acceleration features.

Objective:

My goal is to understand how I can directly call or otherwise utilize Intel AMX and DSA instructions within my JavaScript code or from within a WebAssembly module. Specifically, I’m looking for ways to integrate these instructions to accelerate matrix multiplication operations and optimize data streaming processes in my web application.

What I Have Tried:

  1. Research on existing JavaScript APIs or WebAssembly extensions that may support direct interaction with hardware acceleration features, but found limited resources.
  2. Exploration of Emscripten and WebAssembly System Interface (WASI) documentation for any hints on accessing CPU-specific instructions or features, without success.
  3. Preliminary experiments with WebAssembly modules written in C/C++, attempting to inline assembly with AMX and DSA instructions, but facing challenges in integration and performance measurement.

Challenges:

  • Lack of clear documentation or examples on integrating Intel-specific instructions like AMX or DSA within a web application context.
  • Uncertainty about the feasibility of accessing such low-level hardware features from high-level languages like JavaScript or through WebAssembly.
  • Difficulty in measuring the performance impact or verifying the correct use of these instructions in a web environment.

Questions:

  1. Has anyone successfully integrated Intel AMX or DSA instructions in a web application using JavaScript or WebAssembly? If so, could you share your approach and any sample code?
  2. Are there specific tools, libraries, or methodologies recommended for accessing and utilizing these CPU instructions effectively in a web context?
  3. What are the best practices for ensuring compatibility and maximizing performance when attempting to leverage such hardware-specific features in web applications?

Additional Context:

  • I am specifically targeting modern Intel processors equipped with AMX and DSA capabilities.
  • My web application is computationally intensive and would greatly benefit from any performance optimizations these technologies can offer.
  • I understand the challenges of working at such a low level in a web environment but am hopeful there are solutions or workarounds.

Spoonacular Api login/signup page not working properly

So for a test project I’m trying to make an account on spoonacular Api website. Now, I’ve made an account on just the normal side of spoonacular but when I try to login or make an account or anything on spoonacular it doesn’t work. Either I get “Request Failed with a 404” or some other error message.

I’ve searched the internet and found nothing.

Sorting products on the site using the tag in React

Good afternoon, I’m new to React and I’m just starting to understand the basics. Now I’m making a clothing store website for training, imitating an existing site “spbtusa.ru”
At the moment, I have a problem with sorting products on the main page. According to the idea, when choosing the sorting type, the user acts on the onChange tag . With this action, the software changes State, adding the sorting function to it. When changing the State, the list of products displayed on the page should be re-rendered.

The tag and the called state change function is setCurrentSorting, which I passed as props from the parent component
Passing setCurrentSorting to the child component
The parent component linking the list of products and the for sorting selection
A child component displaying a list of products. The *loopWithSlice *function decides how many products I need to display first from the list.

The problem is that I need to call the loopWithSlice function once during the first render (as I understood using the useEffect hook), and every time the state of the parent (sort type) changes, the sortProductList should change and the ProductSection component should be re-rendered. However, the code either goes into an endless loop or does not re-render anything..

I will be glad if you, as more experienced, can tell me what I’m doing wrong and why it doesn’t work. I repeat, I’m a beginner and I haven’t figured out much else. Thank you in advance.

How to print the exact time on the screen when clicking a button with JavaScript?

I am working on a web project where I need to print the exact time on screen when a user clicks a specific button. I’m using JavaScript to handle the client side logic, but I’m not sure how to get the current time and display it in the UI at click time.

I have tried a few solutions using Date() to get the current time, but I have not been able to find a way to display it on the screen when the user clicks the button.

Could anyone offer me some guidance or code examples on how to achieve this? I appreciate any help you can give me. Thank you!

JavaScript not reading HTML input value

On my main website, website.com, I have a functioning JS function that takes an input value from my HTML form – a response to a yes-or-no question. It then processes this input value through a switch statement. I wanted to emulate that functionality on my subdomain for mobile browsers, m.website.com. However, the exact same JS code, reading from the same HTML code, returns an undefined value for my x.

Can anyone see why it will not read the value correctly? Note that I know the function is being triggered correctly, as I get my default alert as soon as I select any value.

HTML:

<div>
     <label for="rsvp">Will you be joining us?<br></label>
     <select id="rsvp" name="rsvp" onchange="didTheySayYes()" required> <!-- Function didTheySayYes() triggers follow-up questions as needed -->
     <option value="null"></option>
     <option value="1">Yes, I/we will be there!</option>
     <option value="0">Sorry, I/we can't make it...</option>
     </select>
</div>

JS:

function didTheySayYes() {
    let x = document.getElementById('rsvp').value;               //Extract answer value
    if (x == 'null') {                                           //Don't respond to empty option
        return
    }
    alert(x);
    switch (Number(x)) {
    case 0:                                                       //Response to 'not joining'
        let name1 = document.createElement('div');
        name1.id = 'rsvp_no';
        name1.className = 'RSVPyesorno';
        document.getElementById('rsvp').insertAdjacentElement('afterend', name1);
        name1.innerHTML = `We're sorry you won't be there!<br><label for="name1">Name:<br></label>
        <input type="text" id="name1" name="name1" required>`;
        break;
    case 1:                                                        //Response to 'will join'
        let some = document.createElement('div');
        some.className = 'RSVPyesorno';
        document.getElementById('rsvp').insertAdjacentElement('afterend', some);
        some.innerHTML =`<br><label for="groupsize">With how many people?<br></label>
                        <select id="groupsize" name="groupsize" onchange="RSVPsize()" required>
                            <option value="null"></option>
                            <option value="gs1">1</option>
                            <option value="gs2">2</option>
                            <option value="gs3">3</option>
                            <option value="gs4">4 or more</option>
                        </select>`;                        
        break;
    default:
        alert("Error! Please refresh the page and try again, and if you keep having issues, contact the organizer.");
        break;
    }
}