VARIABLE VALUE FECTH FROM GOOGLE SHEET CELL VALUE (GOOGLE APPS SCRIPTS) (JAVASCRIPT)

Good afternoon everyone, I was hoping to see if someone can help me with this question. I have a code that detects if an input has been filled with the correct data (for example: user name), validating it from the value of a variable. I wanted to see if there is a possibility that instead of validating the value from a variable, that value could be validated from a google sheet. Or see if the value of the variable, instead of setting it directly in the code, can be read from a google sheet. Hope there is a way, preferably using only Javascript. I am attaching a copy of the HTML and GS code and an image of a google sheet (pic 1), where the value to be validated is located.
In this example, if the name “JHON” is captured in the input, a “correct” message will be displayed, if a different value is entered, the “incorrect” message will be displayed. The data to be validated is found in the value of a variable (var value_name = “JHON”), which is entered directly in the variable (pic 2), but I need the data to be validated from the google sheet. Hope there is a way, thanks in advance.

HTML

<!DOCTYPE html>
<html>
<head>
    <base target="_top">
</head>
    <br>   
    NAME:<br>
    <input type="text" id="name">

    <script>
     var user_name = "JHON"
    </script>       
  
    <script>
function checkUser() {
    if (document.getElementById("name").value == user_name) {
         alert ("correct");
    }
        else {
        alert ("incorrect");
    }
    }
    </script>  

   <input type='button' value='VALIDATE' onclick="checkUser()" >

</html> 

GS
(function “fetchUserValues1()”, is the function a think is need to fecth the value from GoogleSheets, but cant get it to work)

 function doGet() {
  var template = HtmlService.createTemplateFromFile("HTML_start_page")
  return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
  return HtmlService.createHtmlOutputFromFile('HTML_start_page');
}


function fetchUserValues1(){
    var ss = SpreadsheetApp.openByUrl("GoogleSheet URL"); 
     var sheetNames = ss.getSheetByName("Sheet 1"); 
  var user_name  =  sheetNames .getRange("A2").getValue();
    return user_name;
}

enter image description here

Style individual features based on their geojson properties + Leaflet.Markercluster

I’ve been stuck for days trying to get this to work. I have a function to display geojson points based on their properties (i.e. “Type”). However, I cannot manage to cluster them and at the same time preserve their custom icons.

I’m able to cluster in general by making some adjustments and leaving out the function geojsonType(). That’s not what I’m after, though. I’m caught in a vicious circle.

Thanks to this post I can display the points based on their properties.

// create function for pointToLayer when loading geojson
 function geojsonType(feature, latlng) {
            switch (feature.properties["Type"]) {
                case "bar":
                    var barIcon = new L.icon({
                        iconUrl: 'images/pub.png', //assign PNG
                        iconSize: [42, 50], // size of the icon
                        iconAnchor: [22, 22], // point of the icon which will correspond to marker's location
                        popupAnchor: [-3, -26] // point from which the popup should open relative to the iconAnchor    
                    });
                    return L.marker(latlng, { icon: barIcon });

                case "recordclothingstore":
                    var venueIcon = new L.icon({
                        iconUrl: 'images/venue.png', //assign PNG
                        iconSize: [42, 50], // size of the icon
                        iconAnchor: [22, 22], // point of the icon which will correspond to marker's location
                        popupAnchor: [-3, -26] // point from which the popup should open relative to the iconAnchor    
                    });
                    return L.marker(latlng, { icon: storeIcon });

                case "venueandbar":
                    var venueandbarIcon = new L.icon({
                        iconUrl: 'images/pub.png', //assign PNG
                        iconSize: [42, 50], // size of the icon
                        iconAnchor: [22, 22], // point of the icon which will correspond to marker's location
                        popupAnchor: [-3, -26] // point from which the popup should open relative to the iconAnchor    
                    });
                    return L.marker(latlng, { icon: venueandbarIcon });
            }
        };
        // get geojson
        var url = "points.geojson";
        $.getJSON(url, function (data) {
            pointData.addData(data);
        });
        // load geojson
        var pointData = L.geoJson(null, {
            pointToLayer: geojsonType,
            onEachFeature: function (feature, layer) {
                layer.bindPopup("<a href='" + feature.properties.Website + "'>" + feature.properties.Name + "</a>" + "<br>" + feature.properties.Address + "<br>" + feature.properties.Descriptio);
            }
        });

