WHy in my recursion function the code after the if condition is repeated?

// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
    countDown(newNumber);
  }
  console.log(newNumber);
}

countDown(4); 

// output => 4 3 2 1 0 1 2 3

I can’t visualize what happens after the if condition. I mean I understand that there is “loop” with countDown(newNumber). But I don’t understand why there is the output 0 1 2 3. I know I can put an else keyword, but I’d like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).

How to import Three.js from CDN to WordPress? – Webpack

I’m trying to import three.js from CDN to WordPress but console returns: example.js:2 Uncaught Error: Cannot find module 'three'. I’m also using Webpack.

example.js:
import * as THREE from 'three'; […]

app.js: import "./example.js";

functions.php:

//wp enqueues

function example_scripts() {

    wp_enqueue_script( 'three-js', 'https://cdn.skypack.dev/[email protected]', array(), null );
    }
add_action( 'wp_enqueue_scripts', 'example_scripts' );
    
//three-js
function set_scripts_type_attribute( $tag, $handle, $src ) {
    if ( 'three-js' === $handle ) {
        $tag = '<script type="module" src="'. $src .'"></script>';
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'set_scripts_type_attribute', 10, 3 );

part of webpack config:

module.exports = {
  externals: {
    THREE: 'three',
  },
};

it appears in html : <script type="module" src="https://cdn.skypack.dev/[email protected]"></script>

How do I add a nested object to an object in same schema?

I’m having a difficult time on solving this one. but before that I will show first my controller, route and schema.

Here is my controller:

module.exports.checkoutOrder = async (data) =>{

    let id = data.userId;
    

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)

    User.findById(id).then(user=>{

        user.totalAmount.push({total,oTotal})
        return user.save().then((savedtotal,err)=>{
            if (savedtotal) {
                return savedtotal

            } else {

                return 'Failed to checkout order. Please try again'

            }

        })

})
}

here is my route:

route.get('/checkout',auth.verify,(req,res)=>{
    let token = req.headers.authorization;
    let payload = auth.decode(token)
    let isAdmin = payload.isAdmin
    let id = payload.id
    !isAdmin ? controller.checkoutOrder(id).then(result => 
        res.send(result)) 
    : res.send('Unauthorized User')

})

and the schema:

userOrders:[
            {
                productId:{
                    type: String,
                    required: [true, "ProductId is required"]
                },

                quantity:{
                    type: Number,
                    required: [true, "Quantity is required"]
                },

                subtotal:{
                    type: Number,
                    required: [true, "subtotal is required"]
                }
            }
        ],

    
                totalAmount:{
                    type: Number,
                    required: [true, "Quantity is required"]
                },

                PurchasedOn:{
                    type: Number,
                    default:  new Date()
                }
        
})

when i run a postman get, i receive this error

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)
                                                             ^

TypeError: Cannot read properties of null (reading 'userOrders')

I’ve tried googling how objects work but without requesting from body, I cannot pull “subtotal”(i have values for subtotal) object from “userOrders” to add it to “TotalAmount”. Any tips?

“Failed to load resource: the server responded with a status of 404 (Not Found)”

I get this error message when trying to load in a JS-file in Ionic.

I made sure that the path is correct but I still end up with this response.

Error-Msg

My Index.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8"/>
  <title>Ionic App</title>
  <base href="/"/>
  <meta name="color-scheme" content="light dark"/>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <meta name="format-detection" content="telephone=no"/>
  <meta name="msapplication-tap-highlight" content="no"/>
  <script type="text/javascript" src="galerie.js"></script> <!---------------------JS-file->

  <link rel="icon" type="image/png" href="assets/icon/favicon.png"/>

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes"/>
  <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
</head>

<body>
  <app-root></app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

I’m still new to Ionic, so I don’t really know where the problem could lie.

Find first value in array with set num difference

Given a sorted array, I am looking to find the first value in the array where the next value has an increase/difference of >=1000. In the below array, my goal is to return the value 11710, because the next value in array (13271) has a difference of >= 1000.

Sample Array

