How to Find element inside iframe by its text in cypress

I’m trying to locate an element within an iframe based on its text using Cypress

Neither of the following methods is not working in order to find or interact with element based on its text:

`

import "cypress-iframe";

cy.iframe('[data-testid="iframe"]').within(() => {
cy.contains('The cost is £500.00.', { timeout: 30000 }).should('be.visible');
});

cy.iframe().contains('The cost is £500.00')
cy.iframe().find('The cost is £500.00')`

Discord.js Interaction has failed

I am trying to create a simple ticketbot for discord, but I ran into an issue that I cannot seem to fix, I have tried several different approaches and adding a deferReply aswell, but whenever the button to create a ticket is clicked, I get the “interaction has failed” error.
I also added error handling to check if there might be another issue related to permission, but there is no console output at all, so i am really unsure on what the error is.

If anyone knows of a way to fix this I would greatly appreciate it.
Below is my code

const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, PermissionsBitField } = require('discord.js');
const { translate } = require('../locales/en.json');

class TicketManager {
    constructor(client) {
        this.client = client;
        this.setupInteractionHandler();
    }

    setupInteractionHandler() {
        this.client.on('interactionCreate', async interaction => {
            if (!interaction.isButton()) return;

            switch (interaction.customId.split('_')[0]) {
                case 'create_ticket':
                    await this.handleTicketCreation(interaction).catch(error => {
                        console.error('Error handling ticket creation:', error);
                        interaction.followUp({ content: translate("ERROR_CREATING_TICKET"), ephemeral: true }).catch(console.error);
                    });
                    break;
                case 'close_ticket':
                    await this.handleTicketClosure(interaction).catch(error => {
                        console.error('Error handling ticket closure:', error);
                        interaction.followUp({ content: translate("ERROR_CLOSING_TICKET"), ephemeral: true }).catch(console.error);
                    });
                    break;
            }
        });
    }

    async handleTicketCreation(interaction) {
        await interaction.deferReply({ ephemeral: true });

        try {
            const supportCategory = interaction.guild.channels.cache.find(c => c.type === ChannelType.GuildCategory && c.name.toLowerCase() === "support");
            if (!supportCategory) {
                console.error('Support category does not exist');
                return interaction.editReply({ content: translate("SUPPORT_CATEGORY_MISSING") });
            }

            if (!interaction.guild.me.permissions.has(PermissionsBitField.Flags.ManageChannels)) {
                console.error('Missing permission to manage channels');
                return interaction.editReply({ content: translate("MISSING_MANAGE_CHANNELS_PERMISSION") });
            }

            const ticketChannel = await interaction.guild.channels.create({
                name: `ticket-${interaction.user.username.toLowerCase()}-${Date.now()}`,
                type: ChannelType.GuildText,
                parent: supportCategory.id,
                permissionOverwrites: this.getPermissionOverwrites(interaction)
            });

            const closeTicketButton = new ButtonBuilder()
                .setCustomId(`close_ticket_${ticketChannel.id}`)
                .setLabel(translate("CLOSE_TICKET"))
                .setStyle(ButtonStyle.Danger);

            const row = new ActionRowBuilder().addComponents(closeTicketButton);
            const embed = new EmbedBuilder()
                .setColor(0x00AE86)
                .setTitle(translate("TICKET_CREATED_TITLE"))
                .setDescription(translate("TICKET_CREATED_DESCRIPTION", { user: interaction.user.username }))
                .setFooter({ text: translate("USER_ID_LABEL") + `: ${interaction.user.id}` });

            await ticketChannel.send({ content: interaction.user.toString(), embeds: , components: [row] });
            await interaction.editReply({ content: translate("TICKET_CREATED_REPLY") });
        } catch (error) {
            console.error('Failed to create ticket:', error);
            throw error;
        }
    }

    async handleTicketClosure(interaction) {
        try {
            if (!interaction.guild.me.permissions.has(PermissionsBitField.Flags.ManageChannels)) {
                console.error('Missing permission to manage channels');
                throw new Error(translate("MISSING_MANAGE_CHANNELS_PERMISSION"));
            }

            const ticketChannel = interaction.channel;
            await ticketChannel.delete();
        } catch (error) {
            console.error('Failed to close ticket:', error);
            throw error;
        }
    }

