Google App Script – Save the sheet file Id created from my sheet file template

thank you for the time you will take to resolve my issue !

I am not sure that Google app script allows to do what I need.
Could you please tell me if it is possible?
If yes, do you have already a script code to do it?

I have created a file which I have shared it with others colleagues (in a shared drive), and it is used as a “template”.

When a colleague creates a copy of it, I would like that the script to give me the new Google sheet id created from the model and saved this id in my Google sheet dashboard?

Is it possible with appscript?

Thanks a lot and have a good day !

Use user input for multiple calculations in a component

I’m trying to use a user inputted number for multiple calculations in a component. I am able to use the input for the first calculation (deckboards) but not for the others. For example, newArea / 0.145 is output. But the next calculation for joists (newArea / 0.45) is not output, and neither are the following calculations. Any help would be much appreciated!

import { useState } from "react";
import AddPercent from "./AddPercent";

const Counter = () => {
  const [area, setArea] = useState("");
  const newArea = (e) => {
    const value = e.target.value;
    const deckCalc = deckBoards(value);
    setArea(deckCalc);
  };

  const deckBoards = (newArea) => {
    return (newArea / 0.145).toFixed(2);
  };
  const joists = (newArea) => {
    return (newArea / 0.45 + 1).toFixed(2);
  };
  const sixMJoists = (joists) => {
    return (joists / 6).toFixed(2);
  };
  const fourMJoists = (joists) => {
    return (joists / 4.8).toFixed(2);
  };
  const screws = (joists) => {
    return (joists * 13.2).toFixed(0);
  };

  return (
    <div label="Deck">
      <h2>Total area of deck</h2>
      Area
      <input
        placeholder="Enter area here"
        type="text"
        onChange={newArea}
        type="number"
      />
      <br />
      <h2>Deck boards</h2>Deck boards at 140mm wide : {area} lineal metres
      <AddPercent />
      <br />
      <h2>Joists</h2>Joists based on 450mm spacing : {joists} lineal metres
      <p>Which is equal to this many 6m lengths : {sixMJoists}</p>
      <p>or</p>
      <p>This many 4.8m lengths : {fourMJoists}</p>
      <AddPercent />
      <br />
      <h2>Screws</h2>Number of screws needed : {screws}
      <AddPercent />
    </div>
  );
};

How do I remove filters if filter already exists and create new filter in Google Scripts

I am trying to create a script that runs across 11 different sheets throughout my google sheet. This function essentially will just remove the current filter (if applicable) and create a filter with updated information. The problem I am running into is that my logic to only remove the filter if it does not equal null doesn’t seem to be working because I keep getting an “Exception: you can’t create a filter in a sheet that already has a filter” however my filter.remove should have already removed it.I have been staring at this for hours, some help would be really appreciated. Here is a copy of my script, its a bit long, preferably I would also like to shorten it if possible.

