Get an element from an array at an index a user specified

I want to build a function that takes two inputs:

  1. an array of arrays
  2. index number

and then returns an array inside the input array that it located at the input index.

The following is the code I got so far.

So, if a user calls the function with the following inputs, the expected result is [4,5,6] .

 const input = [
       [1,2,3],
       [4,5,6],
       [7,8,9]
    ];
    
 const index = 1;

function grab(input, index){
   var result = [];

   return result = input[index];
   console.log(result);
};

Why isn’t the data rendered in sorted order

Why isn’t the rendered data in sorted order

I am passing rides as a prop in the NearestRides component and inside the NearestRides component, first i am sorting the rides and setting to sortedRides and then i am mapping sortedRides.

but why is the sortedRides not sorted?

is sortedRides getting rendered before getting sorted? if so, how do i sort rides before rendering?

Rides.js

import { useEffect, useState } from "react";
import Navbar from "./Navbar";
import NearestRides from "./NearestRides";

const Rides = () => {
  const [rides, setRides] = useState([]);
  const [user, setUser] = useState({});


  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch('https://assessment.api.vweb.app/rides');
      const json = await data.json();
      setRides(json);
    }

    const fetchUser = async () => {
      const data = await fetch('https://assessment.api.vweb.app/user');

      const json = await data.json();
      console.log(json);
      setUser(json);
    }
    
    const makeNetworkCalls = async() => {
      await fetchRides();
      await fetchUser();
    }

    makeNetworkCalls().catch((e) => {
      console.log(e);
    })

  }, [])

  useEffect(() => {
    const calculateDistance = async(path, user_station) => {
      let min = Math.abs(user_station - path[0]);
      for(let i = 0; i<path.length; i++){
        if(path[i] === user_station){
          return 0;
        }
        if(Math.abs(path[i] - user_station) < min){
          min = Math.abs(path[i] - user_station);
        }
      }
      return min;
    }

    const updaterides = async () => {
      rides.map(async (ride) => {
        ride.distance = await calculateDistance(
          ride.station_path,
          user.station_code
        );
      });
    };

    if (rides?.length > 0) {
      updaterides().catch((e) => {
        console.log(e);
      });
    }
  }, [rides,user]);

  return (
    <div>
      <Navbar user = {user}/>
      <div className="home">
        <NearestRides rides = {rides}/>
      </div>
    </div>
  );

}

export default Rides;

NearestRides.js

import { useEffect, useState } from "react";

const NearestRides = ({rides}) => {
  const [sortedRides, setSortedRides] = useState([]);

  useEffect(() => {
    const sortRides = async() => {
      const sorted = await rides.sort((ride1,ride2) => {
        return ride1.distance > ride2.distance ? 1 : -1;
      })

      setSortedRides(sorted);
    }

    sortRides().catch((e) => console.log(e));

  }, [rides]);

  return(
    <div className="rides">
      {console.log(sortedRides)}
      {sortedRides?.map((ride) => {
        return (
          <div className="ride-detail">
          <img src={ride.map_url} alt="Ride_map" />
          <div>
            <p>Ride Id : {ride.id}</p>
            <p>Origin Station : {ride.origin_station_code}</p>
            <p>Station Path : {ride.station_path}</p>
            <p>Date : {ride.date}</p>
            <p>Distance : {ride.distance}</p>
          </div>
        </div>
        )
      })}
    </div>
  )
}

export default NearestRides;

fcc Cash Regiister problem I can’t figure out

In this fcc challenge, I’m supposed create a virtual cash register and return change to a person. For some reason there is a problem with “FIVE”, and I can’t figure out whats wrong with it, it seems to be identical to the others

let typesOfCash =
        {"PENNY"          :       0.01 ,  
         "NICKEL"         :       0.05 ,  
         "DIME"           :       0.1  , 
         "QUARTER"        :       0.25 , 
         "ONE"            :       1    , 
         "FIVE"           :       5    , 
         "TEN"            :       10   , 
         "TWENTY"         :       20   , 
         "ONE HUNDRED"    :       100   };