    getPermissionOverwrites(interaction) {
        return [
            {
                id: interaction.guild.id,
                deny: [PermissionsBitField.Flags.ViewChannel]
            },
            {
                id: interaction.user.id,
                allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages]
            },
            {
                id: interaction.guild.roles.cache.find(r => r.name === "Administrator").id,
                allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.ManageMessages]
            }
        ];
    }
}

module.exports = TicketManager;


How can we store data in storage using Capacitor JS with Angular?

I read this documentation, which is capacitor JS provided

This is my code for storing the data in capacitor js.

/*
 * this function is used for the set Value
 */
async setUser(data: any) {
  await Preferences.set({
        key: 'value',
        value: JSON.stringify(data)
  });
}

/*
 * this function is used for the get-Value
 */
async getUser() {
  const user: any = await Preferences.get({ key: 'value' });
  this.UsersDetails = user.value;
}

This is working fine when my app is running in the background.
When I trash my app in the background and call for getUser(). It’s giving a null value. it’s not work.

Can anyone suggest if I am missing anything, or is there any other way available to Store the data in Capacitor JS?

Selling My Projects: Tips and Strategies? [closed]

Basically my personal website is about selling coding projects like users can purchase projects from my website . i have multiple projects that are listed on my official website snipbyte.com i want to sell these project there are various projects such as advance attendance managment system built via next js and mongodb and also lms system built in mern stack but i am not getting much sales is there any way ?
Thank you

I want to get sales because as you can see i have very advance system such as this one
https://snipbyte.com/blogpost/next-js-tailwind-css-advanced-attendance-management-system-optimize-workforce-efficiency

How to write test case to delete the cookies in angular

My interceptor look like this:

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie-service';
@Injectable({
  providedIn: 'root'
})
export class HttpErrorService implements HttpInterceptor {
  constructor(private cookieService: CookieService) { }
  intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
    if(document.cookie.length > 4500){
      document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
    }
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        return throwError(() => { return 'Something bad happened; please try again later.' })
      })
    );
  }
}

I am just focused on if block before return.next. I want write test case for deleting the cookies.

 if(document.cookie.length > 4500){
      document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
    }

Not found suitable resource. I need to write test case for only deleting the cookies.

JavaScript fetch with body [duplicate]

I’m trying to retrieve a list of quests from this page using this url:

https://graphigo.prd.galaxy.eco/query

Here is my code

const galxeQuestsURL = 'https://graphigo.prd.galaxy.eco/query';

let queryBody = '{"operationName":"CampaignList","variables":{"input":{"listType":"Trending","credSources":null,"gasTypes":null,"types":null,"rewardTypes":null,"chains":null,"isVerified":null,"statuses":null,"spaceCategories":null,"backers":null,"first":20,"after":"-1","searchString":null,"claimableByUser":null},"address":"0x955cc96a6ae344bc9d576b62c6cfbb68d3479bb2"},"query":"query CampaignList($input: ListCampaignInput!, $address: String!) {n  campaigns(input: $input) {n    pageInfo {n      endCursorn      hasNextPagen      __typenamen    }n    list {n      ...CampaignSnapn      isBookmarked(address: $address)n      idn      numberIDn      namen      childrenCampaigns {n        idn        typen        rewardNamen        rewardInfo {n          discordRole {n            guildIdn            guildNamen            roleIdn            roleNamen            inviteLinkn            __typenamen          }n          __typenamen        }n        __typenamen      }n      whitelistInfo(address: $address) {n        usedCountn        __typenamen      }n      watchlistPro {n        watchListIdn        rewardIconGifn        rewardIconn        rewardCampaignn        __typenamen      }n      infon      useCredn      formulan      thumbnailn      gasTypen      createdAtn      requirementInfon      descriptionn      enableWhitelistn      chainn      startTimen      statusn      requireEmailn      requireUsernamen      distributionTypen      endTimen      rewardNamen      capn      loyaltyPointsn      tokenRewardContract {n        idn        addressn        chainn        __typenamen      }n      tokenReward {n        userTokenAmountn        tokenAddressn        depositedTokenAmountn        tokenRewardIdn        tokenDecimaln        tokenLogon        tokenSymboln        __typenamen      }n      space {n        idn        namen        thumbnailn        aliasn        isVerifiedn        __typenamen      }n      rewardInfo {n        discordRole {n          guildIdn          guildNamen          roleIdn          roleNamen          inviteLinkn          __typenamen        }n        premint {n          startTimen          endTimen          chainn          pricen          totalSupplyn          contractAddressn          bannern          __typenamen        }n        __typenamen      }n      participants {n        participantsCountn        bountyWinnersCountn        __typenamen      }n      recurringTypen      __typenamen    }n    __typenamen  }n}nnfragment CampaignSnap on Campaign {n  idn  namen  inWatchListn  inNewYearWatchListn  ...CampaignMedian  dao {n    ...DaoSnapn    __typenamen  }n  __typenamen}nnfragment DaoSnap on DAO {n  idn  namen  logon  aliasn  isVerifiedn  __typenamen}nnfragment CampaignMedia on Campaign {n  thumbnailn  rewardNamen  typen  gamification {n    idn    typen    __typenamen  }n  __typenamen}n"}';

