How to check if a zip code falls within a specific boundary in google map?

I want to implement a find a local home buyer just like the one present in this website :

Website: https://www.homevestors.com/locations (Use VPN to access this site, might not be available in few regions)

I want to check if the zip code falls under this(boundary or radius) https://www.google.com/maps/d/viewer?mid=1LYhtKj4kq_Uix_VTi3d_S-W3GudiKhw&femb=1&ll=43.82540821745644%2C-77.99870023257755&z=8 (this is for Country Canada) How can I achieve this in angular ?

I tried few alternative ways to look up using zip code, but not a solution to this problem.

Is there a way to call mysql query from WebdriverIO/Mocha/Javascript frmaework test case?

Not able to call sql query from it block
Not even executed db.query statement but simply test passed

**Here is the code block **

var db = require("../utils/db");

it("DB Testing", () => {
 db.query('SELECT type FROM docket.story_types where id="4"', function(error, results){
console.log("DB Results +results[0].types);
 })
console.log("testing end")
}) 

Note: database connection established successfully but the line inside it block (db.query…) is not getting executed. Anyone have any idea how to call query from here

Can’t install express on windows

i tried to install express on my project, i done the tutorial step by step(wich is just make a new dir, npm init)and when i run “npm install express” the console freezes and trow a connection error.

I tried clearing the cache, running several commands changing some options but nothing seems to help

How to render a dropdown box with nested array?

I am trying to render a dropdown box with nested array. My Question is how to implement rendering ?

  1. How to show the selected value?

         Selected Value:
         {`fields.${parentFieldIndex}.props.${index}.value`}
    
  2. As I cannot get the current selected value in option, I can’t render the button here.

function handleChange(event) {
  if (e.value === "first") {
    setShow(true);
  } else {
    setShow(false);
  }
}
        
{showBtn === "true" ? (
        <div>
          <button type="button">Button</button>
        </div>
      ) : null}

Expected result:
If user selected “first” option, the sub list option will show the Button.

Here is sample code: https://codesandbox.io/s/naughty-pasteur-59lyrs

Cypress – How to get url from result

I’m a cypress beginner. I have a website and when I click on ‘Login‘ button —> it opens a Microsoft login window. I want to access to MS login window to input my account BUT I don’t know how to do it. Can anyone help me? I also try to perform like code

describe('Login to PortalCX', () => {
  
  it('login', () => {
    cy.visit('https://develop-portal.teamscx.com/', {
      onBeforeLoad(win){
        cy.stub(win, 'open')
      }
    })

    cy.get('[type="Submit"]').click()
    cy.contains('Sign in')
  })

})

And it isn’t work. But I see command log, I have a URL and I want to take this url to visit but I don’t know how to do it. do we have the way to get this url? enter image description here

Animated.View and useRef are inexplicably being shared between child components

I am rendering a list of items like so:

{formattedJournal[meal].map((food, idx, arr) => {
                const isLast = idx === arr.length - 1;
                return (
                  <View key={idx}>
                    <JournalItem
                      isLast={isLast}
                      idx={idx}
                      food={food}
                    />
                  </View>
                );
              })}

// JournalItem.js
  
const translateX = useRef(new Animated.Value(0)).current || 0;
  handleDelete = (food) => {
    Animated.timing(translateX, {
      toValue: -width,
      duration: 350,
      useNativeDriver: false,
    }).start(() => null);
  };

return (<Swipeable
        renderRightActions={renderRightActions}
        overshootRight={false}
        onSwipeableOpen={() => handleDelete(food)}
        rightThreshold={75}
        containerStyle={[
          {
            transform: [{ translateX }],
          },
        ]}
      > ... )

What I want to accomplish is simple, I want to delete an item when the user swipes it. Instead, what happens is, the last item in the list receives the animation, no matter which element you triggered the swipe on, which makes no sense, because each useRef call is scoped to its own instance of JournalItem, so I have no idea why it’s only using the last reference when swiping.

Click to Popup image tailwind css React js

I’m working on a React.js project and I’m trying to create a pop-up image feature using Tailwind CSS. I have a list of images, and when a user clicks on one, I want it to open in a pop-up modal or lightbox with the ability to close it. I’m relatively new to React and Tailwind, so I’m not sure where to start. Can someone please guide me on how to achieve this functionality? Any code examples or pointers on which React components or Tailwind CSS classes to use would be greatly appreciated. Thank you in advance for your help!
Here is my Code:

 <Dialog
      //   PaperProps={{ style: { overflowY: "visible" } }}
      //   classes={{
      //     paperFullWidth: classes.paperFullWidth,
      //     dialogPaper: classes.paperFullWidth,
      //     scrollPaper: classes.topScrollPaper,
      //     paperScrollBody: classes.topPaperScrollBody,
      //   }}
      onClose={onResetValues}
      aria-labelledby="customized-dialog-title"
      open={show}
    >
      <DialogTitle id="customized-dialog-title" onClose={onResetValues}>
        Foto Tier Shipment {datas.Nama_Checker ? datas.Nama_Checker : ""} -{" "}
        {datas.Nomor_Shipment ? "Nomor Shipment: " + datas.Nomor_Shipment : ""}
        <IconButton
          sx={{
            position: "absolute",
            top: 8,
            right: 8,
            color: (theme) => theme.palette.grey[500],
          }}
          onClick={onResetValues}
        >
          <Close />
        </IconButton>
      </DialogTitle>
      <DialogContent
        // style={{ overflowY: "visible" }}
        // classes={{
        //   root: classes.dialogContentRoot,
        //   dialogPaper: classes.paperFullWidth,
        // }}
        sx={{
          margin: 0,
        }}
        dividers
      >
        <div className="col-xs-12 col-sm-12 col-md-6 col-lg-3">
          <div className="-m-1 flex flex-wrap md:-m-2">
            {datas.Upload_Photos
              ? datas.Upload_Photos.map((image, index) => (
                  <div
                    key={index}
                    className="flex w-full image kf-image-hover sm:w-1/2 md:w-1/3 lg:w-1/4 p-1 md:p-2 group relative"
                  >
                    <a
                      href={image.URL}
                      className="kf-image-hover has-popup-image"
                      target="blank"
                    >
                      <div className="opacity-0 group-hover:opacity-100 transition-opacity absolute inset-0 flex items-center justify-center">
                        <p className="text-white text-lg">{image.Nama}</p>
                      </div>
                      <img
                        className="block mx-auto h-full object-center rounded-lg shadow-md hover:scale-110 transition duration-500 cursor-pointer object-cover"
                        src={image.URL}
                        alt={`Image ${image.Nama}`}
                        title={`Image ${image.Nama}`}
                      />
                    </a>
                  </div>
                ))
              : "NO DATA"}
          </div>
        </div>
      </DialogContent>
      <DialogActions
        style={{
          display: "flex-end",
          justifyContent: "",
          padding: "1rem 1.5rem",
        }}
      >
        <Button
          autoFocus
          onClick={onResetValues}
          color="error"
          variant="outlined"
          endIcon={<ClearIcon />}
          style={{
            marginRight: "1rem",
          }}
        >
          close
        </Button>
      </DialogActions>
    </Dialog>

any help on this? here is my desire Result:
enter image description here

so when i clicked the image its not moving on the link but instead showing it as popup…

Filter multiple key values(Array of an obvjects) in one array

I have a key and value pair format, i want to filter all the values which are in array into a single array

const holiday_expenses = {
  food: [{name: "abc", place: "xyz"}],
  travel: [{name: "abcd", place: "xyz1"}],
  accommodation: [{name: "xysz", place: "xyz2"}]
}

Expected Result:

result : [{name: "abc", place: "xyz"}, {name: "abcd", place: "xyz1"}, {name: "xysz", place: "xyz2"}]

Props being passed as null (Uncaught TypeError: Cannot read properties of undefined (reading ‘map’))

import React, { useState, useEffect } from "react";
import { TaskLists } from "./TaskLists";
import { Daycard } from "./daycard";
import { getTasks, deleteTask } from "../api/task.api";

export function TaskManager() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = async (id) => {
    await deleteTask(id);
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      <TaskLists tasks={tasks} removeTask={removeTask} />
      <Daycard tasks={tasks} removeTask={removeTask} />
    </div>
  );
}


