How can I return my data in this nested promise model?

I have this function, I created it but then I’m getting confused and don’t know how to return the data.

I have tried Promise.all() before but it’s seems I do not quite understand it so I have removed it from my code, I don’t know if it’s a correct way to do it or not.

I’m following this AniList Node Document

Here’s how the code work. I’m using POSTMAN to query the Title, for example, One Piece, it’ll then search the query title and get the ID of that Title in AniList. Then, it’s using that ID to find all the info (it’s in the detailInfo)

Here’s my Model:

static async getAnilist(title) {
const Anilist = new anilist()

const animeInfo = Anilist.searchEntry
    .anime(title, null, 1, 1)
    .then((titleToID) => {
        const animeID = titleToID.media[0].id
        const detailInfo = Anilist.media.anime(animeID).then((data) => {
            return {
                AnimeID: animeID,
                Schedule: data.airingSchedule[0],
                Score: data.averageScore,
                BannerImg: data.bannerImage,
                Character: data.characters,
                Country: data.countryOfOrigin,
                CoverImg: data.coverImage,
                Duration: data.duration,
                EndDate: data.endDate,
                EpisodeTotal: data.episodes,
                Genre: data.genres,
                Season: data.season,
                SeasonYear: data.seasonYear,
                Status: data.status,
                Studio: data.studios,
                UpdateAt: data.updatedAt,
            }
        })

        return detailInfo
    })
return animeInfo
}

Here’s my Controller:

static async getAnilist(req, res, next) {
    const { title } = req.query
    try {
        const { data } = await Model.getAnilist(title)

        res.json({
            success: true,
            data: data,
        })
    } catch (err) {
        next(err)
    }
}

What I’m hoping for:

"success" : true,
"data" : {
     AnimeID,
     Schedule,
     Score,
     BannerImg,
     ...
     UpdateAt
}

What I’m getting right now

"success" : true

but without any data due to I can’t return it.

The request is succeeded, but I don’t know how to actually return it from nested promise.

Here’s what I get from using console.log({AnimeID, Schedule...}) instead of return

INFO

Any way to force js engines to unroll a loop?

I have a performance critical queue container that does a lot of random inserts/deletes. In my container class, I have a fixed size Uint32Array called updates and in my insert logic, I need to compare a value to every value in this update array.

Originally, I did it simply like this:

const u = this.updates;
for (let i = 0; i < u.length; i++) bucket_offset += bi >= u[i];

Then, just as I was putting finishing touches on the container and just screwing around, I tried unrolling said loop

const u = this.updates;
bucket_offset += (bi >= u[0]) + (bi >= u[1]) + (bi >= u[2]) + (bi >= u[3]) + (bi >= u[4]) + (bi >= u[5]) + (bi >= u[6]) + (bi >= u[7]) + (bi >= u[8]) + (bi >= u[9]) + (bi >= u[10]) + (bi >= u[11]) + (bi >= u[12]) + (bi >= u[13]) + (bi >= u[14]) + (bi >= u[15]);

And turns out this is around 10x faster on chrome, making the whole insert ~30% faster.

After that revelation, I’m looking for a way to make the VM understand that its okay to unroll that loop, after all, this.updates.length is a constant.

At the end of the day, it can stay the way it is but I’d prefer a loop since it would just look nicer. Any ideas?

Iterate geojson data in a flatlist

Hello i want to make a flatlist with the geojson data
i want to access to 3 properties attributes and iterate it
the problem is i have only access in one data the same data is iterate it
//mon code

//la requete retourne un geojson
    const getAllAgr = () => {
          fetch('https://api.tolbico.com/api/agences/1/agriculteurs/', {
             method: 'GET',
             headers: { 
               'Authorization': 'Bearer '+ Token,
              'Content-Type': 'application/json'
             },
           }).then((response) => response.json())
           .then((json) =>{
              setAgriculteurs(geo.getProperties(json))
           
             })
          
    }
    useEffect(()=>{
        getAllAgr() 
        
         },[])            
    
       
    
        return (
                 //flatlist pour afficher les information      
                 <SafeAreaView>
                
                   <FlatList
                        
                      data={agriculteurs}
                      //keyExtractor={(item) => item.id.toString()}
                       renderItem={({item}) => <ListesAgr agro={item}/> }
                       />
    
                 </SafeAreaView>
        )
    }

How to reset button style in Javascript

