Execution Timed Out (12000 ms): How can I optimize JS kata to run faster? [Upside-Down Numbers – Challenge Edition]

    function upsideDown(x, y) {
      const list = ["0", "1", "6", "8", "9"];
      let count = 0;
      for (let i = parseInt(x); i <= parseInt(y); i++) {
        let curr = i.toString().split("");
        let upsideDownCurr = "";
        if (
          !curr.every(function (x) {
            return list.includes(x);
          })
        )
          continue; // Skips if number includes non-upDown num
        for (let j = 0; j < curr.length; j++)
          if (curr[j] === "6") upsideDownCurr = "9" + upsideDownCurr;
          else if (curr[j] === "9") upsideDownCurr = "6" + upsideDownCurr;
          else upsideDownCurr = `${curr[j]}` + upsideDownCurr;
        if (upsideDownCurr === curr.join("")) count++;
      }
      return count;
    }

Input:

Your function will receive two strings, each comprised of digits representing a positive integer. These two values will represent the upper and lower bounds of a range.
Output:

Your function must return the number of valid upside down numbers within the range of the two input arguments, including both upper and lower bounds.
What is an Upside-Down Number?

An upside down number is an integer that appears the same when rotated 180 degrees, as illustrated below.

This works fine untill
Test.assertEquals(upsideDown('100000','12345678900000000'),718650)
any idea how to optimize the code?

addEventListener: click just one element of a bunch of elements

I’m beginner and have trouble with something in JS that might be simple to solve.

I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can’t send a totally empty quiz.

The quiz has 4 questions with 2 options each, and I found this way…

const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");


button.disabled = true;




input_a.addEventListener('click', () => {
    button.disabled = false;

});

input_b.addEventListener('click', () => {
    button.disabled = false;

});

…to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there’d also be q2a, q2b, q3a, q3b, q4a & q4b..

As there is a way to include all the answers in one JS element, what should I do in the event function to say “when you click any of this 8 options, enable the button”? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .

Thank you! 🙂

Regex for ISO8601 temporal duration but only with minutes and seconds

I’m attempting to write Regex to match the ISO8601 standard for temporal durations, but only where PT and M or S are valid.

So far I have found a full example of ISO8601 regex but it is more complex than I need. I need match durations like the following:

  • PT7S
  • PT10M50S
  • PT150S

Essentially I want the Regex to always check that:

  • capitalised PT is at the beginning of the string
  • M is preceded by a whole number
  • S is preceded by a whole number
  • M comes before S

My attempt so far:

  • capitalised PT at the beginning = ^PT
  • M preceded by a whole number = [0-9]+M – except this allows something like 10.5M because the 5M counts
  • S preceded by a whole number = same as above
  • M comes before S. Again no idea!

I’m really stuck on trying to figure this out, I’ve been trying to get each part to match so I could try and combine them all later but I can’t get over the first hurdle.

d3.js visualisation won’t centre on iPhone screen

I am working on a project with d3.js where I want a visualisation to centre on the screen. My current solution works perfectly on desktop screens, even when resizing, but when I load the webpage on my iPhone screen, the visualisation is no longer centred. The target div for this visualisation is:

<div id="grades_circular" class="my_dataviz"></div>

The css to style is:

.my_dataviz {
display: flex;
justify-content: center;}

The JavaScript code for the visualisation is :

const grades_margin = {top: 30, right: 0, bottom: 70, left: 0},
      grades_width = 460 - grades_margin.left - grades_margin.right,
      grades_height = 460 - grades_margin.top - grades_margin.bottom;
      innerRadius = 50,
      outerRadius = Math.min(grades_width, grades_height) / 2;

const grades_svg = d3.select("#grades_circular")
  .append("svg")
    .attr("width", grades_width + grades_margin.left + grades_margin.right)
    .attr("height", grades_height + grades_margin.top + grades_margin.bottom)
  .append("g")
    .attr("transform", `translate(${grades_width/2+grades_margin.left}, ${grades_height/2+grades_margin.top})`);