const array = [11006, 11256, 11310, 11710, 13271, 327027, 327027]

Current Code // not returning correct value

const found = array.find((element, index) => {
   console.log('element', element),
   console.log('array[index + 1]', array[index + 1])
   return Math.abs(element, array[index + 1]) >= 1000
})

Getting response that there is “no XML declaration in the XML document” however, there is. Any input?

I am having an issue when posting to the ups api. That doesn’t matter too much for the issue I am having but just for context. My XML is as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<AccessRequest xml:lang="en-US">
<AccessLicenseNumber>licensenumber</AccessLicenseNumber>
<UserId>userid</UserId>
<Password>password</Password>
</AccessRequest>
<?xml version="1.0" encoding="ISO-8859-1"?>
<ShipmentAcceptRequest>
<Request>
<TransactionReference>
<CustomerContext>Customer Comment</CustomerContext>
</TransactionReference>
<RequestAction>ShipAccept</RequestAction>
<RequestOption>1</RequestOption>
</Request>
<ShipmentDigest>//a whole lot of text</ShipmentDigest>
</ShipmentAcceptRequest>

I am aware that I am concatenating the xml documents. The UPS api requires I do so to authenticate. Certainly not the right way to do it but that is besides the point. Can anyone tell me why I am getting an error stating “no XML declaration in the XML document?”

Edit: This is how I am posting the ShipAccept

function shipAccept(digest) {
  xml = fs.readFileSync('./xml/response.xml', 'utf8');

  xml2js.parseString(xml, (err, result) => {
    if (err) {
      console.err(err)
    }
    const resJsonString = JSON.stringify(result, null, 4);
    const resJson = JSON.parse(resJsonString);
    digest = resJson.ShipmentConfirmResponse.ShipmentDigest.toString();
  })


  var xmlAcc = "<?xml version="1.0" encoding="ISO-8859-1"?>"
  xmlAcc += "n<AccessRequest xml:lang="en-US">"
  xmlAcc += `n<AccessLicenseNumber>${licenseId}</AccessLicenseNumber>`
  xmlAcc += `n<UserId>${userId}</UserId>`
  xmlAcc += `n<Password>${password}</Password>`
  xmlAcc += "n</AccessRequest>"

  xmlAcc += "n<?xml version="1.0" encoding="ISO-8859-1"?>"
  xmlAcc += "n<ShipmentAcceptRequest>"
  xmlAcc += "n<Request>"
  xmlAcc += "n<TransactionReference>"
  xmlAcc += "n<CustomerContext>Customer Comment</CustomerContext>"
  xmlAcc += "n</TransactionReference>"
  xmlAcc += "n<RequestAction>ShipAccept</RequestAction>"
  xmlAcc += "n<RequestOption>1</RequestOption>"
  xmlAcc += "n</Request>"
  xmlAcc += `n<ShipmentDigest>${digest}</ShipmentDigest>`
  xmlAcc += "n</ShipmentAcceptRequest>"

  fs.writeFile("xml/Acceptrequest.xml", xmlAcc, function (err) {
    if (err) {
      console.log(err);
    }
    console.log("ShipAccept Request file written successfully");
  });

  var options = {
    url: `${upsPath}/ShipAccept`,
    method: "POST",
    body: xmlReq
  };

  function callback(error, response, body) {
    console.log("callback");
    if (!error) {
      var cbResponse = (body);
      fs.writeFile("xml/responseAccept.xml", cbResponse, function (err) {
        if (err) {
          console.log(err);
        }
        console.log("ShipAccept Response file written successfully");
      });
    } else {
      console.log(body);
    }
  }

  request.post(options, callback);
}

shipAccept();

Array values, set all to 0 [closed]

const clicker = {
TC:0,
CC:0,
FM:0,
};

function prestige(){
//Object.values(clicker)==0//
}

I have a prestige function that needs to reset every value in an array at once.
I can log the name or the values as an array, but any attempt to alter them is met with errors.

Make a sepecific button load in JSON state react using setState

