How to read from a Popup in Puppeteer

I’m trying to receive a notification when a booking website shows that there is a new appointment available in the near future (eg. through a cancellation). The site in question is booksy.com.

I have written a Puppeteer script which will navigate to the page and click a button which will then open a popup displaying text about when the next available appointment is. The script works for that.

My next step is to get the scrip to actually read the contents of the popup. Which has been an issue, as it is just trying to read the original page prior to the popup opening.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto('https://booksy.com/en-gb/45005_gents-of-richmond_barber_311817_london#ba_s=sgr_1');

  await page.waitForSelector('button[data-testid="service-button"]');
  const button = await page.$('button[data-testid="service-button"]');
  await button.click();

})();

I think if I could read the page, I could extract the month and date displayed, and perhaps evaluate that output against the current date and determine if it is in a timeframe such as the next 7 days. Sending me a notification if it is within that period.

What I’m asking is simply how I can actually evaluate the contents popup, getting it’s month and/or date as an output. Thanks!

How to anchor tag to a specific div from a dropdown menu

I have a page where I am using a dropdown selector, and am looking to anchor link the sections in my URL, but when I use #show1 at the end of my URL, the specified dropdown does not show.

Any insight as to what I am doing incorrectly?

Thank you in advance!

Snippet of current HTML:

<center><select id="myselection">
    <option>Select Your Model</option>
    <option value="1">Section 1</option>
    <option value="2">Section 2</option>
    <option value="3">Section 3</option>
    </select>


<div id="show1" class="myDiv">
<center>

  <div class="responsive-two-column-grid">

<div><img src="#"></div>
<div><h3 style="margin-top: 70px!important;">Header 1</h3><p>copy goes here</p></div>
</div>

<div id="show2" class="myDiv">
<center>

  <div class="responsive-two-column-grid">

<div><img src="#"></div>
<div><h3 style="margin-top: 70px!important;">Header 1</h3><p>copy goes here</p></div>
</div>

<div id="show3" class="myDiv">
<center>

  <div class="responsive-two-column-grid">

<div><img src="#"></div>
<div><h3 style="margin-top: 70px!important;">Header 1</h3><p>copy goes here</p></div>
</div>

I would like the specified div to show when I specify the id at the end of the URL. ie - using *#show1* at the end of my URL would bring the person to this part: 

<div id="show1" class="myDiv">
<center>

  <div class="responsive-two-column-grid">

<div><img src="#"></div>
<div><h3 style="margin-top: 70px!important;">Header 1</h3><p>copy goes here</p></div>
</div>

How to implement a search functionality in a React application? [closed]

I am building a web application using React and I would like to add a search feature that allows users to search for specific items in a list of items. The list is retrieved from a REST API and displayed in a component using the map function.

I have researched various approaches to implementing search in React, such as filtering the array of items based on a search query or using a third-party library like Fuse.js. However, I am not sure which approach would be best for my use case.

Can anyone provide guidance on how to implement search in a React application? Is there a preferred approach or library that is commonly used for this purpose?

Optional code snippet:

import { useState, useEffect } from 'react';

function ItemList() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch('https://my-api.com/items')
      .then(response => response.json())
      .then(data => setItems(data));
  }, []);

  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

I am trying to implement a sorting functionality in my React application using the sort method on an array of objects. I have written a function to sort the array by a particular property, but when I click the sort button, nothing happens.

Express and Node.js, res.render() refreshing the page when I don’t want it to [duplicate]

I am using express and node.js to run a website. I have anchor elements on each page that refer back to the get function and render the page I am asking for. However, I am making changes to one of the pages, where I add a row to a table and change the innerHTML. Whenever I press on the anchor links to go to another page and then press the anchor link to return, the page resets and the new rows added go away. Is there a way to prevent this?

const express = require('express');
const app = express();

app.use(express.static('public'));
app.use(express.urlencoded({extended: false}));
app.use('/css', express.static(__dirname + 'public/css'));

app.set('view-engine', 'ejs');

app.get("/", (req, res) => {

    res.render("index.ejs");

} );

app.get("/dashboard", (req, res) => {

    res.render("dashboard.ejs");

} );