function Filter_All() {
///Set Variables
  var spreadsheet = SpreadsheetApp.getActive();
  var filter = spreadsheet.getActiveSheet().getFilter();
  var criteria = SpreadsheetApp.newFilterCriteria()
  var daycount = 0
  var MILLIS_PER_DAY = 1000*60*60*24*daycount
  var now = new Date();
  var filterdate = new Date(now.getTime() - MILLIS_PER_DAY);
///Select "MTD Assignments"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('MTD-Assignments'), true);
///Remove filter
    if (filter !== null) {
    filter.remove();
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Torian"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Torian'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Luke"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Luke'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Charity"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Charity'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Tenisha"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Tenisha'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Shannon"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Shannon'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Siley"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Siley'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Macheera"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Macheera'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Nia"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Nia'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Alicia"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Alicia'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
///Select "Shannon/Johan/Meybeling"
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Shannon/Johan/Meybeling'), false);
///Remove filter
    if (filter !== null) {
    filter.remove();
    return;
    }
///Create Filter
  spreadsheet.getActiveSheet().getRange('A:N').createFilter();
  criteria = SpreadsheetApp.newFilterCriteria()
  .whenDateAfter(filterdate)
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(5, criteria);
};

Assistance for medium-zoom implementation in Angular 13

I am trying to implement medium-zoom from [https://www.npmjs.com/package/medium-zoom][1]

These are the steps I followed

  1. ng new medium_zoom_test (Angular 13) with routing & css
  2. npm install medium-zoom
  3. image is kept in assets

app.component.html

<h1>Zoom test</h1>
<img class="zoomy" width="50%" src="assets/image.svg">

app.component.ts

import { Component } from '@angular/core';
import mediumZoom from 'medium-zoom';

mediumZoom('.zoomy', {
  margin: 40,
  background: '#ffffff',
  scrollOffset: 40
})

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'medium_zoom_test';
}

When I serve the application I can see the page with image but I don’t see zoom icon. The image won’t zoom on click. It’s just a normal webpage with no change

How To Replace Image Colors with Blue Using Opencv.js

We use the opencv.js to process images from web browser. the complete procedures are:

  1. load the image. This image has 6 types of pixels which are 0,1,2,3,4 and 5
  2. convert all colors to blue except those pixels which have values of 0
  3. show the new image

The problem is it takes so much time for step 2.
what we do now is like below:

let maskImgMat = cv.imread(maskElement);
let metaData = new Array();

for (var i = 1; i <=5; i++) {
    var metaItem = new Object();
    metaItem.ID = i
    metaData.push(metaItem)
}

let objectIds = new Set();
if (maskMeta) {
    maskMeta.forEach(function (s) {objectIds.add(s["ID"])} )
}

// below code snippet will take about 3 seconds 
// to process an image of size 2000 * 30000 
for (var i = 0; i < maskImgMat.rows; i++) {
  for (var j = 0; j < maskImgMat.cols; j++) {

      var pixel = maskImgMat.ucharPtr(i, j);
      var R = pixel[0];

      if (objectIds.has(R)) {

          maskImgMat.ucharPtr(i, j)[0] = 0   // red
          maskImgMat.ucharPtr(i, j)[1] = 0   // green
          maskImgMat.ucharPtr(i, j)[2] = 255 //  blue          
          maskImgMat.ucharPtr(i, j)[3] = 128 // alpha 
          

      } else {
          maskImgMat.ucharPtr(i, j)[3] = 0 
      }
  }
}

Is there other way to do that with good performance? how can we do it by opencv api?

Find mongodb docs based on array of object contains two fields

Example: Mongo db collection:

[
  {
    "user_id": 1,
    "lead_id": 901,
     ...
     ...
  },
  {
    "user_id": 2,
    "lead_id": 902,
     ...
     ...
  },
   {
    "user_id": 2,
    "lead_id": 903,
    ...
    ...
  },
 {
    "user_id": 3,
    "lead_id": 999,
    ...
    ...
  },
]

I have an array of objects:

const reqArr = [
  {
    "user_id": 1,
    "lead_id": 901,
  }, 
   {
    "user_id": 2,
    "lead_id": 999,
   }
]

I want to query the DB based on both user_id and lead_id present in each object in the array reqArr. something like this or with aggregate pipeline

Model.find(reqArr)

My desired output would be something like this:

[{
 "user_id": 1,
 "lead_id": 901,
  ...
  ...
}]

I only know how to query based on the array of one field like Model.find({_id: {"$in": [array of ids ]}}) but not with more than one field in an array of object.
Any idea or workaround to achieve something like the above output or negation of the above output? I only need which objects in reqArr are present in db collection or which are not. Thank you.

Prisma ORM relation

Trying to figure out how to make this relation between two tables by doing a lookup on second table.

model Person {
  personId                 String                     @id @default(uuid())
  address                  String                     @unique
  displayName              String?                    @unique
  emailAddress             String
  allow                    Allow[]
}

model Allow {
  allowId    String   @id @default(uuid())
  address    String
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt
  profile    Profile  @relation(fields: [address], references: [address])

  @@unique([creatorId, address])
}

I’m trying to return a Profile object with a property of ‘canAllow’ which basically pulls back all the data for a Person with another property of ‘canAllow’ which gets set by checking if there is a matching address in the Allow table.

Firebase: How to log the value returned from Firebase collection?

In my React Native app I get a value from Firebase using

this.getRef()
.doc(<something>)
.collection(<something>)
.doc(<something>)

I want to log the value returned by that, but I don’t know if it returns a promise. I’d like to do something like

let a = this.getRef()
  .doc(<something>)
  .collection(<something>)
  .doc(<something>)
console.log(a)

How should I approach this?

Bootstrap Modal On Php Submit using Ajax

Here I’m working on a simple withrawal page where users can select the amount they want to withdraw and submit afterwhich a bootstrap modal pops up confirming to the user that the request has been sent whilst updating the section in the db with the amount selected.

So far im facing no issues when user selects the amount and click on submit, the modal pops up but unfortunately the database is not updated, I can’t fathom where i’m getting it wrong.

Here is the Php


<?php

// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
      // Validate Withrawal
    if(empty(trim($_POST["withraw"]))){
        $withraw_err = "Please Choose a Amount.";     
    } else{   
            $withraw = trim($_POST["withraw"]);
            }

    // Check input errors before inserting in database
    if(empty($withraw_err)){
        
        // Prepare an insert statement
        $sql = "UPDATE users SET withraw = (?) WHERE id = ".$id;

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_withraw);
            
            // Set parameters
           
            $param_withraw  = $withraw;
           
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
               echo "";
            } else{
                echo "Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>

Here is the code for the form im using.

<form  onsubmit="openModal()" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" id="myForm" >
           

              <div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
               

                <div  style='width:50%;' class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
        <option value="500">500</option>
        <option value="1000">1,000</option>
        <option value="1500">1,500</option>
        <option value="2000">2,000</option>
        <option value="2500">2,500</option>
                <option value="3000">3,000</option>
        <option value="3500">3,500</option>

</select>
        
        </div>
                <span class="help-block"><?php echo $withraw_err; ?></span>
            </div>    
        
        
    


          <div class="form-group"  >
               <button type="submit"  class="btn btn-info btn-lg"   value="Submit">
                    Withraw  <i class="fa fa-check-circle"></i> </button> 
                <button type="reset" class="btn btn-default"  value="Reset"><i class="fas fa-redo"></i> Reset </button>
            </div>

        </form>

And I’ve added some javascript to load the bootstrap modal after the form is Submitted

<script>$('#myForm').on('submit', function(e){
     e.preventDefault();
     $('#myModal').modal('show');
                  });</script>

Here is where I’m completely lost as, when I remove the e.preventDefault() the form Updates the database row called withraw but the bootstrap does not load at all and I’ve been trying to set so that the bootstrap loads and the database row is updated as well I do not have more knowledge on how to tackle this situation as I read similar questions and some suggestions are to use Ajax but I have limited knowledge on how to do that.

I didn’t post the bootstrap because i don’t see it necessarily its a normal Bootstrap modal setup

Using delay in for loop, then i becomes undefined [duplicate]

Title says all. My code basically looks like this:

for (i = 0; i < tickers.length; i++){
   console.log(i)//returns number from 1 to 10
   delay(15000)
   console.log(i)//returns undefined

Do you have any idea why this happens? I need a for loop that runs code every 15 seconds without making i undefined. By the way the delay function uses the npm delay function

How to convert european date format to Date Object in react native and/or javascript?

Given a date such as November 23, 2021 in this European format: 23/11/2021. I try converting it to a date object like this:

const dateString =  '23/11/2021'
const dateObj = new Date(dateString)

However, this is giving me an error saying this is an invalid date. I don’t want to just convert it to the US date format, since I am trying to see if I can sort the dates given the European format. Anyone know how I can convert this to a date object given the european date format?

Set element max length

searching here for an answer I found the following question:

Answer for similar issue

I’m trying to replicate this answer but in a different scenario and seems that it doesn’t work when I call a function instead of jQuery key events on document.ready().

This is what I have:

function maxLenght(event) {
  var input = $('p[data-id="111"]').get(0);

  if (parseInt(input.textContent.length) >= 10) {
    event.preventDefault();
  } else {
    $(input).outerHeight(32).outerHeight(input.scrollHeight + 4);
  }
        
  $('span').text('Total chars:' + (input).textContent.length);
}
p {
    height: 100px;
    width: 300px;
    border: 1px solid grey;
    outline: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p contenteditable="true" data-id="111" onkeyup="maxLenght(event)"></p>
<span></span>

Also I should be able to paste text using right click or ctrl + v, navigate the text using arrow keys, backspace, delete key, etc.

So my question is if is possible to do it keeping this functionallity (calling a function) and how can I do it and what’s wrong from what I have right now?

How to store a favourite pet for a logged in user?

Using React and Express, how can I store a favourite pet for a logged in user? Currently pulling the pets from an API and then using PostgreSQL for the DB

const favPetDetails = {
    id,
    name,
    media,
    breeds,
    location,
    distance,
    sort,
    url,
    tags,
    type,
    gender,
    contact,
    environment,
    attributes,
  };
  const addFavouritePet = (Pet) => {
    const newFavList = [...favourites, Pet];
    setFavourites(newFavList);
  };


 <button onClick={() => addFavouritePet(favPetDetails)} </button>