I have 3 buttons which are rendered from a loop over an array and rendered in react.

The 3 buttons are represented in a state as follows:

const [buttonLoading, setButtonLoading] = UseSafeState({
    free: { is_loading: false },
    starter: { is_loading: false },
    professional: { is_loading: false },
})

(UseSafeState is just a hook component that do exactly the same thing as useState, but safely)

I would like that by clicking on one of the buttons, a loader is displayed on this specific button while waiting for the end of a request.

I created this test component to shorten my code and test.
What I’m trying to do here is display the loader on the button that is clicked relative to its name.

export default function Test() {
    const [buttonLoading, setButtonLoading] = UseSafeState({
        free: { is_loading: false },
        starter: { is_loading: false },
        professional: { is_loading: false },
    })
    
    // To set the is_loading property of the specific key of the json state
    const changeButtonLoading = (type, isLoading) => {
        const buttonLoadingChanged = buttonLoading
        buttonLoadingChanged[type].is_loading = isLoading

        setButtonLoading(buttonLoadingChanged)
    }

    const BUTTONS = [
        { name: 'free', label: 'FREE' },
        { name: 'starter', label: 'STARTER' },
        { name: 'professional', label: 'PROFESIONAL' },
    ]

    return BUTTONS.map((button, key) => {
        return (
            <Button key={key} onClick={() => changeButtonLoading(button.name, true)}>
                {buttonLoading[button.name].is_loading ? <LoaderButton /> : button.label}
            </Button>
        )
    })
}

(LoaderButton /> component is just a basic loader with some css and html)

But the problem is that when I click on one of the button, he don’t display the loader. But he display it if I modify something in my code to force a render.

adding hours , minutes and seconds to innerHTML in javascript

i’m trying to add the current seconds to my div innerHTML but i really can’t
and this is my code :
i tryed to get any way to do it but i failed


var d = new Date();
var getHours = d.getHours();
var getMinuts = d.getMinutes();
var getScounds = d.getSeconds();
var getMInner = $(".minutes").InnerText;
var getSInner = $(".scounds").InnerText;
var getHInner =$(".hours").InnerText;


window.on("load", function(){
  var oo = for(i = getScounds ; i < 60 ; i++){
    $(".hours").innerHTML = pad(i % 60);
  }
})

Apply changing markers array to Google map in react

I have a Google map in my react application which allows one single marker to be shown moving around the map (as the latitude is being changed every few seconds)

However if i had a markers array (which keeps being updated with new markers with corresponding latitude/longitude), is there a way to loop through these markers and add them to the map. It would need to keep checking they haven’t changed location, or new markers haven’t appeared in the array, or been deleted from the array. Essentially, it would look something like this:

 const Map = ({ location, zoomLevel, markers }) => {
    for(let marker of markers)
    {
        const [marker.markerLatVal, marker.setMarkerLatVal] = 
        useState(marker.markerLat)
    }

    useEffect(() => {
        const interval = setInterval(() => {
            changeMarkerLatitude();
        }, 2000);
        return () => clearInterval(interval);
    }, []);

    const changeMarkerLatitude = () => {
        for(let marker of markers)
        {
           marker.setMarkerLatVal(prev => prev + 50);
        }
    };
 
        return (
            <div className='map'>
                <div className='google-map'>
                    <GoogleMapReact
                     for(let marker of this.markers)
                     {
                        <MyGreatPlace lat={marker.markerLat} 
                        lng={marker.markerLong} text= 
                        {marker.markerText} />
                     }
                    </GoogleMapReact>
                </div>
            </div>
        );

}

Is this possible?

axios and msgpack decoding

There’s not much of answer from this: https://stackoverflow.com/search?q=axios+msgpack
and also not much to find using googlefu.

I’m trying to decode response data with msgpack using axios but having error with TypeError: stream.getReader is not a function. However, if I use fetch, it works.

Using fetch:

async request = postData => {
  let response = await fetch("/api/filter-genes-by-organ", {
    method: "POST",
    body: JSON.stringify(_data),
    headers: { "Content-type": "application/json" },
  });
  return decodeAsync(response.body);
}

