How to write some Google Apps Script code for increasing the number of rows of every table from 20 to 40 in a Google Docs file easily?

This is the file. It is supposed to be a worksheet.

There are lots of tables in the file. Each table has 20 blank rows (for 20 students). I need 40 blank rows (for 40 students).

Adding the rows manually is a menially repetitive task. I found a relatively easy method. Select the 20 rows using the mouse, and then right click. Then an option comes up asking if I want to add 20 rows below or not, but it is still a cumbersome process to repeat for all the tables. How do I accomplish this task more easily?

I don’t know the JavaScript, but still I stupidly tried the following code:

function myFunction() {      

  for (let table in DocumentApp.getActiveDocument().getTables()) {      

    for (let i = 0; i < 20; i++) {              
      table.insertTableRow(20); 

    }   

  }

}

Gives me the following error:

Error TypeError: table.insertTableRow is not a function

Can’t read/write data with Firebase Realtime Database

Following the Firebase Database Setup, I can’t Read/Write anything. I’ve been googling for hours trying different approaches and nothing is working. I’m using Discord.js so I’ll remove the stuff unrelated to Firebase. For now I’m just hard coding the values for testing purposes.

require("dotenv").config();

const { initializeApp } = require('firebase/app');
const { getDatabase, ref, set } = require('firebase/database');

const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
  measurementId: process.env.MEASUREMENT_ID,
};

// Initialize firebase
const app = initializeApp(firebaseConfig);

// Initialize Realtime Database
const database = getDatabase(app);

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

client.on("ready", () => { // when bot goes online
  console.log("Ready!");
  writeUserData("UserId", "Terry", "[email protected]", "https://imgur.com/t/bees/3bt83")
});

All of my firebaseConfig info is correct. My Read/Write permissions are both true.

Any help is appreciated.

I’ve tried the official Firebase documentation as well as other forums regarding the same problem.

How can I select and navigate to last row in grid when open Interactive grid?

How can I navigate to last line when open the interactive grid in oracle apex

and when click Add Row button add new line after last line in the Interactive grid ?

I turned off Select first row option but still when click add Row new row created on first line not last line in the grid 

Can I do it by java script code also in Java script Execute when Page Loads ?

enter image description here

Any Idea please ?

current datetime is 6 hours behind nodejs

I need to compare current datetime with datetime in database column. In my computer new Date() returns datetime that is 2023-05-21T04:35:07.903Z whereas My computer time is 10:35:07. How can I adjust this ? .

Note : I cannot convert them to string as I need to compare them.
My code :

        console.log("current time", new Date());
        console.log("db time", new Date(results[i].start));

        if ( new Date(results[i].start) >= new Date()){
            ..............
        }

Can javascript cause 1-2 min delay randomly before displaying a web page?

Since I added the following javascript in the header of my webpages code as well as used hisorange/browser-detect in Laravel, I experienced random delay every 10-15 min before the requested page appears on screen. After that everything is completely normal for another 10-15 min then it happens again and again…

In Firefox dev tools, there is no network activity… just a long delay.

The purpose of the above is to detect window size and resize and display the correct html code in Laravel blade.

 <script type="text/javascript" src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js"></script>
 <script type="text/javascript">
 var limit = 769;
 var width = $(window).width();
 Cookies.set('windowW',$(window).width(),{ expires:7});
 $(window).resize(function() {
     if ((width > limit && $(window).width() < limit) || (width < limit && $(window).width() > limit)) {
           Cookies.set('windowW',$(window).width(),{ expires:7});
           location.reload();
      }
 });
 </script>

For xxx, here is the code I have in AppServiceProvider.php:

 use Browser;

 $platform = 'desktop'; $is_mobile = false;
 if (Browser::isMobile()) { $platform = 'mobile'; $is_mobile = true; }
 else if (Browser::isTablet()) { $platform = 'tablet'; $is_mobile = false; }
 if (getCookie('windowW')) { $windowW = getCookie('windowW')[0]; } else { $windowW = 1000; }

When I remove the javascript above as well as the use of Browser, I do not get delays anymore.

So my question is … is there anything wrong in the way I am doing that? And is it possible that the code above could cause the error?

TypeScript/ES6: what is an “:” in the below context?

I understand below two usages in TS/ES6.

  1. Below, a variable myname of type string which is going to be constant(final) is declared.

    const myname: string = ‘abcd’;

  2. Below a variable/function initialPath is declared and is assigned a function body using the => operator.

    const initialPath = ({pathRoot, myvar = ”, locale = ”}) =>
    path.join(process.cwd(), pathRoot, myvar, locale.toLowerCase());

