How to have only unique values from data in a drop down select list using d3.js?

I’d like to populate a dropdown list (select tag) with only unique values from an object.

This is the object with the data:

[
    {
        "code": 1,
        "abbr": "BR",
        "vote": 49277010
    },
    {
        "code": 1,
        "abbr": "BR",
        "vote": 31342051
    },
    {
        "code": 43,
        "abbr": "RS",
        "vote": 3353623
    },
    {
        "code": 31,
        "abbr": "MG",
        "vote": 3037957
    },
    {
        "code": 31,
        "abbr": "MG",
        "vote": 5017922
    },
    {
        "code": 35,
        "abbr": "SP",
        "vote": 2650440
    },
    {
        "code": 42,
        "abbr": "SC",
        "vote": 2603665
    },
    {
        "code": 1,
        "abbr": "BR",
        "vote": 71347057
    },
    {
        "code": 26,
        "abbr": "PE",
       "vote": 2309104
    }
]

And here is how I get the data to build the dropdown list:

//initialize the dropdown
var dropdown = d3.select("#sel")

dropdown
    .selectAll('myOptions')
    .data(data)
    .enter()
    .append('option')
    .text(function (d) { return d.abbr; }) //text showed in the options
    .attr("value", function (d) { return d.code; }) //values returned by each option

The problem is that repeated values are shown instead of only one for each code/abbr as you can see below:

<select id="sel">
  <option value="1">BR</option>
  <option value="1">BR</option>
  <option value="43">RS</option>
  <option value="31">MG</option>
  <option value="31">MG</option>
  <option value="35">SP</option>
  <option value="42">SC</option>
  <option value="1">BR</option>
  <option value="26">PE</option>
</select>

How can I filter the data to have only unique values in the options instead?

<select id="sel">
  <option value="1">BR</option>
  <option value="43">RS</option>
  <option value="31">MG</option>
  <option value="35">SP</option>
  <option value="42">SC</option>
  <option value="26">PE</option>
</select>

Is it possible to use the Google charts api to create charts without using html elements for rendering?

I used this code to render some charts in my html page.

function drawChart(id, arrayPrice) {

    let dataChart = [
        ['', 'Price']
    ];
    for (let index = 0; index < arrayPrice.length; index++) {

        dataChart.push(['', arrayPrice[index]])
    }

    const firstPrice = dataChart[1][1];
    const lastPrice = dataChart[dataChart.length - 1][1];

    var data = google.visualization.arrayToDataTable(dataChart);

    var options = {
        width: 130,
        height: 50,
        colors: (firstPrice < lastPrice) ? ['#50afb2'] : ['#ab5780'],
        legend: 'none',
        tooltip: {
            trigger: 'none'
        },
        enableInteractivity: false,
        vAxis: {
            textPosition: 'none',
            gridlines: {
                color: 'transparent'
            },
            baselineColor: 'transparent'
        },
        hAxis: {
            textPosition: 'none',
            gridlines: {
                color: 'transparent'
            },
            baselineColor: 'transparent'
        },
        backgroundColor: { fill: 'transparent' }
    };

    var chart = new google.visualization.LineChart(document.getElementById(id));

    chart.draw(data, options);
}

I was wondering if it was possible to do this server-side with NodeJS without using html elements in which to do the rendering.

My goal is to generate chart images to download locally to the server.

Is it dangerous using HTTP Basic Authentication and storing usename/password in local storage for future requests? (without XSS)

I’m developing an app in React and Spring Boot + Spring Security. Right now I’ve added HTTP Basic Auth for user authentication. User inputs username and password in a login form, and I send them (of course over HTTPS) to my backend. If the user is authenticated, I send back success, and the frontend saves the credentials into local storage for future requests (i.e. no session server-side). Then whenever I navigate to a “secured” route in React, I check the local storage, and then use the credentials for my secured requests. When user needs to logout, the app removes the credentials from local storage.

