Issue with filtering Charts on Button click – Web app GAS

I am trying to Build a chart in Web App – GAS. I have Dropdown

Dropdown List values are – All, North, South. By default when page loads I need to render the chart with “All” Values. On selection of dropdown and button click, the chart has to filtered.

I am getting the error “Cannot read properties of undefined (reading ‘length’)” With this error I could not move forward, I got stuck here.

Is this because of getRange in my GAS script, which is an 2D array. Help me out with the solutions.

My Sample data from Google Sheets looks like

enter image description here

Here is what I am trying

My GAS Code:

function draw_linechart(){
  var ss = SpreadsheetApp.openById('XXXXXXXXXXXXXXX');
  var metrics_sheet = ss.getSheetByName('test_chart');

  var c_data= metrics_sheet.getRange("A1:B").getValues();
  var c_data1 = JSON.stringify(c_data);   
  return c_data1;
}

My HTML Code

<!DOCTYPE html>
<?!= HtmlService.createHtmlOutputFromFile('p_style').getContent();?>
<html>  
  <head>
    <base target="_top">    
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">   
    
      google.charts.load('current',{'packages':['corechart']});
      google.charts.setOnLoadCallback(drawchart);

      function drawchart(){
        window.alert('Inside Draw Chart func');
        google.script.run.withSuccessHandler(displaychart).draw_linechart();
      }

      function displaychart(c_data1){

        var chartdata =  new google.visualization.arrayToDataTable(JSON.parse(c_data1));
        console.log(chartdata);        

      //Setting Chart Options

      var options={
        title: 'Checking the Charts',
        is3D: true
      }

      // Draw our chart passing some options
      var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
      chart.draw(chartdata,options);
      }
      </script>
  </head>
<body>
<?var url =getUrl(); ?>    
<form method="post" action="<?= url ?>" >
<div class="filter_container">
      <br><br>
      <div class="box1">      
        <label class="label_"> DGraph </label> <br>
        <select name="s_d" id="dg" class="cselect">
        <option style="color:#D3D3D3" value="All"  selected disabled hidden > Choose </option>
        <? for(var i=0; i< dg.length;i++){ ?>
        <option value="<?= dg[i] ?>" ><?= dg[i] ?></option>
        <? } ?>
        </select><br><br>
      </div>
<button id ="btn" type="button">Click!</button>
</div>
<div id ="line_chart"><div>
</form>
</body>
</html>

Many Thanks in Advance.!!

Manually clearing out Pyscript from Browser Memory

I’m working on a project that uses PyScript in a pop-up window to load a large amount of data and libraries, which causes the browser’s memory usage to increase significantly to around 4 GB. Even after closing the pop-up, the memory usage remains at 4 GB, whereas it was only about 900 MB before loading PyScript.

Is there a way to manually clear PyScript from the browser’s memory once the pop-up is closed?

Thanks!

  1. I attempted to manually clear PyScript from the memory by removing script elements from the DOM and using JavaScript functions to clear variables and perform garbage collection.

  2. I also tried using various methods to unload or destroy the PyScript environment and any associated Pyodide instances, but none of these approaches seem to free up the memory.

  3. Additionally, I searched for documentation or methods that would allow me to manually close the PyScript session or unload it from memory but didn’t find a direct solution.

App.js file not being created inside project foldeer using Expo

I’m a newbie to React Native and am using this tutorial to learn it. I used Expo to set up my project folder to develop an Android application. The tutorial, at 19:39, instructs you to edit the App.js file. No such file exists in the project folder I set up.

I found this, which notes that apparently App.js has been “replaced with _layout.tsx, but also index.tsx to some degree”.

Where am I supposed to edit the code which is equivalent to writing it in App.js as in the tutorial, though? The following is a screenshot of my project folder:

Screenshot of project root in VSCode

Use retry kind of mechanism to reuse the token generation API from a third party service

I have to use a third party API for eg A, this A have some payload and it gives output as a authToken. This authToken when used in another API for eg B as payload header to fetch some details.
The B api which uses the token fetches the details upto when the token is not expired. After some time the B API gives response as Token expired, so when this happens, will have to again call the A API to give the new token and then use this new token in B and call it. I have node typescript code base.

