Likelyhood of blocking when using chaining vs consecutive async/await with cpu intensive tasks

I would like to know whether there is a higher likelyhood of blocking the main thread if using chaining vs using consecutive async/await when the async functions contain cpu-intensive work.

I believe that chaining would be more likely to cause blocking based on my understanding of microtask queueing of promise callbacks.

Let’s take for example the following two functions.

async mainFunction1() {
   await asyncFunction1().then(() => asyncFunction2()).then(() => asyncFunction3());
}

async mainFunction2() {
   await asyncFunction1();
   await asyncFunction2();
   await asyncFunction3();
}

As I understand it, in mainFunction1 all callbacks would be pushed to the microtask queue once asyncFunction1 was resolved. Then when the event loop starts, all callbacks would be pushed to the call stack at the same time from the microtask queue and all callbacks would have to be executed before any subsequent functions could run on the main thread.

Whereas, in mainFunction2, after asyncFunction1 resolves the remainder of mainFunction2 is pushed to the microtask queue. Then, when the event loop starts, the remainder of mainFunction2 gets pushed back to the call stack. The following async function resolves and once again the remainder of mainFunction2 gets queued in the microtask queue. This would carry on until there were no more internal async functions left to execute in mainFunction2.

Leaflet JS widget in Filament won’t execute

For a non-profit I’m creating a Filament admin panel with a widget running a Leaflet.js map.

I’ve set this up according to the Filemant docs

All goes well, the data gets passed to the JS. But leaflet doesn’t create the map. It seems that the L.map() command can’t find the DIV I’m referrencing.

i’ve tried hardcoding it as const map = L.map(‘map’), L.map(document.getElementById(‘map’)); L.map(this.$refs.leafletMap), L.map(this.$refs.leafletMap.id), … none does the tric

Any help is hugely appreciated 🙂

AdminPanelProvider.php

class AdminPanelProvider extends PanelProvider
{
    public function boot()
    {
        FilamentAsset::register([
            Css::make('leaflet-1-9-4-css', 'https://unpkg.com/[email protected]/dist/leaflet.css'),
            Js::make('leaflet-1-9-4-js', 'https://unpkg.com/[email protected]/dist/leaflet.js'),
            AlpineComponent::make('visitor-heatmap-js', __DIR__ . '/../../../resources/js/leaflet-heatmap.js'),         
        ]);
    }
    
   ..
}

visitor-heatmap-widget.blade

<x-filament-widgets::widget>
    <x-filament::section>
    HEATMAP
        
        
        <div
            x-ignore
            ax-load
            ax-load-src="{{ FilamentSupportFacadesFilamentAsset::getAlpineComponentSrc('visitor-heatmap-js') }}"
            x-data="leafletVisitorsHeatmap({
                cities: @js($data)
            })"
        >
            
                <div x-ref="leafletMap" id="map" style="width: 100%; height: 100%">

                </div>
            
        </div>
    </x-filament::section>
</x-filament-widgets::widget>

leaflet-heatmap.js (stripped to the bare minimum)

export default function leafletVisitorsHeatmap({ cities }) 
{
    return {
 
        init: function () {
            console.log('start leafletVisitorsHeatmap');
            //console.log('cities:');
            //console.log(cities);
                    
            const map = L.map(this.$refs.leafletMap.id).setView([51.505, -0.09], 13);

            const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
            }).addTo(map);
            
            
        },
        
    }
}

How can I override the behavior of valueOf() as a prototype of the Number in JavaScript?

I am getting an error when I trying to override this:

Number.prototype.toString = function () {
  return "This is the number: " + this
};

Number.prototype.valueOf = function () {
  //console.log(this)
  return this;
}

console.log(new Number(33).toString());
console.log(new Number(34).valueOf())

Js returns an error RangeError: Maximum call stack size exceeded, how can I override value of to return, for example, string – ‘The number is ${this}’

I have tried to console.log this and got such output:
Code output

outbound link within an iframe not opening

The iframe is rendered from a html file which contains basic text and some outbound links. The links within the iframe when attempting to open will currently open within the iframe.

Ive tried adding target="_blank" or target="_top", but then when you click it nothing happens, this is the same which each target="..." that ive seen on stackoverflow or other sites that say might fix the problem. Ive tried others ways through javascript including event listeners on the link which then window.open(url, _blank) ect. Ive tried changing the sandbox settings for allow-popups allow-popups-to-escape-sandbox and researching about sandboxing but this has not fixed the problem.