app.get("/history", (req, res) => {

    res.render("history.ejs");

} );

I tried a few things like preventDefault() in some spots but it didn’t work.

Filtering GeoJson data in Leaflet

I’ve been tring to filter multiple checkboxes in a geojson. Im using leaflet with the leaflet ajax plug in. Im a begginer at this.

I put this code on the buttons


            $("#btnFltGeralALL").click(function(){
                $("input[name=fltGeral]").prop('checked',true);
            });
            
            $("#btnFltGeralNONE").click(function(){
                $("input[name=fltGeral]").prop('checked',false);
            });
            
            $("#btnFltGeral").click(function(){
                arDoencasEnd = [];
                doencas.refresh();
            });

And this function:

function fltDoencas (json){
                var arProjectFilters=[];
                $("input[name=fltGeral]").each(function(){
                    if(this.checked) {
                        arProjectFilters.push(this.value);
                    }
                });
                var atributos = json.properties;
                switch (atributos.type){
                    case "1835":
                        return (arProjectFilters.indexOf('1835')>=0);
                        break;
                    case "1836":
                        return (arProjectFilters.indexOf('1836')>=0);
                        break;
                    case "1839":
                        return (arProjectFilters.indexOf('1839')>=0);
                        break;
                    case "F":
                        return (arProjectFilters.indexOf('F')>=0);
                        break;
                    case "M":
                        return (arProjectFilters.indexOf('M')>=0);
                        break;
                    case "Disenteria":
                        return (arProjectFilters.indexOf('Disenteria')>=0);
                        break;
                    case "Tísica":
                        return (arProjectFilters.indexOf('Tísica')>=0);
                        break;
                    case "N/A":
                        return (arProjectFilters.indexOf('N/A')>=0);
                        break;
                 }
            };

and this is the object

doencas = L.geoJSON.ajax('data/Doencas.geojson',{filter:fltDoencas, pointToLayer:returnDoencas}).addTo(meumapa);

Closing the cloudinary upload widget, how to distinguish between ‘Done’ button and closing widget using ‘X’ in top right?

Using the Cloudinary Upload Widget I can succesfully upload images to cloudinary and use the response to store the image data to a separate database. (Node.js + Javascript)

What I want to achieve is a page redirect after succesful upload when user clicks on “Done” in the widget. The issue I’m facing is figuring out which result event can be used to trigger the page redirect? The widget sends same event ‘close’ when ‘Done’ is clicked and when widget is closed using the ‘X’ in top right. How to distinguish between ‘Done’ and ‘X’?

My test case is as follows

  1. Open widget
  2. Upload image(s) using widget
  3. Click Done in widget
  4. Page is redirected

In short, if user opens the widget and immediately closes it using ‘X’, my page redirect will trigger. Cannot use the upload ‘success’ event to redirect because when multiple images are being uploaded this event is sent for each upload.

close event on ‘X’
success and close events

This script is too long to paste here in full and making it reproduceable means exposing my cloudinary accound credentials.

From Cloudinary documentation, the syntax for opening the widget is
cloudinary.openUploadWidget(options, resultCallback)
resultCallback is an optional function called for event handling. The callback method has the following signature function(error, result) where error is either null if successful or an error message if there was a failure, while result is a JSON object detailing the triggered event.

Below is my beginner attemps to identify which result.event I can use.

The page redirect is initiated by changing html element data-set dataDivResults.dataset.uploadResult = 'success';. A seperate script with an observer monitors for changes to this html element attribute.

// result is a JSON object detailing the triggered event.
// error is either null if successful or an error message if there was a failure
// See https://cloudinary.com/documentation/upload_widget#upload_widget_events
// and https://cloudinary.com/documentation/upload_widget_reference#events
const processResults = async (error, result) => {
  if (error) {
    console.log(error); 
  }

  if (!error && result && result.event === 'success') {
    // Send the result object to backend to save image data in database
    // When multiple images are uploaded, this event happens for each image
    const serverResponseData = await sendImageDataToServer(result); // returns {success: true or false}
    // ...
  }
  if (error && result && result.event === 'close') {
    // do not redirect. Reload page.
  }

  if (!error && result && result.event == 'close') {
    // In a separate script, observer is listening for data-set attribute changes to dataDivResults
    // When the attribute changes, the observer will redirect to the album page
    const dataDivResults = document.getElementById('dataDivResults');
    dataDivResults.dataset.uploadResult = 'success';
  }
};

