Allow curly brackets in url validation

I’m working with Yup and would like it to match urls that use curly brackets in the query string in cases like these (currently it doesn’t match as a valid url):

https://blah.blahblah.net/register/{0}
https://blah.blahblah.net/provider/tool.php?id={0}

I know that I need to have a custom regex match for this.

It would be great if the solution could be “built” on top of current Yup url regex match case which is:
/^((https?|ftp):)?//(((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:)*@)?(((d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]))|((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?)(:d*)?)(/((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)+(/(([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)*)*)?)?(?((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|[uE000-uF8FF]|/|?)*)?(#((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|/|?)*)?$/i;

Calculate hours and minutes between two values that contains 4 digits with Javascript [closed]

I have three fields in an eForm called Start, Stop and Total. In the field start and stop i want to enter four digits (ex 1100). I want to calculate the difference between the two values an that sum should show up in Total field as HH.mm .

So:

Start: 1030
Stop: 1200

Total 1.30

I have tried some diifrent scripts but i end up getting for example this problem:

If i a enter 1000 and 1100 it gets a total of 1.00 (CORRECT)
If i a enter 1000 and 1030 it gets a total of .30 (CORRECT but i would like 0.30)
If i a enter 0930 and 1000 it gets a total of .70 (WRONG, it should give .30 or as i wish 0.30)

Can it be that i need to convert the two first digits to hours and the last two to seconds?
How do i do that?

Best regards
Daniel

White screen on initial load when updating my progressive web app

I’m using create react app and recently added a service worker so as to make it a PWA. It was very easy and seemed to work great. However, now whenever I build a new version of my app I get the following error on the initial load of the website:

enter image description here

I believe the problem is that when I build my app the file names are randomly generated and don’t match the old ones. The PWA is using the old index.html trying to fetch the old files which don’t exist anymore.

What is the best way of fixing this?

Reuse react individual components in JSP

I have an existing application that’s written on core java, i mean no java framework has been used. I have another frontend application that’s built on react. Is it possible to import any react component for e.g menu. Instead of creating a new menu, can i reuse component that’s part of another application?

Any help would be appreciated!

Repeater doesn’t work how i wanted to work, react

I am working in wordpress and trying to create a custom gutenberg block with react. I am using the and that is working fine. I have the following fields that requires input like text or a image or a star rating:

Name:,
Workfunction:,
Image:,
Rating:,
Testimonial:

But the output in the editor field isn’t working properly as i wanted. So what is happening:

I put the info in the the info should be displayed in the editor and that is working. So if i add 1 block it’s working like a charm, so you get this:

Name: ben
Workfunction: DEV
Image: media
Rating: 5 stars (i choose 5 stars)
Testimonial: story

When i add a second the following is happening based on the fields i fill in.

Name: ben
Name: test
Workfunction: DEV
Workfunction: DEV
Image: media
Image: media
Rating: i choose 5 stars again, so the output is 10
Rating: i choose 5 stars again, so the output is 10
Testimonial: story
Testimonial: story

Name: ben
Name: test
Workfunction: DEV
Workfunction: DEV
Image: media
Image: media
Rating: i choose 5 stars again, so the output is 10
Rating: i choose 5 stars again, so the output is 10
Testimonial: story
Testimonial: story

It seems te duplicate and add to the same fields. What i am trying to get is the following:

Name: ben
Workfunction: DEV
Image: media
Rating: 5
Testimonial: story

Name: test
Workfunction: DEV
Image: media
Rating: 5
Testimonial: story

This is all happening in the return area and above i think. Could some on explain to me how to resolve this problem and what i have done wrong?

Here is mine code for a better understanding:

/**
 * BLOCK: project-drie
 *
 * Registering a basic block with Gutenberg.
 * Simple block, renders and saves the same content without any interactivity.
 */

//  Import CSS.
import './editor.scss';
import './style.scss';
import React from 'react';
import ReactDom from 'react-dom';
import { FaStar } from "react-icons/fa";
import {Helmet} from "react-helmet";



// import components
import { useBlockProps, RichText, InnerBlocks, MediaUpload, InspectorControls, MediaUploadCheck } from '@wordpress/block-editor';


const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { Button, IconButton, PanelBody, TextareaControl, TextControl, SelectControl, CustomSelectControl } = wp.components;
const { Fragment, useState } = wp.element;