d3.csv("https://raw.githubusercontent.com/ben-austin27/ben-austin27.github.io/main/data/results.csv").then( function(grades_data) {
  
const grades_x = d3.scaleBand()
      .range([0, 2 * Math.PI])    // X axis goes from 0 to 2pi = all around the circle. If I stop at 1Pi, it will be around a half circle
      .align(0)                  // This does nothing
      .domain(grades_data.map(d => d.module)); // The domain of the X axis is the list of states.

const grades_y = d3.scaleRadial()
      .range([innerRadius, outerRadius])   // Domain will be define later.
      .domain([40, 100]); // Domain of Y is from 0 to the max seen in the data

  // Add the bars
bars = grades_svg.append("g")
    .selectAll("path")
    .data(grades_data)
    .join("path")
      .attr("fill", d => "#" + d.color )
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(innerRadius)
          .outerRadius(innerRadius+0.05)//d => grades_y(d['grade'])
          .startAngle(d => grades_x(d.module))
          .endAngle(d => grades_x(d.module) + grades_x.bandwidth())
          .padAngle(0.05)
          .padRadius(innerRadius))
  
modules = grades_svg.append("g")
      .selectAll("g")
      .data(grades_data)
      .join("g")
        .attr("text-anchor", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; })
        .attr("transform", function(d) { return "rotate(" + ((grades_x(d.module) + grades_x.bandwidth() / 2) * 180 / Math.PI - 90) + ")"+"translate(" + (innerRadius+10) + ",0)"; })//
      .append("text")
        .text(function(d){return(d.module)})
        .attr("transform", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; })
        .style("font-size", "11px")
        .attr("alignment-baseline", "middle")

grades = grades_svg.append("g")
      .selectAll("g")
      .data(grades_data)
      .join("g")
        .attr("text-anchor", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; })
        .attr("transform", function(d) { return "rotate(" + ((grades_x(d.module) + grades_x.bandwidth() / 2) * 180 / Math.PI - 90) + ")"+"translate(" + (grades_y(d['grade'])+7) + ",0)"; })//
      .append("text")
        .text(function(d){return(d.grade)})
        .attr("transform", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; })
        .style("font-size", "11px")
        .attr("alignment-baseline", "middle")

function update_bars() {
  d3.selectAll("path")
      .transition()
      .ease(d3.easePolyInOut.exponent(3)) //https://observablehq.com/@d3/easing-animations
      .duration(2000)  
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(innerRadius)
          .outerRadius(d => grades_y(d['grade']))
          .startAngle(d => grades_x(d.module))
          .endAngle(d => grades_x(d.module) + grades_x.bandwidth())
          .padAngle(0.05)
          .padRadius(innerRadius))
// alter opactity of the labeling as well, after 2 seconds
}

var controller = new ScrollMagic.Controller();
new ScrollMagic.Scene({
  // the element to scroll inside
  triggerElement: '#grades_circular'
})
.on('enter', function(e) {
    update_bars(e);
}).addTo(controller)
});

Thanks!

Uncompress a string

Write a function, uncompress, that takes in a string as an argument.
The input string will be formatted into multiple groups according to
the following pattern:

number + char

for example, ‘2c’ or ‘3a’.

The function should return an uncompressed version of the string where
each ‘char’ of a group is repeated ‘number’ times consecutively. You
may assume that the input string is well-formed according to the
previously mentioned pattern.

test_00: uncompress(“2c3a1t”); // -> ‘ccaaat’

Here is my code which is using a stack. The problem is that it’s only returning ‘cc’ and I can’t figure out why. I’ve console logged what goes into the IF ELSE and I’m hitting both so I don’t understand why nothing gets pushed to the stack.

Would really appreciate the help if someone can spot what I’m missing.

const uncompress = (s) => { 
  const nums = '23456789';
  const stack = []; 
  for (let char of s) {
    if (nums.includes(char)) {
      stack.push(Number(char));
    } else {
      const num = stack.pop();
      stack.push(char.repeat(num));
    };
  };
  return stack.join('');
};

I can’t read the form elements [closed]

I can’t get the values of these three fields; it only returns an empty value (a space).
The ids are correctly set in the form.

Is there a code setting error?

const data = {
  id: document.getElementById('id').value,
  nameBook: document.getElementById('namebook').value,
  priceBook: document.getElementById('pricebook').value
};

How to scrape Yahoo Finance with Cheerio in Javascript?

I’m trying to pull a real time price from Yahoo Finance, based on an old post, and the latest price attribute (data-reactid=”47″) seen in Yahoo Finance. But the following code doesn’t extract the price data. What am I missing? I would appreciate any help. Thank you!

