Google app scripts variability, sometimes my code runs and sometimes it does not? automation

I work for a big organisation and we have some large google sheets that multiple users use (however maybe at one time it would be maximum 7-10). I am working on automating some processes for this sheet. For example one of the app scipts i am working on, I would like users to once they have inputted data into a row to complete a QA check and once completed they would input ‘r’ into one of the cells and this will then print out the users email and date they reviewed. The issue is, this does work. however sometimes it wont work for some cells and some sheets. some days it wont work at all and some days it does. I checked the google app script quota limits and from what it seems we are not exceeding the limit here. Therefore I am completely baffled as to why its not working, perhaps its my code? maybe theres a way to optimise this code also? its annoying to have to keep updating the column index numbers if changes happen to the sheet. the title of the column is the same on all the sheets (QA) so i thought about using that as a reference instead of referncing each sheet and the index of the column affected?

function team_QA(e) {
  // Ensure the event object is defined, if false ignore
  if (!e) return;

  var sheet = e.source.getActiveSheet(); 
  var sheetName = sheet.getName();

  // Define the columns to watch for each sheet
  var sheetConfigurations = {
    'Paid': 123, // Column DS
    'Dis': 137,   // Column EH
    'Review': 115, // Column DK
    'Third': 115, // Column DK
    'Lead: 119 // Column DO
  };

  // Check if the edited sheet is one of the specified sheets
  if (!sheetConfigurations.hasOwnProperty(sheetName)) {
    return;
  }

  // Get the column to watch for the current sheet
  var columnToWatch = sheetConfigurations[sheetName];

  // Get the range of the cell that was edited
  var range = e.range;
  var column = range.getColumn();

  // Check if the edited cell is in the column to watch and contains "R"
  if (column == columnToWatch && range.getValue() == "r") {
    // Get the user's email and current date
    var userEmail = Session.getActiveUser().getEmail();
    var currentDate = new Date();

    // Format the date as desired
    var formattedDate = Utilities.formatDate(currentDate, Session.getScriptTimeZone(), "MM-dd-yy");

    // Combine the email and date
    var reviewInfo = userEmail + " reviewed on " + formattedDate;
    
    // Set the review information in the edited cell
    range.setValue(reviewInfo);
  }
}

Formatting a form input field

How can you format a form input field such that it only accepts numbers from users, takes a maximum of 16 digits, and adds a space after each four digits? I am trying to create a debit card such that the data a user enters in the form input fields are updated in real time on the card displayed by the side. And I want the card number to be arranged in fours, just as it is on a real card.

I tried saving the user input in a variable and then using a loop to insert a space after every four digits. Well, I don’t know why but it didn’t work.

How to dynamically update Chart.js horizontal bar chart to show only team members with data in selected modules?

I’m working with a horizontal bar chart in Chart.js where each bar represents a team member. The chart’s vertical axis lists team members, while the horizontal axis depicts different time periods indicating their involvement in various modules. Each dataset in the chart corresponds to a module, showing the duration of each team member’s engagement.

My goal is to enable dynamic updates based on module selection. When I select or deselect a module (dataset) using the chart’s legend, I want the chart to reflect these changes by adjusting which team members are displayed. Specifically, the chart should only show team members who have logged any activity within the currently selected modules.

How can I implement this feature effectively using Chart.js?

Based on the selections, I’d not want chart to represent the names of Yashdeep Paul Singh & Rajat Khade based on the present selection of datasets. However, when I reselect those datasets where they have activity these labels should display back again.

Is it possible?

enter image description here

Is there any in-built functionality that can help with this? One of the approaches that comes to mind is that every time a dataset is selected/deselected, go through each of the team members in each dataset and check if there is no time logged for him/her, and then update the chart again, but that seems to be a brute force approach. Any other better options?

@ng-idle/core: Timeout happening on one idle instance is causing the interrupt to stop working on the other idle instance