function checkCashRegister(price, cash, cid) {

    let changeToBeReturned = cash - price;
    let cidObject = Object.fromEntries(cid);
    let result = {
        status: null,
        change: [] 
    }

    let testArray = Object.keys(result.change);
    let totalCash = 0;
    for (let i = 0; i < cid.length; i++) {
        totalCash += cid[i][1];
    }

    if (changeToBeReturned > totalCash) {
        result.status = 'INSUFFICIENT_FUNDS';
        return result;
    }
    if (changeToBeReturned == totalCash) {
        result.status = 'CLOSED';
        result.change = cid;
        return result;
    }

    while (changeToBeReturned >= typesOfCash['ONE HUNDRED'] && cidObject['ONE HUNDRED'] > 0) {
        if (testArray.indexOf('ONE HUNDRED') < 0) {
            testArray.push('ONE HUNDRED');
            result.change.push(['ONE HUNDRED', 100]);
            changeToBeReturned -= 100;
            cidObject['ONE HUNDRED'] -= 100;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'ONE HUNDRED') {result.change[a][1] += 100}
                changeToBeReturned -= 100;
                cidObject['ONE HUNDRED'] -= 100;
            }
        }}
    while (changeToBeReturned >= typesOfCash.TWENTY && cidObject.TWENTY > 0) {
        if (testArray.indexOf('TWENTY') < 0) {
            testArray.push('TWENTY');
            result.change.push(['TWENTY', 20]);
            changeToBeReturned -= 20;
            cidObject.TWENTY -= 20;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'TWENTY') {result.change[a][1] += 20}
                changeToBeReturned -= 20;
                cidObject.TWENTY -= 20;
            }
        }}
    while (changeToBeReturned >= typesOfCash.TEN && cidObject.TEN > 0) {
        if (testArray.indexOf('TEN') < 0) {
            testArray.push('TEN');
            result.change.push(['TEN', 10]);
            changeToBeReturned -= 10;
            cidObject.TEN -= 10;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'TEN') {result.change[a][1] += 10}
                changeToBeReturned -= 10;
                cidObject.TEN -= 10;
            }
        }}

Here is the code that addresses the FIVE, but in the console I’m getting a ‘5’ instead of ’15’, which would be the corrrrect answer; Everything else is correct in the result though; I’ve been staring at the code for hours, I just don’t see the problem.

    while (changeToBeReturned >= typesOfCash.FIVE && cidObject.FIVE > 0) {
        if (testArray.indexOf('FIVE') < 0) {
            testArray.push('FIVE');
            result.change.push(['FIVE', 5]);
            changeToBeReturned -= 5;
            cidObject.FIVE -= 5;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'FIVE') {result.change[a][1] += 5}
                changeToBeReturned -= 5;
                cidObject.FIVE -= 5;
            }
        }}

    while (changeToBeReturned >= typesOfCash.ONE && cidObject.ONE > 0) {
        if (testArray.indexOf('ONE') < 0) {
            testArray.push('ONE');
            result.change.push(['ONE', 1]);
            changeToBeReturned -= 1;
            cidObject.ONE -= 1;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'ONE') {result.change[a][1] += 1}
                changeToBeReturned -= 1;
                cidObject.ONE -= 1;
            }
        }}
    while (changeToBeReturned >= typesOfCash.QUARTER && cidObject.QUARTER > 0) {
        if (testArray.indexOf('QUARTER') < 0) {
            testArray.push('QUARTER');
            result.change.push(['QUARTER', 0.25]);
            changeToBeReturned -= 0.25;
            cidObject.QUARTER -= 0.25;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'QUARTER') {result.change[a][1] += 0.25}
                changeToBeReturned -= 0.25;
                cidObject.QUARTER -= 0.25;
            }
        }}
    while (changeToBeReturned >= typesOfCash.NICKEL && cidObject.NICKEL > 0) {
        if (testArray.indexOf('NICKEL') < 0) {
            testArray.push('NICKEL');
            result.change.push(['NICKEL', 0.05]);
            changeToBeReturned -= 0.05;
            cidObject.NICKEL -= 0.05;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'NICKEL') {result.change[a][1] += 0.05}
                changeToBeReturned -= 0.05;
                cidObject.NICKEL -= 0.05;
            }
        }}
    while (changeToBeReturned >= typesOfCash.PENNY && cidObject.PENNY > 0) {
        if (testArray.indexOf('PENNY') < 0) {
            testArray.push('PENNY');
            result.change.push(['PENNY', 0.01]);
            changeToBeReturned -= 0.01;
            cidObject.PENNY -= 0.01;
        } else {
            for (let a = 0; a < result.change.length; a++) {
                if (result.change[a][0] == 'PENNY') {result.change[a][1] += 0.01}
                changeToBeReturned -= 0.01;
                cidObject.PENNY -= 0.01;
            }
        }}

    if (changeToBeReturned > 0) {
        result.status = 'INSUFFICIENT_FUNDS';
        result.change = [];
        return result;
    } else {
        result.status = 'OPEN';
        return result;
    }
    }
  