function test() {
  const url = 'https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  const $ = Cheerio.load(res);
  var price = $("span[data-reactid='47']").text().toString();
  console.log(price)
}

Item deletion using jquery ajax

Am having a problem with my jquery

i want to delete some products

but the only problem am getting, the deletion works only on first items even if i click the last item

Lets say i want to delete <p>INFO 20002</p> it will delete <p>INFO 2000</p>

i want to be able to delete any item i want

<script>
   function callB() {
    
    $("#button1").click(function(event) {
        Execute();
    });
   
    function Execute() {
        
        $.ajax({
            type: 'POST',
            url: 'ajax/file.aspx',
            data: {
                'custId': $("input[name='custId']").val()
            },
            success: function(response) {
                    
            },
            error: function() {
                alert("error");
            }
        });
    };
   }
   
   $(document).ready(function() {
    callB();
   });
</script>



<div>
<p>INFO 2000</p>
<input type="button" id="button1" value="Erase this">
 <input type="hidden" name="custId" value="348700">
</div>

<div>
<p>INFO 20001</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="4443487">
</div>

<div>
<p>INFO 20002</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="8883487">
</div>

<div>
<p>INFO 20003</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="1113487">
</div>

How can I access the return value of a Flask route within a Javascript file?

The problem I’m having is accessing the value within the return statement in the flask route (resp[“login”]). I’m trying to use this value in a javascript file and use it as a query parameter. But whenever i try the console.log() in the javascript file I get a promise object. But I am not able to find where I could find the value coming in from the Flask app. I thought it would be within the response object below but no such luck.

@app.route('/route', methods=['GET', 'POST'])
@cross_origin(supports_credentials=True)
def handle_callback():

    if request.method == 'POST':

        payload = {
            blahhh
        }
        headers = {'Accept': 'application/json', 'Access-Control-Allow-Origin': '*'}
        req = requests.post(token_url, params=payload, headers=headers)
        # make another request after this using access token with updated header field 
        resp = req.json()

        if 'access_token' in resp:
            oauthHeader = "token " + resp['blahhh']
            headers = {'Authorization': oauthHeader}
            access_token_url = 'https://blahhh.com'
            r = requests.get(url=access_token_url, headers=headers)
            resp = r.json()
            return resp["login"]
        else:
            return "error", 404
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const codeGit = urlParams.get('code')

const sub = {codeGit};
 

const res = fetch('http://localhost:4000/route', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'code': codeGit
    },
    credentials: 'include'
}).then(response => {
    if(response.status == 200){
        console.log('Success! ' + response.json() )
    }
}).catch(error => {
    console.log('error with access token req!')
})

console.log(res)

Adding element to the list on keypress and clearing the list

As in topic my job is to do a code where user writes some text into textbox and when user hits enter key, the text from the textbox should be added to ul list under Things header.
I added also reset button but it’s not working because adding elements to list isn’t working but I think it should work when I will fix it. I don’t know where I made mistake. Could anyone help me or give me advice what should I do?

<!DOCTYPE html>
<html>
<head>
    <title>List</title>
</head>
<body>
    <h1 id="title">List</h1>

    <form>
        <input type="text" id="user-todo" placeholder="List" required>
    </form>

    <h2 id="todo-header">Things</h2>
    <ul id="list">

    </ul>
    <button id="clear">Reset</button>
    <script>
        var input = document.getElementById("user-todo");
        input.addEventListener("keyup", function(event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                // what happens when user hits ENTER
                $(document).ready(function() {
                    $('ul').append("<li>"+($('#user-todo').val()) + "</li>");
                });
            }
        });

        function clear() {
            document.getElementById("list").innerHTML = '';
        }
    </script>
</body>

</html>

Cannot run external script inside index.html

It is impossible to run any external script inside my index.html. I am getting the following message in the console:

Refused to load the script xxx because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-eval'”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

I tried to apply suggestions from Refused to load the script because it violates the following Content Security Policy directive
with no success. Any other idea?

When using POST with Fetch API to send user input to php file / Session variable it returns undefined array key

I’m trying to send user inputs with Fetch API to my php file using the POST method. I’ve tried this with XMLHttprequests and has no issue but now I want to start using Fetch API. When I use the GET method to send the variable to the $_SESSION array I have no problem and I can echo it out. When I use the POST method it would return always “Undefined array key” for the variables.

I’m new to this so any help is much appreciated.

PHP