Using axios:

async request = postData => {
let headers = { "Content-Type": "application/json" };
  let response = await axios.post(`/api/${endpoint}`, postData, { headers }, {responseType: 'text' });
  return decodeAsync(response.data)
}

I’m still doing some tests and if i find a solution I will update this question, thank you.

Using toggle function to highlight one element when clicked

I have a couple of li elements imported from an API. When clicked on one of the elements, that element should change background color and stay that color until another element is clicked on. At that point the new element will change color and the old one go back to its original color. I was trying to make this work a few different ways but can’t make it work. Can anyone help? thank you.

       axios
  .get(showUrl + "?api_key=" + apiKey)
 .then((response) => {
  showsArray = response.data;
 showsArray.forEach((show) => {
 displayShows(show);

})
})
 .catch(error => {
console.log(error);
})



  function displayShows(arr) {
    
    let show = document.createElement("li")
    show.classList.add("shows__table")

    let dateHeading = document.createElement('h5');
    dateHeading.innerText = "Date";

    let dateNum = document.createElement("h3");
    dateNum.innerText = new Date(Number(arr.date)).toDateString();

    let venueHeading = document.createElement('h5');
    venueHeading.innerText = "Venue"

    let venueName = document.createElement('p');
    venueName.innerText = arr.place;  
    
    let locationHeading = document.createElement('h5');
    locationHeading.innerText = "Location";

    let locationName = document.createElement('p');
    locationName.innerText = arr.location;

    let button = document.createElement('button');
    button.innerText = "Buy Tickets";
    // button.addEventListener('click', () => {
    //     console.log("hit")
    // })
    
    showsList.appendChild(show);
    show.appendChild(dateHeading);
    show.appendChild(dateNum);
    show.appendChild(venueHeading);
    show.appendChild(venueName);
    show.appendChild(locationHeading);
    show.appendChild(locationName);
    show.appendChild(button);
 }

  // first option:
  // let listItem = document.querySelectorAll(".shows__table");


   // listItem.addEventListener('click', (e) => {

   //     listItem.classList.toggle(".shows__table--active")
  // })

   //second option :
   // document.querySelectorAll('.shows__table').addEventListener('click', changeColor);
  // function changeColor() {
  //     this.style.backgroundColor = "red";
  //     return false
  // }
  //third option :
  // let listItem = document.querySelectorAll(".shows__table")
  // listItem.forEach((listItem) => {
   //     listItem.addEventListener('click', (e) => {
  //         listItem.classList.toggle(".shows__table--active")
  //     })
 // })

 // 4th option
 // let listItem = document.querySelectorAll(".shows__table");
  //   for (let i = 0; i < listItem.length; i++) {
  //     listItem[i].addEventListener('dblclick', function (e) {
 //       e.preventDefault();
 //       listItem[i].classList.toggle("shows__table--active");
  //       console.log("clicked");
 //     });
  // }

React how to render only parts of an array?

I am still a bit new to react and how it works. I have a projects.js file with a list of objects that look like this:

id: 0,
    name: "Placeholder Project 1",
    description: "Project description",
    image: "./assets/images/placeholder-01.png"

There are 6 objects in this array. I am trying to render only 3 project objects at a time, and then include a button that will “load more” projects later. However, I am having trouble with just the rendering part. My component looks like this:

import React, { Component } from "react";
import NavTab from "./NavTab";
import { Card } from "react-bootstrap";
import { PROJECTS } from "../shared/projects";

function RenderProject({projects, projectsDisplayArray}) {
    const tempArray = projectsDisplayArray;
    return( 
        <div className="row">
            {                 
                projects.map(project => {
                    tempArray.indexOf(project) > -1 ? console.log('in array already') : tempArray.push(project) 
                    console.log(tempArray.length)
                    if (tempArray.length >= 3){
                        console.log('in the if')
                        return (
                            <Card key={project.id}>
                                <Card.Img variant="top" src={project.image} />
                                <Card.Body>
                                    <Card.Title>{project.name}</Card.Title>
                                    <Card.Text>
                                        {project.description}
                                    </Card.Text>
                                    
                                </Card.Body>
                                <button className="btn align-self-center">Go somewhere</button>
                            </Card>

                        )
                    }
                    else {
                        return(<div>Else return div</div>)
                    }
                })
            }
        </div>
    )
}