console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]))

The problem with adding property to object [duplicate]

I’m practising in JS and trying to get list with amount of free emails.

var _ = require('lodash');

const freeEmailDomains = ['gmail.com', 'yandex.ru', 'hotmail.com'];

const getFreeDomainsCount = (emails) => {
  let res = [];
  res = emails.map((email) => {
    let [, domain] = email.split('@');
    return domain;
  });
  res = res.filter((domain) => freeEmailDomains.includes(domain));
  res = res.reduce((freeDomains, domain) => {
    console.log(domain);
    if(!_.has(freeDomains,domain)) {
      freeDomains[domain] = 0;
    }
    freeDomains[domain] += 1;
  },
  {});
  return res;
}


const emails = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
];

getFreeDomainsCount(emails);

but my problem is that on the second step of reduce I see the erroe “TypeError: Cannot set properties of undefined (setting ‘yandex.ru’)”
As I understand I cannot add key ‘yandex.ru’ to object ‘freeDomains’.
What is wrong?

Passing object as prop returns undefined in destination component ReactJS

I’m trying to pass a JSON object (id) returned from an API call to another component via props and use that object(id) to fetch more data from a different endpoint. The problem is, when i pass the prop using object literal to the api, it gives an error undefined but when i console log the object(id) it works fine. What could be the issue? Just started learning React.

component passing object as prop

<Cast id={details?.id}/>

component receiving prop

import React, { useState, useEffect } from "react";
import axios from "axios";

const Cast = (props) => {
  const [cast, setCast] = useState([]);
  const sid = props.id;

  useEffect(() => {
    
      axios
        .get(
          `https://api.themoviedb.org/3/movie/${sid}/credits?api_key=56fbaac7fd77013cc072d285a17ec005&language=en-US`
        )
        .then((response) => {
          setCast(response.data.cast);
          console.log(response.data.cast);
        });

  }, []);

  console.log(sid);
  return (
    <div className="absolute">
      {cast && cast.map((item, index) => <p className="">{item.name}</p>)}
      <p>{sid}</p>
    </div>
  );
};

export default Cast;

It doesn’t work initially but when I edit the code, since the change is happening live, it fetches the data but when I refresh the page, Axios reports an error 404

xhr.js:220 GET https://api.themoviedb.org/3/movie/**undefined**/credits?api_key=56fbaac7fd77013cc072d285a17ec005&language=en-US 404

i don’t know how to solve this, using java script

Using JavaScript, add an event listener to all divs with color class that, when hovering over an element,
will cause the color of the div to change to a random color, and the text stored in the data-text to be displayed on the div.

Hovering over the div should remove the text, but the div should be colored.

Hovering again should change the background color and display the text again.

Hint:.
To get a random color use the code below:

let randomColor = "#" + Math.floor(Math.random()*16777215).toString(16);

How to access the html of a page from a Firefox extension?

I am trying to develop a Firefox extension. The trouble is I cannot figure out how to access the html of the activetab when the toolbar button is pressed. I have not added the toolbar button yet, I will do that once I get the function getHTML working.

This is the manifest file.

{
  "manifest_version": 2,
  "name" : "Example",
  "version": "1.0",

  "description": "Example extension",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["js/content.js"]
    }
  ],

  "background": {
    "scripts": ["example.js"]
  },

  "permissions": [
    "tabs",
    "storage",
    "activeTab",
    "webRequest",
    ]
}

This is the background script example.js:

function getHTML() {
    browser.tabs.query({
        active: true,
        lastFocusedWindow: true
    }, function(tabs) {
        // and use that tab to fill in out title and url
        var tab = tabs[0];
        var tabId = tab.id;
        browser.tabs.executeScript(tabId, {
            code : "console.log(document.body.innerHTML)"
        })})};

getHTML()

What am I doing wrong?

Thanks in advance.

Autocomplete on HTML Select Field

I have this simple select html field, i am learning JS, I just want to have a autocomplete kind of thing in this field, so when user type it should have this kind of functionality, can It be done?

