If/else statement in case JSON endpoint doesn’t exists

I am trying to create a scenario where if endpoint doesn’t exists, function still returns a value.

When the endpoint exists, I get a value, no problem.

var main = function(){
json_url = "http://ergast.com/api/f1/current/next.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);

let race = " ";

if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
  race = " ";
} 
else {
  race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}

I get the following result

2022-07-09

But in case the endpoint doesn’t exists, I get a error.

var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);

let race = " ";

if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
  race = " ";
} 
else {
  race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}

How can I rectify this. Do I have to assign something other than undefined in this case.

How to store task in localstorage than onload make it appear in individual tasks

I am trying to make a To Do list but I have encountered a problem with storing it in local storage. I have tried storing the task in a var than it in localStorage but than when a new task is added it overwrites the variable and when I tried to store it in array and than when I tried to retrieve it from array all tasks appeared in a single task div. I want to store the tasks in local storage and have the task be edited, deleted, marked done also for localStorage too. I am providing the code.

<–JS–>

let tasksDiv = document.getElementById("tasks");
let oldTasksDiv = document.getElementById("old-tasks");
let input = document.getElementById('input');
var clear = document.getElementById('clear');
input.value = "What do you have planned?";

addBtn.addEventListener('click' , onclickBtn);
input.addEventListener('keypress' , function(){
    if(event.keyCode === 13){
        onclickBtn();
    }
});
input.addEventListener('click' , function (){
    if(input.value === "What do you have planned?"){
        input.value ="";
    }
})
clear.addEventListener('click' , function (){
    input.value ="";
})

function onclickBtn(){
    if(input.value.length !== 0){

        var tasksName = document.createElement('div');
        tasksName.classList.add("tasks-div")
        
        var task = document.createElement('p');
        task.innerText = input.value;
        task.classList.add("task");
        
        var del = document.createElement('button');
        del.classList.add("del");
        del.innerHTML = '<i class="fas fa-solid fa-trash"></i>';
    
        var edit = document.createElement('button');
        edit.classList.add("edit");
        edit.innerHTML = '<i class="fas fa-solid fa-pen-to-square"></i>';
    
        var save = document.createElement('button');
        save.classList.add("save");
        save.innerHTML = '<i class="fas fa-solid fa-floppy-disk"></i>';

        var chkbox = document.createElement('input');
        chkbox.classList.add("chkbox")
        chkbox.type = "checkbox";

        tasksName.appendChild(chkbox);
        tasksName.appendChild(task);
        tasksName.appendChild(del);
        tasksName.appendChild(edit);
        tasksName.appendChild(save);
        tasksDiv.appendChild(tasksName);

        chkbox.addEventListener('click' , function(){
            if(chkbox.checked === true){
                task.style.textDecoration = "line-through red";
                edit.style.display = "none";
                save.style.display = "none";
            }
            else{
                task.style.textDecoration = "none";
                edit.style.display = "block";
            }
        })
    
        del.addEventListener('click' , function(){
            tasksDiv.removeChild(tasksName);
        })
            
        edit.addEventListener('click' , function(){
            task.contentEditable = true;
            task.focus();
            edit.style.display = "none";
            save.style.display = "block";
        })

        save.addEventListener('click' , function(){
            if(task.innerHTML === '<br>'){
                alert('This task will be deleted');
                tasksDiv.removeChild(tasksName);
            }
            task.contentEditable = false;
            task.blur();
            edit.style.display = "block";
            save.style.display = "none";
        })
    }

    else{
        alert("Please enter a task");
    }
}

<-- HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tasks Keeper</title>
    <link rel="stylesheet" href="./css/style.css">
    <link rel="stylesheet" href="./css/resp.css">
    <script src="https://kit.fontawesome.com/6bf6193572.js" crossorigin="anonymous"></script>
    <script src="https://kit.fontawesome.com/9b41c17796.js" crossorigin="anonymous"></script>
</head>
<body>
    <header>
        <div class="brand-div">
            <h1><span class="brand">Tasks Keeper</span></h1>
            <span class="made-by">Made By <a href="https://raghavsrvt.ml" target="_blank">Raghav Srvt</a></span>
        </div>
        <div class="input-div">
            <div class="input-div-clear">
                <input type="text" placeholder="What do you have planned?" id="input" value="What do you have planned?">
                <i class="fa-solid fa-xmark" id="clear"></i>
            </div>
            <button type="submit" id="add-btn">Add</button>
        </div>
    </header>

    <div id="tasks">
        
    </div>

    <script src = "./app.js"></script>
</body>
</html>

Need Clarification on Execution Context

function a(){
    b();
    var c;
}

function b(){
    var d;
}

a();
var d;