export default class Projects extends Component {
    
    constructor(props){
        super(props);
        this.state = {
            projectsPerScreen: 3,
            currentPage: 0,
            projects: PROJECTS,
            projectsDisplayArray: []
        }
    }
    modifyProjectsDisplayArray = props => {
        this.setState({projectsDisplayArray: [...this.state.projectsDisplayArray, props]})
    }
    render() {
        let i = 0;
        return(
            <React.Fragment>
                <NavTab/>
                <div className="projects">
                    <div className="container">
                        <button type="button" className="btn">Click</button>
                        <h1>Projects: </h1>
                        <RenderProject projects={this.state.projects} projectsDisplayArray={this.state.projectsDisplayArray} />
                        <button type="button" className="btn" onClick={() => console.log(this.state.projectsDisplayArray)}>console log</button>
                    </div>
                </div>
            </React.Fragment>
        )
    
    }
}

I am very confused on how the return method for RenderProject is working. When I begin the mapping process, I want to add each project to an array so I can keep track of how many and what projects are being rendered. When the array length hits three, I want it to stop rendering. But whenever I do this, my line if (tempArray.length <= 3) behaves in a way I don’t expect it to. With how it is now, it won’t return the <Card> and will instead return the else <div> for all 6 objects. But if I change the if statement to be if (tempArray.length >= 3) it will render all 6 objects inside of the array and no else <div>s. What should I be doing instead?

unable to call javascript function from angular 13 component

There is a recent change introduced in Angular 13 where the old way of calling javascript functions from angular components isn’t working anymore.

I am facing an issue with calling a javascript function from a specific component.

I already tried the usual way and here is my approach.

FILE: srcassetsjsmain.js

(function($) {
"use strict";
function animatedProgressBar () {
    $(".progress").each(function() {
        var skillValue = $(this).find(".skill-lavel").attr("data-skill-value");
        $(this).find(".bar").animate({
            width: skillValue
        }, 1500, "easeInOutExpo");
        $(this).find(".skill-lavel").text(skillValue);
    });
}
})(jQuery);

FILE: srcappabout-meabout-me.component.ts

import { Component, OnInit } from '@angular/core';
declare function animatedProgressBar(): any;
@Component({
    selector: 'app-about-me',
    templateUrl: './about-me.component.html',
    styleUrls: ['./about-me.component.css']
})

export class AboutMeComponent implements OnInit {
    //declare animatedProgressBar: any;
    constructor() {}
    ngOnInit(): void {
        animatedProgressBar();
    }
}

This code snippet throws an error: ERROR ReferenceError: animatedProgressBar is not defined

I checked the answer on This StackOverflow topic but it didn’t work for me.

Looking forward to some valuable inputs on this issue.

Why do we need to have two same ids in alert-component and alert-service

I am trying to implement alerts on my webpage. I have found some guides that go through how to create alerts in angular. Most of them are implementing it in the same way which makes me believe it’s the way to go. What I don’t understand is that all of those guides have an id in the alertComponent with the annotation @input

Alert-component.ts

@Input() id = 'default-alert';

Then we call the onAlert method and provide the id as an argument

this.alertSubscription = this.alertService.onAlert(this.id)

The alert-service.ts class have also a field called defaultId with the same value as alert-component

alert-service.ts

private defaultId = 'default-alert';

Then in the implementation of OnAlert method in alert-service we take the id we recieve in as an argument and assign it to the default id ? is this a common thing in angular? I don’t understand

onAlert(id = this.defaultId): Observable<Alert> {
        return this.subject.asObservable().pipe(filter(x => x && x.id === id));
    }

I would appricate yours answers to help me understand. Thanks!