It’s a very trivial security implementation, but unless I have XSS vulnerability, or there is downgrade to HTTP (for my domain, not possible – HSTS preloading), I don’t think it’s vulnerable. But the main problem I see with it is that I can’t for example logout users remotely, which might come in handy at some point. Have I found myself in a dead-end? Is HTTP Basic Auth just not meant for stateless authentication with SPAs?

How to get invisible recaptcha token correctly?

I’m using react-google-invisible-recaptcha to generate validation token. I need to pass this token as props and I created a sendData function that uses async/await.

In a way this works, it generates the token, but at build time it breaks with the error:

TypeError: Cannot read property ‘execute’ of undefined

This is the code:

import GoogleRecaptcha from 'react-google-invisible-recaptcha';

const Wrapper = branch(
  ({ status }) => status,
  renderComponent(StatusResponses)
)(Progress);

const MyPage = () => {
  const [recaptchaLoaded, setRecaptchaLoaded] = useState(false);

  const recaptcha = useRef();
  const dispatch = useDispatch();

  useEffect(() => {
    const sendData = async () => {
      const recaptchaToken = await recaptcha.current.execute();

      dispatch(sendStatusPage(recaptchaToken))
        .then((data) => dispatch(getStatus(data)))
        .catch(identity);
    };

    sendData();
  }, []);

  const onRecaptchaLoaded = () => {
    setRecaptchaLoaded(true);
  };

  const onRecaptchaResolved = () => recaptcha.current.getResponse();

  return (
    <Container>
      {RECAPTCHA_KEY && (
        <GoogleRecaptcha
          onLoaded={onRecaptchaLoaded}
          ref={recaptcha}
          sitekey={RECAPTCHA_KEY}
          onResolved={onRecaptchaResolved}
          onError={identity}
        />
      )}
      <Wrapper progress={progress} />
    </Container>
  );
};

export default MyPage;

I tried to wrap the function that creates the token in this way

if (recaptchaLoaded) {
   const recaptchaToken = await recaptcha.current.execute();
}

But it ends up giving the same error as above.

What am I doing wrong? How can I get this token?
Thanks if anyone can help me

How to get the value of a table field when checking and unchecking a checkbox

So, I have this html table, with a checkbox as the last column (id = reconciled), I also have an id field in the first column (id = aopayid) , how do I check the last column and get the first column value, I also want to uncheck and get the first column value – they must be as I click each checkbox and I need the check and uncheck to be separate as I will run a separate script for each.

I have found a few solutions, but they all seem to loop through the table and give the value of each that are checked, or unchecked. Hope that makes sense.

<table id="example" class="display" style="width:100%;display:none" >
            <thead>
                <tr>
                <th >AoID</th>
                <th>Merchant</th>
                <th >Reference</th>
                <th  >Date</th>
                <th style=" text-align: right">Amount</th>
                <th >Status</th>
                <th >Edit</th>     
                <th >Complete</th>     
                </tr>
            </thead>
            <tbody>
                <tr>
                <td name="aopayid" id="aopayid" >{{$transaction->id}}</td>
                <td>{{$transaction->merchant_name}}</td>
                <td>{{$transaction->merchant_reference}}</td>
                <td><span class="date"><?php echo substr($transaction->created,0,10); ?></td>
                <td style=" text-align: right"><?php echo number_format($transaction->amount,2); ?></td>
                <td><span class="badge {{($transaction->status == 'Paid') ? 'badge-success' : (($transaction->status == 'Failed') ? 'badge-danger' : (($transaction->status == 'Pending') ? 'badge-warning' :  (($transaction->status == 'Charge back') ? 'badge-primary':''))) }}">{{$transaction->status}}</span></td>
                <td><input type="button" class="edit" name="edit" value="Edit" ></td>
                <td><input type="checkbox" class="reconciled" name="reconciled" id="reconciled" value = 'yes'  ></td>
            </tr>
          </tbody>
 </table>