I’m using “@ng-idle/core”: “~11.1.0” and Angular 13 application.

I have two idle instances, one for auto logout and another one for screensaver.

If my screensaver is “Active” and if timeout happens on the first instance(i,e. autologout) and if I try to interrupt the screen then screensaver is not going off and its blocking the UI.(One thing is clear that interrupt subscription stops working in this scenario).

How to resolve this issue?.

Sample code for reference:

import {Component, NgZone, OnInit} from '@angular/core';
import {DEFAULT_INTERRUPTSOURCES, Idle, LocalStorage, LocalStorageExpiry} from '@ng-idle/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
  title = 'my-idle-app';
  private readonly screenSaver!: HTMLElement;
  private readonly screenSaverText!: Text;
  idleTime1: number = 1;
  private screenSaverIdle = new Idle(new LocalStorageExpiry(new LocalStorage()), this.ngZone);

  constructor(readonly ngZone: NgZone, private idle1: Idle) {
    this.screenSaver = document.createElement('div');
    this.screenSaver.id = 'screensaver';
    this.screenSaver.className = 'screen-saver';
    this.screenSaverText = document.createTextNode('---%');
    const movingTxt = document.createElement('span');
    movingTxt.appendChild(this.screenSaverText);
    this.screenSaver.appendChild(movingTxt);
    this.removeScreenSaver();

    this.screenSaverIdle.setIdleName('screenSaverIdleService');
    this.screenSaverIdle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
    this.screenSaverIdle.setTimeout(false);
    this.screenSaverIdle.setIdle(10);
    this.screenSaverIdle.watch();

    this.screenSaverIdle.onIdleStart.subscribe(() => {
      document.body.appendChild(this.screenSaver);
    });

    this.screenSaverIdle.onIdleEnd.subscribe(() => {
      console.log('IDLE END ::');
      this.removeScreenSaver();
    });
  }

  ngOnInit() {
    this.idle1.setIdleName('AutoLogoutIdleService');
    this.idle1.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    this.idle1.setIdle(this.idleTime1);
    this.idle1.setTimeout(10);

    this.idle1.onIdleStart.subscribe(() => {
      console.log("IDLE 1 STARTS")
    });

    this.idle1.onIdleEnd.subscribe({
      next: () => {
        console.log("IDLE 1 END");
      },
      complete: () => {
        console.log("idle 1 completed");
      }
    });

    this.idle1.onTimeout.subscribe(()=> {
      console.log("User session timed Out",);
    });

    this.idle1.watch();
  }

  private removeScreenSaver() {
    const ex = document.getElementById('screensaver');
    if (ex) {
      document.body.removeChild(ex);
    }
  }
}

I analyzed the source code of the ng-idle library and it seems like, since timeout value is “false” for screensaver ideal instance it should not cancel the interrupt subscription.

So, my question will be regarding the instances of the services being created. Is it causing any problem here?.

in vscode Autocompletion does not occur when manipulating the dome