const launchWidget = () => {
  console.log('FE => Launching widget');
  const myWidget = window.cloudinary.createUploadWidget(options, processResults);
  myWidget.open();
};

Express.js and speakeasy totp. Getting false and verify

I always getting false when verifying with speakeasy. I tried different window parameters and it does not help.

I am generating secret with:
const secret = speakeasy.generateSecret({ length: 20 });

And after, I am trying to verify like this:
const verified = speakeasy.totp.verify({ encoding: 'base32', secret: decryptedSecret, token: tokenFromQrCode, });

I want to be verified = true 🙂 Also, I tried to hardcode my values, and it did not help. ChatGpt told me that issue can be in timestamps, but his suggestion did not help me either

How to update HTML elements in Svelte and Sveltekit via onMount

I am down with Covid and wanted to write a fun little game. I am writing a Hangman Game in Svelte and Sveltekit.

I have most of the game written, but I a stuck revealing the divs of the hangman.

Here is the code:
https://timscodebase-didactic-palm-tree-7wx4w55459xfpxq5.github.dev/

In src/lib/HangGrid.svelte, am subscribing to numberWrong and am trying to react to when it changes. it is working but I am getting errors trying to add a class to an element in a nodelist.

Here is the code:

<script lang="ts">
    import { numberWrong } from '$lib/stores'
    import { onMount } from 'svelte'

    $: console.log('numberWrong from grid', $numberWrong)
    $: wrong = $numberWrong - 1

    let pieces_of_man: NodeListOf<Element>
    const setPiecesOfMan = (pieces: NodeListOf<Element>) => {
        pieces_of_man = pieces
        console.log(pieces_of_man)
    }

    onMount(async () => {
        setPiecesOfMan(document.querySelectorAll('.piece_of_man'))
    })

    $: current_piece = pieces_of_man[wrong]

    // This gives the error
    $: current_piece.classList.remove('white')

    // This gives "
    $: console.log('current_piece', current_piece)
</script>

Here is the error:

[HMR][Svelte] Unrecoverable HMR error in <HangGrid>: next update will trigger a full reload
logError @ proxy.js?v=02947d2a:15
Proxy<HangGrid> @ proxy.js?v=02947d2a:380
create_if_block_2 @ +page.svelte:61
create_if_block_1 @ +page.svelte:57
create_if_block @ +page.svelte:56
update @ +page.svelte:55
update @ index.mjs:1273
flush @ index.mjs:1233
Promise.then (async)
schedule_update @ index.mjs:1184
make_dirty @ index.mjs:2066
(anonymous) @ index.mjs:2104
handleSubmit @ +page.svelte:40
(anonymous) @ index.mjs:428
HangGrid.svelte:18 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '-1')
    at $$self.$$.update (HangGrid.svelte:18:21)
    at init (index.mjs:2109:8)
    at new HangGrid (HangGrid.svelte:23:47)
    at createProxiedComponent (svelte-hooks.js?v=02947d2a:341:9)
    at new ProxyComponent (proxy.js?v=02947d2a:242:7)
    at new Proxy<HangGrid> (proxy.js?v=02947d2a:349:11)
    at Array.create_if_block_2 (+page.svelte:61:11)
    at Array.create_if_block_1 (+page.svelte:57:16)
    at Array.create_if_block (+page.svelte:56:16)
    at Object.update [as p] (+page.svelte:55:19)

Convert OOXML to HTML using C# or javascript

I have an issue to be able to convert extracted ooxml text to HTML.

this is my ooxml text for example:

<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:rPr> <w:rFonts w:ascii="Times New Roman" w:cs="Times New Roman" w:hAnsi="Times New Roman" /> <w:b /> <w:bCs /> </w:rPr> <w:t>“TEST”</w:t> </w:r>

and i need to convert it to html with the format using c# or javascript.