The code that I have is as follows , but it does not give the value when unchecking

$(document).on("click", "#example .reconciled", function () {

 //Reference the Table.
  var grid = document.getElementById("example");
 
 //Reference the CheckBoxes in Table.
  var checkBoxes = grid.getElementsByTagName("INPUT");
  var message ;
  var checkedornot;

 //Loop through the CheckBoxes.
 for (var i = 0; i < checkBoxes.length; i++) {
     if (checkBoxes[i].checked) {
         var row = checkBoxes[i].parentNode.parentNode;
         message = row.cells[0].innerHTML;
         checkedornot = 'Yes';
     
     }
  }



 alert(message ); 


});

Constant Problems With my Bot That i never had on my old one?

Ok. so the problem I have I don’t know if its because of discord updates or node updates every time I open my project I get a different error when initializing a command and its starting to bug me its ever since I started implementing a database I will use source bin to put up my folders but I’m getting frustrated its the same way as my old bot was I had a massive econ system with levels inventory etc but now its just a big pain

main.js

message.js

profileSchema.js

guildMemberAdd.js

clear.js
beg.js

first time the error was

Bot Is Online
(node:6396) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
MongooseError: Operation `profilemodels.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (Roleplaynode_modulesmongooselibdriversnode-mongodb-nativecollection.js:151:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Roleplayeventsguildmessage.js:37
    if(!cooldowns.has(command.name)){
                              ^

TypeError: Cannot read properties of undefined (reading 'name')
    at module.exports (Roleplayeventsguildmessage.js:37:31)
PS Roleplay>

after i decided to make sure it was saved turned it all off went to bed loaded it up the next morning then i got the same sort of error but instead of

TypeError: Cannot read properties of undefined (reading ‘name’)

it was
TypeError: Cannot read properties of undefined (reading ‘id’)
under beg.js message.author.id

and now the erorr i got after going out for abit and saved and turned all of come back on i now get

Bot Is Online
(node:4712) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)
MongooseError: Operation `profilemodels.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (Roleplaynode_modulesmongooselibdriversnode-mongodb-nativecollection.js:151:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Roleplaycommandsclear.js:8
        if(isNaN(args[0])) return message.reply("please enter a real number");
                                          ^

TypeError: message.reply is not a function
    at Object.execute (Roleplaycommandsclear.js:8:43)
    at module.exports (Roleplayeventsguildmessage.js:60:17)
PS Roleplay>

How can I make react js editable table columns a required field?

I added textareas in React Js EditableTable as in the images below. When the Save button is pressed, I want to give a warning as a mandatory field in case these textareas are entered empty. How can I do that? As I shared in the codes below,

validation={[
             {
               required: true,
               message: "required",
             },
           ]}

I added parts of it, but it had no effect. How do I edit?

enter image description here

Code base:

   const columns = [
    {
      title: "Order Type",
      dataIndex: "orderType",
      type: "string",
    },
    {
      title: "Before 1330",
      dataIndex: "before1330",
      type: "string",
      editable: true,
    },
    {
      title: "After 1330",
      dataIndex: "after1330",
      type: "string",
      editable: true,
    },
  ];
  
  
  const getInput = (dataIndex, record, props) => {
    if (record.key == 0 && dataIndex == "before1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: "required",
            },
          ]}
        />
      );
    } else if (record.key == 0 && dataIndex == "after1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: required,
            },
          ]}
        />
      );
    } else if (record.key == 1 && dataIndex == "before1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: required,
            },
          ]}
        />
      );
    } else if (record.key == 1 && dataIndex == "after1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: required,
            },
          ]}
        />
      );
    } else if (record.key == 2 && dataIndex == "before1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: required,
            },
          ]}
        />
      );
    } else if (record.key == 2 && dataIndex == "after1330") {
      return (
        <TextInput
          maxLength={200}
          {...props}
          validation={[
            {
              required: true,
              message: required,
            },
          ]}
        />
      );
    }

    return (
      <TextInput
        maxLength={200}
        {...props}
        validation={[
          {
            required: true,
            message: required,
          },
        ]}
      />
    );
  };
  
         <Form ref={formRef} colSpan={{ span: 24 }} onSubmit={handleSubmit}>