/**
 * Register: aa Gutenberg Block.
 *
 * Registers a new block provided a unique name and an object defining its
 * behavior. Once registered, the block is made editor as an option to any
 * editor interface where blocks are implemented.
 *
 * @link https://wordpress.org/gutenberg/handbook/block-api/
 * @param  {string}   name     Block name.
 * @param  {Object}   settings Block settings.
 * @return {?WPBlock}          The block, if it has been successfully
 *                             registered; otherwise `undefined`.
 */


registerBlockType( 'cgb/block-project-drie-testimonials', {
    title: __( 'project-drie - Testimonials' ), // Block title.
    icon: 'shield',
    category: 'project drie',
  supports: {
        align: true,
    },
    keywords: [
        __( 'project-drie — CGB testimonials' ),
        __( 'testimonials' ),
    __( 'testimonial' ),
    ],
  attributes: {
    title: {
      type: 'string',
      source: 'text',
      selector: 'figcaption',
    },
    subtitle: {
      type: 'string',
      source: 'text',
      selector: 'figcaption',
    },
    testimonial: {
            type: 'array',
            default: [],
        },
  },

    /**
     * The edit function describes the structure of your block in the context of the editor.
     * This represents what the editor will render when the block is used.
     *
     * The "edit" property must be a valid function.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Component.
     */


   edit: props => {
    const { attributes: {title, subtitle, testimonial, media, selectcontrol}, className, setAttributes } = props;
    const onChangeTitle = title => { setAttributes ( { title } ) };
    const onChangeSubtitle = subtitle => { setAttributes ( { subtitle } ) };
    const onSelectImage = ( media ) => { setAttributes( { media: media} );};
    const handleAddTestimonial = () => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial.push( {
                author: '',
        position: '',
        testimonial: '',
        media: '',
        selectcontrol: '',
            } );
            props.setAttributes( { testimonial } );
        };

    const handleRemoveTestimonial = ( index ) => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial.splice( index, 1 );
            props.setAttributes( { testimonial } );
        };

    const handleTestimonialChange = ( key, value, index  ) => {
            const testimonial = [ ...props.attributes.testimonial ];
            testimonial[ index ][key] = value;
            props.setAttributes( { testimonial } );
        };


    let testimonialFields,
            testimonialDisplay;

    let authorFields,
            authorDisplay;

    let positionFields,
            positionDisplay;

    let mediaFields,
            mediaDisplay;

    let selectcontrolFields,
            selectcontrolDisplay;


        if ( props.attributes.testimonial.length ) {
            testimonialFields = props.attributes.testimonial.map( ( testimonial, index ) => {

                return <Fragment key={ index }>
            <TextControl
                        className="author__react__testimonials"
                        placeholder="Add testimonial."
                        value={ testimonial.testimonial }
                        onChange={ ( value ) => handleTestimonialChange('testimonial', value, index ) }
                    />

            <TextControl
                        className="author__react__name"
                        placeholder="Add Author Name. Example: Ben"
                        value={ testimonial.author }
                        onChange={ ( value ) => handleTestimonialChange('author', value, index ) }
                    />

            <TextControl
                        className="author__react__name"
                        placeholder="Add Function. Example: CEO."
                        value={ testimonial.position }
                        onChange={ ( value ) => handleTestimonialChange('position', value, index ) }
                    />
            <MediaUpload
              onSelect={ (value) => handleTestimonialChange('media', value, index ) }
              allowedTypes="image"
              value={ testimonial.media.id }
              render={ ( { open } ) =>  (
                  <Button className={ testimonial.media.length > 0 ? 'image-button' : 'button button-large' } onClick={ open }>
                      { testimonial.media.length > 0 ? __( 'Upload Image', 'gutenberg-examples' ) : <img src={ testimonial.media.url } alt={ __( 'Upload Recipe Image', 'gutenberg-examples' ) } />  }
                  </Button>

              )   }
            />
            <SelectControl

              label={ __( 'Press ctrl to multiple stars:' ) }
              value={ testimonial.selectcontrol } // e.g: value = [ 'a', 'c' ]
              onChange={ (value) => handleTestimonialChange('selectcontrol', value, index ) }
              options={ [
                  { value: null, label: 'Select a Star', disabled: false },
                  { value: 'star' ,  label: 'Add 1 star' },
                  { value: 'star2', label: 'Add 2 stars' },
                  { value: 'star3', label: 'Add 3 stars' },
                  { value: 'star4', label: 'Add 4 stars' },
                  { value: 'star5', label: 'Add 5 stars' },
              ] }
            />

                    <IconButton
                        className="testimonials__remove__react__testimonial"
                        icon="no-alt"
                        label="Delete location"
                        onClick={ () => handleRemoveTestimonial( index ) }
                    />
                </Fragment>;
            } );

        testimonialDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{ testimonial.testimonial  } </p>;
            } );

            authorDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{ testimonial.author  } </p>;
            } );

        positionDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
                return <p key={ index }>{testimonial.position}</p>;
            } );

        mediaDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
          return <img key={index} src={testimonial.media.url} alt={testimonial.media.alt} />
            } );

        selectcontrolDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
          if (testimonial.selectcontrol == 'star') {
            return  (testimonial.selectcontrol == 'star') ? <span><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star2') {
            return  (testimonial.selectcontrol == 'star2') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star3') {
            return  (testimonial.selectcontrol == 'star3') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star4') {
            return  (testimonial.selectcontrol == 'star4') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span>: testimonial.selectcontrol;
          } else if (testimonial.selectcontrol == 'star5') {
            return  (testimonial.selectcontrol == 'star5') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
          }
        } );
        }

        return [
      <div className={ className }>
            <InspectorControls key="1">
                <PanelBody title={ __( 'Testimonial' ) }>
                    { testimonialFields }
                    <Button
                        isDefault
                        onClick={ handleAddTestimonial.bind( this ) }
                    >
                        { __( 'Add Testimonials' ) }
                    </Button>
                </PanelBody>
            </InspectorControls>
            <div key="2" className={ props.className }>
          <div className="wp-block-cgb-block-project-drie-testimonial-info">
            <div className="wp-block-cgb-block-project-drie-testimonial-title">
              <h2>{ __('Title', 'cgb')}</h2>
                <RichText
                  tagName="div"
                  className="wp-block-cgb-block-project-drie-testimonial-titles"
                  placeholder={ __('Add your title here', 'cgb')}
                  onChange={ onChangeTitle}
                  value={ title }
                />
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-subtext">
            <h2>{ __('Sub-Text', 'cgb')}</h2>
              <RichText
                tagName="p"
                className="wp-block-cgb-block-project-drie-testimonial-subtexts"
                value={ subtitle }
                onChange={ onChangeSubtitle }
                placeholder={ __('Add your sub-text here', 'cgb')}
              />
            </div>
          </div>
          <div className="wp-block-cgb-block-project-drie-testimonial-repeater">
            <div className="wp-block-cgb-block-project-drie-testimonial-repeater-title">
                    <h2>Employee</h2>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-skillname">
              <h3>Author Name:</h3>
              <span>{ authorDisplay }</span>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-percentage">
              <h3>workFunction:</h3>
              <span>{ positionDisplay }</span>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-bgimages">
              <div className="wp-block-cgb-block-project-drie-testimonial-bgimage">
                <h2>Author Image</h2>
                {mediaDisplay}
              </div>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-ratings">
              <div className="wp-block-cgb-block-project-drie-testimonial-rating">
                <h2>Rating</h2>
                {selectcontrolDisplay}
              </div>
            </div>
            <div className="wp-block-cgb-block-project-drie-testimonial-testimonials">
              <div className="wp-block-cgb-block-project-drie-testimonial-testimonial">
                <h2>Review</h2>
                {testimonialDisplay}
              </div>
            </div>
          </div>
        </div>
      </div>

        ];

    },

    /**
     * The save function defines the way in which the different attributes should be combined
     * into the final markup, which is then serialized by Gutenberg into post_content.
     *
     * The "save" property must be specified and must be a valid function.
     *
     * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
     *
     * @param {Object} props Props.
     * @returns {Mixed} JSX Frontend HTML.
     */
    save: ( props ) => {
    const {attributes: { title } } = props;
    const {attributes: { subtitle } } = props;
    const {attributes: { media} } = props;
    const {attributes: { testimonial } } = props;
    const {attributes: { selectcontrol } } = props;

    const selectcontrolDisplay = props.attributes.testimonial.map( ( testimonial, index ) => {
      if (testimonial.selectcontrol == 'star') {
        return  (testimonial.selectcontrol == 'star') ? <span><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star2') {
        return  (testimonial.selectcontrol == 'star2') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star3') {
        return  (testimonial.selectcontrol == 'star3') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star4') {
        return  (testimonial.selectcontrol == 'star4') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span>: testimonial.selectcontrol;
      } else if (testimonial.selectcontrol == 'star5') {
        return  (testimonial.selectcontrol == 'star5') ? <span><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i><i className="fas fa-star checked"></i></span> : testimonial.selectcontrol;
      }
    } );






    // const skillnameFields = props.attributes.skillname.map( ( skillname, index ) => {
        //  return <p key={ index }>{ skillname.skill } { skillname.percentage }</p>;
        // } );

    return (
      <section className="testimonial">
        <Helmet>
          <script type="text/javascript" src="//cdn.jsdelivr.net/gh/kenwheeler/[email protected]/slick/slick.min.js"></script>
        </Helmet>
        <div className="container testimonial__container">
          <div className="row testimonial__row">
            <div className="testimonial__info">
              <div className="testimonial__subtext">
                <span>{ subtitle }</span>
              </div>
              <div className="testimonial__title">
                <h2>{ title }</h2>
              </div>
            </div>
            <div className="items testimonial__testimonials">
              {testimonial.map((field, i) => (
              <div className="testimonial__testimonial">
                <div className="testimonial__card" key={ i }>
                  <div className="testimonial__image">
                    <img src={field.media.url} />
                  </div>
                  <div className="testimonial__review">
                    <p>{field.testimonial}</p>
                  </div>
                  <div className="testimonial__stars">
                    <span>{selectcontrolDisplay}</span>
                  </div>
                  <div className="testimonial__author">
                    <div className="testimonial__name">
                      <span>{ field.author }</span>
                    </div>
                    <div className="testimonial__function">
                      <span>{ field.position }</span>
                    </div>
                  </div>
                </div>
              </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    );
    },
 } );

Draw line don’t work fine when local storage is used in js

I am storing user locations . when user has internet connection it goes directly to the server and store in database if user is not having internet it gets stored in localstorage and after having internet data uploaded on server.

It works fine with having internet but when i store in localstorage it draws weired lines on map.

enter image description here

code

 saveLocation(location){
      let data = {

          longitude: location?.longitude,
          latitude:location?.latitude,
          staff_id:TokenService.getUserInfo().id,
          work_order_id: TokenService.getWorkOrder(),
          deal_id: TokenService.getDealId()
        };
        let url = `api/save-location`;
     var offline_location = { url: url, method: "post", data: data };

       let options = {
        url: process.env.VUE_APP_ROOT_API+url,
        headers: {
            Authorization: `Bearer ${TokenService.getToken()}`
          },
        params: data,
      };
if(this.networkStatus){

   Http.post(options)
}else{
        var today = new Date();
        var time = today.getHours() + ":" + today.getMinutes()+ 
        ":"+today.getSeconds();
        this.$localStorage.set(`save_current_location_store_${time}`,JSON.stringify(offline_location));
      
     


    }
    },

How to get file name from the uploaded file using javascript?

i want to get the file name and show it in input element using javascript.

i have a button upload clicking that would open the browser to choose file once chosen i should display the chosen file name in input element.

below is my code,

const kubeConfig = get(values, `${fieldRoot}.kubeConfig`);

const fileName = useMemo(() => {
    if (kubeConfig) {
        return kubeConfig.name; //cannot read property name of undefined

    }
}, [kubeConfig]) 

<FormField
   label="file"
   fieldId={`${fieldRoot}.kubeConfig`}
>
    {({form}: FieldProps) => (
        <>
            <input 
                type="text"
                value={fileName ?? 'Upload file'}
            /> 
            <input
                type="file"
                style={{display: 'none'}}
                accept=".pem"
                ref={inputRef}
                onChange={async() => {
                   const file = inputRef?.current?.files?.[0];
                   if (file) {
                       try {
                           form.setFieldValue(
                                `${fieldRoot}.kubeConfig`,
                                 file
                           );
                        }
                    }
                }}

            />
            <button onClick={handleUploadClick}> Upload </button>
        )}
    </FormField>
    

i get error cannot read property name of undefined.

kubeconfig data is like below

enter image description here

I am new to programming learning on the go. could someone help me with this. thanks. how can i access name from kubeConfig data.

HOW TO RESOLVE EPSON PRINTER NOT COMMUNICATING WITH MAC?

What to attempt when you locate that your printer isn’t connecting with the Mac? If you still can’t connect your Epson printer to your Mac tool after many attempts, after that you could want to read this blog site right here. Check out the blog site to recognize the fixing actions. Dial the helpline number if you cannot aid on your own with Epson printer troubles. With the help of technical experts, you will certainly have the ability to find the answer to the printer bug. Well, you will straight try yourself to resolve the Epson Communication Error with Mac. It will be made complex to comply with.

https://www.onesparkles.com/how-to-resolve-epson-printer-not-communicating-with-mac/

I want to implement direction service from user location to shown marker in the map

I can show markers from database on the map and get user location. What i want is to add get direction button on the infowindow which gives the direction of that maker from the user location. Is it possible? if yes then please share the logic. Here is my js for showing markers and user location.

<script type='text/javascript'>
    <?php
        echo "var markers=$markers;n";

    ?>

    function initMap() {

        var latlng = new google.maps.LatLng(25.5941, 85.1376);
        var myOptions = {
            zoom: 15,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false
        };

        var map = new google.maps.Map(document.getElementById("map"),myOptions);
        var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
        

       for( i = 0; i < markers.length; i++ ) {
    lat = (markers[i].lat);
    lng = (markers[i].lng);
    name = (markers[i].name);
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat,lng),
                name:name,
                map: map
            }); 
            google.maps.event.addListener( marker, 'click', function(e){
                infowindow.setContent( this.name );
                infowindow.open( map, this );
            }.bind( marker ) );
        }
        infoWindow = new google.maps.InfoWindow();

  const locationButton = document.createElement("button");

  locationButton.textContent = "Locate Yourself";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };

          infoWindow.setPosition(pos);
          infoWindow.setContent("you are here");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter());
        }
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(
    browserHasGeolocation
      ? "Error: The Geolocation service failed."
      : "Error: Your browser doesn't support geolocation."
  );
  infoWindow.open(map);
        
        
    }
    </script>