enter image description here

<html>
<body>

<select>
 <option>USA</option>
 <option>India</option>
  <option>Canada</option>
   <option>UK</option>
</select>

</body>

</html>

Best way to merge and transform keys and arrays from an object

I have an object that looks like this:

{ role1: ["id1", "id2", "id3"], role2: ["id1", "id2"], role3: ["id2", "id4"] }

I would like to transform this into an array of objects, making the ids the unique identifiers and the roles into arrays, like so:

[
  { id: "id1", roles: ["role1", "role2"] },
  { id: "id2", roles: ["role1", "role2", "role3"] },
  { id: "id3", roles: ["role1"] },
  { id: "id4", roles: ["role3"] },
]

This is how I do it right now, but I’m not sure if there’s a better way. It feels like I’m overcomplicating things.

const obj = {
  role1: ["id1", "id2", "id3"],
  role2: ["id1", "id2"],
  role3: ["id2", "id4"]
};
const users = [];

Object.entries(obj).forEach(([key, ids]) => {
  ids.forEach(id => {
    const user = users.find(x => x.id === id);
    if (user) {
      user.roles.push(key);
      return;
    }
    users.push({
      id,
      roles: [key]
    });
  });
});

console.log(users);

Visualizing dataframes in ipython/jupyter notebook by using javascript

I recently discovered that it’s quite easy to inject HTML into Jupiter notebook to visualize python objects. That seems particularly useful to me to write a custom interactive plot for pandas dataframes.

The most basic example is:

from IPython.display import HTML
import pandas as pd
HTML( pd.DataFrame([[1,2],[3,4]]).to_html() )
# prints the html representation of a dataframe