I would like a clarification on Execution Context for the code above. From what I understand, during the creation phase of Execution Context functions a and b are set as pointers to the location in heap memory and var d is set to undefined. During the execution phase, function declarations a and b are simply ignored.

What I’m confused about is whether function invocation a() is ignored or not ignored during the execution phase. Do we push function execution context a() on execution stack during the execution phase of Global Execution Context or after it? If we push it during the execution context will var d be ignored until we pop the Global Execution Context?

Same questions as above will be for phases of execution context of function a. Is b() invoked during the execution context of function a or after it?

How to extract data from the invoice text

I am trying to extract the GST number buyer and seller details invoice number invoice date from the invoice pdf. Still, the invoice pdf has a different format than the how-to get details from that
I have made an upload file system where users can upload their invoices. I am using google vision API for parsing the pdf it gives me text but I have to extract useful info from that text?
here are the extracted text from one of the invoices
here there is 2 json because invoice is of 2 pages

[
  {
    "text": "examplenGSTIN: 27AEAPK1413P1ZJnPANKAJ ENTERPRISES (PROP. PANKAJ RIKHABCHAND KASLIWAL)n1. e-Invoice DetailsnIRN: Nulln2 Transcation DetailsnSupply Type Code: B2BnPlace of Supply: MaharashtranDocument Type:: INVn3. Party DetailsnSellernGSTIN: 27AEAPK1413P1ZJnPANKAJ ENTERPRISES (PROP. PANKAJ RIKHABCHAND KASLIWAL)nH.NO.5073 SWEETY NAGAR DHANKASTURI BANGLOW, SHIWAR NIPHADnOZHAR, Maharashtra, 422206nOZHARn422206 MaharashtranPAN: AEAPK1413Pn4. Goods DetailsnSNOn1n2nProduct HSN Quantity UnitnDescription CODEnAdministrator 998594n998533nFemalenHousekeepingnStaffnTaxblenAmtn15000.00nCGSTnAmtn1350nAck. No: Nulln50n50nGenerated By: 27AEAPK1413P1ZJnPrint Date: 27th Jan 2022n6.1. Delivery HistorynGRN No: GRN 1nGoods Received by: Amarjeet SharmanUnitnPricen(Rs.)n100.00n200.00nDocument Number: 2021-22/GRFL/24nDocument Ref No:nDocument Date: 27/01/2022nPurchasern400061 MaharashtranGSTIN: 27AAPCA2998B1ZEnARSALANS SHAWARMA KING FOODS PRIVATE LIMITEDn203, PLOT NO-9 JUBILEE MANSION CHS LTD., YARI ROADnANDHERI WESTnPAN: AAPCA2998BnDiscount TaxablenTax Raten(Rs.) Amount (GST+Cess |n0n0nAck. Date: NullnCESS StatenAmt CESS Amtn0n0n0n0nAck. No: NullnSGST IGSTnDiscount Othercharges Round offnAmtnAmtnAmtn0.00n0n0n0n1350nAmount in Words: SEVENTEEN THOUSAND SEVEN HUNDRED AND ZERO PAISA ONLYnThis is computer generated invoice no signature required.nOthernTotalnState Cess charges(Rs)nINVOICEn+CessnNon.Advol)n18+0 | 0+0n18+0 | 0+0nDelivery Date:27th Jan 2022n0n0nTotaln5900.00n11800.00nTotalnInv.Amtn17700.00"
  },
  {
    "text": "Delivery Branch: SHIWAR NIPHAD OZHAR PANKAJ ENTERPRISES (PROP. PANKAJ RIKHABCHAND KASLIWAL)nDelivery Stage: NULLnDelivery Stage Name: NULL"
  }
]

How to create and display an event only with Calendar Strip React Native npm package?

I am a newbie in React Native and Expo world, and I have read the documentation of Calendars in React Native and Expo. I also saw a great npm package called Calendar Strip, which is what I want for my application. But I am confused on one thing, onDateSelected() props for this package, how can create an event or just display a based on a specific date.

For example, July, 10th, 2022 should show a specific view container but other dates should not show that view as a component can be called on that particular date only. Hope I am clear on this. Appreciate your help.

Or if the same can be done with any well-known package or library, that would be appreciated.

Link for the npm package: https://www.npmjs.com/package/react-native-calendar-strip

Use state keeps coming back undefined. I want to make a loading screen with a button that renders the the rest of the site onClick

   import * as react from "react";
    import App from './App';
    import { useState } from 'react';
    import './index.css';
    import { deepOrange } from "@mui/material/colors";
    
    function LoadingScreen() {
        const Entrance = () => {
            const [visible, setVisible] = useState(false);
             }
        return (
            <div sx={{
                width: '100%', position: "absolute", zIndex: 1, color: "orange"
            }}>
                <>
                    <button sx={{ color: "deepOrange" }} variant="outlined" onClick={  ()=>  setVisible(true) }>
Welcome, Please come in!</button>
                    {visible && <App />}
                    </>
                </div >
        );

    }