But I am not sure of the below usage, what is : in the below doing.

module.exports = {
  application: myname,
  myservicePostfix,
  loadablePath: ({pathRoot, myvar}) =>
    path.join(basePath({pathRoot, myvar}), 'loadable.json')
}

-> does application: myname mean that application = myname and application is of type typeof(myname).
-> similarily what does loadablePath: above mean

is sync state with prop bad in react?

If I do this, passing prop as default state, it won’t update if I do

const MyComp = ({ isOpen: _isOpen }) => {
const [isOpen, setIsOpen] = useState(_isOpen)

return <div>{isOpen.toString()}<button onClick={() => setIsOpen(true)}></button></div>
}

I fixed it with this

const MyComp = ({ isOpen: _isOpen }) => {
const [isOpen, setIsOpen] = useState(false)

useEffect(() => {
setIsOpen(_isOpen)
}, [_isOpen])

return <div>{isOpen.toString()}<button onClick={() => setIsOpen(true)}></button></div>
}

is this an anti-pattern?

canvasjs-chart in angular 2way binding

I am using canvasjs-chart in my angular to draw chart.(I am new in Angular)
here is my component ts code :

import { Component } from '@angular/core';
import { NgModule } from '@angular/core';
@Component({
  selector: 'app-counter-component',
  templateUrl: './counter.component.html'
})
export class CounterComponent {
  public books = [{
    title: "Life is good",
    author: "benny",
    category: "life"
  }, {
    title: 'Canned in',
    author: "francis",
    category: "style"
  }];
  chartOptions = {
    title: {
      text: "Basic Column Chart in Angular"
    },
    data: [{
      type: "line",
      dataPoints: [
        { label: "Apple", y: 121 },
        { label: "Orange", y: 15 },
        { label: "Banana", y: 25 },
        { label: "Mango", y: 30 },
        { label: "Grape", y: 28 }
      ]
    }]

  };
  public changeChartData() {
    this.chartOptions.data[0].dataPoints[0].y =20;
  }

As you can see I have a books object which it passed to html :

<button class="btn btn-primary" (click)="changeChartData()">change chart Data</button>
<canvasjs-chart [options]="chartOptions"></canvasjs-chart>

The data is shown correctly but my problem is when I click on the change chart Data to change the value of my books object I can’t see the changes in the chart .I think the problem is the chart is not binding to books object

in angular v16 project I need to wait for an http response in a sync manner for a guard and other components handle the result

I’m using an AuthService into which I created a function that returns a boolean, isUserAuthenticated(): boolean. Into this function according some conditions, I need to make an http call to recover user data from backend, and according to the response, the function will return true/false to a guard or other components take the decision to redirect user to login page.

Here is my function:

isUserAuthenticated(): boolean {
  return this.checkUserAuthenticated();
}

Due to http is async I had to use async/await this way:

private async checkUserAuthenticated() {
    const token = this.sessionStorageService.getTokens();
    const user = this.sessionStorageService.getUser();
    const isUserDataOk = user.username !== '' && user.username != undefined;

    if (token != null && user.id != null && isUserDataOk) {
      this.userAuthenticated = true;
      return true;
    } else if (!isUserDataOk && user.id != null) {
      const result = await this.recoverUserData(user.id);
      if (result.body?.user != undefined) {
        this.userAuthenticated = true;
        return true;
      }
    } else {
      this.userAuthenticated = false;
      return false;
    }

    return this.userAuthenticated;
  }

Code is going through await this.recoverUserData(..) that calls the http:

private async recoverUserData(userId: string)  {
    console.log('recovering user data');

    return await firstValueFrom(
      this.http.post<LoginResponseDto>(
        AppApis.Auth.signInData, { 'userId': userId }, { observe: 'response' }
      )
    );
  }

The problem is these chain of async calls are becoming hard to manage as sync, the line of code: return this.checkUserAuthenticated(); is returning a promise<boolean> but I need a simple boolean because for example can activate guard condition is: if (authService.isUserAuthenticated()) return true.

firstValueFrom is new and it returns a promise from an observable.

React Echarts Error for render custom Svg floor plan

I use react to visualise a Svg floor plan (heatmap) in reactjs.
However, it will return error at「cannot read properties of undefined (reading regions)」.

I have struggled for this issue several weeks, please give me some hints! Thanks

Kindly find the source code and Svg file below for your further investigation

Code:

import React, { useRef, useEffect } from "react";

import * as echarts from "echarts";

import mapData from "./map.svg";

export default function Heatmap(){

const ref = useRef(null);

let mapInstance = null;

const option = {

    tooltip: {},

    visualMap: {

    left: 'center',

    bottom: '10%',

    min: 5,

    max: 100,

    orient: 'horizontal',

    text: ['', 'Price'],

    realtime: true,

    calculable: true,

    inRange: {

        color: ['#dbac00', '#db6e00', '#cf0000']

        }

    },

series: [

  {

    name: 'French Beef Cuts',

    type: 'map',

    map: 'testing',

    roam: true,

    emphasis: {

      label: {

        show: false

      }

    },

    selectedMode: false,

    data: [

      { name: 'Queue', value: 15 },

      { name: 'Langue', value: 35 },

      { name: 'Plat de joue', value: 15 },

      { name: 'Gros bout de poitrine', value: 25 },

      { name: 'Jumeau à pot-au-feu', value: 45 },

      { name: 'Onglet', value: 85 },

      { name: 'Plat de tranche', value: 25 },

      { name: 'Araignée', value: 15 },

      { name: 'Gîte à la noix', value: 55 },

      { name: "Bavette d'aloyau", value: 25 },

      { name: 'Tende de tranche', value: 65 },

      { name: 'Rond de gîte', value: 45 },

      { name: 'Bavettede de flanchet', value: 85 },

      { name: 'Flanchet', value: 35 },

      { name: 'Hampe', value: 75 },

      { name: 'Plat de côtes', value: 65 },

      { name: 'Tendron Milieu de poitrine', value: 65 },

      { name: 'Macreuse à pot-au-feu', value: 85 },

      { name: 'Rumsteck', value: 75 },

      { name: 'Faux-filet', value: 65 },

      { name: 'Côtes Entrecôtes', value: 55 },

      { name: 'Basses côtes', value: 45 },

      { name: 'Collier', value: 85 },

      { name: 'Jumeau à biftek', value: 15 },

      { name: 'Paleron', value: 65 },

      { name: 'Macreuse à bifteck', value: 45 },

      { name: 'Gîte', value: 85 },

      { name: 'Aiguillette baronne', value: 65 },

      { name: 'Filet', value: 95 }

    ]

  }

]

}

const renderMap = (myChart) => {

    /*const renderedMapInstance = echarts.getInstanceByDom(ref.current);

    if (renderedMapInstance) {

      mapInstance = renderedMapInstance;

    } else {

      mapInstance = echarts.init(ref.current);

    }

    mapInstance.setOption(option);*/

    myChart.setOption(option)

  };

  useEffect(() => {

    fetch(mapData)

      .then((response) => response.text())

      .then((svgText) => {

        echarts.registerMap("testing", { svg: svgText });

      });

    var chartDom = document.getElementById('beef');

    var myChart = echarts.init(chartDom);

    renderMap(myChart);

  }, []);

/*

  useEffect(() => {

    window.onresize = function () {

    };

    return () => {

      mapInstance && mapInstance.dispose();

    };

  }, []);  mapInstance.resize();

    

*/

  return (

    <div>

      <div style={{ width: "100%", height: "50vh" }} ref={ref} id='beef'></div>

    </div>

  );

}

———————————————————————————————

Svg file

