How to render traffic polyline from Google Maps Routes API in React

I am trying to create a traffic polyline in React through the Google Maps library. I currently have a polyline from the directions API via the below code:

export const renderDirections = async (map, origin, destination) => {
    const directionsService = new google.maps.DirectionsService()
    directionsDisplay = new google.maps.DirectionsRenderer({
        polylineOptions: {
            strokeColor: '#65a30d',
            strokeOpacity: 1,
            strokeWeight: 6,
        },
        suppressMarkers: true,
    })
    const routePolyline = await directionsService.route({
        origin: origin,
        destination: destination,
        travelMode: google.maps.TravelMode.DRIVING,
    })
    directionsDisplay.setMap(map)
    directionsDisplay.setDirections(routePolyline)
}

The objective is to color-code the polyline based on the traffic conditions, as done in the demo Routes API tool on the Google Maps API documentation:

https://developers.google.com/maps/documentation/routes/demo

However, I do not see any option to enable routingPreference: "TRAFFIC_AWARE" as there’s an error that the property does not exist in type DirectionsRequest

My next approach was creating a POST request to the API using the connection (in Postman):

https://routes.googleapis.com/directions/v2:computeRoutes?key=APIKEY (with the API Key)

Request body:

{
    "origin": {
        "location": {
            "latLng": {
                "latitude": 37.419734,
                "longitude": -122.0827784
            }
        }
    },
    "destination": {
        "location": {
            "latLng": {
                "latitude": 37.417670,
                "longitude": -122.079595
            }
        }
    },
    "travelMode": "DRIVE",
    "routingPreference": "TRAFFIC_AWARE",
    "departureTime": "2023-10-15T15:01:23.045123456Z",
    "computeAlternativeRoutes": false,
    "routeModifiers": {
        "avoidTolls": false,
        "avoidHighways": false,
        "avoidFerries": false
    },
    "languageCode": "en-US",
    "units": "IMPERIAL",

}

However, this fails with FieldMask is a required parameter. See https://cloud.google.com/apis/docs/system-parameters on how to provide it. As an example, you can set the header 'X-Goog-FieldMask' to value 'routes.distanceMeters,routes.duration,routes.polyline.encodedPolyline' to ask for the route distance, duration, and polyline in the response

and the documentation is unclear how to address this issue. I appreciate any help on computing a traffic-aware polyline in React or Javascript and how to render it onto a map

Thanks in advance!

TypeScript: How do I get get rid of TS2322 error when assigning object values in a loop?

TS2322: Type ‘string | undefined’ is not assignable to type ‘”top” |
“center” | undefined’.   Type ‘string’ is not assignable to type
‘”top” | “center” | undefined’.

Code:

export type AlertType = 'success' | 'exclamatory' | 'danger' | 'warning' | 'info';

interface RenderProps {
  title?: string;
  content?: string;
  type?: AlertType | string;
}

const defaultProps: RenderProps = {
  title: '',
  content: '',
  type: 'success',
}

const getProps = ( props: RenderProps ): RenderProps => {
  const _props: RenderProps = {};
  for ( let prop in defaultProps ) {
    const _prop = prop as keyof RenderProps;
    _props[ _prop ] = typeof props[_prop] !== 'undefined' ? props[_prop] : defaultProps[_prop];
  }
  return _props;
}

enter image description here

I want the text chase the curser like train

please take a look at this website:
http://alexandercoggin.com/

and see how the curser drags the text. I want to implement exact the same effect. here I have tried to use the paper.js library to do so but the result is not like what I want. Can anyone help me to write the code snippet please; There is no limitation in using any other library at all.

    <!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/paper"></script>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        #myCanvas {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .custom-cursor {
            position: absolute;
            top: -3px;
            left: -3px;
            width: 7px;
            height: 7px;
            border: 2px solid black; /* Customize the cursor border color */
            border-radius: 50%;
            background-color: transparent; /* Make the cursor transparent */
            pointer-events: none;
            z-index: 9999;
        }
    </style>