fetch(galxeQuestsURL, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: queryBody,
})
.then(response => response.json())
.then((jsonData) => {
  // jsonData is parsed json object received from url
  //console.log(jsonData);

})
.catch((error) => {
  // handle your errors here
  console.error(error);
});

In Postman the response works fine but when I run this locally with my own code above I get the error:

graphigo.prd.galaxy.eco/query:1 
    
    
Failed to load resource: the server responded with a status of 400 ()

How can I set up my request correctly? Thank you!

How to fix errors and warnings vite/vue

How to fix errors and warnings vite/vue.
After adding the data, I will give it axios data and then I want to create a datatable. It can be done but the error and warning like in the picture always come up.

  async createDataTable() {
      await this.$nextTick();
      const table = await window.$("#myTableCorporation").DataTable();
      if (table) {
        await table.destroy();
      }
      await window.$("#myTableCorporation").DataTable({
        oLanguage: {
          sDecimal: "",
          sEmptyTable: "ไม่มีรายการข้อมูล",
          sInfo: "แสดงรายการที่ _START_ ถึง _END_ จาก _TOTAL_ รายการ",
          sInfoEmpty: "ไม่มีรายการข้อมูล",
          sInfoFiltered: "(กรองจากทั้งหมด _MAX_ รายการ)",
          sInfoPostFix: "",
          sThousands: ",",
          sLengthMenu: "แสดง  _MENU_ รายการ",
          sLoadingRecords: "กำลังโหลดข้อมูล...",
          sProcessing: "กำลังประมวลผล...",
          sSearch: "ค้นหา:",
          sZeroRecords: "ไม่พบรายการที่ค้นหา",
          oPaginate: {
            sFirst: "หน้าแรก",
            sLast: "หน้าสุดท้าย",
            sNext: "ถัดไป",
            sPrevious: "ก่อนหน้า",
          },
        },
        columnDefs: [
          { className: "dt-center", targets: "_all" },
          { className: "dt-body-left", targets: [3, 4, 6, 7] },
          { width: "10%", targets: [2, 5] },
          { width: "20%", targets: [3, 4] },
          { width: "5%", targets: [0, 1, 6, 7] },
        ],
        scrollX: true,
        autoWidth: false,
        responsive: true,
      });
    },
  },
watch: {
    _getCorporation() {
      this.createDataTable();
    },
  },

enter image description here

NotReadableError: Could not start video source

I have a web app that lets user toggle camera view similar to a video call app. But everytime I press the switch camera view button I get the error: “NotReadableError: Could not start video source”. Im fairly new to camera functions in javascript so Im not sure why I keep triggering this error. Its worth mentioning that Im using Webex to integrate the video calling functions. Any help would be greatly appreciated. Thanks in advance.

Code for switching camera view:

//Switching camera view:
(() => {
  const videoElm = document.querySelector('#self-view');
  var camSwitch = document.getElementById('but1');

  // const supports = navigator.mediaDevices.getSupportedConstraints();

  if (navigator.mediaDevices && navigator.mediaDevices.getSupportedConstraints) {
    const supports = navigator.mediaDevices.getSupportedConstraints();
    if (!supports['facingMode']) {
      alert('Browser Not supported!');
      return;
    }

    let stream;

    const capture = async facingMode => {
      const options = {
        audio: false,
        video: {
          facingMode,
        },
      };

      try {
        if (stream) {
          const tracks = stream.getTracks();
          tracks.forEach(track => track.stop());
        }
        stream = await navigator.mediaDevices.getUserMedia(options);
      }
      catch (e) {
        alert(e);
        return;
      }

      // Get active deviceID
      const videoTrack = stream.getTracks()?.find(track => track.kind === "video");
      devID = videoTrack.getSettings().deviceId;

      console.log('VideoID:' + devID);
      setVideoInputDevice();
    }

    if (camSwitch) {
      camSwitch.addEventListener('click', () => {
        if (document.getElementById('but1').value == 'front') {
          capture('environment');
          document.getElementById('but1').value = 'back';
        }
        else {
          capture('user');
          document.getElementById('but1').value = 'front';
        }
      });
    }
  }
  else {
    console.error('navigator.mediaDevices or getSupportedConstraints is not supported in this browser');
  }
})();