i thought about using a regex but don’t know if there is a better solution.

Choose Crop Preset in PS via AppleScript or JavaScript

I would really appreciate some help with this issue.

There is a larger AppleScript which opens the pictures inside of a folder and applies different Photoshop steps on them.

The Script crops the pictures multiple times in it’s life cycle by using a selection and executing the PS Crop tool via System Events (key codes). The last crop has to be with specific dimensions which i saved as a Crop preset with specific name. The problem is that i can’t find a way to tell AppleScript to use that preset. I’ve tried all kinds of cropping methods by setting the desired dimensions (crop bounds, image events and more) but all of those methods delete the pixels after cropping and i need them not to be deleted, as PS crop tool allows. Also PS crop tool changes the aspect ratio of the resulted pictures according to the new dimensions and not distorting the image during the process (not sure if i explained this right). So i have to think of a way to switch to that crop preset somehow.

A solution with Java Script also will be useful. Even that i dont know how to program in JavaScript i can tell AppleScript to run a JavaScript file in certain point. The Java Script has to work on already opened picture, the name of the preset have to be hard-coded (no need to ask the user), and ofc to execute the cropping.
I’ve done something kinda similar before with Indesign but no luck with PS so far.

tell application "Adobe InDesign 2021"
set my_pdf_export to get the name of every PDF export preset
set my_pdf_choice to (choose from list my_pdf_export) as string
tell active document
export format PDF type to PathToDocuments & (characters 1 thru -6 of doc_name) & ".pdf" using my_pdf_choice
end tell

Thank you in advance for the time spend helping with my issue !

gallery content skips fast when I click the prev and next button. why?

I took this gallery from w3school and modified it. the issue i am facing is when i click the next or prev button the items skips fast. when nothing is click it behaves normal. how do i stop it from jumping and for it to behave normal. here is the code

 [style]

.mySlides {display: none;}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  background:#000
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
  display:none
}

/* The dots/bullets/indicators */
.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}
.prev, .next{
cursor:pointer;
}

.active {
  background-color: #717171;
}

#num{
background:red;
}

[html]

<h2>Automatic Slideshow</h2>

<div class="slideshow-container">

<div class="mySlides fade">
  <div class="numbertext">1 / 3</div>
 <img src="img_nature_wide.jpg" style="width:100%">
 <div class="text">Caption Text</div>
</div>

<div class="mySlides fade">
  <div class="numbertext">2 / 3</div>
  <img src="img_snow_wide.jpg" style="width:100%">
  <div class="text">Caption Two</div>
</div>

<div class="mySlides fade">
 <div class="numbertext">3 / 3</div>
 <img src="img_mountains_wide.jpg" style="width:100%">
 <div class="text">Caption Three</div>
 </div>
  <div id="num">num</div>
  </div>
  <br>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>

[javascript]

let slideIndex = 0;
showSlides(slideIndex);
document.getElementsByClassName("num").innerText = "s";


  //showSlides();
  function plusSlides(n) {
  showSlides(slideIndex += n);
  }

  function currentSlide(n) {
  showSlides(slideIndex = n);
 }
 function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
 let numval =   document.getElementById("num");

if (n > slides.length) {slideIndex = 1}    
if (n < 1) {slideIndex = 1}
for (i = 0; i < slides.length; i++) {
  slides[i].style.display = "none";  
}
 slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}    

  slides[slideIndex-1].style.display = "block";  

  setTimeout(showSlides, 5000); // Change image every 5 seconds
}

how do i stop it from jumping and for it to behave normal

my calculation is failing in my code for 0.5 adding or not

I am trying to select dates along with AM and PM, but i am getting confused where i am doing it wrong, here is my piece of code

if (($('##StartDate_TmZone').length != 0 && $('##EndDate_TmZone').length != 0) && ($('##StartDate_TmZone').val() != null && $('##EndDate_TmZone').val() != null) && ($('##StartDate_TmZone').val() != $('##EndDate_TmZone').val())) {
                        if ($('##calfield1').val() == $('##calfield2').val()) {
                            iNumWorkDays = 0.5;
                        } else {
                            if ($('##calfield1').val() != $('##calfield2').val()) {
                                iNumWorkDays += 0;
                            } else {
                                iNumWorkDays += 0.5;
                            }    
                        }
                    }