import React from "react";
import { TaskCard } from "./TaskCard";

export function TaskLists({ tasks, removeTask }) {
  return (
    <div>
      {tasks.map((task) => (
        <TaskCard
          key={task.id}
          task={task}
          onDelete={() => removeTask(task.id)}
        />
      ))}
    </div>
  );
}

 import React from "react";
import { useNavigate } from "react-router-dom";
import { TaskCard } from "./TaskCard";
import { useState } from "react";

export function Daycard({ tasks, removeTask, hashv }) {
  let b = 0;
  const [hash, setHash] = useState(hashv);
  const navigate = useNavigate();

  const handleClick = () => {
    if (b === 0) {
      navigate(`/tasks-create?hash=${hash}`);
      console.log(`the hash is ${hash}`);
    }
  };

  return (
    <div
      onClick={handleClick}
      className="col pb-5 bg-light border border-dark flex-grow-1"
      style={{ height: "auto" }}
    >
      {tasks.map((task) => {
        if (task.hash === hash) {
          b = 1;
          return (
            <TaskCard
              key={task.id}
              task={task}
              onDelete={() => removeTask(task.id)}
            />
          );
        }
      })}
    </div>
  );
}

the first one is the parent component and the others are the children why I am getting the error:

TaskLists.jsx:7 Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)
at TaskLists (TaskLists.jsx:7:14)
at renderWithHooks (react-dom.development.js:16305:18)