function setVideoInputDevice() {
  console.log("Function: SetVideoInputDevice")
  var meeting = activeMeeting;
  const { video } = getAudioVideoInput();
  var videoID = devID;

  if (meeting) {
    const mediaSettings = {
      receiveVideo: true, // set receiveVideo to false to only receive audio
      receiveAudio: true,
      receiveShare: false,
      sendShare: false,
      sendVideo: true, // set sendVideo to false to only send audio
      sendAudio: true
    };

    stopMediaTrack('video');
    meeting.getMediaStreams(mediaSettings, { video })
      .then((mediaStreams) => {
        const [localStream, localShare] = mediaStreams;
        meeting.updateVideo({
          sendVideo: true,
          receiveVideo: true,
          stream: localStream
        });
      })
      .catch((error) => {
        console.log('MeetingControls#setVideoInputDevice :: Unable to set video input device');
        console.error(error);
      });
  }
  else {
    console.log('MeetingControls#getMediaDevices() :: no valid meeting object!');
  }
}

function getAudioVideoInput() {
  const deviceId = (id) => ({ deviceId: { exact: id } });
  const audioInput = 'default';
  const videoInput = devID;

  return { audio: deviceId(audioInput), video: deviceId(videoInput) };
}


function stopMediaTrack(type) {
  console.log("Function: stopMediaTrack");
  const meeting = activeMeeting;

  if (!meeting) return;
  const { audioTrack, videoTrack, shareTrack } = meeting.mediaProperties;

  // Note: sometimes we are adding new track so the old track might not be present
  // eslint-disable-next-line default-case
  switch (type) {
    case 'audio':
      audioTrack?.stop();
      break;
    case 'video':
      videoTrack?.stop();
      break;
    case 'share':
      shareTrack?.stop();
      break;
  }
}

React Router Loader Behavior

I’m currently diving into React-Router, and I’ve set up my routing structure as follows:

const router = createBrowserRouter([    
  {
    path: "/",
    loader: rootLayoutLoader,
    element: <RootLayout />,
    children: [
      {
        path: "student",
        loader: commonPageLoader,
        element: <Student />,
      },
      {
        path: "teacher",
        loader: commonPageLoader,
        element: <Teacher />,
      },
    ],
  },
]);

In my setup, the rootLayoutLoader function is responsible for calling an API to gather some common information used by both the Teacher and Student components. Meanwhile, the commonPageLoader function is calling an API based on the location path to fetch specific data.

Now, here’s the issue I’m encountering: when I’m in the "/teacher" route and click the "Teacher" link, it triggers both the rootLayoutLoader and commonPageLoader functions. How can I prevent this double loading behavior while still ensuring the necessary data is fetched appropriately?

Generate PDF and append into database

This is the js file that i use to generate the pdf

    src="https://unpkg.com/[email protected]/dist/index.js"
function generatePDF() {
    var pdfObject = jsPDFInvoiceTemplate.default(props);

    var csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    var formData = new FormData();
    formData.append('pdfData', pdfObject);
    // Send PDF data to Laravel controller for saving
    $.ajax({
        url: '/save-pdf',
        type: 'POST',
        data: formData,
        contentType: false, // Don't set contentType manually, let jQuery handle it
        processData: false, // Don't process the data, let jQuery handle it
        headers: {
            'X-CSRF-TOKEN': csrfToken
        },
        success: function(response) {
            // Handle success response
            console.log('PDF saved successfully. PDF ID:', response.pdfId);
        },
        error: function(xhr, status, error) {
            // Handle error response
            console.error('Error saving PDF:', error);
        }
    });
}