.....        
          <Form.Item >
            <EditableTable
              title={() => <TableHeader title={"Table"} />}
              mode="cell"
              columns={columns}
              data={data}
              setData={setNewData}
              getInput={getInput}
            />
          </Form.Item>  
          
            <Button className="right-floated" htmlType="submit" type="primary">
              {"Save"}
            </Button>         
...
</Form>

Checking an object child value

lets say i have a object like this,

let error = {
 Password: {type: required }
 
 Email: {type: pattern }

 name: {type: required}
}

is there a way to chack the error of any type. like if i want to know
error type i have to type like this.

error.password.type    //required
error.Email.type      //pattern
error.name.type      //required

for this i have to type multiline, is there a way to chack the value of error type in single line.

like if i want to create a if statement

if(error.type == "pattern"){
//do somthing
}
if(error.type == "required"){
//do somthing
}

what to write in between error and type? in javascript.

Export GPX route from leaflet map

I’m trying to find a way of producing a GPX string from a Leaflet map so I can then save it into my DB. I am using Leaflet Routing Machine to create the route and then display it on an embedded map. So far I found many ways to import a GPX to Leaflet but I cannot figure out a way to do the opposite.

So far my (simplified) code to display the map and generate the route is as it follows:

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
    <script src="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.js"></script>
    
    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>




<div id="map" class="map"></div>
        



<style>
        .map {
            position: absolute;
            width: 50%;
            height: 50%;
            justify-content: right;         
        }
</style>



<script>
            var map = L.map('map').
            setView([40.416729,-3.703339], 5);
                
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
            
            L.Routing.control({
                routeWhileDragging: true,
                geocoder: L.Control.Geocoder.nominatim()    
            }).addTo(map);
        
</script> 

Vinted request blocked in JavaScript

I want to do some requests on the Vinted website, I have a code python which works perfectly, but the “same” code in JavaScript doesn’t. Vinted’s Cloudflare block the request after 1 request, with the code 1020 (access denied).

Here is the python code

import requests;

headers = requests.utils.default_headers()
headers.update({"User-agent":"Mozilla/5.0"})
response = requests.get("https://www.vinted.fr/vetements?search_text=casquette&brand_id[]=362&order=newest_first&color_id[]=12", headers=headers)

print(response)

headers = requests.utils.default_headers()
headers.update({"User-agent":"Mozilla/5.0"})
response = requests.get("https://www.vinted.fr/vetements?search_text=casquette&brand_id[]=362&order=newest_first&color_id[]=12", headers=headers)

print(response)

And here the JS one

const config = {
    method: 'get',
    url: 'https://www.vinted.fr/vetements?search_text=casquette&brand_id[]=362&order=newest_first&color_id[]=12',
    headers: { 
      'User-Agent': 'Mozilla/5.0', 
      'Accept-Encoding': 'gzip, deflate', 
      'Accept': '*/*', 
      'Connection': 'keep-alive'
    }
  };
  
axios(config).then(function (response) {
    console.log(response);
    axios(config).then(function (response) {
        console.log(response);
    })
})

Why does javascript not run this if block when it should?

I am trying to create a program which is able to find the mean of two sets of 3 numbers (user inputs) and is able to determine which average is the winner (based on which one is bigger and some extra criteria). Here is the code.

const splitter = (promptChoice, numberAmount) => {
    return Number(promptChoice.split(" ", numberAmount)[numberAmount - 1]);
}