I think the issue is because the initial API call to fetch tasks might not have completed by the time these child components are rendered.

Use of a restructured variable results in ReferenceError

I am working with a function that returns the variable nextPage as shown below:

async function scrapeCurrentlyShownPosts(mainPage) {
        let postsAddedFromMainPage = 0;

        ... 

        await Promise.all(postPromises);
        console.log(`Found ${postsAddedFromMainPage} new posts to backup`);

        // If the main page has an href to older posts, return this href
        const nextPageFound = await mainPage.evaluate(() => {
            const idToFind = "Blog1_blog-pager-older-link";
            const anchorElement = document.getElementById(idToFind);

            if (anchorElement) {
                return anchorElement.getAttribute("href");
            } else {
                return null;
            }
        });

        return { nextPage: nextPageFound, numNewPostsFound: postsAddedFromMainPage };
}

The values returned by the above function are used in a Crawl() function. The problem is that the value of nextPage is not initialized inside of the while loop of this function:

async function crawl() {
        async function crawl() {
    try {

        // Read backup.json into memory if it exists 
        backup = loadOrCreateFile();

        const browser = await puppeteer.launch();
        const mainPage = await browser.newPage();
        await mainPage.goto(baseURL, {
            waitUntil: 'networkidle2',
            timeout: 30000
        });
        let numMainPagesWithNoNewPosts = 0;
        let { nextPage, numNewPostsFound } =  await scrapeCurrentlyShownPosts(mainPage); //await reTryCatch(scrapeCurrentlyShownPosts, mainPage); 
        let numTimesOlderPostsClicked = 1;

        console.log(`Next page: ${nextPage}`); // Prints a valid URL

        while (nextPage) { // While loop enters
            console.log(`Older posts has been clicked ${numTimesOlderPostsClicked} times`);
            
            await mainPage.goto(nextPage, { // ReferenceError: Cannot access 'nextPage' before initialization
                waitUntil: 'networkidle2',
                timeout: 30000
            });

            let { nextPage, numNewPostsFound } = await scrapeCurrentlyShownPosts(mainPage); //await reTryCatch(scrapeCurrentlyShownPosts, mainPage);
            numTimesOlderPostsClicked++;

            // If the second main page clicked didn't have new posts, prompt the user to stop scraping
            if (numNewPostsFound === 0) {
                numMainPagesWithNoNewPosts++;
            } else {
                numMainPagesWithNoNewPosts = 0;
            }

            if (numMainPagesWithNoNewPosts > 0) {
                let userChoice = prompt("No new posts have been found lately. Enter 'Q' to stop searching or any key to continue: ");
                if (userChoice === 'Q') {
                    break;
                }
                else {
                    numMainPagesWithNoNewPosts = 0;
                }
            }
        }

The program output demonstrates that the ReferenceError is thrown on the very first execution of the while loop:

Found 26 new posts to backup
Next page: some_url
Older posts has been clicked 1 times
ReferenceError: Cannot access 'nextPage' before initialization

How to center zoom around the cursor in an infinite pinboard app with panning

I’m trying to create an infinite pinboard Javascript app, similar to Miro or Figma, where users can zoom in and out using the wheel event, pan left/right/up/down by dragging from a blank spot on the workspace, and move individual elements anywhere on the workspace by dragging and dropping them. I’m using React without JSX. No HTML canvas.

I’ve got each of these functionalities working, except for zooming while centered around the cursor. (Rather than zooming relative to the static (0,0) origin point of the workspace element.)

The closest I’ve gotten to it working is transforming the origin of the zoomable element (#workspace) to the current mouse position when the wheel event fires. This mostly works, but when you are at any zoom scale other than 1.0, if you move your cursor to a different position and then zoom again, the entire workspace jumps and what’s under your cursor has changed (it should stay the same, just appear at a different zoom scale). Then when you zoom again, without moving the mouse, it behaves as desired, with what’s under your cursor staying put, and just getting bigger or smaller.

The “jumping” behavior is more pronounced the further the current zoom scale is from 1.0. (An easy way to see it is to zoom in or out fairly far, move the cursor, then zoom again and watch the workspace contents move out from under you.) That makes me think that maybe I need to make an equation for the new transformOrigin values that in some way incorporates the zoom value. But I’m not sure how to write that equation. Nothing I’ve tried has worked.

Current code is here: https://codepen.io/swelmel/pen/zYeNpPO

Pulling out key functions:

Here’s my makeZoomable() function driving this behavior:

/*
 * Make workspace zoomable, capturing wheel events for the whole document.
 * Pass in appState.workspace for the state. Will change the 'zoom' prop.
 * FIXME: Trying to center the zoom around the current mouse position, 
 * but it isn't working.
 */ 
function makeZoomable(state, el) {
    console.log(`Making element zoomable:`,el);
    function wheel(event) { 
        event.preventDefault();
        event.stopPropagation();

        // Move the zoomable element's origin to be at the current cursor pos
        // Doesn't work -- when you move cursor and then zoom from a scale other
        // than zoom=1.0, it'll jump around. Not sure why.
        state.transformOrigin.x = event.clientX;
        state.transformOrigin.y = event.clientY;

            // Zoom in or out based on the scroll direction 
            const currentZoom = state.zoom;
            let newZoom = currentZoom + ( event.deltaY * -(state.zoomRate) );
            // Restrict scale
            newZoom = restrictRange(newZoom,0.1,10);
            state.zoom = newZoom;

            renderUI();
    };
    document.addEventListener('wheel', wheel, { passive: false });
}

I’m passing the #workspace div to makeZoomable(), along with my React app state object, which stores the transformOrigin and zoom values, which are then passed as props to the render function for the Workspace React component (below). The workspace is re-drawn every time we run renderUI(), which we do whenever the state changes.

Note that the wheel event has to be on the entire document, rather than just the zoomable element, because the zoomable workspace element size is 0x0 and therefore couldn’t capture any wheel events. I have it set to 0x0 because we’re trying to simulate an infinite workspace, so we can’t prescribe a size for it. That means that the event.pageX/Y values are relative to the document rather than the zoomable element. That could be a source of the problem or why similar answers aren’t working for me but when I tried to offset it it didn’t work.

The Workspace React component:

function Workspace(props) {
    const workspace = document.getElementById("workspace");
    const { zoom, translate, mouse, transformOrigin } = props.workspace;
    return e('div', {id: 'workspace', style: {
            // To change the origin only when you zoom in/out:
            transformOrigin: `${transformOrigin.x}px ${transformOrigin.y}px`,
            // To change the origin whenever the mouse moves:
            //transformOrigin: `${mouse.x}px ${mouse.y}px`,
        transform: `scale(${zoom}) translate(${translate.x}px, ${translate.y}px)`
      }},
      e(Crosshairs, {x: mouse.x - translate.x, y: mouse.y - translate.y }),
      //e(Crosshairs, {x: transformOrigin.x, y: transformOrigin.y }),
    props.scraps.map((scrap) => e(Scrap, {key: scrap.id, scrap}))
    );
}

The translate values in the transform CSS property are used for the panning functionality.

Any pointers would be greatly appreciated! I’ve been banging my head on this for a while.

no result on the secreen

The code not working on react localhost 3000 ans ive tried many ways

The code:
` class Counter extends Component {

   state={
    counters:[
        {id : 1, value: 0},
        {id : 1, value: 0},
        {id : 1, value: 0},
        {id : 1, value: 0},
        {id : 1, value: 0}
    ]
    };

    render() { 
   
    return<div> 
             {this.state.counters.map(counter=><Counter key={counter.id}/>)}


         </div>;
    };



}

export default Counter;``

ive tried to run the code manyt time but it didnt work

ive face this problem many times and start the page again and it work but this time no answer

How to respond automatically a confirm window on Chrome? [duplicate]

i´m using tampermonkey extension to execute js automatically on a web. Part of the procces is to fill a form. Just when i use an event to click the “save” button, a confirm window appears and stop my script. I need to make all the process to be automatic. How can a respond this alert or confirm using js or an extension, o wathever that works.


Using Apps Script to count background colours in google sheets

Apologies in advance for the long one! Let me know if you need any more info/example of the full js file/spreadsheet I’m using.

Context:

I’m having some trouble getting GAS to work, counting the number of background colours in a child’s schedule I’ve created.

I have a simple week view, broken into 30 min chunks from 5:30am to 7:30pm. I’ve then coloured different cells based on being at home or not, and different recurring events.
That leaves me with something like the following:
enter image description here

What I am trying to do is count the number of cells that are purple, orange and green. I’ll divide these by 2 to then get the number of hours at each location throughout the week.

Steps Taken:

A key piece here is that I need to be using merged cells within the target range that I’m counting.

The following has been a big help: Script Google Sheets that will count the amount of cells with a specific background colour

This got me to use a custom function as follows:

//Gets the count of cells with a particular colour within the range. Merged cells count as 1
function countColouredCells(countRange,colorRef) {
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  var rangeA1Notation = formula.match(/((.*),/).pop();
  var range = activeSheet.getRange(rangeA1Notation);
  var bg = range.getBackgrounds();
  var values = range.getValues();
  
  var colorCellA1Notation = formula.match(/,(.*))/).pop();
  var colorCell = activeSheet.getRange(colorCellA1Notation);
  var color = colorCell.getBackground();
  
  var count = 0;
  
  for(var i=0;i<bg.length;i++)
    for(var j=0;j<bg[0].length;j++)
      if( bg[i][j] == color )
        count=count+1;
  return count;
};

//Usage in cell formula: "=countcolouredcells($E$11:$K$39,L46)" where $E$11:$K$39 is the range to count the occurances of cells with the same background as L46

However this counts merged cells as 1, not the number of cells the merge is for. E.g. in the picture above, Monday’s green “School” merged cell is 1, where as I want the function to count it as 14.

Embarking on a bit more of an investigation, I’ve created (copied and adapted from other people on stackoverflow) two functions that break apart merged cells, then stitch them back together.

var mergedRanges;

function breakApartRange(breakRange){
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();
  var fullRange = activeSheet.getRange(breakRange);
  
  //break merged cells
  mergedRanges = fullRange.getMergedRanges();
  mergedRanges.forEach(range => range.setValue(range.breakApart().getValue()));
};


function reMergeRange(breakRange){
  var activeRange = SpreadsheetApp.getActiveRange();
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();
  var fullRange = activeSheet.getRange(breakRange);
  
  //re merge cells
  mergedRanges.forEach(range => range.merge());
};

A small complication with this is that you cannot call the breakApart() method within a custom function from a formula. A workaround I found for this was to run my custom function from a custom menu item that I create in the onOpen method.

//Adds a menu item to run the function:
// The onOpen function is executed automatically every time a Spreadsheet is loaded
function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [];

  menuEntries.push({name: "Calculate Hourly Split", functionName: "calcHourlySplitByColour"});

  ss.addMenu("CustomFunctions", menuEntries);
};

This means that I needed to use static references for the range I wanted to count, and the references to the colours, but that’s acceptable for what I’m doing. Now I have a custom function called calcHourlySplitByColour that is triggered by opening the menu item, that will:

  1. break apart the merges
  2. call another custom function (countColouredCells) to count the coloured cells
  3. store that count in a seperate cell so i can view it
  4. remerge the cells back so that it looks like the original view.

Individually, this works (the break apart and remerge I have tested and work when called from the custom menu item, and the countColouredCells seems to work if I just call it from typing into a formula in the sheet.)

Issue I’m Stuck On:

My issue comes when I try to stitch it all together, in particular, when I try to use the countColouredCells, called via the custom menu item. To make it work I need to pass the ranges into countColouredCells statically, but I always end up getting an issue when it runs the pop() method:

//Gets the count of cells with a particular colour within the range. Merged cells count as 1
function countColouredCells2(countRange,colorRef) {
 
  var activeRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(countRange);
  var activeSheet = activeRange.getSheet();
  var formula = activeRange.getFormula();

  //Testing code just to see if the activeRange was null - it wasn't, this returned "1st PopCalibri" in the alert
  SpreadsheetApp.getUi().alert("1st Pop" + activeRange.getFontFamily());
  
  //This is the line that causes the error (i.e. I never see an alert for "2nd Pop"):
  var rangeA1Notation = formula.match(/((.*),/).pop();
  var range = activeSheet.getRange(rangeA1Notation);
  var bg = range.getBackgrounds();
  var values = range.getValues();
  
  SpreadsheetApp.getUi().alert("2nd Pop");
  var colorCellA1Notation = formula.match(/,(.*))/).pop();
  var colorCell = activeSheet.getRange(colorCellA1Notation);
  var color = colorCell.getBackground();
  
  SpreadsheetApp.getUi().alert("Post 2nd Pop");
  var count = 0;
  
  for(var i=0;i<bg.length;i++)
    for(var j=0;j<bg[0].length;j++)
      if( bg[i][j] == color )
        count=count+1;
  return count;
};

The above is a work in progress, refactoring my original countColouredCells method. I know that I haven’t done anything to address the colorRef parameter yet, but the line of code that is causing the issue:

    var rangeA1Notation = formula.match(/((.*),/).pop();

is just addressing the first parameter, countRange. Here is the error I get:
enter image description here

enter image description here

How do get response data in a firefox extension with webRequest.onBeforeRequest on a site that blocks connections

Im trying to middle man all requests made to a website using webRequest.onBeforeRequest and then using webRequest.filterResponseData to get the body, the issue is that with the way this site works with events is that the client sends a post request, and the server will block that connection until an event goes through. This in combination with my firefox extension will cause all requests to block. Im not sure how should go about fetching the response bodies.

function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");

  filter.ondata = (event) => {
    let data = decoder.decode(event.data, {stream: true})
    console.log(data)
    filter.disconnect();
  }

  return {};
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {urls: ["*://*.omegle.com/events"]},
  ["blocking"]
)