        <svg

                              xmlns="http://www.w3.org/2000/svg"

                              width="591"

                              height="373"

                              preserveAspectRatio="xMidYMid meet"

                              viewBox="0 0 376 237"

                            >

                              <g transform="translate(-7.69,10.06)">

            

            <path

              

              d="m 536.375,106.46875 c 5.2885,14.34201 10.52945,33.1769 13.78125,43.21875 -0.0655,0.0771 -0.13181,0.1476 -0.21875,0.21875 l 16.5625,0.9375 10.5,-8.5 11,-17 -13.5,-18 -38.125,-0.875 z"

              stroke="#A5A5A5" 

              stroke-width="0.75"

              stroke-linecap="round"

              fill="#FFFFFF"

              fill-rule="evenodd"

              id="path3702"

              name="Langue" 

              transform="matrix(0.6362812,0,0,0.6362812,7.6936433,-10.065285)"

            />

            

            </g>  

        </svg> 

What is the best way to pass session data from a Client component to a server component in NEXT.js 13>?

I am developing a web app where I need to pass session?.user?.email from useSession() in next-auth/react to a sever side component where it carries out a fetch request to /api/users/email/ to find out if a user exists with that particular email address.

After reading the documentation, I realised that you are not supposed to use server components inside 'use client' components where I have my useSession()

What is the best way to structure this?

org.jinterop.dcom.common.JIException: The object name is not found [0xC0000034]

I am having a problem using “J-INTEROP” trying to make an OPC DA client for andriod devices.

I made all the DCOM configurations and today I can connect to the server from any PC that is within my network regardless of the user that connects.

The error that is throwing me is: org.jinterop.dcom.common.JIException: The object name is not found [0xC0000034]

The OPC DA server I am using is KepServerEX.V4

The error occurs in the following line: val comServer = JIComServer(JIProgId.valueOf(“KEPware.KEPServerEx.V4”), “192.168.1.11”, session)

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.jacob.com.Dispatch
import org.jinterop.dcom.common.JIException
import org.jinterop.dcom.common.JISystem
import org.jinterop.dcom.core.IJIComObject
import org.jinterop.dcom.core.JIComServer
import org.jinterop.dcom.core.JIProgId
import org.jinterop.dcom.core.JISession
import org.jinterop.dcom.impls.JIObjectFactory
import org.jinterop.dcom.impls.automation.IJIDispatch
import java.net.UnknownHostException



class MainActivityOPCDA : AppCompatActivity() {