Using request module of npm to first place a call to A then get the response, use that in B and after B gives the response check it if its expired again call both the APIs, A and B. But i am not sure as this is not looking a good approach to go with. IS there any other way to get this done?

Is it possible to add CSS to an embed code?

We are using TypeForm’s embed code to add a question flow to our website.

<div data-tf-live="FORMCODE"></div>
<script src="//embed.typeform.com/next/embed.js"></script>

The issue is when you get to the end and try to book a call using the embedded Calendly integration, a massive cookie popup comes up. We can’t use the Calendly hide cookie popup options because it’s via an integration with TypeForm. This is a mobile only issue for us.

go.automaters.com/application1725123778005

They have Embed SDK options but not sure how to build that code profile.

<style>
div#onetrust-banner-sdk {display: none!important;}
#onetrust-banner-sdk {display: none!important;}
.otPcPanel { display:none; }
</style>

Seems like this code should work but it doesn’t apply to the embed. We can use iFrame if necessary but not sure how to make it all work together.

Anybody ever ran into this and have a solution?

Thank you.

enter image description here

Deployment application

I have a problem with deploying a web application that I created with React.js. When I deploy the application on Netlify I get the error message “Page not found”:

Error

I created the _redirects file in the public folder with this code to configure the application, but I still get the same error :