var props = {
    outputType: jsPDFInvoiceTemplate.OutputType.Save,
    returnJsPDFDocObject: true,
    fileName: "Invoice 2021",
    orientationLandscape: false,
    logo: {
        src: "https://raw.githubusercontent.com/edisonneza/jspdf-invoice-template/demo/images/logo.png",
        type: 'PNG', //optional, when src= data:uri (nodejs case)
        width: 53.33, //aspect ratio = width/height
        height: 26.66,
        margin: {
            top: 0, //negative or positive num, from the current position
            left: 0 //negative or positive num, from the current position
        }
    },
    stamp: {
        inAllPages: true, //by default = false, just in the last page
        src: "https://raw.githubusercontent.com/edisonneza/jspdf-invoice-template/demo/images/qr_code.jpg",
        type: 'JPG', //optional, when src= data:uri (nodejs case)
        width: 20, //aspect ratio = width/height
        height: 20,
        margin: {
            top: 0, //negative or positive num, from the current position
            left: 0 //negative or positive num, from the current position
        }
    },
    business: {
        name: "Business Name",
        address: "Albania, Tirane ish-Dogana, Durres 2001",
        phone: "(+355) 069 11 11 111",
        email: "[email protected]",
        email_1: "[email protected]",
        website: "www.example.al",
    },
    contact: {
        label: "Invoice issued for:",
        name: "Client Name",
        address: "Albania, Tirane, Astir",
        phone: "(+355) 069 22 22 222",
        email: "[email protected]",
        otherInfo: "www.website.al",
    },
    invoice: {
        label: "Invoice #: ",
        num: 19,
        invDate: "Payment Date: 01/01/2021 18:12",
        invGenDate: "Invoice Date: 02/02/2021 10:17",
        headerBorder: false,
        tableBodyBorder: false,
        header: [
          {
            title: "#",
            style: {
              width: 10
            }
          },
          {
            title: "Title",
            style: {
              width: 30
            }
          },
          {
            title: "Description",
            style: {
              width: 80
            }
          },
          { title: "Price"},
          { title: "Quantity"},
          { title: "Unit"},
          { title: "Total"}
        ],
        table: Array.from(Array(10), (item, index)=>([
            index + 1,
            "There are many variations ",
            "Lorem Ipsum is simply dummy text dummy text ",
            200.5,
            4.5,
            "m2",
            400.5
        ])),
        additionalRows: [{
            col1: 'Total:',
            col2: '145,250.50',
            col3: 'ALL',
            style: {
                fontSize: 14 //optional, default 12
            }
        },
        {
            col1: 'VAT:',
            col2: '20',
            col3: '%',
            style: {
                fontSize: 10 //optional, default 12
            }
        },
        {
            col1: 'SubTotal:',
            col2: '116,199.90',
            col3: 'ALL',
            style: {
                fontSize: 10 //optional, default 12
            }
        }],
        invDescLabel: "Invoice Note",
        invDesc: "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary.",
    },
    footer: {
        text: "The invoice is created on a computer and is valid without the signature and stamp.",
    },
    pageEnable: true,
    pageLabel: "Page ",
};

and i declared the laravel web.php route
and this is the controller function

public function savePDF(Request $request)
    {
        try {
            $username = Session::get('username');
            // // Get the PDF data from the request
            // $pdfData = $request->input('pdfData');
            $pdfData = $request->file('pdfData');
            // Save the PDF data to the database using Eloquent
            $pdf = new pdfsaver();
            $pdf->username = $username;
            $pdf->files = $pdfData;
            $pdf->save();

            // Respond with success message and PDF ID
            return response()->json(['success' => true, 'pdfId' => $pdf->id]);
        } catch (Exception $e) {
            // Log the error

            // Respond with an error message
            return response()->json(['success' => false, 'error' => 'Error saving PDF']);
        }
    }

So the issue i encounter is that when i try to upload it as blob into the database. The blob generated in the database seems not working (just some C::location data instead of the PDF content).Hence, I try to think if I can just fetched the generated PDF and upload the PDF into the database. This js code currently functioning only until the generate PDF part. The PDF do generate but the file did not uploaded into the database

Why do I get a nested URL of ‘/auth/auth/ ‘ if the URL is not existing?

so I was following a tutorial and somehow stuck in a problem wherein if the URL is not existing in the routes.ts. It redirects to a nested /auth/auth/...../login/ instead of redirecting it to localhost:3000/auth/login