<?php
// a sessions start
session_start();
// session variable
$number1 = $_POST['n1'];
$number2 = $_POST['n2'];

$_SESSION['numbers'] = $_POST;

echo $_SESSION['numbers']['n1'];
echo $_SESSION['numbers']['n2'];
?>

JS

document.getElementById('btn').addEventListener('click', addNumbers);

function addNumbers(){
    var input1 = document.getElementById('one').value;
var input2 = document.getElementById('two').value;
    fetch('serv.php',{
        method:"POST",
        body:'n1='+input1+'&n2='+input2,
        header: {   'Content-Type': 'application/x-www-form-urlencoded' }
        
    }).then((response) => response.text())
        .then((data) => {
            output.innerHTML += data;
            
        })
}

I know that I should check if the Session variable is empty or isset but i removed it just for visibility purposes.

Progress bar with multiple divisions

Hello to the whole stackoverflow community! Unfortunately, I have a problem and I can’t deal with it alone :c . I hope for your understanding and help in calculating this progress bar. How to properly calculate the completion of this progress bar? I am doing it in Vue. P.S already know about the fact that you can’t access the item through querySelector, I will fix that in the future.

enter image description here

<div class="main__position-bar">
            <div class="main__position-bar-junior-minus">
              <p class="main__position">Junior -</p>
              <div class="main__position-progress main__position-progress--beginning">
                <span class="main__position-progress--beginning"></span>
              </div>
              <p class="main__position-number">50</p>
            </div>

            <div class="main__position-bar-junior-plus">
              <p class="main__position">Junior +</p>
              <div class="main__position-progress">
                <span></span>
              </div>
              <p class="main__position-number">150</p>
            </div>

            <div class="main__position-bar-middle-minus">
              <p class="main__position">Middle -</p>
              <div class="main__position-progress">
                <span></span>
              </div>
              <p class="main__position-number">200</p>
            </div>

            <div class="main__position-bar-middle-plus">
              <p class="main__position">Middle +</p>
              <div class="main__position-progress">
                <span></span>
              </div>
              <p class="main__position-number">300</p>
            </div>

            <div class="main__position-bar-senior-minus">
              <p class="main__position">Senior -</p>
              <div class="main__position-progress">
                <span></span>
              </div>
              <p class="main__position-number">350</p>
            </div>

            <div class="main__position-bar-senior-plus">
              <p class="main__position">Senior +</p>
              <div class="main__position-progress main__position-progress--end">
                <span class="main__position-progress--end"></span>
              </div>
            </div>
          </div>

          export default {
           data() {
            return {         
             positionProgressValueOne: 150,
             positionProgressValueTwo: 1,
            }
           },
  methods: {
    positionProgressBar() {
      let positionJuniorMinus = document.querySelector('.main__position-bar-junior-minus .main__position'),
          positionJuniorMinusTime = document.querySelector('.main__position-bar-junior-minus .main__position-number'),
          progressBarJuniorMinus = document.querySelector('.main__position-bar-junior-minus span'),

          positionJuniorPlus = document.querySelector('.main__position-bar-junior-plus .main__position'),
          positionJuniorPlusTime = document.querySelector('.main__position-bar-junior-plus .main__position-number'),
          progressBarJuniorPlus = document.querySelector('.main__position-bar-junior-plus span'),

          percent = 100,
          valueOne = this.positionProgressValueOne,
          valueTwo = this.positionProgressValueTwo,
          calculationOne = valueOne / valueTwo,
          calculationTwo = percent / calculationOne;


      if (this.positionProgressValueOne <= 50) {
        this.userPosition = 'Junior -'

        function calculationProgressBar() {
          positionJuniorMinus.classList.add('main__position--active');
          positionJuniorMinusTime.classList.add('main__position-number--active');
          progressBarJuniorMinus.style.width = `${calculationTwo}%`
        }
      } else if (this.positionProgressValueOne >50 && this.positionProgressValueOne <= 150) {
        this.userPosition = 'Junior +'

        function calculationProgressBar() {
          positionJuniorPlus.classList.add('main__position--active');
          positionJuniorPlusTime.classList.add('main__position-number--active');
          progressBarJuniorMinus.style.width = '100%';
          progressBarJuniorPlus.style.width = `${calculationTwo}%`
        }
      }
    },
  },
   mounted() {
    this. positionProgressBar();
  }
}