/* /index.html 200

I created the _redirects file to configure the application with the code to fix this problem, but it doesn’t work.

I expect you to help me solve this problem, because I still can’t solve this error and I don’t have more solutions to fix this problem.

Show Item based on the pathName in NextJs Server Component

I have a layout in which I have two Detail Pages One is User and another is Company and In this two I need to highlight user or company based on the page they are in I have urls as below

  • /user/details
  • /company/details

Now I need to highlight the tab based on the page they are in

/user/details –> High Light the User Tab

/company/details –>High Light the company Tab

import { useTranslation } from '@/app/i18n'
import { fallbackLng, languages } from '@/app/i18n/settings'
import { headers } from 'next/headers'
import Image from 'next/image'
import Link from 'next/link'
import { Trans } from 'react-i18next/TransWithoutContext'

const Layout = async ({
  children,
  params: { lng },
}: {
  children: React.ReactNode
  params: {
    lng: string
  }
}) => {
  if (languages.indexOf(lng) < 0) lng = fallbackLng
  const { t } = await useTranslation(lng)
  let isUserTab = false

  if (headers().get('referer')?.includes('user')) {
    isUserTab = true
  }

  return (
    <div className="fixed top-0 left-0 w-screen h-screen z-1000">
      <div className=" flex  items-center justify-center w-full h-full bg-red-500 absolute z-1000 ">
        <div className=" flex  bg-[rgb(255,255,255)] items-center justify-center">
          <div className=" flex flex-col bg-[white] w-[500px] items-center justify-center">
            <Image
              src="/assets/Icons/test.svg"
              width={100}
              height={72}
              alt="test"
            />
            <p>
              <Trans t={t} i18nKey="Welcome">
                Welcome
              </Trans>
            </p>
            <p>
              <Trans t={t} i18nKey="Details">
                Details
              </Trans>
            </p>
            <div className=" flex flex-row gap-[10px] ">
              <Link href="/user/details">
                <p className={`${isUserTab ? 'bg-[green]' : ''} min-w-[100px]`}>
                  <Trans t={t} i18nKey="USER">
                    USER
                  </Trans>
                </p>
              </Link>
              <p className={`${!isUserTab ? 'bg-[green]' : ''} min-w-[100px]`}>
                <Link href="/company/details">
                  <Trans t={t} i18nKey="COMPANY">
                    COMPANY
                  </Trans>
                </Link>
              </p>
            </div>
            <div>{children}</div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Layout

I know how to do it in client side but Is there any way to achieve it by using ssr I’m missing something important any help is appreciated.

Google Cloud Function 403 Error After Adding Permissions

I am working on refactoring my backend to use Google Cloud Functions. I have deployed a function and am trying to test it from my localhost.

I am getting a 403 error. I followed the steps here to allow public access but I still get a 403 403 Response from Google Cloud Functions

The function does require header credentials which I believe I am passing in properly:

        const response = await axios.post(
          `${process.env.REACT_APP_API_URL}/function-1`,
          { idToken },
          {
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            withCredentials: true,
          }
        );

I can’t find any other resources to debug a 403 other than those detailing how to add the public invoker permission.

My cloud function looks like:

import firebase_admin
from firebase_admin import credentials, auth, exceptions
from firebase_admin import storage
from firebase_admin import firestore
from google.cloud.firestore import FieldFilter

from fastapi import FastAPI, Request, HTTPException, APIRouter

# @app.post('/session_login')
async def session_login(request: Request):
    data = await request.json()
    id_token = data['idToken']

    try:
        decoded_claims = auth.verify_id_token(id_token)
        if time.time() - decoded_claims['exp'] < 5 * 60:
            expires_in = timedelta(days=10)
            session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in)
            email = decoded_claims['email']
            uid = decoded_claims['uid']
            
            # Get a reference to the Firestore database
            db = firestore.client()
            
            # Query the user document by user_id
            user_ref = db.collection("customers").where(filter=FieldFilter("user_id", "==", uid))
            user_docs = user_ref.get()

            if user_docs:
                user_doc = user_docs[0]
                user_data = user_doc.to_dict()
            else:
                # If user document doesn't exist, create it with initial credits
                new_user_data = {
                    'email': email,
                    'user_id': uid,
                    'credits': 50,
                    'current_subscription_tier': 'Free'
                }
                db.collection("customers").add(new_user_data)
                user_data = new_user_data

            response = JSONResponse({'status': 'success', 'user_data': user_data})
            response.set_cookie(
                'session', session_cookie, expires=expires_in, max_age=10*24*60*60, path="/", samesite='None', secure=True, httponly=True)
            return response
        else:
            raise HTTPException(status_code=401, detail='Recent sign in required')
    except auth.InvalidIdTokenError:
        raise HTTPException(status_code=401, detail='Invalid ID token')
    except exceptions.FirebaseError:
        raise HTTPException(status_code=401, detail='Failed to create a session cookie')

how to point to sun and moon in cesiumjs?

CesiumJS does properly simulatr both Sun and Moon positions in realtime, but for some reasons they are apparently not directly accessible: Moon object is just an ellipsoid, placed “somewhere”.

  • How to know the cartesian coordinates of this somewhere?
  • How to look at this point?
  • How to draw a line from observer to this point?

I tested several sources from stackoverflow and cesium community, but they all sparse, approximate, buggy…

I even found an undocumented lookAtMoon() function in MoonSpec.js file, but I can’t figure out how to access it!

function lookAtMoon(camera, date) {
  const icrfToFixed = new Matrix3();
  if (!defined(Transforms.computeIcrfToFixedMatrix(date, icrfToFixed))) {
    Transforms.computeTemeToPseudoFixedMatrix(date, icrfToFixed);
  }

  const moonPosition = Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame(
    date
  );
  Matrix3.multiplyByVector(icrfToFixed, moonPosition, moonPosition);

  camera.viewBoundingSphere(
    new BoundingSphere(moonPosition, Ellipsoid.MOON.maximumRadius)
  );
}

Javascript, map a object array to return new array

I have been looking online for a solution. Most show you how to map an array but not an object array:

club    = [];

club[0] = {};
club[0].team        = "Manchester United";
club[0].ground  = "Old Trafford";


club[1] = {};
club[1].team        = "Manchester City";
club[1].ground  = "Etihad";

club[2] = {};
club[2].team        = "Liverpool";
club[2].ground  = "Anfield";

I want to product a new array with just the ground object key from the original object. This eventually will include a lot more teams that can be added and deleted thus why I want to map a new array of the ground names.

I should end up with a new array:

search = [‘Old Trafford’, ‘Etihad’, ‘Liverpool’];

I need to map rather that a for/next or for/each.

Thanks.

Read data from excel & update on PSD file via photoshop script option using javascript

Here is the excel sheet format
here is the PSD File Format two texts marked are in two different text layers
here is the PSD File Format two texts marked are in two different text layers

i want to update 2 text layer on my psd file and save as a jpg after collecting the data from a spreadsheet via photoshop scripting using a javascript code.

i want a alert a everytime before it saves a jpg having 2 options ‘edit’ and ‘yes’ and Question of the alert will be Confirm Save as a jpg.

data on the spreadsheet is like this :
Column 1
J5L0001
J5L0002
J5L0003
J5L0004
J5L0005

Column 2
GAUTAMI
DEVAHARINI
KANNAN V
THARUN
SAHASRA
LIYAAN
T.DEVARAJAN
V.ARUNACHALAM

now i want 2 to take a certain row and Update the text layers save as jpg in designated folder

like J5L0002 & DEVAHARINI
here you can see J5L0002 & DEVAHARINI are both on the same row which Row 3 taking Column 1 and Column 2 as a header row

1 jpg should saved in a designated folder by updating these 2 layers J5L0002 & DEVAHARINI after alert.

Please give the edit part of from it will start the automation for ex. i want to start from Row 3 and in the next time i want to start from row 10.

Also give layer mapping code as well as there are several other columns in the spreadsheet which are named differently.

Automation must run Continuously every time i click yes on the Alert and automation should stop if i select edit on the alert. And for the next time i want to start the automation from a different Row thats why i want the portion of selection selecting ROW from where i can start the Automation.

for Renaming the JPG’s give me the code from which column i want i my data to be taken and saving as jpg

Writing Regex for handling optional floating point symbols at start of string?

I’m currently using a regex for detecting valid floating point numbers which looks like this:

/^[0-9]{1,10}(.d{0,3})?$/

I am able to match the following values as expect:

0
0.
0.1
0.12
0.123

I do however need to be able to validate and match the following inputs as these values can be parsed as a Number type in JavaScript.

.1
.12 
.123

I’ve looked at optional first character matching but so far I haven’t been able to come up with a tangible solution. I think the fact that it’s optional makes it tricky to implement

load site from cacheStorage with iframe tag

When offline, you can access cacheStorage using fetch(), etc.

The address entered in the src tag of <iframe> will not be bypassed to cacheStorage and will fail to view the site.

Using fetch() to collect text information from cacheStorage, convert it to a blob, and use URL.createObjectURL() to get the blob address, it works in the <iframe> tag.

However, files such as scripts linked to the html file also fail to load from cacheStorage, causing the page to break.

Any good ideas?

——

How to reproduce the action

this link is the page I’m working on that supports Offline-pwa:

is2you2.github.io/godotchat_pwa

When you enter a page, it stores about 1527 page files in cacheStorage. Once all are stored, it will work normally offline.

To configure the environment that reproduce the action:

1. Second tab at the bottom: In the Channels tab, click the + button to create a channel with any name.

2. Enter the created channel and send a *.blend file. Example *.blend files can be received from this link. (pjcone.ddns.net:9002/cdn/…)

3. When a file is sent to the channel, a gray square box is created. Clicking on the box will open the *.blend file.

4. There are some errors, but the important thing is that it opens. That’s all for the online test.

5. When you change the network status to offline and try to open the file sent to the channel again, it doesn’t open.

When opening a *.blend file, the action is to create an iframe object in JavaScript and open “assets/js.blend/index.html” in src. When fetch() this address, page information is normally received from cacheStorage. However, it is not in the iframe.

Projeto Bingo em ReactJs Dezenas Duplicadas

blz?
Estou estudando ReactJS e estou com um projeto em que o cliente tem um projeto de Bingo online,porém o código que ele me enviou está selecionando dezenas duplicadas(por exemplo o número 21 duas ou mais vezes) como se o usuário pudesse escolher o mesmo número infinitas vezes na mesma cartela;
Alguém poderia me informar onde eu removo ou modifico esta função, para que o número seja único em cada cartela?
Segue o código…
Desde já agradeço…