what i am trying is:

  1. if the start date and end date are same and they ended up in AM and AM, so its 0.5
  2. if Start Date is today and end date is tomarrow and Start Date is AM and end Date is PM, so its total of 2 days
  3. if Start date is Today and started in AM and end date is tomarrow ended in AM, its 1.5
    4, if start date is Today and started in PM and ended in PM tomarrow, its is again 1.5
  4. if the start is today and end is tomarrow and started in morning AM and ended in morning on next to next day, its 2.5

what i am doing wrong here, please guide

Recursive Vue 3 component doesn’t update props

I have two recursive components. The first is the wrapper of the elements, the second, respectively, by the element itself

The wrapper

<template>
  <div class="filter-tree">
    <filter-tree-item
      v-for="item in items"
      :key="item.id"
      :deep="deep"
      :item="item"
      @on-interact="interact"
    ></filter-tree-item>
  </div>
</template>

<script setup lang="ts">
export interface Props {
  items: Items[];
  deep?: number;
}

const props = withDefaults(defineProps<Props>(), {
  deep: 0
})

const interact = () => {
  console.log(props.deep) // logs always 0
}
</script>

The item

<template>
  <p @click="handle">{{ deep }}</p> <!--Shows correct deep-->
  <filter-tree v-if="hasChildren" :items="item.children" :deep="deep + 1"></filter-tree>
</template>

<script setup lang="ts">
export interface Props {
  item: Item;
  deep?: number;
}

const props = withDefaults(defineProps<Props>(), {
  deep: 0,
});

const emits = defineEmits(['on-interact'])

const handle = () => {
  emits('on-interact')
}
</script>

The deep prop is output correctly in the template, but when I try to get it inside my script, I always get the topmost one, in my case 0. Although 2 came out and I should have gotten 2.

What could be the problem?

Google Maps Javascript API not loading map on my React/Typescript app

Here is my code. I have been following this documentation and implemented the code as follows.

import styled from "@emotion/styled";
import { useEffect, useState } from "react";

const MapWrapper = styled.div`
  width: 300px;
  height: 300px;
`;

const MapElement = styled.div`
  height: 300px;
  width: 300px;
`;


declare global {
  interface Window {
    initMap: () => void;
  }
}

const API_KEY = "key code here";

export function Map() {
  const [loadScript, setLoadScript] = useState(false);

  useEffect(() => {
    // Create a google maps initializer function for the script to use
    let map: google.maps.Map;
    function initMap(): void {
      map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
      });
    }
    window.initMap = initMap;

    setLoadScript(true);
  }, []);

  return (
    <>
       <MapWrapper>
         <MapElement id="map" />
       </MapWrapper>
       {loadScript && (
           <script
             src={`https://maps.googleapis.com/maps/api/jskey=${API_KEY}&callback=initMap&v=weekly`}
             async
           />
       )}
    </>
  );
}

This code yields no errors in the dev console, just an empty blank spot on my page. I can see the initMap function on the window object and I can see the google object in the dev console too. I’ve looked at other posts about people who’ve faced this issue and it seems to be something to do with the id="map" div or its wrapper not having a height/width css prop. I’ve done both of that and still I cannot see the map.
I’ve also gone into Google Cloud > Apis and Services > Credentials > Edit Key and verified that my key is:

  1. Has no application restrictions in place
  2. Is restricted to only use the Maps JavasCript API

Any ideas on what else I could try? Thanks!

Why does Math.random() is not generating different values when called multiple times?

I want to change color of an element dynamically but when i use random function, the values aren’t changing during runtime.

This is my code:-

var r = 0
var g = 0
var b = 0
function changeColor()
{
    r = Math.floor(Math.random()*256)
    g = Math.floor(Math.random()*256)
    b = Math.floor(Math.random()*256)
    document.querySelector('.gameEnter').style.borderColor = 'rgb(' + r + ',' + g + ',' + b + ')'
}
console.log(r,g,b)
setInterval(changeColor(), 5)