middleware.ts

import authConfig from "./auth.config"
import NextAuth from "next-auth"
import {
    DEFAULT_LOGIN_REDIRECT,
    publicRoutes,
    apiAuthPrefix,
    authRoutes
} from '@/routes'

 const { auth } = NextAuth(authConfig)

export default auth((req) => {
    const { nextUrl } = req;
    const isLoggedIn = !!req.auth;

    const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
    const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
    const isAuthRoute = authRoutes.includes(nextUrl.pathname);
    
    if(isApiAuthRoute){
        return ;
    }

    
    if(isAuthRoute){
        if(isLoggedIn){
            return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
        }

        return ;
    }


    if(!isLoggedIn && !isPublicRoute){
        return Response.redirect(new URL('auth/login', nextUrl))
    }

    return ;
  
})
 
export const config = {
    matcher: ["/((?!.+\.[\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
}

routes.ts

export const publicRoutes = [
    "/",
    "/auth/new-verification"
    
]

export const authRoutes = [
    "/auth/login",
    "/auth/register",
    "/auth/error"
]


export const apiAuthPrefix = "/api/auth"


export const DEFAULT_LOGIN_REDIRECT = "/settings"

For example, I’ve created a button here that will redirect to another page that is not included yet in my routes.ts.

<Button size="sm" variant="link" asChild className="px-0 font-normal">
  <Link href="/auth/reset">Forgor Password?</Link>
</Button>;

For example I clicked it.

this is the url

http://localhost:3000/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/login

What is the issue with the handleClick function in the Counter component provided?

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count++);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick = handleClick>Increment</button>
    </div>
  );
}

export default Counter;

React component code that renders a simple counter, but it doesn’t update properly when the button is clicked, What fix would you suggest for this code?

Get data sleep duration from goole fite with Fitness API