I want to make a loading screen with a button that renders the the rest of the site onClick.

Bot Programming

I am trying to write a Bot Program that purpose is to simulate Human accessing the website to make booking.

So basic things is that whenever 7AM, all people start accessing to the website and it makes the booking very difficult.

So I decided to write an automatic bot programming to keep accessing the website until successful (possible with a Timing Parameter on Initial Access like 7AM -0.5MS).

One difficulty is that when accessing, we need to input 3-5 digits verification code from a picture (usually different each time).

So I m thinking whether I should start doing this project using JavaScript or Node.JS.

I programmed C# before, so web programming is completely new.

That’s why I wanna ask you guys what kind of language I should use, and is there any reference material or article you can share?

Thanks and Warm regards,
Wilson

how to use analytics.js library

function formatQs() {
var output = {};
var qs = document.location.search.substring(1);
qs = qs.split('&');

for (var i = 0; i < qs.length; i++) {
    var tokens = qs[i].split('=');
  output[tokens[0].toLowerCase()] = tokens[1];
}

return output;

}

**

Assuming that the analytics.js library is loaded on the page, please
> update the code block above to send through the standard utm
> parameters as properties in an analytics.track() call. Additional
> requirements:
>
> – Send only officially supported utm parameters as properties
> – Send only utm parameters included in the URL query string (i.e. don’t send null utm parameters)
> – # Name the track call: “User Referred”

**

How to save notebook in JupyterLab on Firefox browser

The version of JupyterLab is 3.4.3.

Here is the “save” button in the toolbar of Jupyter Lab Notebook:

%%javascript
console.log(document.querySelector('[data-command="docmanager:save"]').outerHTML);

here is the console output in Firefox:

<button type="button" class="bp3-button bp3-minimal jp-ToolbarButtonComponent minimal jp-Button" aria-disabled="false" data-command="docmanager:save" title="Save and create checkpoint (Ctrl+S)"><span class="bp3-button-text"><span class="jp-ToolbarButtonComponent-icon f1vya9e0"><svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" data-icon="ui-components:save"><g xmlns="http://www.w3.org/2000/svg" class="jp-icon3" fill="#616161"><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"></path></g></svg></span></span></button>

And then run click on the “save” button in notebook cell:

%%javascript
document.querySelector('[data-command="docmanager:save"]').click();

There is no any error, but the current notebook is not saved at all.

If I run this command in the Firefox’s console directly:

document.querySelector('[data-command="docmanager:save"]').click();

It’s the same as running in notebook cell, not save at all.

It seems like Firefox can detect the button object but Firefox can’t click on the “save” button.

What’s the problem and how to fix?

Woocommerce add thousand separator in custom price field

I want to add a thousand separator in custom input field in Woocommerce product page.

this is my code:

jQuery(document).ready(function () {
  jQuery(document).on('input', '.number-separator', function (e) {
    if (/^[0-9.,]+$/.test(jQuery(this).val())) {
      jQuery(this).val(
        parseFloat(jQuery(this).val().replace(/,/g, '')).toLocaleString('en')
      );
    } else {
      jQuery(this).val(
        jQuery(this)
          .val()
          .substring(0, jQuery(this).val().length - 1)
      );
    }
  });
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tmcp_textfield_6" class="number-separator" value="" >

Everything seems right, But when I add the product to the cart
Only the first part of the price is added.

For example, when I enter the number 5,000,000
Only number 5 will be added to the cart

How to get return value from cripting.executeScript() in Manifest V3

I want to use value from function:countPlaylist for put it into popup.html.
But can’t read output value at the outside of chrome.tabs.query()

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  chrome.scripting.executeScript({
    target: {tabId: tabs[0].id},
    function: countPlaylist
  });
 });