function showQuestion(questionAndAnswers) {
    const shuffledAnswers = _.shuffle(questionAndAnswers.answers);
    questionTag.innerText = questionAndAnswers.question;
    shuffledAnswers.forEach(({ text, correct }, i) => {
        answerTag[i].innerText = text;
        answerTag[i].dataset.correct = correct;
    });
}
document.querySelectorAll(".answer").forEach((answer) => {
    answer.addEventListener("click", (event) => {
        if (event.target.dataset ) {
            answer.style.border = "1.5px solid"
        } 
    });
});
function nextQuestion() {
    const nextIndex = currentQuestionIndex + 1;
    if (nextIndex <= myQuestions.length - 1) {
        showQuestion(myQuestions[nextIndex]);
        currentQuestionIndex = nextIndex;
    } else {
        end.style.visibility = "visible";
        nxt_question_btn.style.visibility = "hidden";
    }
}

Basically, In this quiz app, I have 4 buttons for answers and once you click on one answer it makes the border black. The problem I am facing is that once I press the next question, it loads up another question with 4 different answers but one of the buttons will still have the border black. How do I get it to reset once I load up another question? and Extra question if it’s okay, how can I only select one button at a time per question?

Templating preselected values of Select2

I am using AJAX fetched data in Select2. My code is like below.

      let selectEle = cellEle.children("select").select2({
          ajax: {
            //more code here
          },
          processResults: function (data) {                
            var options = [];
            if (data) {
              $.each(data, function (index, text) {

                var user_data = '<table> 
                  <tr> 
                    <td>Organisation</td> 
                    <td>'+text[2][1]+'</td> 
                  </tr> 
                  <tr> 
                    <td>Age</td> 
                    <td>'+ text[2][0]+'</td> 
                  </tr> 
                </table>';            

        options.push({ id: index, text: text[0], text1: text[1], text2: user_data });
                
              });
            }
            return {
              results: options,
              more: false
            };
          },
        },
        templateSelection: formatState,
        templateResult: resultfucntion,
      });

My formatState function is like below.

function formatState(state) {
        if (!state.id) { return state.text; }
        var output = $(
            '<span class="tooltip" title="'+ state.text2 +'">' + state.text + '</span>'
        );
        return output;
      };