The iframe first code is:
<gwd-iframe id="gwd-iframe_1" source="" class="gwd-iframe-op97"></gwd-iframe>

I have some javascript which uses srcdoc to replace the inner of the iframe so it doesnt need an external .html file to populate it and the html can be held in a variable:

function iframeSrc() {
  const iframe = document.getElementById('gwd-iframe_1');
  iframe.srcdoc = iframeInner;
}

Code inside iframe: (link is to stackoverflow for this use case)

<div style="color: black; font-size: 11px; font-family: Oswald, sans-serif; overflow-x: hidden; word-wrap: break-word; line-height: 1.4;">
  <p style="margin-top: 0 !important"> <span style="color: #8e5295"><strong>Exercitation incididunt tempor.</strong></span><br> <strong>Dolore minim cupidatat.</strong> <br> </p>
  <p><strong>lorem</strong><br> ipsum<span>&#174;</span> Fugiat occaecat consequat labore anim incididunt irure adipisicing labore dolore veniam consequat occaecat nulla.<br> <span>&#8226;</span> Elit dolor veniam sed culpa quis est do dolore velit minim nulla.<br> <span>&#8226;</span> Anim ut in irure id cupidatat quis cupidatat eiusmod ex irure reprehenderit elit in ad.<sup>2</sup> </p>
  <p><strong>References</strong> Veniam amet. <a href="https://stackoverflow.com/">https://stackoverflow.com/</a></p>
</div>

Confusing behavior: Connection.query return empty. Unless another connection is got from the pool and released immediately

below Ive pasted a function that validates and approves a paypal order. Ive been trying to fix an issue for a while now, where the first query just return an empty [] for no apparent reason. I think it might be an issue with race conditions, but I dont know.
The interesting thing is that the query DOES work when I quickly get a connection from the pool and instantly release it.
I´d love an explanation to why this might be happening…
TL;DR:
Query only work when getting and releasing a connection right before it.