</head>
<body>
    <div class="custom-cursor"></div>
    <canvas id="myCanvas"></canvas>

    <script>
        // Setup Paper.js
        paper.setup('myCanvas');

        var word = 'Hello, World!';
        var characters = [];

        var offsetX = 0;
        var offsetY = 0;
        var characterSpacing = 20;
        var chasingSpeed = 0.9;
        var delayIncrement = 100;

        for (var i = 0; i < word.length; i++) {
            var character = new paper.PointText({
                content: word[i],
                fillColor: 'black',
                fontFamily: 'Arial, sans-serif',
                fontWeight: 'bold',
                fontSize: 24,
                justification: 'center'
            });

            character.targetPosition = new paper.Point(0, 0);
            character.position = new paper.Point(0, 0);
            character.delay = i * delayIncrement;

            characters.push(character);
        }

        function onMouseMove(event) {
            var mousePosition = event.point;
            var cursor = document.querySelector('.custom-cursor');

            cursor.style.top = mousePosition.y - cursor.offsetHeight / 2 + 'px';
            cursor.style.left = mousePosition.x - cursor.offsetWidth / 2 + 'px';

            // for (var i = 0; i < characters.length; i++) {
            //     var character = characters[i];
            //     var targetPosition = mousePosition.add(new paper.Point(i * characterSpacing + 20, 0));

            //     setTimeout(function(char, targetPos) {
            //         char.targetPosition = targetPos;
            //     }, character.delay, character, targetPosition);
            // }

            var wordLength = word.length;
var totalWidth = wordLength * characterSpacing;
var angleIncrement = Math.PI * 2 / totalWidth;
var initialAngle = Math.atan2(mousePosition.y, mousePosition.x) - Math.PI / 2;

for (var i = 0; i < characters.length; i++) {
    var character = characters[i];

    var angle = initialAngle + angleIncrement * i;
    var radius = totalWidth / (2 * Math.PI);
    var targetX = mousePosition.x + Math.cos(angle) * radius;
    var targetY = mousePosition.y + Math.sin(angle) * radius;

    setTimeout(function(char, posX, posY) {
        char.targetPosition = new paper.Point(posX, posY);
    }, character.delay, character, targetX, targetY);
}

            
        }

        function onFrame(event) {
            for (var i = 0; i < characters.length; i++) {
                var character = characters[i];
                var distance = character.targetPosition.subtract(character.position);
                character.position = character.position.add(distance.multiply(chasingSpeed));
            }
        }

        paper.view.onMouseMove = onMouseMove;
        paper.view.onFrame = onFrame;

        paper.view.onResize = function(event) {
            paper.view.viewSize = new paper.Size(window.innerWidth, window.innerHeight);
        }

        paper.view.draw();
    </script>
</body>
</html>

Is there any chance to get calendar events of other person using app script if their calender is private?

I am working in a company, I want to access the calendar events of other employees with app script. but I am getting null as there events are private. However I am able to access my own calendar events even if they are private. How can I access my other employees calendar events. I want to send an email with feedback form for all of their events.

this is the code I am using for getting calendar events of specific email. it is giving events if I provide my email but giving null If I provide same domain email of other employee. please help me if you have any thoughts or suggestions.

function getAllCalendarEvents() {
  // Get the OAuth client ID and client secret from script properties
  var clientId = PropertiesService.getScriptProperties().getProperty('clientId');
  var clientSecret = PropertiesService.getScriptProperties().getProperty('clientSecret');

  // Authorize and set up the Calendar service
  var service = getService(clientId, clientSecret);
  var calendar = CalendarApp.getCalendarById('[email protected]');

  // Retrieve all events from the calendar
  var events = calendar.getEvents(new Date('2000-01-01'), new Date('2100-12-31'));

  // Process the events
  for (var i = 0; i < events.length; i++) {
      var event = events[i];
    // Access the event properties
    var title = event.getTitle();
    var startTime = event.getStartTime();


    var endTime = event.getEndTime();
    // Perform further processing as needed
    Logger.log('Event: ' + title + ' (' + startTime + ' - ' + endTime + ')');
  }
}

React Hook “useSWR” is called conditionally. React Hooks must be called in the exact same order in every component render

My page receives parameters from the previous page and uses useSWR to fetch the data base on the parameters:

export default function Model() {
    const searchParams = useSearchParams();
    const selectedMatch = searchParams.get("data")
    if (selectedMatch == "") {
        return <p>no data is found</p>}
    const { data, error, isLoading } = useSWR(["api/model", selectedMatch], fetcher)
    return (...)
}

It seems that react hooks useSWR must be on top of the component before any return and condition, however, I want to handle the empty case of selectedMatch before passing to useSWR, how can I do it?

S3 upload progress not working properly, only one time the upload progress shows in mern

This is my nodejs code, after the file upload only one time progress get logging as 100% , not logging continues

exports.uploadFile2 = async (req, res) => {
  try {
    const file = req.files.file;

    const fileName = file.name;
    const parts = fileName.split(".");
    const extension = parts[parts.length - 1];

    const params = {
      Bucket: "buckname",
      Key: `${uuidv4()}.${extension}`,
      Body: file.data,
      ACL: "public-read",
      ContentEncoding: "7bit",
      ContentType: file.mimetype,
    };

    s3.upload(params, (err, data) => {
      if (err) {
        console.log(err);
      }
      console.log(data.Location);

      res.json(data);
    }).on("httpUploadProgress", (p) => {
      console.log(p);
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({
      error: "No User Found",
    });
  }
};

This is my react code

import axios from "axios";
import React from "react";
import { fileUploadFunction } from "../function/fileUpload";
import { useSelector } from "react-redux";
import { useRouter } from "next/router";

const index = () => {
  const { auth } = useSelector((state) => ({ ...state }));

  const router = useRouter();

  const handleUploadFile = async (e) => {
    if (auth.token) {
      try {
        const file = e.target.files[0];
        const formData = new FormData();
        formData.append("file", file);
        const { data } = await axios.post(
          `http://localhost:5000/api/uploadFile2`,
          formData,
          {
            headers: {
              authtoken: auth && auth.token,
            },
            onUploadProgress: (e) => {
              const { loaded, total } = e;
              console.log(Math.round((100 * loaded) / total));
            },
          }
        );
        // if (data) router.push(`chat/${data}`);
      } catch (error) {
        console.log(error);
      }
    }
  };
  return (
    <div>
      <h1>Upload file</h1>
      <input type="file" onChange={handleUploadFile} />
    </div>
  );
};

export default index;

In my react code , only it shows 100% ,not starting from 0 to 100, the progress is not getting continuously .

How to get progress continuesly from 0 to 100, i checked many docs, but they are providing the code , what i have.

Please help me to solve this, I am looking for a days

Grapesjs – issue with Storage manager “type: ‘remote'”

I am using Grapesjs version 0.16.45 and the following is my storage manager

Storage manager

const storageManager = useMemo(() => ({
        type: "remote",
        fromElement: false,
        id: "gjs-",
        contentTypeJson: true,
        urlStore: storeTemplate,
        headers: { ... } ,
    }), []);

See I run my react app in 3000 and server app in 8080 when type: 'remote' a request is sent to the current client URL.

In my case, a GET request is sent to http://localhost:3000/editor/update/Znfqkl6Ho (which is my current URL where I am using editor) and the response is 304

Other than this everything is working fine. My urlStore is getting called as expected and the template is updated in the DB.

What is the issue here?

When i changed the type to local its working fine because no request will go at all. other than that i couldn’t figure out the problem.

React Native Giphy Clipboard Not Animated

I’ve somehow successfully gotten a Giphy url to copy into the Clipboard first time I tried (lucky me) but when I paste it to Notes it just shows a still image…is there a way to get it to animate (iMessage) like other apps do on paste?

I’m just downloading the Giphy URL, loading the file in base64 and then paste to clipboard using Expo Clipboard

const source = await ReactNativeBlobUtil.config({
  fileCache: true,
}).fetch('GET', item.body?.media?.url);

const local = await source.path();

const base64 = await RNFS.readFile(local, 'base64');

await Clipboard.setImageAsync(base64);

I know this is a minimal code example, but I’m sort of just hoping someone who knows what this is can just answer the question 🙂

There is something with iOS here but I don’t have direct access:

Copy GIF to UIPasteboard

Automatic check the checkbox when I Filled Out : App Script Gsheet

I create my own project own gsheet where is I want to create a Event in checkbox to automatically check if I choose one which is the NON COD its automatically check if i choose COD it wont uncheck the checkbox .

function checkBoxes() {

  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DATA ENTRY');
  var range1 = ss.getRange('J2:J998');
  var range2 = ss.getRange('K2:K998');
  var values = range1.getValues();
  

  const numRows = range2.getNumRows();
  const numCols = range2.getNumColumns();
  
  

  for(let i = 1; i <=numRows; i++){
    for(let j = 1; j <= numCols; j++){
      let checkbox = range2.getCell(i,j);
      let tfValue = values[i-1][j-1];
      if(tfValue == "COD"){
        checkbox.uncheck();

      }
      else if (tfValue == "NON COD"){
        checkbox.check();
        
      }
    }

Im using for loop , but the problem its delay trigger the event , I want upon entry when I choose NON COD .

Adding files to hostgator site directory

So guys, I need help.

Basically I’ve created a site using the Word Press plugin inside Hostgator. So far so good.

There is a page in my site that has a form so the users can submit their names and emails so they are able to download a free ebook. Since I`m using elementor for WordPress and the form widget is only available with elementor pro, I’ve inserted the form using the HTML widget, with a js script inside the HTML to handle the data and send them to a realtime database on firebase.

The point is, to send the data to firebase, I need to initialize the firebase app using my project config object inside the js script, which contains my API, and that should not be available to anyone who simply try to inspect the code through chrome tools, for example.

A workaround would be to put the firebase project config object in a separate locked file inside the site directory so I can simply import it whithin my script inside the HTML widget and initialize the firebase app with the project config, without exposing my API and project config object to everyone.

So, is there a way to do this? Sorry if I did not make myself clear!

Download svg created by d3js as svg file with another svg in it

I created a download function for my svg graph, it successfully download the svg file, but there is another svg icon in the svg tag disappear.

enter image description here

document.querySelector(".download").addEventListener("click", () => {
  const svgElement = document.querySelector("svg");
  const svgString = new XMLSerializer().serializeToString(svgElement);
  const blob = new Blob([svgString], {
    type: "image/svg+xml;charset=utf-8"
  });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "my_svg_file.svg";
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(url);
});
<div>
  <svg width="300" height="200">
            <rect stroke="black" x="20" y="50" width="200" height="100" fill="navy"></rect>
            <rect stroke="black" x="200" y="0" width="50" height="200" fill="brown"></rect>
            <clipPath id="icon-4-29">
                <rect class="icon" width="26.095396561286744" height="26.09539656128674" x="0" y="0"></rect>
            </clipPath>
            <image xlink:href="https://expo.taiwan-healthcare.org//data/tmp/20230413/202304131zc6g3.svg" visibility="visible" clip-path="url(#icon-4-29)" width="26.095396561286744" height="26.09539656128674" x="0" y="0"></image>
        </svg>
</div>

<button class="download">download</button>

I tried to copy the path from svg icon, change the number in the path to get the size I expect, paste it to svg tag then download it.

But it will change the curve setting (ex: A4.61,4.61,0,0,1,.59,37.34) and mass the shape.

const svg1 = `
<path d="M42.39,42H5.2A4.61,4.61,0,0,1,.59,37.34V5.57A4.61,4.61,0,0,1,5.2,1H42.39A4.6,4.6,0,0,1,47,5.57V37.34A4.6,4.6,0,0,1,42.39,42"/>
<path d="M23.58,14.69c1.9-1.91,3.83-3.77,5.67-5.71a6.79,6.79,0,0,1,5.12-2.17c2.13,0,4.27,0,6.39,0a5.76,5.76,0,0,1,5.54,4.78c.38,3.07-1.41,6.06-4.22,6.64a18.62,18.62,0,0,1-4.42.12A3.32,3.32,0,0,0,35,19.47C29.43,25.06,23.83,30.6,18.26,36.18a7,7,0,0,1-5.37,2.22c-2,0-3.89,0-5.84,0a5.94,5.94,0,0,1-5.7-5.82,5.77,5.77,0,0,1,5.54-5.81c1.2,0,2.41.05,3.61,0A2.49,2.49,0,0,0,12,26.13c1.68-1.59,3.31-3.23,4.91-4.91A2,2,0,0,0,17.39,20c.05-2.22,0-4.45,0-6.67s1.71-3.68,3.74-3.18a2.73,2.73,0,0,1,2.2,2.73c0,.57,0,1.15,0,1.73l.2.13M10.29,35.43c.77,0,1.55,0,2.32,0a4.79,4.79,0,0,0,3.95-1.61C22.12,28.19,27.78,22.61,33.36,17a4.67,4.67,0,0,1,3.77-1.58c1.11.06,2.22,0,3.34,0a2.76,2.76,0,0,0,2.88-2.92,2.84,2.84,0,0,0-2.9-2.72c-2,0-4,0-6,0a4,4,0,0,0-3.12,1.31c-5.8,5.86-11.65,11.67-17.47,17.51a3.92,3.92,0,0,1-3,1.24c-1.2,0-2.41,0-3.61,0-1.82,0-2.89,1-2.89,2.65a2.86,2.86,0,0,0,2.87,3c1,0,2,0,3.06,0"/>
<path d="M20.48,3.53a3.09,3.09,0,0,1,3,3.08,3,3,0,0,1-3.11,3,3,3,0,0,1-2.91-3.09,3.12,3.12,0,0,1,3.06-3"/>
<path d="M31.58,35.13c1.86-1.86,3.52-3.51,5.16-5.16.24-.24.49-.47.72-.73a1.45,1.45,0,0,0,.08-2.13,1.41,1.41,0,0,0-2.06.17c-1.67,1.64-3.32,3.31-5,5a8.63,8.63,0,0,0-.62.81l-.32-.13c0-.9,0-1.8,0-2.69s-.45-1.43-1.29-1.45a1.22,1.22,0,0,0-1.39,1.27c0,2.1-.05,4.2,0,6.29a1.4,1.4,0,0,0,1.54,1.5c2.06,0,4.13,0,6.19,0a1.24,1.24,0,0,0,1.32-1.35,1.29,1.29,0,0,0-1.4-1.38c-.89,0-1.78,0-3,0"/>
`;

const multipliedSvg = svg1.replace(/(d+.d+|d+)/g, (match) => parseFloat(match) * 10);

Is there any way to download the svg with <image> in it?

retrieve id and data and then build dropdown

I have the following data I’m receiving from the service. The following console logs prints the following in browser:

console.log("Inside data");
console.log(data);

Inside data 
[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]

If I want to build a options tag using jQuery, is it easy to extract the id as 1,3 and 4 and name for the value parameter of options tag and build a select dropdown?

For example, if I’ve the following code and if I want to work it like it is showing now.

var data = "[[id=1, name=BOTTLE-1], [id=2, name=BOTTLE-2], [id=4, name=BOTTLE-3]]";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars">
<option  value="-">"Please Select"</option>
<option id = "1" value="BOTTLE-1">BOTTLE-1</option>
  <option id = "3" value="BOTTLE-2">BOTTLE-2</option>
  <option id="4" value="BOTTLE-3">BOTTLE-3</option>
</select>

Building part using append method should be easy but I am wondering if it’s easy to extract the required values

Nested el-popover in el-table, the popover does not appear on the second click

In the table, there is a column showing the order number, if the data does not have the order number, display the icon, click on it to display an input pop-up box. If there is an order number in the data it displays the order number, and also clicking on the order number brings up the input popup. I used the el-popover component of element-ui (version 2.15.6).
enter image description here
The code implementation is as follows
enter image description here
But there is a problem, when there is no order number in a row of data, the icon appears, I click the icon to fill in the order number, then the page shows the order number on this row, under normal circumstances, then click the order number that is shown, the popover popup box should appear. But after clicking on it, no popover box appears, there is no interaction on the page, only click on the browser refresh after clicking to come out with the popover popover box. Why is this?

When I change the v-if to v-show, the popover icon does not pop up at all, not even the first time.