And also i want the distance matrix input boxes (sorry i dont know what its called but the input boxes to enter starting point and end point)and the transport mode selection only two walking or by bike.

context is not behaving properly in react

I created below context in react.

NameContext.tsx

import { createContext } from 'react';
export  const AppContext = createContext(""); 

I used this context inside my Layout.tsx . I am using inside Layout because I have some business logic to execute. based on that isActive value will be set.

const [isActive,setIsActive]=useState("NO");
return(
    <AppContext.Provider value={isActive}>
             <User/>
     </AppContext.Provider> 
)

now under User.tsx I am accessing this tab.

import { useContext } from "react";
import { Link } from "react-router-dom"
import { AppContext } from "../context/NameContext";

const User = ()=>{

 const context = useContext(AppContext);
  let isActive:any;

 if(context=="YES")
  isActive=true;

  else
  isActive=false;

  console.log("context is:"+context);
  console.log(isActive);
  
    return(
        <>
                  <span>
                 {isActive && <Link to="user" > List of Users</Link> } 
                  </span>

          </>        

    )
}
export default User;

in just one page refresh it is delivering values many times and most of the time default values. I dont want default values but the value which I set in provider.
how can I avoid this abnormal behaviour.

enter image description here

Algorithmic inclusion relation

I have an algorithmic problem where I used to have an array with an index and now I want to have all of them