However, the following bit of code when added to the bottom has no effect. There are no errors in the console either.

    var clusters = L.markerClusterGroup({
        spiderfyOnMaxZoom: true,
        showCoverageOnHover: false,
        zoomToBoundsOnClick: true
    });
    clusters.addLayer(pointData);
    map.addLayer(clusters);

React Query UseQuery not returning async api calls NextJS

I am trying to return an array of data that returns the firebase data that I fetched and the API call to return data. I already have two useQuery hooks and the one that only returns the firebase documents works fine. On my second useQuery hook, it doesn’t return the price when I render the data, but the function is being called and it console.logs all the correct prices. I tried a similar version transferring the code to onSettled, but that returns a similar issue. I created two versions of the second useQuery hook, one with Promise.all, and another without promises completely. They both return nothing.

No Promise

  const fetchListDocs = async () => {
    try {
      const queryCollection = query(collection(db, loc));
      const snapshot = await getDocs(queryCollection);
    //   let arr = [];
      let retArr = []
      let newRetMap = new Map();
      snapshot.forEach(async (doc) => {
        const docTicker = doc.data().stockTicker
        // console.log(doc.data())
        // arr.push(doc.data());
        if (newRetMap.has(docTicker)) {
            //averaging price code here
        } else {
            const newPrice = await getStockPrice(docTicker).then((result) => result);
            const currentPrice = parseFloat(newPrice.toFixed(2));
            newRetMap.set(docTicker, currentPrice)
            retArr.push(currentPrice)
        }
      });
      console.log(retArr)
    //   newRetMap.entries((value) => {
    //     retArr.push(value)
    //   })

      return retArr;
    } catch (error) {
      console.log(error);
    }
  };

  const { data: listDocs, status } = useQuery({
    queryKey: ["firestoreListDocuments", db],
    queryFn: () => fetchListDocs(),
    onSettled: (dataCollection) => {

        return dataCollection

    }
  });

With Promise

const fetchListDocs = async () => {
    try {
      const queryCollection = query(collection(db, loc));
      const snapshot = await getDocs(queryCollection);
    //   let arr = [];
      let retArr = []
      let newRetMap = new Map();
      snapshot.forEach(async (doc) => {
        const docTicker = doc.data().stockTicker
        // console.log(doc.data())
        // arr.push(doc.data());
        if (newRetMap.has(docTicker)) {
            //averaging price code here
        } else {
            let newPrice = await getStockPrice(docTicker).then((result) => result);
            newPrice = Promise.resolve(newPrice)
            console.log(newPrice)
            const currentPrice = parseFloat(newPrice);
            
            newRetMap.set(docTicker, currentPrice)
            retArr.push(currentPrice)
        }
      });
      console.log(retArr)
    //   newRetMap.entries((value) => {
    //     retArr.push(value)
    //   })

      return Promise.all(retArr);
    } catch (error) {
      console.log(error);
    }
  };

I would appreciate any and all help. Please let me know if there are any questions.

Images will not display on PointAnnotations – React Native MapboxGL

I’m transitioning over from react-native-maps to rnmapbox but am having issues getting any images to display on markers. I’m rendering an image marker and an additional badge for some markers. This issue only occurs when using an image, CSS markers work fine.

The image on the left is the expected result from when I was using React Native Maps, and the image on the right is the result with MapboxGL.


Here is a snippet of my code below:

<MapboxGL.PointAnnotation
  key={"vehicle-" + vehicle._id}
  id={"vehicle-" + vehicle._id}
  coordinate={[vehicle.longitude, vehicle.latitude]}
  anchor={
    vehicle.status !== "riding" &&
    vehicle.status !== "adminCollected" &&
    vehicle.status !== "warehoused"
      ? { x: 0.5, y: 1 }
      : { x: 0.5, y: 0.5 }
  }
  onSelected={() => centerOnMarker(vehicle)}
>
  <View style={{ height: 75, width: 75 }}> {/* sized used for testing */}
    {vehicle.status === "available" ? (
      vehicle.batteryPercentage > 65 ? (
        <Image
          source={require("../../assets/scooter-pins/green-full.png")}
          style={{ height: 54, width: 43.5 }}
        />
      ) : vehicle.batteryPercentage > 30 && vehicle.batteryPercentage < 66 ? (
        <Image
          source={require("../../assets/scooter-pins/green-medium.png")}
          style={{ height: 54, width: 43.5 }}
        />
      ) : (
        <Image
          source={require("../../assets/scooter-pins/green-low.png")}
          style={{ height: 54, width: 43.5 }}
        />
      )
    ) : vehicle.status === "riding" ? (
      <View style={{ ...styles.vehicleDot, backgroundColor: "#0096FF" }} />
    )}
    {vehicle.task &&
      vehicle.status !== "riding" &&
      vehicle.status !== "adminCollected" &&
      vehicle.status !== "warehoused" && (
        <View
          style={{
            ...styles.vehicleTaskBadge,
            backgroundColor:
              vehicle.task.colour === "red"
                ? "#FF0000"
                : vehicle.task.colour === "orange"
                ? "#FF8C00"
                : "#D3D3D3",
          }}
        >
          <Text
            style={{
              color: "#FFF",
              fontWeight: "bold",
              textAlign: "center",
              fontSize: 12,
            }}
          >
            {vehicle.task.priority}
          </Text>
        </View>
      )}
  </View>
</MapboxGL.PointAnnotation>

Any help would be appreciated as I’ve been spending the last few hours trying different things.

How to make a one page website with no scroll

I want to make a website that contains multiple sections like home,about,contact, my recent works,photos.(navbar links).
But the issue is that I want all of these parts to be displayed only by clicking the particular navbar links mentioned above and replacing the previous section .
So in general we won’t have any scrolling in the home section and only by clicking the navbar links we can walk around the website.

I searched alot in Google and YouTube but I couldn’t find the thing that I want so I thought here should be the place to find my answer so please help me overcome it.
Thank you!

In addition I want these sections to have an animation when coming and disappearing so it might be good to have the track of them too, so if I go to the last or middle option so I should be able to have the animation applied to them .

check if any property of an object with nested properties has any value – fail for dates

The following function returns true if any of the properties of an object have a value. This object could have nested objects

function hasValue(obj) {
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];
            if (typeof value === "object") {
                if (hasValue(value)) {
                    return true;
                }
            } else if (value) {
                return true;
            }
        }
    }
    return false;
}

For example for the following object returns true

const model = {
    criteria: '',
    category: '',
    range: {
        start: null,
        end: null
    },
    sample: '',
    another: {
        a: {
            b: {
                c: {
                    d: '',
                    e: {},
                    f: [1]
                }
            }
        }
    }
}

This is because the property f nested within another has the value of an array with a value

But this function fails with dates. For example. The following object should return true since the a and end properties have values. In this case dates

const model = {
    criteria: "",
    category: "",
    range: {
        start: { a: [new Date()] },
        end: new Date(),
    },
};

What is the reason for this behavior? and how could i solve it? Identify dates too

I am trying to bind the same function to two images. When I click on an Img, I want that image to be resized only, not all images

As you see I am trying to change the style of an image when I click on the image. However, when I run the function,