async function validateAndApproveOrder(paypal_id, status, accessToken) {
    const sql = "SELECT total_price FROM Orders WHERE paypal_id = ?"
    const sqlTwo = "UPDATE Orders SET order_status = 'Processing' WHERE paypal_id = ?"
    const url = `${baseURL.sandbox}/v2/checkout/orders/${paypal_id}`;
  
    const response = await fetch(url, {
      method: "GET",
      headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${accessToken}`,
      }
    })
    const data = await response.json();
    const payment = data.purchase_units[0].amount.value;
    
    connection.getConnection((err, connect) => {
      connect.release();
    })
    if(data.status === "COMPLETED" && data.intent === "CAPTURE" && status === data.status) {
      return new Promise((resolve, reject) => {
        connection.getConnection((err, connection) => {
          if(err) {
            connection.release();
            reject("connection error while validating: " + err);
          }
          console.log("pid: ", paypal_id);
          connection.query(sql, [paypal_id], (err, results) => {
            if(err) {
              connection.release();
              reject("query error while validating: " + err);
            }
            console.log("results: " + JSON.stringify(results));
            let price;
            if(results.length > 0) {
              const unconverted = results[0].total_price;
              price = unconverted.toFixed(2);
            }

            if(payment === price) {
             connection.query(sqlTwo, [paypal_id], (err) => {
              if(err) {
                connection.release();
                reject("query error while validating: " + err);
              }
              connection.release();
              resolve("OK");
             }) 
            }
          })
        })
      })
    } else {
    console.error("Verification Error: " + data.status + " -- " + status + " -- " + data.intent)
      return;
    }
}

How to inject jQuery to a plugin within a ESM

My code is failing because a plugin is expecting a jQuery object, but I’m not sure how to pass it in.

I’m using modules (and importmap), but the javascript plugin isn’t a module.

In webpack, i set autoProvideJQuery to trun and I could do a require(). Now I’m not sure what to do.

My hackish attempts. Set up an importmap for jquery and the plugin, then

    <script type="module">
    import jQuery from 'jquery';
    window.jQuery = jQuery;

    import '@tetranz/select2entity-bundle'

</script>

I keep getting an undefined reference jQuery. Not too surprising, but I can’t figure out how to “inject” jQuery into the plugin.

BehaviorSubject/Subject Emits Values for Primitive and References for Non-Primitive – POC Results

Can somebody put some light on below, as it is not widely discussed topic over the internet. Will be helpful, if someone confirms it with further analysis.

I wonder to see that Subject and BS emits only references for non-Primitive data types within the subscription. So if multiple components are using an emitted object, those are accessing only single copy which is shared across components.

These are observations from my POC : https://stackblitz.com/edit/angular-12-starter-project-daidh-4x2jth?file=src%2Fapp%2Fstudent.service.ts

For quick look sharing the code screen shots below :

student.service.ts :

  studentSubject = new Subject<any>();
  counterSubject = new Subject<any>();
  emitValues() {
    //get student obj from db here
    let student = { rollNo: 1, name: 'student1', age: 20 };
    this.studentSubject.next(student);

    let counter = 1;
    this.counterSubject.next(counter);
  }

Above 2 subjects are subscribed in 3 components and the emitted values are bound with the textbox values.

For Student object (non-Primitive) : changes from any component to the emitted value, will reflect in the other components, though the object is not actually shared object through the service.

For Counter value (Primitive) : changes from any component to the emitted value, will not reflect to other components.

student1.component.ts:

  student: any = {};
  counter: any;
  ngOnInit() {
    this._studentService.studentSubject.subscribe((stud) => {
      this.student = stud;
      console.log(stud);
    });
    this._studentService.counterSubject.subscribe((counter) => {
      this.counter = counter;
    });
  }

student2.component.ts:

  student: any = {};
  counter: any;
  ngOnInit() {
    this._studentService.studentSubject.subscribe((stud) => {
      this.student = stud;
      console.log(stud);
    });
    this._studentService.counterSubject.subscribe((counter) => {
      this.counter = counter;
    });
  }

Playwright locators and CMS content

I am adding Playwright tests for a site with multiple locales. Page content is mainly rendered via CMS content (I’m using Contentful).

Using locators with hardcoded text, such as await page.getByLabel('Blog Article Foo').click(); seems very brittle, especially with multiple locales.

Should I just avoid using any text-based locators and just use await page.getByRole('heading').click();?

This doesn’t seem the “Playwright” way of testing, as I’m not testing what a user sees / interacts with, however the only alternative I can see is writing lots of very flakey tests for each locale and constantly update them.

Am I missing something?

How to redirect hyperlinks with a custom chrome extension

I am kind of a noob at chrome extensions. So far I have a chrome extension, which adds a context menu option that allows you to open a YouTube shorts video as a regular video.

Right clicking the short every time is quite cumbersome and I would like to find a way to redirect this to the regular video, i.e. replace “shorts/” with “watch?v=” when this hyperlink is clicked.

Cypress runner compresses the window when run on the CI pipeline

The tested page contains iframes. I was able to find required element and do assertions locally. But on the CI server I see that tested window is compressed
Also, was trying to run tests locally in headless mode – all good.
how it looks on the CI server

UI and headless mod works good on my local machine
Could be that this window compressed because of iframes or something?
Or how to make this window full sized again?

An Issue In TranslateY (React Native)

This is my code for React Native.

import React, { useState, useEffect, useRef } from 'react';
import { View, Image, StyleSheet, Animated, TouchableOpacity, Text } from 'react-native';
import Modal from 'react-native-modal';
import PickerSelect from 'react-native-picker-select';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  logo: {
    width: 200,
    height: 200,
    resizeMode: 'contain',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 30,
    borderRadius: 10,
    width: '80%',
  },
  chooseLanguageText: {
    marginBottom: 20,
  },
  picker: {
    width: '100%',
    marginBottom: 20,
    borderBottomWidth: 1,
    borderColor: 'gray',
    paddingVertical: 10,
  },
  nextButton: {
    backgroundColor: '#4CAF50',
    padding: 15,
    borderRadius: 5,
    alignItems: 'center',
    marginTop: 20,
  },
  nextButtonText: {
    color: 'white',
    fontSize: 16,
  },
  background: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'lightblue',
    opacity: 0,
  },
  buttonContainer: {
    marginVertical: 10,
    opacity: 0,
  },
  yellowButton: {
    backgroundColor: 'yellow',
    padding: 15,
    borderRadius: 10,
    marginVertical: 10,
  },
  grayButton: {
    backgroundColor: 'gray',
    padding: 15,
    borderRadius: 10,
    marginVertical: 10,
  },
  orangeButton: {
    backgroundColor: 'orange',
    padding: 15,
    borderRadius: 10,
    marginVertical: 10,
  },
  greenButton: {
    backgroundColor: 'green',
    width: 50,
    height: 50,
    borderRadius: 25,
    marginVertical: 10,
  },
  buttonText: {
    textAlign: 'center',
    color: 'black',
  },
  grayButtonContainer: {
    flexDirection: 'row',
  },
});

const handleButtonPress = (buttonName) => {
  console.log(`Button pressed: ${buttonName}`);
};

// ... (previous imports)

const DisplayLogo = () => {
  const translateY = useRef(new Animated.Value(0)).current;
  const opacity = useRef(new Animated.Value(0)).current;
  const buttonOpacity = useRef(new Animated.Value(0)).current;
  const backgroundOpacity = useRef(new Animated.Value(0)).current;
  const [isModalVisible, setModalVisible] = useState(false);
  const [selectedLanguage, setSelectedLanguage] = useState('');
  const [selectedRegion, setSelectedRegion] = useState('');
  const [step, setStep] = useState(1);

  const handleButtonPress = (buttonName) => {
    console.log(`Button pressed: ${buttonName}`);
  };

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  useEffect(() => {
    const imageAnimation = Animated.sequence([
      Animated.timing(translateY, {
        toValue: 0,
        duration: 500,
        useNativeDriver: true,
      }),
      Animated.delay(2000),
      Animated.timing(translateY, {
        toValue: -200,
        duration: 500,
        useNativeDriver: true,
      }),
      Animated.timing(opacity, {
        toValue: 0,
        duration: 500,
        useNativeDriver: true,
      }),
    ]);

    imageAnimation.start(() => {
      if (step === 1) {
        setModalVisible(true);
      }
    });

    return () => {
      translateY.setValue(0);
      opacity.setValue(0);
    };
  }, [translateY, opacity, step]);

  const handleNext = () => {
    if (step === 1) {
      setStep(2);
    } else if (step === 2) {
      console.log('Selected Language:', selectedLanguage || 'English');
      setModalVisible(false);
      Animated.parallel([
        Animated.timing(buttonOpacity, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }),
        Animated.timing(backgroundOpacity, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }),
      ]).start();
      console.log('Selected Region:', selectedRegion || 'North India');
    }
  };

  return (
    <View style={styles.container}>
      <Animated.Image
        style={{ ...styles.logo, transform: [{ translateY }], opacity }}
        source={require('./assets/Logo.png')}
      />

      <Modal
        isVisible={isModalVisible}
        animationIn="slideInUp"
        animationOut="slideOutDown"
        onBackdropPress={null}
        style={styles.modalContainer}
      >
        <View style={styles.modalContent}>
          {step === 1 && (
            <>
              <Text style={styles.chooseLanguageText}>Select Your Region:</Text>
              <PickerSelect
                style={styles.picker}
                value={selectedRegion}
                onValueChange={(value) => setSelectedRegion(value)}
                items={[
                  { label: 'North India', value: 'North India' },
                  { label: 'South India', value: 'South India' },
                ]}
                placeholder={{}}
                Icon={() => (
                  <View
                    style={{
                      backgroundColor: 'transparent',
                      borderTopWidth: 10,
                      borderTopColor: 'gray',
                      borderRightWidth: 10,
                      borderRightColor: 'transparent',
                      borderLeftWidth: 10,
                      borderLeftColor: 'transparent',
                      width: 0,
                      height: 0,
                      alignSelf: 'center',
                    }}
                  />
                )}
              />
            </>
          )}

          {step === 2 && (
            <>
              <Text style={styles.chooseLanguageText}>Choose Your Preferred Language:</Text>
              <PickerSelect
                style={styles.picker}
                value={selectedLanguage}
                onValueChange={(value) => setSelectedLanguage(value)}
                items={[
                  { label: 'English', value: 'English' },
                  { label: 'Hindi', value: 'Hindi' },
                  { label: 'Telugu', value: 'Telugu' },
                ]}
                placeholder={{}}
                Icon={() => (
                  <View
                    style={{
                      backgroundColor: 'transparent',
                      borderTopWidth: 10,
                      borderTopColor: 'gray',
                      borderRightWidth: 10,
                      borderRightColor: 'transparent',
                      borderLeftWidth: 10,
                      borderLeftColor: 'transparent',
                      width: 0,
                      height: 0,
                      alignSelf: 'center',
                    }}
                  />
                )}
              />
            </>
          )}

          <TouchableOpacity style={styles.nextButton} onPress={handleNext}>
            <Text style={styles.nextButtonText}>Next</Text>
          </TouchableOpacity>
        </View>
      </Modal>

      <Animated.View style={{ ...styles.background, opacity: backgroundOpacity }} />

      <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
        {/* Yellow buttons */}
        {[
          'Tips For Farming',
          'Weather Updates',
          'Buy Implements',
          'Sell Harvest',
          'Discuss On Forums',
          'Donate',
          // Add more yellow buttons as needed
        ].map((buttonName, index) => (
          <TouchableOpacity
            key={index}
            style={styles.yellowButton}
            onPress={() => handleButtonPress(buttonName)}
          >
            <Text style={styles.buttonText}>{buttonName}</Text>
          </TouchableOpacity>
        ))}
      </Animated.View>

      <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
        {/* Gray buttons */}
        <View style={styles.grayButtonContainer}>
          {['Help', 'Settings'].map((buttonName, index) => (
            <TouchableOpacity
              key={index}
              style={styles.grayButton}
              onPress={() => handleButtonPress(buttonName)}
            >
              <Text style={styles.buttonText}>{buttonName}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </Animated.View>

      <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
        {/* Orange button */}
        <TouchableOpacity
          style={styles.orangeButton}
          onPress={() => handleButtonPress('Return Feedback')}
        >
          <Text style={styles.buttonText}>Return Feedback</Text>
        </TouchableOpacity>
      </Animated.View>

      <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
        {/* Green button */}
        <TouchableOpacity
          style={styles.greenButton}
          onPress={() => handleButtonPress('Contact')}
        />
      </Animated.View>
    </View>
  );
};

export default DisplayLogo;

In my app, I want the logo to appear from bottom to the center, stay there for 2 seconds, go to the top, and then fade away. However, I am not getting the expected results. I tried changing the values but nothing happened. I got this code from ChatGPT but it has not been able to help me. I face problems with the logo, though there are some other bugs. I currently want to handle the logo more efficiently.

Invalid date on SQL with JavaScript

Error inserting data into table: RequestError: Validation failed for parameter ‘hourStart’. Invalid date.
enter image description here
the table is in a SQL database, it is locked for NULL values
the date is working, but the hour dont insert into database

I used chatGPT to try to find the error but I couldn’t resolve it, I believe it has something to do with the SQL language, as the language I’m programming in is Brazilian Portuguese, and the date and time format is different.

code:

`const dataInput = document.querySelector(‘.input[title=”data”]’)
const horaInicioInput = document.querySelector(‘.input[title=”horaInicio”]’);
const horaFimInput = document.querySelector(‘.input[title=”horaFim”]’);

// Formatação da data para o formato YYYY-MM-DD
const dataFormatada = dataValue.split(‘/’).reverse().join(‘-‘);

// Formatação das horas para o formato HH:MM:SS
const horaInicioFormatada = horaInicioValue + ‘:00’;
const horaFimFormatada = horaFimValue + ‘:00’;`

How to destructure nested object? [closed]

I’m trying to destructure nested object in JavaScript and I think it should be working but for some reason I’m getting error:

script.js:126  Uncaught ReferenceError: Cannot access 'team1' before initialization
    at script.js:126:38

const game = {
  team1: 'Bayern Munich',
  team2: 'Borrussia Dortmund',
  players: [
  [
  'Neuer',
  'Pavard',
  'Martinez',
  'Alaba',
  'Davies',
  'Kimmich',
  'Goretzka',
  'Coman',
  'Muller',
  'Gnarby',
  'Lewandowski',
  ],
  [
  'Burki',
  'Schulz',
  'Hummels',
  'Akanji',
  'Hakimi',
  'Weigl',
  'Witsel',
  'Hazard',
  'Brandt',
  'Sancho',
  'Gotze',
  ],
  ],
  score: '4:0',
  scored: ['Lewandowski', 'Gnarby', 'Lewandowski',
  'Hummels'],
  date: 'Nov 9th, 2037',
  odds: {
  team1: 1.33,
  x: 3.25,
  team2: 6.5,
  },
  };

const {
    odds: {team1, x: draw, team2},
  } = game

  console.log(team1, draw, team2);

I want to destructure odds object into three variables.