What I am trying to accomplish is something similar to what apache zeppelin implements (https://zeppelin.apache.org/, data visualization), where you can pivot columns interactively to explore the data frame.

The first solution I can think of is writing a function get_html that takes the pandas df as input in a json format and visualizes it via d3, pseudocode:

def get_html(json_data):
    big_html = 
    f"""
    <html>
    <script>
    // inject {json_data} into the js library of your choice
    <script>
    </html>
    """
    return big_html
HTML( get_html(df.to_json(orient="records")) )

This seems suboptimal for a number of reasons, for instance

  1. performance (df are often big)
  2. ease of development (get_html should actually call a custom js library, instead of embedding js that way)

However, I cannot figure out how to make this work better.
An idea could be dumping the df onto a json and then re-reading from the disk, but I don’t know how to do it.

CSS does not take effect unless I resize the window?

Problem

Strange issue: Some CSS appears correctly in Chrome’s developer tools but does not actually take effect until I resize the browser window. Just expanding the window by a pixel or two is enough. But the window needs to be resized to force the browser to update this particular detail.

More detail

Attached is a screenshot of the issue. A corner maintains a 10px radius even though the CSS says it should be 0px.

What happened just before this screenshot: When the user clicks a <tr> (dark blue row in image) a hidden row beneath it is exposed (white). This action also triggers the CSS update through a classList.toggle, and the update is correctly shown in the developer tools. But it does not take effect, as you can see.

enter image description here

I have made a simplified version of the code as a snippet. But in this example, the CSS does takes effect, so there is no issue with the code.

So my question is if anyone else has experienced anything like this in their own work? And can point to what the issue may be? Cheers.

$('tr.clickable').on('click', (e) => {
$(e.currentTarget).toggleClass('open')
e.target.parentElement.nextElementSibling.classList.toggle('shown')
})
table {
  width: 100%
  table-layout: fixed}

tr {color: #fff}
tr.open {background-color: #bb0000}
tr.childrow:not(.shown) {display: none}

td {padding: 20px;}
tr:not(.open) {background-color: #000}

tr td:nth-child(1) {width: 5%; border-radius: 10px 0 0 10px}  
tr td:nth-child(2) {width: 5%}  
tr td:nth-child(3) {width: 40%}  
tr td:nth-child(4) {width: 15%}  
tr td:nth-child(5) {width: 10%}
tr td:nth-child(6) {width: 10%}
tr td:nth-child(7) {width: 10%} 
tr td:nth-child(8) {width: 5%} 

tr:not(.open) td:nth-child(8) {border-radius: 0 10px 10px 0} 
tr.open td:nth-child(8) {border-radius: 0 10px 0 0}
tr.open td:nth-child(1) {border-radius: 10px 0 0 0}
tr.childrow td {border-radius: 0 0 10px 10px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class='clickable'>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>E</td>
<td>F</td>
<td>G</td>
<td>H</td>
</tr>
<tr class='childrow'><td colspan="8">I am no longer hidden</td></tr>
</table>

Ajax GET Request inside ajax post request?

Is it possible to make an ajax request inside another ajax request? because I need some data from first ajax request to make the next ajax request.

I tried to make a script, but i see that instead of GET, my request is POST and i dont know where is the problem..

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

        }
    });
    $('#file-upload').submit(function(e) {
        e.preventDefault();
        let formData = new FormData(this);
        $('#file-input-error').text('');
        $.ajax({
            type: 'POST',
            url: "{{ route('resume.store') }}",
            data: formData,
            contentType: false,
            processData: false,
            success: (response) => {
                if (response) {
                    this.reset();
                    $("#showResponseArea span").html(response); //you will paste your response msg to the 
                    $.ajax({
                        type: 'GET',
                        url: "{{ route('resume.api') }}",
                        dataType: 'json',
                        data: {
                            'url': response,
                        }
                    })
                }
            },
            error: function(response) {
                $('#file-input-error').text(response.responseJSON.message);
            }
        });
    });
</script>

filtering bounding boxes on image

enter image description here
As shown in the image, I wrote the code to display the image and the bounding boxes by reading the annotations file.

enter image description here

this is the format for the annotation file

‘671 57 663 53 672 37 679 42 small-vehicle 0’

462 394 459 384 486 375 489 385 large-vehicle 0

696 483 713 519 610 546 595 510 tennis-court 0

677 440 692 476 591 504 575 469 tennis-court 0

498 502 528 493 536 515 507 525 swimming-pool 0

and then I store all the classes of the image (for eg: small-vehicle,swimming pool etc) in a set and display it on the top right of the webpage as shown in image.

Now I am interested only in vehicles so I want to display the bounding boxes of small-vehicles and large-vehicle with one color (lets say blue ) and all the other classes with another color (lets say yellow) and if I click on small-vehicles/large vehicles only the bounding boxes of those should be displayed and bounding boxes of other classes should be hidden and vice versa.

Someone suggested I use legend, but I don’t know how to start this with bounding boxes as I have seen only tutorials with line charts or is there any other better way?. If an example with a code for bounding boxes is shown.is shown that would be great

This is my first experience with javascript at all and I have to finish this task soon no matter what at work. Please help me. Thank you

…

 async function fetchData(annotationpath, imagesource, template, width, height) {

        await fetch(annotationpath)
            .then(response => response.text())
            .then(text => {
                filecontent= text; //s contains the content of the file
                console.log(filecontent);
            var lines = this.filecontent.split(/rn|n/);

            for (var line = 2; line < lines.length; line++) { //array to loop through each lines an
                    console.log(line + " --> " + lines[line]);
                    var annotationline = lines[line].split(' '),
                        x1 = annotationline[0],
                        y1 = annotationline[1],
                        x2 = annotationline[2],
                        y2 = annotationline[3],
                        x3 = annotationline[4],
                        y3 = annotationline[5],
                        x4 = annotationline[6],
                        y4 = annotationline[7],
                        classes = annotationline[8],
                        detected = annotationline[9];

                        classarray.push(classes);
                    

                    //bounding boxes(bb)
                    var bb= d3.select(template).append("svg")
                        .attr("width", width)
                        .attr("height", height),
                        poly = [{
                                "x": x1,
                                "y": y1
                            },
                            {
                                "x": x2,
                                "y": y2
                            },
                            {
                                "x": x3,
                                "y": y3
                            },
                            {
                                "x": x4,
                                "y": y4
                            }
                        ];

                    bb.selectAll("polygon")
                        .data([poly])
                        .enter().append("polygon")
                        .attr("points", function(d) {
                            return d.map(function(d) {
                                return [d.x, d.y].join(",");
                            }).join(" ");
                        })
                        .attr("stroke","red")
                        .attr("fill", "none");


                }
            console.log(classarray);
            classarray.sort();
            classset=new Set(classarray);
            console.log(classset);
            text = "";
            classset.forEach (function(value) {

              text += value + "<br>";

            })
                document.getElementById("classname").innerHTML = text;
               classarray.length = 0;
           })

 }



}

…