I am fetching preselected values using AJAX and attached with Select2 like below.

          $.ajax({
            type: 'POST',
            dataType: 'json',
            url: "/wp-admin/admin-ajax.php",
            data: {
              element_id: element_id,
              action: 'get_preselect_values',
            },
          }).then(function (data) {
            var options = [];
                
            if (data) {
              $.each(data, function (index) {
                options.push(new Option(data[index].text, data[index].id, true, true));
              });
            }
                
            selectEle.append(options).trigger('change');

Everything is working fine all above.

How can I template preselected values like above ?

How to Periodically Check Whether Data from API Has Changed

I’m fetching weather data from OpenWeather API for a given location and want to check, every minute, whether that data is still current (and if not, change it). I’ve used setInterval but the data doesn’t seem to update every minute–here are the functions in question.

In the controller…

const controlStation = async function (station) {
  try {
    // Updates weather given station
    const weather = await model.updateWeather(station);

    // Periodically checks if weather data is current
    //  If not, updates weather
    let checkWeather = await model.checkWeather(station);
    setInterval(checkWeather, 1 * MINUTES);

    // Renders weather
    weatherView.render(model.stations[station], weather);
  } catch (err) {
    console.log(err);
  }
};

controlStation("fbi");

In the model…

export const state = {};

export const stations = {
  fbi: {
    name: "fbi",
    city: "Sydney, Australia",
    coordinates: [-33.5346, 151.12],
  },
  kutx: {
    name: "kutx",
    city: "Austin, Texas, United States of America",
    coordinates: [30.1721, -97.4402],
  },
  cism: {
    name: "cism",
    city: "Montreal, Quebec, Canada",
    coordinates: [45.3023, -73.3644],
  },
};

export const updateWeather = async function (station) {
  try {
    const [lat, lng] = stations[station].coordinates;
    const url = `${API_WEATHER_URL}lat=${lat}&lon=${lng}&appid=${API_WEATHER_KEY}&units=imperial`;

    const data = await fetch(url);
    const weather = await data.json();
    state.station = station;
    state.weather = weather;

    return weather;
  } catch (err) {
    console.error(err);
  }
};

export const checkWeather = async function (station) {
  try {
    console.log("Checking weather!");
    const needsUpdate = false;

    const prev = state;
    console.log("prev", prev.weather);
    const cur = await updateWeather(state.station);
    console.log("cur", cur);

    if (
      prev.weather.wind.speed !== cur.wind.speed ||
      prev.weather.wind.dir !== cur.wind.dir ||
      prev.weather.main.temp !== cur.main.temp ||
      prev.weather.weather[0].description !== cur.weather[0].description
    ) {
      console.log("Changing now");
      needsUpdate = true;
    } else console.log(`They were same at ${Date.now()}`);

    return needsUpdate;
  } catch (err) {
    console.error(err);
  }
};

I know I still need to do something if the weather data has changed and is different than what’s in state, but I don’t even see it making a new comparison through the checkWeather function every minute.

Cannot read properties of undefined (reading ‘statusCode’) Nodejs using cheerio

am trying to get the title of a webpage for this amusing request and cheerio there am facing this issue Cannot read properties of undefined (reading ‘statusCode’) but when I run to try to run separately with the static value it works

can anyone please help to identify the miskate I have done in my code?

here is my code

var request = require("request");
var cheerio = require("cheerio");

jsonData = [
  { Domain: "bar-n-ranch.com" },
  { Domain: "barcelona-enabled.com" },
  { Domain: "barefootamelia.com" },
  { Domain: "barmranch.com" },
  { Domain: "barnstablepatriot.com" },
  { Domain: "barrieapartmentrentalsonline.com" },
  { Domain: "basquehomes.com" },
  { Domain: "bassmaster.com" },
  { Domain: "basswoodresort.com" },
];

function fetchTitle(url, onComplete = null) {
  request(url, function (error, response, body) {
    var output = url; // default to URL

    if (!error && response.statusCode === 200) {
      var $ = cheerio.load(body);
      console.log(`URL = ${url}`);

      var title = $("head > title").text().trim();
      console.log(`Title = ${title}`);

      output = `[${title}] (${url})`;
    } else {
      console.log(`Error = ${error}, code = ${response.statusCode}`);
    }

    console.log(`output = ${output} nn`);

    if (onComplete) onComplete(output);
  });
}

jsonData.forEach(function (table) {
  var tableName = table.Domain;
  var URL = "http://" + tableName;
  fetchTitle(URL);
});

when am passing a value like fetchtitle(“https://www.googlecom”) it works but am getting error when I try to loop JSON data

Thank you very much in advance

Clarification on React Class based component constructor

I am reviewing some React Js basics and I need some clarifications about the use of the constructor method within a react class based component. My normal practice is to declare a class based component and define state without using the constructor, like so:

import React, { Component } from 'react';

export class Testing extends Component {
  state = {
    example: "Hello World!!!"
  }

  render() {
    return <div>
      {this.state.example}
    </div>;
  }
}

export default Testing;

Since state is so easy to use without the (seemingly) pointless constructor, I began asking myself what the constructor was for. Just to clarify what I mean by the constructor, it is when you declare state like this instead of the above example:

constructor(props) {
  super(props)

  this.state = {
    example: "Hello World!!!"
  }
}

I found the suggestion in the react documentation that it is best practice to utilize the constructor, but it did not say why. After a little searching, I found a source that suggested that the constructor give you access to the props. I tested this and do see how the constructor gives access to props; however, the class can access props WITHOUT using the constructor, simply by stating this.props.myTest. I tested this as well by defining props in a parent component and drilling them down to the child component. I was able to access the props just fine with the this.props.myTest statement, no constructor necessary. So my question is, “What specifically does the constructor do, and when is it necessary (or is it ever necessary)?”

How to convert a javascript shuffling function into a java method [duplicate]

Given this javascript method:

function shuffleKeys(a){
        for(let j,i=a.length;i>1;){
         j=Math.floor(rand*i--);
         if (i!=j) [a[i],a[j]]=[a[j],a[i]]
        }
        console.log("shuffled elarray")
        console.log(a)
        return a
    }

I’d like to convert it into a java method. I’ve found the libraries needed to replace the math functions, but the array swapping is unique to js. I’d like to figure out how to do it in java. This is my attempt so far

private static ArrayList<String> shuffleKeys(ArrayList<String> a){
        for(int j,i=a.size();i>1;){
                double rand = Math.random();
                j=(int) Math.floor(rand*i--);
                if (i!=j) 
                    [a[i],a[j]]=[a[j],a[i]];
        }
        System.out.println("shuffled elarray");
        System.out.println(a);
        return a;
    }

any help figuring out how to fix this piece of code would be greatly appreciated:

if (i!=j) 
        [a[i],a[j]]=[a[j],a[i]];

constructor functions attributes vs properties

quick question, when assigning a property in a constructor i am receiving an issue with the function itself…I have coded as such, using length, width , height in the function…but is this incorrect should only peramiters go there? and properties else?

 function CuboidMaker(length, width, height){
 this.width = width; 
 this.height = height;
 this.length = length;

this issue is when i end up typing this.length =length it immediately reports and issue with it and then also causes my function to highlight. just wondering is the properties are in different spots vs peram?

How to get the position data from the joystick to the flask server?

I would like to get the position data from the js joystick o use it at the flask server. I tried using ajax:

python:

@app.route(‘/test’, methods=[‘GET’, ‘POST’])
def test_ajax():

    if request.method == "POST":
        data = request.json
        print('data:', data)
        result = {'url': url_for('index')}
        print('result:', result)
        return jsonify(result)
    else:
        return render_template('index.html')

<div class="container fluid">
    
            <h1>Joystick</h1>
            
            <div id="joy1Div" style="width:200px;height:200px;margin-bottom:20px;"></div>
    
        </div>
        
        <script type="text/javascript">
                   
          var Joy1 = new JoyStick('joy1Div', {}, function(stickData) {
          joy1IinputPosX.value = stickData.xPosition;
          joy1InputPosY.value = stickData.yPosition;
          joy1Direzione.value = stickData.cardinalDirection;
          joy1X.value = stickData.x;
          joy1Y.value = stickData.y;
          });
            
        </script>
    
        <script>
    
          data = {'ID': 'foobar'};
          var joystick = document.getElementById('joy1Div');
          joy1X.onchange = function() {
            $.ajax({
              type: "POST",
              url: "/test",
              contentType: 'application/json;charset=UTF-8',
              data: JSON.stringify(data, null, 't'),
              dataType: 'json',
              success: function(data) {
                  window.location.href = data['url']
              },
              error: function(response) {
                  alert(response)
              },
          });
          }; 
    
        </script> 

Every time the position of the joystick changed I would like to send the position data to flask

Electron ignores setThumbarButtons([])

I just started to learn about electron. I want to create a window without the Thumbar Buttons, but electron ignores the .setThumbarButtons call
This is my main.js from a tutorial:


const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

let mainWindow

function createWindow () {
 
  mainWindow = new BrowserWindow({width: 800, height: 600})
  mainWindow.setThumbarButtons([])

  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))


 
app.on('activate', function () {
 
  if (mainWindow === null) {
    createWindow()
    mainWindow.setThumbarButtons([])
  }
})

provide leaflet-map to react-component

I’m using react-leaflet to render a map. I created a component that has a map-property:

import * as React from 'react';
import { Map, FeatureCollection } from  'leaflet';

class Car extends React.Component {
    
    state = { 
        map: Map,
        collection: FeatureCollection
    }
    constructor(props) {
        super(props);
        this.state = { 
            map: props.map,
            collection: props.collection
        }
    }

Now I try to use that component within my app:

import React, { useState } from 'react';
import { MapContainer, useMap } from 'react-leaflet';
import Car from './Car';

function Layout() {

    return (
        <div>
            <MapContainer bounds={[[52.475,13.3], [52.477,13.5]]} zoom={12}>
                <Car map={ useMap() }/>
            </MapContainer> 
        </div>
    )
}

export default Layout;

However I don’t know how to provide the map from the MapContainer into my Car-component. Using the above code I get the following error:

TS2322: Type ‘{ map: string; }’ is not assignable to type ‘IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>’.
Property ‘map’ does not exist on type ‘IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>’.

Remove Klarna Payments with cash on delivery method

I have a problem with a code. So I have five different payment methods in my site. When a customer select “Cash on delivery” as shipment method all the payment methods, exept cash on delivery, are hide.
For make that I use the follow code:

/**
* Remove payment methods when select "pagamento in contrassegno"
*/
function my_custom_available_payment_gateways( $gateways ) {

$chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );

// When 'Pagamento in contrassegno' has been chosen as shipping rate
if ( in_array( 'flat_rate:5', $chosen_shipping_rates ) ) :

    // Remove the follow payments
    unset( $gateways['woocommerce_payments'] );
    unset( $gateways['paypal'] );
    unset( $gateways['bacs'] );
    unset( $gateways['klarna_payments_pay_later'] );

    endif;

    return $gateways;

    }
    add_filter( 'woocommerce_available_payment_gateways', 
    'my_custom_available_payment_gateways' );

The code work with all payments exept for Klarna payments that remain if I select “Pagamento in contrassegno” (cash on delivery), how can I solve that?

The site is: https://www.modacapellishop.it/