const checker = arrayValues => {
    for (let index = 0; index < arrayValues.length; index++) {
        (isNaN(arrayValues[index]) == true || !(isFinite(arrayValues[index])) == true) ? checkerResponse = true : checkerResponse = false; 
    }
}

const averageScoresCalculator = scoresList => {
    averageAnswer = 0;

    for (let index = 0; index < scoresList.length; index++) {
        averageAnswer += scoresList[index];
    }

    Math.round(averageAnswer /= scoresList.length);
}

const dolphinPrompt = prompt(`Type the dolphin scores (3 seperate ones), with a space in between each`);
const koalaPrompt = prompt(`Type the koala scores (3 seperate ones), with a space in between each`);

let changer;
let checkerResponse;
let averageAnswer;
let matchResult;

const dolphinScores = [splitter(dolphinPrompt, 1), splitter(dolphinPrompt, 2), splitter(dolphinPrompt, 3)];
const koalaScores = [splitter(koalaPrompt, 1), splitter(koalaPrompt, 2), splitter(koalaPrompt, 3)];

averageScoresCalculator(dolphinScores);
const dolphinAverageScore = averageAnswer;

averageScoresCalculator(koalaScores);
const koalaAverageScore = averageAnswer;

checker([dolphinAverageScore, koalaAverageScore]);

if (checkerResponse) {
    changer = `It appears that there has been a mistake - please reload the page and type the correct amounts.`;
} else {
    if (dolphinAverageScore > 100) {
        if (koalaAverageScore > 100) {
            if (dolphinAverageScore > koalaAverageScore) {
                matchResult = `dolphins`;
            } else if (dolphinAverageScore < koalaAverageScore) {
                matchResult = `koalas`
            } else {
                matchResult = `draw`;
            }
        } else {
            matchResult = `dolphins`;
        }
    } else if (koalaAverageScore > 100) {
        if (dolphinAverageScore > 100) {
            if (dolphinAverageScore < koalaAverageScore) {
                matchResult = `koalas`;
            } else if (dolphinAverageScore > koalaAverageScore) {
                matchResult = `dolphins`
            } else {
                matchResult = `draw`;
            }
        } else {
            matchResult = `koalas`;
        }
    } else {
        matchResult = `none`
    }
};

if (matchResult = `dolphins`) {
    changer = `The ${matchResult} win the cup! The score was ${dolphinAverageScore} to ${koalaAverageScore}.`;
} else if (matchResult = `koalas`) {
    changer = `The ${matchResult} win the cup! The score was ${koalaAverageScore} to ${dolphinAverageScore}.`;
} else if (matchResult = `draw`) {
    changer = `Both teams win the cup! Each team got a score of ${dolphinAverageScore}.`;
} else {
    changer = `No one won the cup.`;
}

document.getElementById('changer').innerHTML = changer;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  </head>
  <body>
    <h1 id="changer">JS Experiments</h1>
    <script src="script.js"></script>
  </body>
</html>

I was handling for the case in which the user gave an invalid or really big value, which my checker function should spot the issue. But this was not the case. Instead, the program would continue as normal, only with invalid inputs instead of regular ones. I thought I had messed something up in my checker function, but no – it too was working just fine. Why then is the error message not showing? All help would be greatly appreciated, as I am going crazy for this.

EDIT

Also, if I do input valid inputs, the Math.round() method doesn’t seem to work. Why is this?

Javascript code refactor to use in Stimulus controller

How to refactor JS code like this:

const fileInput = document.getElementById('input');
const p = document.querySelector('p');
fileInput.onchange = () => {
  const selectedFiles = [...fileInput.files];
  p.textContent = selectedFiles.map(s => s.size).join(', ');
}

to make it work in rail’s Stimulus?
I have very little experience with JS and want to have one or two examples of implementing JS code in Stimulus controllers, so I have material to refactor other cases on my own.
Much thanks.

Creating Flipbook using MVC