const h1 = document.querySelector(‘#hi’);

h1.styl = “red” –> not auto-completed


I would like to autocomplete style. Please tell me how to solve it.

I am aware that auto-completion is not possible when manipulating the DOM with a query selector because it does not recognize whether it is a node or an element, but I still want it to be auto-completion.

I looked into several extensions.

Is there a solution?

Sorry for my poor English….

Capturing Only the Detected Face Image in React Native Camera

Problem
I have created a screen in React Native using the React Native Camera library, which allows us to detect faces. After face detection, it captures an image. However, it captures the entire image instead of just the face. How can I capture only the face image?.

Code

import { Dimensions, View, Alert, TouchableOpacity, Text } from 'react-native'
import React, { useRef, useState, useEffect } from 'react'
import { RNCamera } from 'react-native-camera'
import ImageEditor from "@react-native-community/image-editor"
import { SCREEN } from '../../../constants'
import { styles } from './styles'
// import ImagePicker from 'react-native-image-crop-picker'

const { width: windowWidth, height: windowHeight } = Dimensions.get('window')

const FaceDetection = ({ navigation }) => {
    const [box, setBox] = useState(null)
    const cameraRef = useRef()
    const [alertShown, setAlertShown] = useState(false)
    const [borderColor, setBorderColor] = useState('red')
    const [showCaptureButton, setShowCaptureButton] = useState(false)
    const [capturedImage, setCapturedImage] = useState(null)
    const alertTimeoutRef = useRef(null)

    useEffect(() => {
        if (alertShown) {
            // Delay showing the capture button after 2 seconds
            const timer = setTimeout(() => {
                setShowCaptureButton(true)
            }, 2000)

            return () => clearTimeout(timer)
        } else {
            setShowCaptureButton(false)
        }
    }, [alertShown])

    const handleFacesDetected = ({ faces }) => {
        if (faces.length > 0) {
            const face = faces[0]

            const isFaceProperlyVisible = () => {
                const minFaceWidth = 50
                const minFaceHeight = 50
                const maxFaceWidth = windowWidth - 50
                const maxFaceHeight = windowHeight - 50

                const isWithinBounds =
                    face.bounds.origin.x >= 0 &&
                    face.bounds.origin.y >= 0 &&
                    face.bounds.origin.x + face.bounds.size.width <= windowWidth &&
                    face.bounds.origin.y + face.bounds.size.height <= windowHeight

                // const isOccluded = face.bounds.size.width < minFaceWidth || face.bounds.size.height < minFaceHeight

                // console.log(isOccluded)

                const isFaceStraight = Math.abs(face.yawAngle) < 15 // Adjust angle threshold as needed

                return (
                    face.bounds.size.width >= minFaceWidth &&
                    face.bounds.size.height >= minFaceHeight &&
                    face.bounds.size.width <= maxFaceWidth &&
                    face.bounds.size.height <= maxFaceHeight &&
                    isWithinBounds &&
                    isFaceStraight
                    // && !isOccluded
                )
            }

            const properlyVisible = isFaceProperlyVisible()

            setBox({
                width: face.bounds.size.width,
                height: face.bounds.size.height,
                x: face.bounds.origin.x,
                y: face.bounds.origin.y,
            });

            if (properlyVisible) {
                if (!alertShown) {
                    setAlertShown(true)

                    alertTimeoutRef.current = setTimeout(() => {
                        setBorderColor('green')
                        Alert.alert("Face Detected", "Your face is detected!")
                    }, 2000)
                }
            } else {
                if (alertTimeoutRef.current) {
                    clearTimeout(alertTimeoutRef.current)
                    alertTimeoutRef.current = null
                }
                setBorderColor('red')
                setAlertShown(false)
            }
        } else {
            if (alertTimeoutRef.current) {
                clearTimeout(alertTimeoutRef.current)
                alertTimeoutRef.current = null
            }
            setBox(null)
            setAlertShown(false)
            setBorderColor('red')
        }
    }

    const takePicture = async () => {
        if (cameraRef.current) {
            const options = { quality: 0.5, base64: true }
            const data = await cameraRef.current.takePictureAsync(options)
            setCapturedImage(data.uri)
            navigation.navigate(SCREEN.capturedImage, { capturedImage: data.uri })
        }
    }

    return (
        <View style={styles.container}>
            <RNCamera
                ref={cameraRef}
                style={styles.cameraContainer}
                type={RNCamera.Constants.Type.front}
                captureAudio={false}
                onFacesDetected={handleFacesDetected}
                faceDetectionMode={RNCamera.Constants.FaceDetection.Mode.fast}
            />
    
            {box && (
                <View
                    style={[
                        styles.bound,
                        {
                            width: box.width,
                            height: box.height,
                            left: box.x,
                            top: box.y,
                            borderColor: borderColor,
                        },
                    ]}
                />
            )}
            {showCaptureButton && (
                <TouchableOpacity style={styles.captureButton} onPress={takePicture}>
                    <Text style={styles.captureButtonText}>Capture Image</Text>
                </TouchableOpacity>
            )}
        </View>
    )
}

export default FaceDetection



I just want to cappture face area

Shadcn-vue Dialog issue

The issue is that when I click Edit or Delete, both dialogs pop up, which obiously shouldn’t be the case.

<Dialog>
  <Table v-if="credentialsList">
    <TableCell>
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button
            aria-haspopup="true"
            size="icon"
            variant="ghost"
            class="dark:hover:bg-transparent"
          >
            <EllipsisVertical class="h-4 w-4" />
            <span class="sr-only">Toggle menu</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DialogTrigger class="w-full">
            <DropdownMenuItem
              class="cursor-pointer"
              @click="credentialsDialogRef.editCredential(credential)"
            >
              {{ $t("message.common.edit") }}
            </DropdownMenuItem>                     
          </DialogTrigger>
          <DialogTrigger class="w-full">
            <DropdownMenuItem
              @click="handleDelete(credential)"
              class="cursor-pointer w-full"
            >
              Delete
            </DropdownMenuItem>
          </DialogTrigger>
        </DropdownMenuContent>
      </DropdownMenu>
    </TableCell>
  </Table>
  <credentials-dialog ref="credentialsDialogRef" />
  <delete-dialog ref="deleteDialogRef" />
</Dialog>

I’ve tried using v-if statements on them, but it didn’t help at all.

Prevent chart to resize due to long labels

i am using chart.js and react-chartjs-2. I have this polar chart and a dropdown at top left, as seen in the screenshots, they get resized due to long labels. when I give an empty array to display no labels, so the chart size stays the same, and the labels are the issue here.
is there any way to make the chart stay always the same size regardless of length of labels ?
I have tried setting maintainAspectRatio: false , using fixed dimensions for chart and parent of chart, I already have min max values, some of other questions on SO (link) but did not solve it.

here is my options object;

{
            elements: {
              arc: {
                offset: -160,
              },
            },
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              r: {
                min: 0,
                max: 10,
                beginAtZero: true,
                ticks: {
                  display: false, // 0-10 scale,
                },
                grid: {
                  display: true,

                  color: function (ctx: ScriptableScaleContext, _options: AnyObject) {
                    if (ctx.index === 10) return "rgba(27,22,70,0.4)";
                    if (ctx.index === 6) return "rgba(249,35,7,0.4)";
                    return "rgba(222,222,222,0.5)";
                  },
                },
                angleLines: {
                  display: false,
                },
                pointLabels: {
                  display: true,
                  callback: function (label: string) {
                    return label; // Customize the label if needed
                  },
                  centerPointLabels: true,

                  font: function () {
                    return { size: 13 };
                  },
                },
              },
            },
            plugins: {
              legend: {
                display: false,
              },
              datalabels: {
                anchor: "end",
                align: "start",
                color: "white",
                font: {
                  // weight: "bold",
                  size: 24,
                },

                
              },
            },

and here is my data object;

const perceptionDataGesundheit: ChartData<"polarArea", number[], string[]> = {
  labels: labels_gesundheit,
  datasets: [
    {
      label: "Perception",
      backgroundColor: color_perception,
      borderColor: color_perception,
      borderWidth: 0,
      data: [7.2, 6.1, 7.7],
      spacing: 160,
    },
  ],
}

and here are the screenshots;
enter image description here
enter image description here

Is there a more convenient way for me to export a large image from google earth engine? [closed]

Good morning,
I want to export the image of different indices of my study area in my asset or my drive but I have memory errors. Does anyone have a tip that will help me export this image easily? I’ll give you the link to the script: google earth engine code

I tried to export the image by creating tiles but no image was displayed on the tiles and I had a mix of values. My wish is to export the image without having to cut it into tiles.

Javascript based Radial Bar chart not showing in Oracle Apex region

I’m trying to create a chart in Oracle Apex that shows 2 values based on hidden page items but at the moment the region is empty and I can’t get it to use the values that in the page items. The page items are as follows:

P8_TOTAL => 7405401

P8_TARGET => 7564125

I’ve changed them from hidden to number fields just to ensure they are returning values.

On the page I have added this to the File URLs: https://cdn.jsdelivr.net/npm/apexchart

The region that the chart should be displayed is a static content with this source:

<div id="chart" style="height: 350px; width: 100%;"></div>

I then have a dynamic action which executes on page load with the following JavaScript code:

document.addEventListener("DOMContentLoaded", function() {
    try {
        var totalOrderValue = parseFloat($v('P8_TOTAL').replace(/,/g, '')) || 0;
        var targetValue = parseFloat($v('P8_TARGET').replace(/,/g, '')) || 0;

        if (isNaN(totalOrderValue) || isNaN(targetValue)) {
            throw new Error("Invalid values for P8_TOTAL or P8_TARGET.");
        }

        var options = {
            chart: {
                type: 'radialBar',
                height: 350
            },
            series: [totalOrderValue, targetValue],
            labels: ['Total Order Value', 'Target'],
            plotOptions: {
                radialBar: {
                    dataLabels: {
                        name: {
                            fontSize: '16px',
                            offsetY: 20
                        },
                        value: {
                            fontSize: '24px',
                            offsetY: 10,
                            formatter: function(val) {
                                return val.toLocaleString();
                            }
                        }
                    }
                }
            },
            colors: ['#FF4560', '#00E396'],
            fill: {
                type: 'solid'
            },
            stroke: {
                lineCap: 'round'
            }
        };

        var chartContainer = document.querySelector("#chart");
        if (chartContainer) {
            var chart = new ApexCharts(chartContainer, options);
            chart.render().then(() => {
                console.log("Chart rendered successfully");
            }).catch(error => {
                console.error("Error rendering chart:", error);
            });
        } else {
            console.error("Chart container not found.");
        }
    } catch (error) {
        console.error("JavaScript error:", error);
    }
});

I’ve investigated the browser console and it’s not displaying any errors

Where am I going wrong?

Drag and drop reorder

I am writing a script for drag and drop reordering question type by using cypress where I use plugin as cy.get(sourceElement).drag(targetElement).

I found the source element and target element but that element is not drag and drop. Can aAnyone share the solution for this?

I drag the element from source point and drop it in target point but it doesn’t happen.
This is my code
let collection1 = [];
const origValueArray = [];

                cy.get('.draggable__item').then($items => {
                    let collection = [];

                    $items.each((index, el) => {
                        const attrValue = el.getAttribute('data-rbd-draggable-id');
                        collection.push(attrValue);
                    });

                    const sortedCollection = [...collection].sort();
                    cy.log(sortedCollection);

                    cy.get('div[data-rbd-drag-handle-draggable-id]').then($items1 => {
                        $items1.each((index, el) => {
                            const attrValue1 = el.getAttribute('data-rbd-drag-handle-draggable-id');
                            cy.log(attrValue1);
                            collection1.push(attrValue1);
                        });

                        // Ensure all collections are built before proceeding
                        cy.wrap(sortedCollection).then(sortedArray => {
                            sortedArray.forEach((el, index) => {
                                cy.log(collection1);

                                cy.get(`div[data-rbd-draggable-id="${el}"]`, { timeout: 10000 }).should('be.visible').then($el => {
                                    cy.get(`div[data-rbd-drag-handle-draggable-id="${collection1[index]}"]`, { timeout: 10000 }).should('be.visible').then($target => {
                                        cy.wrap($el).dragTo($target);
                                    });
                                });
                            });
                        });
                    });
                });

How can I compose a method in a class which creates a new instance of it’s child class?

I code TypeScript with React.js. I have a parent class “EntityCollection” and a child class “ProductCollection”. I want to define a method for “EntityCollection” that create a new instance of the class. But in a child class it have to create an instance of the child class.

With PHP I would make something like this:

class Parent 
{
    public function hail(): void
    {
        print "hello, I'm " . static::class;
    }

    public function getNewObject(): static
    {
        return new static();
    }

}

class Child extends Parent {}

$parent = new Parent();
$child = new Child();
$parent->getNewObject()->hail(); // hello, I'm Parent
$child->getNewObject()->hail(); // hello, I'm Child

The closest solution I’ve found is “eval” function:

export class EntityCollection {
    makeNewClass() {
        return new (eval(this.constructor.name))();
    }
}

but the problem is the child class is in a separated file and I’ve got an error: “ReferenceError: ProductCollection is not defined”.
I’ve also tried Object.create(this); – the problem here is we don’t have exactly the same structure, if I did new ProductCollection(), but I need it like it is in PHP with new static(). I don’t like the idea to override the method in each child, it’s just ridiculous.

Playing two videos simultaneously on Chrome is halving frame rate. What can I do about it?

I have an HTML page with a section that contains a video background and a smaller video in the foreground. When both videos play at the same time, the Chrome frame rate is exactly half of the normal frame rate (accordingly to dev tools) — that is, FPS drop from 75 (my screen’s refresh rate) to 37.5 (half of 75) — and I can notice both videos start playing a bit jagged.

This doesn’t seem to be something about performance, though. Maybe it is something related to how Chrome renders video? Also, video format doesn’t seem to make any difference, as I tried MP4 and VP9 videos.

Do you know if this is expected behavior on Chrome, and if it can be solved and how? I could manage to change the design in a way that no two videos play at the same time, by pausing the background video while the foreground video plays, but if there is a way to get away with it, I would like to take it.

How to pass null body through playwright request?

I have a POST request with null as the body. I am not sure how to pass this null through a Playwright POST request.

I tried with data: null, data: 'null', data: Null, data: '%00', data: {}. All these fails the test at the line where I catch the response body as await resp.body().

If I pass null in Postman for the same request, I get a successful JSON response. If no null in the Postman request, I get ‘content type error’ as response.

Blank page after a while when testing on Cypress using UI

When running e2e tests using UI on Cypress, after several seconds of running normally, the explorer suddenly comes white and shows next message on terminal:

<--- JS stacktrace --->

[72464:0716/101731.973912:ERROR:v8_initializer.cc(730)] V8 process OOM (Oilpan: Reserving memory.).
We detected that the Chromium Renderer process just crashed.

This is the equivalent to seeing the 'sad face' when Chrome dies.

This can happen for a number of different reasons:

- You wrote an endless loop and you must fix your own code
- You are running Docker (there is an easy fix for this: see link below)
- You are running lots of tests on a memory intense application
- You are running in a memory starved VM environment
- There are problems with your GPU / GPU drivers
- There are browser bugs in Chromium

You can learn more including how to fix Docker here:

https://on.cypress.io/renderer-process-crashed

Just for information, I’m testing for a UI hosted in Docker, and it works propperly whithout using Cypress UI.

I don’t know how to upgrade memory assigned to process or solve this (apart from spare the test in smaller parts).

I tried to spare the tests and worked perfect.

And limit the resources used with Cypress configuration modification:

    setupNodeEvents(on, config) {
            on("before:browser:launch", (browser, launchOptions) => {
                if (["chrome", "electron", "chromium", "edge"].includes(browser.name)) {
                    if (browser.isHeadless) {
                        launchOptions.args.push("--no-sandbox");
                        launchOptions.args.push("--disable-gl-drawing-for-tests");
                        launchOptions.args.push("--disable-gpu");
                    }
                    launchOptions.args.push("--js-flags=--max-old-space-size=3500");
                }
                return launchOptions;
            });
        }