Here’s an example
Left: The input array originally contained index relationships
Right: New array index contains relationships (results regardless of the number order)

enter image description here
[[2],[],1]

[[2],[3],1,[]]

[[2],[],1,1]

[[2],[],1,[0]]

Close the page after certain interval [Puppeteer]

I have used puppeteer for one of my projects to open webpages in headless chrome, do some actions and then close the page. These actions, however, are user dependent. I want to attach a lifetime to the page, where it closes automatically after, say 30 minutes, of opening irrespective of whether any action is performed or not.

I have tried setTimeout() functionality of Node JS but it didn’t work (or I just couldn’t figure how to make it work).

const puppeteer = require('puppeteer-core');

const browser = await puppeteer.connect({browserURL: browser_url});
const page = await browser.newPage();
// timer starts ticking here upon creation of new page (maybe in a subroutine and not block the main thread)

/**
 ..
 Do something
 ..
*/

// timer ends and closePage() is triggered.

const closePage = (page) => {
    if (!page.isClosed()) {
        page.close();
    }
}

Validation does not work when performing a custom validation, Express Validator Express

Using Express Validator I need to verify what comes in the request but I always get an error with Express Validator indicating “Invalid value“.

This is generated with this code in my route:

        check('detail').not().isEmpty()
        .custom( (value, {req}) => {
            console.log(req.body);
        }),

So I get the error:

error

I have tried with other routes to do the same thing, capture the request but I always get the same error message.

I appreciate your help.