I generate the flip book and I used play button to go next, previous, first, last, autoplay and stop. The flip animation works good, and also previous and next button works good. But when I click autoplay, first and last button, It’s goes first page only. Here I find the issue is- one extra slash added automatically with the image url.

The url is
The issue is
http://localhost:XXXXX/FlipBookGeneration/FlipBookGeneration#/page/4

The slash extra added after the #.

 <script type="text/javascript">
    //Global variables
    var txtGoTo = 0;
    var totPageCount = 0;
    var timeInterval;
    var startAuto;


    $(document).ready(function () {
        startAuto = document.getElementById('hdnTimeInterval').value;
        if (parseInt(startAuto) > 0) {
            Initiate_AutoFlipBook();
            //---To change the URL, which is necessary for the Flipbook Page navigation
            var Location = window.location;
            Location.hash = document.getElementById('hdnStopWin').value;
            window.location = Location;
            document.getElementById('hdnTimeInterval').value = 1;
        }

    });

    function settingsMaintainPage() {

        $('#settings').toggle();
        return false;
        //           var Location = window.location;
        //           lnkSettings.href = Location;
    }


    function Initiate_AutoFlipBook() {

        // To get the Total Page Count of FlipBook
        totPageCount = parseInt(document.getElementById('txtPageCount').value);
        //To intiate the AutoFlipBook
        timeInterval = window.setInterval(function () {

            if (txtGoTo < totPageCount) {
                txtGoTo = txtGoTo + 2;
                FlipBook_GoToNextPage(null);
            }
            else {
                txtGoTo = 0;
            }

        }, 2000);
    }
    function startAutoFlip() {


        var getValue = parseInt(document.getElementById('hdnTimeInterval').value);

        //To check if Auto Flipbook is not started
        if (!isNaN(getValue) && getValue == -1) {
            document.getElementById('hdnTimeInterval').value = 1;
            Initiate_AutoFlipBook();
        }

        return false;

    }
    function Stop_Timer() {

        document.getElementById('hdnTimeInterval').value = -1;
        clearInterval(timeInterval);
        document.getElementById('hdnStopWin').value = window.location.hash;
        return false;
    }

    function Last_Page() {

        totPageCount = document.getElementById('txtPageCount').value;

        window.location.hash = "#page/" + totPageCount;
        document.getElementById('hdnStopWin').value = window.location.hash;
        return false;
    }
    //Goto Page
    function goTo(e) {


        totPageCount = document.getElementById('txtPageCount').value;
        if (e != null) {
            if (e.value == '') {

                txtGoTo = 1;
            }
            else if (e == -1) {

                txtGoTo = totPageCount;
            }
            else if (e == 1) {
                txtGoTo = e;

            }
            else {
                txtGoTo = parseInt(document.getElementById('txtBkMark').value);
            }
        }
        if (txtGoTo == 0) {
            alert('Invalid page number');
            document.getElementById('gotopage').value = "";
        }

        else if (parseInt(txtGoTo) < parseInt(totPageCount) + 1) {
            
            var Location = window.location;
            Location.hash = "#page/" + txtGoTo;
            var str= Location.hash;               
            window.location = Location;  
            
           
            return false;
        } else {
            alert('Invalid page number');
            document.getElementById('txtBkMark').value = "";
        }
    }


    function FlipBook_GoToNextPage(e) {

        totPageCount =parseInt(document.getElementById('txtPageCount').value);
        if (e != null) {
            if (e.value == '') {

                txtGoTo = 1;
            } else {
                txtGoTo = parseInt(document.getElementById('txtBkMark').value);
            }
        }
        if (parseInt(txtGoTo) < parseInt(totPageCount) + 1) {
            var Location = window.location;
            Location.hash = "#page/" + txtGoTo;
            window.location = Location;
        } else {
            var Location = window.location;
            Location.hash = "#page/1";
            window.location = Location;
        }
    }


    function GoToNextPage() {

        return false;
    }

The issue slash is comes in window.location.hash and window.location.href