it changes the style of one image. I want to reuse the function to toggle the style of two images differently. For example, if I click on image1, I want image1 to become larger.

        let x = document.getElementById("img1");
        let myImage2 = document.getElementById("img2");
        function change(x,y) {
            x.classList.toggle("fullsize");
            y.classList.toggle("fullsize");
        }
        x.addEventListener("click", change());


  
        .img {
            width: 200px;
            height: 200px;
        }

        .fullsize {
            background: rgba(0, 0, 0, .5);
            background-size: contain;
            z-index: 999;
            cursor: zoom-out;
            display: block;
            width: 400px;
            max-width: 400px;
            height: 550px;
            margin-left: auto;
            margin-right: auto;
        }
<body>
    <h1>Click to Open Zoom the image</h1>
    <img src="https://picsum.photos/id/287/1000/1000" class="img" id="img1">
    <img src="https://picsum.photos/id/27/1000/1000" class="img" id="img2">
</body>

let x = document.getElementById(“img1”); let myImage2 = document.getElementById(“img2”); function change(x,y) { x.classList.toggle(“fullsize”); y.classList.toggle(“fullsize”); } x.addEventListener(“click”, change());

Can .js, .jsx, .ts and .tsx be used simultaneously in a React project?

I have a React project created using JS only. react-scripts version: 5.0.0.
Now, I want to start using TS in the project (and slowly migrate the project overtime). It’s quite a huge project now and everything can’t be migrated all at once. Thus I want to start adding new components (or pages) written in typescript and also gradually work on migrating the existing javascript files to typescript.

I googled for solution, and answers suggested to create a new TS project and copy the files to the new project after renaming them to .ts or .tsx. But in our case, it’s not very feasible.

Other answers suggested ejecting. But I want to use that if all other ways fail.

Are there any other ways I can do this? If we could somehow allow to have both the type of files and then could disable this in future when all the files have been migrated.

Currently trying to import a .tsx file in .js says module not found. I tried the solution from this post. But still has the same error.

How do I take a users input and use it to search an api in react?

I am trying to take a users input and then use it to get info from an api in react.

my api url is as follows: https://api.dictionaryapi.dev/api/v2/entries/en/${word}

So I want the user input to correspond to ${word}. I have tried countless attempts with failure. I was able to find a solution with JS and HTML, but using react and type script has me very confused. I am completely new to coding.

Pass and return an array from WebAssembly

I want to take an array in JavaScript, pass it to WebAssembly, have WASM transform the array, and have WASM return the transformed array back to JavaScript.

e.g.

/* main.js */

const array = [1, 2, 3, 4, 5];

// WASM code that squares the above array
const squaredArray = wasmModule.exports.squareArray(array);

console.log(squaredArray); // [1, 4, 9, 16, 25]

I figured I could achieve this in C by iterating over the array, like

/* square.c */

// the array variable is [1, 2, 3, 4, 5]
for (int i = 0; i < arrayLength; i++){
    array[i] = array[i] * array[i];
}
return array;

and compiling to WASM by doing

emcc square.c -o square.wasm -s WASM=1

However, some research has lead me to believe that it’s much more complicated than this, involving allocating and de-allocating memory, and a bit more to do on the C end.

Could anybody give me a boilerplate example of passing and returning an array from WebAssembly? I would appreciate any help you could give. I’m new to WebAssembly and haven’t used any other programming language than JS.

If another language that can compile to WASM would better suited for this (C++, Go, Rust), I would be happy for examples on those too.

Is there a javascript function that can search a string, a character in that string and a number of characters after the character to return?

Three arguments:
Define a function, lettersAfter, that accepts three arguments:

haystack– A string: The string to be searched

needle – A string: A character to search for.

limit – A number: The number of letters after the character to return

lettersAfter should return the letters following the first found occurrence of the search character. The letters returned should be limited to the number of the third argument.

For example – lettersAfter('hello', 'e', 2); = // => ll

I have trouble defining the various arguments:

My process:
Loop over haystack string (the first parameter), from let i = 0 to i < haystack.length

If the current character haystack[i] is === to needle (the second parameter):

Start an inner for loop, starting at let j = 0 going until j < limit.

add the current character haystack[i + j + 1] to letters

After the inner for loop, return letters, since we’ve finished adding all the necessary letters.

// outer loop
for (let i = 0; i < haystack.length; i++) {
  let char = haystack[i];

  // optionally save the current character as a variable

  // if we have found the needle character we're searching for...

  if (char === needle) {
    // inner loop, starting at zero, going until one before the limit

    for (let j = 0; j < limit; j++) {
      // Still need to add the character to the letters to be returned

      let innerChar = haystack[i + j + 1];
      letters += innerChar;
    }

    return letters;
  }
}

I am using a nested loop to solve this

How to send large chunks of data with fetch HTTP Post in React Native

I’ve been trying to send some data in React Native with HTTP fetch, but I can’t send fairly large chunks of data. It stops sending from about 2200 characters of text.

export const postServerData = (myURL, myJSONData, callback) => {
  fetch(myURL, {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
  },
  body: JSON.stringify(myJSONData),
})
  .then(response => response.json())
  .then(myReturnedData => {
      callback(myReturnedData);
  })
  .catch(error => {
  });
};  

From a few articles, data cap is quite fairly large :

Can HTTP POST be limitless?

The maximum POST request body size is configured on the HTTP server and typically ranges from
1MB to 2GB

How can I send larger chunks in React Native (Android)?

why datepicker show on top left in react js?

I am using material UI + react hook form .
https://react-hook-form.com/get-started

https://mui.com/material-ui/

I am trying to make datepicker. but I am facing one issue . My date picker open on top left why ?

here is my code
https://codesandbox.io/s/adoring-currying-iuptqe?file=/src/App.tsx

<Controller
        control={control}
        name="date"
        rules={{
          validate: {
            min: (date) => isFuture(date) || "Please, enter a future date"
          }
        }}
        render={({ field: { ref, onBlur, name, ...field }, fieldState }) => (
          <DatePicker
            {...field}
            inputRef={ref}
            label="Date"
            renderInput={(inputProps) => (
              <TextField
                {...inputProps}
                onBlur={onBlur}
                name={name}
                error={!!fieldState.error}
                helperText={fieldState.error?.message}
              />
            )}
          />
        )}
      />

enter image description here

Use a Web Worker (using Workerize) to run Hand Detection (TensorFlowJS)

The goal

I want to run TensorFlow.js hand pose detection in a web worker, to keep my UI responsive.

If I run the detection on the main thread, it works fine, but the whole system gets choppy.

Similar to a previous question I posted, but this time I installed Workerize and was able to trim a lot. Anyway, trying to use native web workers caused the same problem.

Existing system:

index.js

import worker from 'workerize-loader!./worker'

let instance = worker()

instance.CreateHandDetector().then( message => {
    console.log(`Detector creator says: ${message}`)
})

worker.js

importScripts('https://cdn.jsdelivr.net/npm/@tensorflow-models/hand-pose-detection')

const detectors = {handDetector: null, objectDetector: null, pauseAll: false}

export async function CreateHandDetector() {
    const model = handPoseDetection.SupportedModels.MediaPipeHands
    const detectorConfig = {
        runtime: 'mediapipe',
        modelType: 'lite'
    }
    console.log("Ready to make detector") // This is printed
    detectors.handDetector = await handPoseDetection.createDetector(model, detectorConfig)
    console.log("Hand detector made") // Never printed
    return("Done detector")
}

At a breakpoint, I can see that handPoseDetection was imported:

Shows that handPoseDetection is imported correctly

As soon as I continue from this point, I got the following error:

Uncaught (in promise) TypeError: t.Hands is not a constructor
e hand-pose-detection:17
l hand-pose-detection:17
[Many more….]

Any help would be most welcome!