`How do I calculate the duration of sleep I get from Google Fit.

this is an example of json from google fit the code

"session": [
    {
        "id": "healthkit-0B3E9A38-694F-4B88-B15B-9C534759131D",
        "name": "Tidur",
        "description": "",
        "startTimeMillis": "1713798000000",
        "endTimeMillis": "1713817920000",
        "modifiedTimeMillis": "1713826670476",
        "application": {
            "packageName": "com.xiaomi.miwatch.pro",
            "version": "",
            "detailsUrl": ""
        },
        "activityType": 72
    },
    {
        "id": "healthkit-ABA36AB8-09E5-4AEC-9A6B-AA9DC5547567",
        "name": "Tidur",
        "description": "",
        "startTimeMillis": "1713798000000",
        "endTimeMillis": "1713817920000",
        "modifiedTimeMillis": "1713826670476",
        "application": {
            "packageName": "com.xiaomi.miwatch.pro",
            "version": "",
            "detailsUrl": ""
        },
        "activityType": 72
    },
    {
        "id": "healthkit-E5E08251-357B-4620-B0AB-6EDC0321F8BB",
        "name": "Tidur",
        "description": "",
        "startTimeMillis": "1713798000000",
        "endTimeMillis": "1713817920000",
        "modifiedTimeMillis": "1713826670476",
        "application": {
            "packageName": "com.xiaomi.miwatch.pro",
            "version": "",
            "detailsUrl": ""
        },
        "activityType": 72
    }
],
"deletedSession": []

Web automation correction

I am new to cooding. I am doing a project. The steps are mentioned below:-
Step 1 :- Open YouTube then search for a video and find it then click on it and after clicking on the video open pinned comment then click on the link.

I got the solution for step 1 :-
You could bypass the need of starting off at the homepage completely by appending the desired search query to the search_query parameter 🙂

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.maximize_window() wait = WebDriverWait(driver, 3) presence = EC.presence_of_element_located visible = EC.visibility_of_element_located # Navigate to url with video being appended to search_query driver.get(‘https://www.youtube.com/results?search_query={}’.format(str(video))) # play the video wait.until(visible((By.ID, “video-title”))) driver.find_element(By.ID, “video-title”).click()

Now the upper answer is matching with my automation project but please help me add the last lines to :-
Their is a link in pinned comment and i need the code to click it after the upper code finishes it’s work.
I tried my best to explain my problem, incase my explanation is not good then please suggest me with corrections. Thankyou.

Chart js. How to scroll to section when clicked

I just started learning how to include graphs in code but faced some issues.

I have a horizontal bar chart here that shows datas of transportations in countries.
under the chart there are sections with different ids.

Please Help…

    <script>
        var xValues = [['California', 'United States'], ['New York City', 'United States'], ['London','United Kingdom'], ['Paris','France'], ['Shanghai', 'China'], ['Hong Kong'], ['Kuala Lumpur', 'Malaysia'], "Singapore"];

Chart.defaults.global.backgroundColor = '#f9f9f9'
Chart.defaults.global.defaultFontColor = '#f9f9f9'
const config = {
    
    type: "horizontalBar",

    data: {
        labels: xValues,
        datasets: [
            {
                label: 'Bicycle/Electric Bikes',
                backgroundColor: "rgba(160, 206, 128, 0.8)",
                data: [0.8, 1.5, 5.6, 3.25, 20, 1, 0.3, 2.08],
                maxBarThickness: 30,
                link: '#data-bicycle'
            },
            {
                label: 'Electric Car',
                backgroundColor: "rgba(249, 199, 132, 0.8)",
                data: [25, 2.5, 34.3, 25.26, 4.87, 1.1, 1.15, 0.2], 
                maxBarThickness: 30,
                link: '#data-electric-car'
            },
            {
                label: 'Electric Bus/Trolley Bus',
                backgroundColor: "rgba(237, 106, 90, 0.8)",
                data: [4.7, 12, 5.15, 7.64, 11.11, 0.83, 0.77, 0.79], 
                maxBarThickness: 30,
                link: '#data-bus'
            },
            {
                label: 'Tram',
                backgroundColor: "rgba(205, 160, 204, 0.8)",
                data: [2, 0.08, 1.81, 16.3, 0, 3.1, 0, 0], 
                maxBarThickness: 30,
                link: '#data-tram'
            },
            {
                label: 'Metro/Trains',
                backgroundColor: "rgba(81, 163, 163, 0.8)",
                data: [2.68, 66.59, 49.22, 32.6, 49.39, 56, 19.14, 62.4], 
                maxBarThickness: 30,
                link: '#data-train'
            },
            {
                label: 'Electric Ships',
                backgroundColor: "rgba(52, 107, 134, 0.8)",
                data: [0.002, 0.24, 0.16, 0.06, 0.04, 0.2, 0, 0.02], 
                maxBarThickness: 30,
                link: '#data-ship'
            },
            {
                label: 'Others',
                backgroundColor: "rgba(249, 249, 249, 0.2)",
                data: [64.818, 17.09, 3.76, 14.89, 14.59, 37.77, 78.64, 34.51],
                maxBarThickness: 30,
                link: '#data-other'
            }
        ],
    },

    options: {
        legend: {
            display: true,
        },

        title: {
            display: false,
        },

        scales: {
            xAxes: [{
                ticks: {
                    min: 0,
                    max: 100,
                },
                type: 'linear',
                stacked: true,
                gridLines: {
                    color: 'rgba(255, 255, 255, 0.1)'
                },
                afterTickToLabelConversion : function(q){
                    for(var tick in q.ticks){
                        q.ticks[tick] += '%';
                    }
                },
            }],
            yAxes: [{
                stacked: true,
                gridLines: {
                    display: false,
                },
            }],
        },
        responsive: true,
        maintainAspectRatio: false,
    }
};

document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('hero-chart');
    const heroChart = new Chart(ctx, config);

    function clickHandler(event) {
        const firstPoint = heroChart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, true)[0];
        if (firstPoint) {
            const dataset = heroChart.data.datasets[firstPoint.datasetIndex];
            const link = dataset.link;
            if (link) {
                scrollToSection(link);
            }
        }
    }

    ctx.onclick = clickHandler;

    function scrollToSection(sectionId) {
        const section = document.querySelector(sectionId);
        if (section) {
            section.scrollIntoView({ behavior: 'smooth' });
        }
    }
});
 
    </script>

<section class="data-bicycle"></section>

<section class="data-car"></section>

<section class="data-bus"></section>

<section class="data-tram"></section>

<section class="data-trains"></section>

<section class="data-ship"></section>

<section class="data-other"></section>

I tried to make the page scrolled down to specific sections when the bar is clicked

I tried different codes for 24 hours but nothing seems to work as expected