function countPlaylist(){
  var list = document.querySelectorAll('.ytd-playlist-video-list- 
  renderer .ytd-playlist-video-list-renderer #text');
  //...
  return results;
}

document.querySelector("#result").innerText = results;

I know way likes

chrome.tabs.executeScript({
  code: 'function() '
  }, function(result) {});

But that’s not appropriate for ManifestV3
I know this injected code run at the ‘tabs[0]’window.
Please let me know how to bring value to script.js

Really really appriciate your helps 🙂

I am having a problem with Discord.js code I have not found a solution

It gives an error that when I input the command -play music it gives this:

C:UsersUserDesktopDiscord Bot JScommandsplay.js:8
const voiceChannel = message.member.voice.channel;
^

TypeError: Cannot read properties of undefined (reading ‘voice’)
at Object.execute (C:UsersUserDesktopDiscord Bot JScommandsplay.js:8:45)
at Client. (C:UsersUserDesktopDiscord Bot JSmain.js:37:37)
at Client.emit (node:events:527:28)
at MessageCreateAction.handle (C:UsersUserDesktopDiscord Bot JSnode_modulesdiscord.jssrcclientactionsMessag at WebSocketShard.onPacket (C:UsersUserDesktopDiscord Bot JSnode_modulesdiscord.jssrcclientwebsocketWebSock at WebSocketShard.onPacket (C:UsersUserDesktopDiscord Bot JSnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22) at WebSocketShard.onMessage (C:UsersUserDesktopDiscord Bot JSnode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10)
at WebSocket.onMessage (C:UsersUserDesktopDiscord Bot JSnode_moduleswslibevent-target.js:132:16) at WebSocket.emit (node:events:527:28)
PS C:UsersUserDesktopDiscord Bot JS>

heres the code

const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
 
module.exports = {
    name: 'play',
    description: 'Joins and plays a video from youtube',
    async execute(client, message, args) {
        const voiceChannel = message.member.voice.channel;
 
        if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command!');
        const permissions = voiceChannel.permissionsFor(message.client.user);
        if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
        if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
        if (!args.length) return message.channel.send('You need to send the second argument!');
 
        const validURL = (str) =>{
            var regex = /(http|https)://(w+:{0,1}w*)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%!-/]))?/;
            if(!regex.test(str)){
                return false;
            } else {
                return true;
            }
        }
 
        if(validURL(args[0])){
 
            const  connection = await voiceChannel.join();
            const stream  = ytdl(args[0], {filter: 'audioonly'});
 
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', () =>{
                voiceChannel.leave();
                message.channel.send('leaving channel');
            });
 
            await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
 
            return
        }
 
        
        const connection = await voiceChannel.join();
 
        const videoFinder = async (query) => {
            const videoResult = await ytSearch(query);
 
            return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
 
        }
 
        const video = await videoFinder(args.join(' '));
 
        if(video){
            const stream  = ytdl(video.url, {filter: 'audioonly'});
            connection.play(stream, {seek: 0, volume: 1})
            .on('finish', () =>{
                voiceChannel.leave();
            });
 
            await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
        } else {
            message.channel.send('No video results found');
        }
    }
}

I got the code from a youtube tutorial and I looked for many solutions that eventually did not work.

Can’t use props on imported React functional components

I’m trying to get a component (TestCard) to render the output of an API call I’m making with Axios. When I put the code of the TestCard component directly in the App() function of my App.js file, it renders as expected. But when I move this code out into its own function, it doesn’t render the values. This is surprising to me, as I’m calling the same useState and useEffect functions to store the data from the API call in state.

I’ve listed the code below; what am I doing wrong here?

This is the code of the TestCard component:

function TestCard(props) {
    return (
      <Card sx={{ maxWidth: 345 }}>
      <CardActionArea>
        <CardMedia
          component="img"
          height="300"
          image={props.preview_image}
          alt={props.name} />
        <CardContent>
          <Typography gutterBottom variant="h5" component="div">
            {props.description}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {props.description}
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  );
}

export default TestCard

This is the code directly in my App() function (this renders correctly):

function App() {
  const [props, setProps] = useState({});
  useEffect(() => {
     axios.get(`http://localhost:9000/sessions/list`).then((row)=>setProps(row.data))
  })
  return (
    <div>
        <Card sx={{ maxWidth: 345 }}>
    <CardActionArea>
      <CardMedia
        component="img"
        height="300"
        image={props.preview_image}
        alt={props.name} />
      <CardContent>
        <Typography gutterBottom variant="h5" component="div">
          {props.description}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          {props.description}
        </Typography>
      </CardContent>
    </CardActionArea>
  </Card>
    </div> 
  );

And this is the imported function in my App() function (does not render the data correctly):

function App() {
  const [props, setProps] = useState({});
  useEffect(() => {
     axios.get(`http://localhost:9000/sessions/list`).then((row)=>setProps(row.data))
  })
  return (
    <div>
      <TestCard name={props.name} description={props.description} preview_image={props.preview_image} />
    </div> 
  );
}

What is the most RESTful method

I am confused on the most restful way to formulate an api url that will get a users resources. Specifically I have users and I have items, I’m trying to have a get request retrieve the items of a user.

What I thought of so far

  • “api/user/:id/items”
  • “api/item?user=id”