    lateinit var errortextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_opcda)

        errortextView = findViewById(R.id.etextView)

        Thread(Runnable {
            JISystem.setInBuiltLogHandler(false)
            JISystem.setAutoRegisteration(true)


            
            val session = JISession.createSession("192.168.1.11", "opcuser", "123456")
            session.useSessionSecurity(true)
            session.globalSocketTimeout = 5000



try {

   val comServer = JIComServer(JIProgId.valueOf("KEPware.KEPServerEx.V4"), "192.168.1.11", session)


   val serverObj = comServer.createInstance() as IJIComObject

   val opcServer = JIObjectFactory.narrowObject(serverObj.queryInterface("6E6170F0-FF2D-11D2-8087-00105AA8F840"))

                val opcServerDispatch = opcServer.queryInterface(IJIDispatch::class.java.name) as Dispatch
                val server = Dispatch.call(opcServerDispatch, "QueryInterface", IJIDispatch::class.java.name).toDispatch()




            } catch (e: JIException) {

                e.printStackTrace()
                runOnUiThread {
                    errortextView.text = "ERROR: ${e.message.toString()}"
                }


            } catch (e: UnknownHostException) {
                e.printStackTrace()
                runOnUiThread {
                    errortextView.text = "ERROR: ${e.message.toString()}"
                }
            }
 }).start()


    }

I did a lot of testing on the DCOM setup. Assuming a problem with some windows permission, for these tests I am using Windows 10. And the tests are with real andriod devices.

I also did tests with different OPC DA clients for windows and the communication with the server works correctly for me.

How to debug a scroll block in JavaScript

I’m using scrollIntoView(), but the behaviour is the same for scrollTo(...) and even location = '#....

When I use a timeout > 500ms for the scrolling action it works. How can I debug this? Something must be interfering with the programmatic scrolling.

PS: When clicking a button which has as href #..., the scrolling works also. Somehow, the user event goes through without the need for a timeout.

jQuery.remove() and array.splice() issue

So I have a page where there’s an item list and a shopping list. If you add an x number of items from the items list to the shopping list, then try to remove them one by one, by clicking on the items from the shopping list and hitting delete on the modal that opens it works – the first time. Now here’s the problem, if you try doing that all over again, for example adding another set of x number items to the shopping list and try to remove them one by one again. As soon as you hit the delete button on the modal I get unpredictable results, it either removes ALL the shopping list items, or 2 or 3 along with the item you’re supposed to delete.

It’s a simple jQuery.remove() and array.splice yet I can’t get it to work. Apparently it’s more complicated than I thought, and I’ve tried doing it a bunch of different ways.

Here’s the page:
http://bigbiz.io/pos/

Thanks in advance!

Refactoring the code

Search for a keyword in multiple files and return me the result with previous and following line

I’m using Node JS, I want to search for a keyword in multiple .txt files, and then that return me the previous line and the following one.

Im expecting something like this:

Cars
Scooters
Skates
Airplanes
Ships
Trucks
Bikes

Then I search for the word using some nodejs package, in this example is ship. So the package return to me the line that is upper and down. For example something like this:

{"result":"
Airplanes
Ships
Trucks
"}