How to get the buffer of the first frame of a video using ffmpeg? (Node.js)

I am trying to use child_processes and ffmpeg to do this, but it returns this error:

FFmpeg stderr: [AVFilterGraph @ 00000157fd55abc0] No option name near 'eq(n, 0)"'
[AVFilterGraph @ 00000157fd55abc0] Error parsing a filter description around:
[AVFilterGraph @ 00000157fd55abc0] Error parsing filterchain '"select=eq(n, 0)"' around:
[vost#0:0/libx264 @ 00000157fd574700] Error initializing a simple filtergraph
Error opening output file pipe:1.
Error opening output files: Invalid argument

FFmpeg process exited with code: 4294967274

When I run that command in the terminal, it works fine, but it doesn’t work in the code.
Here’s the command (terminal version):
ffmpeg -i input/vid.mp4 -vf "select=eq(n,0)" -vframes 1 out.png

And heres the code:

import { spawn } from 'child_process';

const inputVideoPath = 'input/vid.mp4';

const ffmpeg = spawn('ffmpeg', [
    '-i', inputVideoPath,
    '-vf', '"select=eq(n\, 0)"',
    '-vframes', '1',
    '-f', 'mp4',
    'pipe:1'
]);

let buffer = Buffer.from([]);
ffmpeg.stdout.on('data', (data) => {
    buffer = Buffer.concat([buffer, data]);
});

ffmpeg.stderr.on('data', (data) => {
    console.error('FFmpeg stderr:', data.toString());
});

ffmpeg.on('exit', (code) => {
    if (code == 0) {
        console.log('FFmpeg process exited successfully.');
        console.log(`Buffer size: ${buffer.length} bytes`);
    } else {
        console.error(`FFmpeg process exited with code: ${code}`);
    }
});

ffmpeg.on('error', (err) => {
    console.error('FFmpeg error:', err);
});

Note: I know I’m not doing anything with the buffer, I just want it to work first then I’ll start working with the output

If no changes were made to the script, why would Javascript suddenly stop working?

Disclaimer: I have very little to no knowledge of Javascript.

I have a page that was pre-written by another employee with HTML and Javascript. In attempt to change the display of the date/time format, I made a change to the script from (‘M/D/YY’) to (‘M/YY’), and published those changes. Suddenly, none of the JS works anymore, though the HTML is still appearing on the page. I reverted back to original script with (‘M/D/YY’), and still only the HTML appears, not the JS. Is there something I need to do refresh this page?

I reverted back to the original script (that was originally working just fine), deleted cache/cookies, tried a different browser, and it still isn’t working.

<script>

console.log('id','~(curstudid)');

var uc_capped = parseFloat('~(*gpa method="uc capped")');
var uc = parseFloat('~(*gpa method="uc")');
var calgrant = parseFloat('~(*gpa method="calgrant")');

if (isNaN(uc_capped)) uc_capped = 0;
if (isNaN(uc)) uc = 0;
if (isNaN(calgrant)) calgrant = 0;

console.log('uc capped: ', uc_capped, 'uc', uc, 'calgrant', calgrant);

const testData = [~[tlist_sql;
  select
  t.test_name,
  case
  when t.subtest_name = 'lang' then 'Language'
  when t.subtest_name = 'math' then 'Math'
  when t.subtest_name = 'quant' then 'Quantitative'
  when t.subtest_name = 'reading' then 'Reading'
  when t.subtest_name = 'verbal' then 'Verbal'
  when t.subtest_name = 'comp' then 'Composite'
  
  when t.subtest_name = 'writing' then 'Writing'
  when t.subtest_name = 'english' then 'English'
  when t.subtest_name = 'science' then 'Science'

  when t.subtest_name = 'ebrw' then 'EBRW'
  when t.subtest_name = 'math_test' then 'Math (test)'
  when t.subtest_name = 'reading_test' then 'Reading (test)'
  when t.subtest_name = 'writing_test' then 'Writing (test)'
  when t.subtest_name = 'total' then 'Total'
  end,
  t.date_taken,
  t.test_num,
  t.score
  from u_testresults t
  join students s on t.studentsdcid = s.dcid
  where s.id=~(curstudid)
  order by date_taken, test_name, test_num, replace(replace(subtest_name, 'total', 'Ω'), 'comp', 'Ω')
]['~(test_name)','~(subtest_name)','~(date_taken)','~(test_num)','~(score)'],[/tlist_sql]];

console.log(testData);

function termIDToName(termID) {
 const yearID = parseInt(termID.substring(0,2) + '00');
 const year = 1/100*yearID + 1990;
 let yearStr = '';
 if (termID.substring(3) == '1') {
     yearStr = 'Fall ' + year;
 } else if (termID.substring(3) == '2') {
     yearStr = 'Spring ' + (year+1);
 } else {
     yearStr = year + '-' + (year+1);
 }
 console.log(yearStr);
 return yearStr;
}

const table_terms = $j('#gpa-terms');
fetch('/admin/queries/gpa_by_term.json?sid=~(curstudid)')
.then(response => response.json())
.then(data => {
   if (data.length % 2 == 0) {
       // Odd number of terms, because null is at the end
       data.unshift(null);
   }
   console.log(data);
 for (let i = 0; i < data.length - 1; i += 2) {
     let row = '<tr>';
     row += '<td><b>' + termIDToName(data[i+1][1]) + '</b><br>Weighted: ' + parseFloat(data[i+1][2]).toFixed(2) + '<br>Simple: ' + parseFloat(data[i+1][3]).toFixed(2) + '</td>'
     if (data[i] == null) {
         row += '<td></td>';
     } else {
         row += '<td><b>' + termIDToName(data[i][1]) + '</b><br>Weighted: ' + parseFloat(data[i][2]).toFixed(2) + '<br>Simple: ' + parseFloat(data[i][3]).toFixed(2) + '</td>';
     }
     row += '</tr>';
     table_terms.append(row);
 }
});

const table_cumulative = $j('#gpa-cumulative');
fetch('/admin/queries/gpa_cumulative.json?sid=~(curstudid)')
.then(response => response.json())
.then(data => {
   console.log(data);
 table_cumulative.append('<tr>' +
     '<td style="background-color: #ffecb3">' + parseFloat(data[1]).toFixed(2) + '<span>Weighted GPA</span></td>' +
   '<td style="background-color: #ffecb3">' + parseFloat(data[2]).toFixed(2) + '<span>Simple GPA</span></td>' +
     '<td style="background-color: #bbdefb">' + uc.toFixed(2) + '<span>UC GPA</span></td>' +
     '<td style="background-color: #bbdefb">' + uc_capped.toFixed(2) + '<span>UC GPA (capped)</span></td>' +
     '<td style="background-color: #b3e5fc">' + calgrant.toFixed(2) + '<span>Cal Grant GPA</span></td>' +
   '<td>' + data[3] + '<span>Total Credit Hours</span></td>' +
     '</tr>');
});

tests = {};
let prevTestName = '';
let prevTestNum = 0;
let test = '';
testData.push(['','','','','']); // empty test
testData.forEach(row => {
  let test_name = row[0];
  let subtest_name = row[1];
  let date_taken = row[2];
  let test_num = row[3];
  let score = row[4];
  
  if (test_name != prevTestName || test_num != prevTestNum) {
    // We have a new test
    if (test.length > 0) {
      // Store prev test
      test += '</table>';
      
      if (prevTestName in tests) {
        tests[prevTestName].push(test);
      } else {
        tests[prevTestName] = [test];
      }
      
    }
    test = '<table style="min-width: 0; width: 100%;">';
    test += '<tr>';
    let formattedDate = '';
    try {
      //formattedDate = new Date(date_taken).toLocaleDateString('en-US', {year: 'numeric', month: 'numeric', day: 'numeric'});
      formattedDate = dayjs(date_taken).format('M/D/YY');
    } catch (e) {
      formattedDate = date_taken;
    }
    test += '<td>' + formattedDate + '</td>';
    test += '<td>' + subtest_name + '</td>';
    test += '<td>' + score + '</td>';
    test += '</tr>';

}

  } else {
    // Append to existing test
    test += '<tr>';
    let formattedDate = '';
    try {
      //formattedDate = new Date(date_taken).toLocaleDateString('en-US', {year: 'numeric', month: 'numeric', day: 'numeric'});
      formattedDate = dayjs(date_taken).format('M/D/YY');
    } catch (e) {
      formattedDate = date_taken;
    }
    test += '<td>' + formattedDate + '</td>';
    test += '<td>' + subtest_name + '</td>';
    test += '<td>' + score + '</td>';
    test += '</tr>';
  }
  prevTestName = test_name;
  prevTestNum = test_num;
});
console.log(tests);

// Find max length
let maxLength = 0;
for (const key in tests) {
  if (tests[key].length > maxLength)
    maxLength = tests[key].length;
}

// Add the tests
for (let i = 0; i < maxLength; i++) {
  let row = '<tr>';
  ['hspt', 'psat', 'sat', 'act'].forEach(x => {
    if (x in tests && i < tests[x].length) {
      row += '<td style="padding-left: 0; overflow: hidden;">';
      row += tests[x][i];
      row += '</td>';
    } else {
      // Empty col in this row
      row += '<td></td>';
    }
  })
  row += '</tr>';
  $j('#test-results').append(row);
}


</script>

Firefox input range does not work, gives “TypeError: rangeNode is null”

I am creating a webpage with a slider, and it works on other browsers on mobile and desktop. But on firefox, the slider does not work no matter what.

Pretty sure this is a problem with firefox itself, because the error message says that the error is in content.js:461:9. No idea how to fix it.

The slider looks like this,

<input type="range" min="1000" max="20000" value="6000" class="slider" id="myslider">

and the code commanding it looks like this

var slider = document.getElementById("myslider");
slider.oninput = function() {
    value = this.value;
    console.log('working')
}

The rangeNode error is a part of the huge content.js. The error is specifically this function, in the first rangeNode.data variable.

if (rangeNode.data && rangeOffset === rangeNode.data.length) {
    rangeNode = findNextTextNode(rangeNode.parentNode, rangeNode);
    rangeOffset = 0;
}

Is there a way to implement the input range on firefox?

Angular Interactive SVG map with external api call errors

I am creating an interactive SVG map of the world that when hovered over specific country, that specific country info populates in an area to the side.

I’m attempting to look at the info needed to call in the inspector>console log but I’m receiving a few errors that I don’t know how to fix. I’ve been trying to fix these errors for 2 days. Can someone please help?

Thanks!

I tried creating a proxy configuration with a new proxy.conf.json file but this just threw more errors. I’m new to working with JSON and API’s. Any help is appreciated.

Changing Image Based on What Image is Shown

I have three images-one shown, the other two with display:none.

I’d like, when I press the button, for the script to check which image is currently being displayed and switch to the next image accordingly.

The buttons seem to call to the .js file properly, because the browser console returns the final else log.

HTML

<div id="visit-us-parking-and-directions-container" class="section-container">
            <div id="visit-us-parking-and-directions-content" class="section-content">
                <h2>Parking and Directions</h2>
                <div id="parking-directions-images-container">
                    <img id="stc-parking-map" class="peirce-directions-image" src="images/stc-parking-map.png" alt="">
                    <img id="stc-first-floor" class="peirce-directions-image" src="images/stc-first-floor.png" alt="">
                    <img id="stc-second-floor" class="peirce-directions-image" src="images/stc-second-floor.png" alt="">
                    <div id="directions-image-number-indicator-container">
                        <div id="directions-image1-indicator" class="directions-image-number-indicator"></div>
                        <div id="directions-image2-indicator" class="directions-image-number-indicator"></div>
                        <div id="directions-image3-indicator" class="directions-image-number-indicator"></div>
                    </div>
                    <div id="directions-image-change-button-container">
                        <button id="directions-left-image-button" class="directions-image-change-button" onClick="leftImage()">&larr;</button>
                        <button id="directions-right-image-button" class="directions-image-change-button" onClick="rightImage()">&rarr;</button>
                    </div>
                </div>
            </div>
        </div>

CSS (There are some properties that belong to a class, so you’ll see things like display:flex missing from containers)

#visit-us-parking-and-directions-content{
        justify-content:flex-end;
    }
    
    .peirce-directions-image{
        width:100%;
    }
    
    #stc-parking-map{
        display:flex;
    }
    
    #stc-first-floor{
        display:none;
    }
    
    #stc-second-floor{
        display:none;
    }
    
    #directions-image-change-button-container,#directions-image-number-indicator-container{
        display:flex;
        flex-direction:row;
        justify-content:center;
        width:100%;
    }
    
    .directions-image-number-indicator{
        height:15px;
        width:33.33%;
        border-right:solid;
        border-color:rgba(224,224,219,1.00);
        background-color:rgba(0,0,0,0.92);
    }
    
    .directions-image-number-indicator:first-child{
        border-left:solid;
        border-color:rgba(224,224,219,1.00);
    }
    
    #directions-image1-indicator{
        background-color:rgba(37,53,81,1.00);
    }
    
    .directions-image-change-button{
        padding:38px 0 30px 0;
        width:50%;
        height:100%;
    }

Javascript

function rightImage() {
    var image1 = document.getElementById("stc-parking-map");
    var image2 = document.getElementById("stc-first-floor");
    var image3 = document.getElementById("stc-second-floor");
    var image1Indicator = document.getElementById("directions-image1-indicator");
    var image2Indicator = document.getElementById("directions-image2-indicator");
    var image3Indicator = document.getElementById("directions-image3-indicator");
    if (image1.style.display === "flex") {
        image1.style.display = "none";
        image2.style.display = "flex";
        image1Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image2Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    } else if (image2.style.display === "flex"){
        image2.style.display = "none";
        image3.style.display = "flex";
        image2Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image3Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    } else if (image3.style.display === "flex"){
        image3.style.display = "none";
        image1.style.display = "flex";
        image3Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image1Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    } else {
        console.log("Everything Failed?");
    }
}

function leftImage() {
    const image1 = document.getElementById("stc-parking-map");
    const image2 = document.getElementById("stc-first-floor");
    const image3 = document.getElementById("stc-second-floor");
    const image1Indicator = document.getElementById("directions-image1-indicator");
    const image2Indicator = document.getElementById("directions-image2-indicator");
    const image3Indicator = document.getElementById("directions-image3-indicator");
    if (image1.style.display === "block") {
        image1.style.display = "none";
        image3.style.display = "block";
        image1Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image3Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    } else if (image3.style.display === "block"){
        image3.style.display = "none";
        image2.style.display = "block";
        image3Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image2Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    } else if (image2.style.display === "block"){
        image2.style.display = "none";
        image1.style.display = "block";
        image2Indicator.style.backgroundColor = "rgba(0,0,0,0.92)";
        image1Indicator.style.backgroundColor = "rgba(37,53,81,1.00)";
    }
}

I’ve tried block and flex for the image display values. I put logs inside of the ifs at one point to see if it passed the if but failed to change the style-it did not pass the ifs, ever. I’ve tried both const and var for getting the elements.

How to draw a line with rounded edge in D3?

I got at task that requires an X & check mark in D3.

enter image description here

I tried to add an svg to the existing chart, but it does scale well since the svg keeps its dimension.

So, I tried it another way to directly draw two lines in the chart at the desired position. However, the line doesn’t have round edge.

enter image description here

Any idea on how to create them in D3? Thanks,

Is it possible to have the first and last swiper-button-prev/next buttons point to another html file?

Is it possible to change the functionality of the swiper-button-prev/next BUTTONS in Swiper JS?

The default functionality of the swiper-button-prev/next BUTTONS are to be disabled if you are the first image in a Swiper Thumbs Gallery or also be disabled if you are on the last slide in the gallery. Is it possible to change or replace this button with another that points you to a new html file?

enter image description here

Here is an example of one of the html files I generate with a script.

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

<head>
    <meta charset="utf-8" />
    <title>Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

    <!-- Swiper JS Stylesheet -->
    <link rel="stylesheet" href="../template/swiper/swiper-bundle.min.css" />

    <!-- Tigercat Stylesheet -->
    <link rel="stylesheet" href="../template/css/style.css" />
</head>

<body>
    <div class="wrapper">
        <div class="logo" onclick="window.location.href = 'Example_WI.html';" style="background-image: url('.svg');">
        </div>
        <div class="index" onclick="window.location.href = 'Index.html';" style="background-image: url('.svg');"></div>

        <!-- Swiper -->
        <div class="swiper mySlider">
            <div class="swiper-wrapper">
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-000.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-001.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-002.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-003.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-004.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-005.svg"></object>
                </div>
                <div class="swiper-slide lazy">
                    <object type="image/svg+xml" data="000-006.svg"></object>
                </div>
            </div>
            <!-- Navigation -->
            <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div>

            <!-- Pagination -->
            <div class="swiper-pagination"></div>
        </div>

        <!-- Swiper Thumbs -->
        <div thumbslider="" class="swiper myThumbs">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-000.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-001.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-002.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-003.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-004.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-005.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
                <div class="swiper-slide">
                    <img class="lazy" data-src="000-006.svg" />
                    <div class="swiper-lazy-preloader"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- Initialize Lazy Sizes -->
    <script type="text/javascript" src="../template/vanilla-lazyload/dist/lazyload.min.js"></script>

    <!-- Initialize Swiper JS -->
    <script type="text/javascript" src="../template/swiper/swiper-bundle.min.js"></script>

    <!-- Initialize Swiper -->
    <script type="text/javascript" src="../template/js/script.js"></script>

</body>

</html>

Instead of placing

<!-- Navigation -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>

inside

<div class="swiper mySlider"> or <div class="swiper-wrapper">

I tried placing the Navigation buttons inside each

 <div class="swiper-slide lazy">

I felt this was duplication but was hoping that I could use the

onclick="window.location.href

on the last <div to point the button at the desired html file.

//Initialize Swiper
var swiperThumbs = new Swiper(".myThumbs", {
    slidesPerView: 1,
    spaceBetween: 6,
    breakpoints: {
        "@0.00": {
            slidesPerView: 4,
        },
        "@.75": {
            slidesPerView: 6,
        },
        "@1.00": {
            slidesPerView: 8,
        },
        "@1.50": {
            slidesPerView: 10,
        },
    },
    centeredSlides: true,
    loop: false,
    slideToClickedSlide: true,
});
var swiperSlider = new Swiper(".mySlider", {
    slidesPerView: 1,
    centeredSlides: true,
    speed: 500,
    effect: 'fade',
    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
    },
    keyboard: {
        enabled: true,
    },
    pagination: {
        el: ".swiper-pagination",
        type: "progressbar"
    },
});

//Initialize Vanilla Lazy-Load
var lazyLoadInstance = new LazyLoad({
    // Your custom settings go here
});

swiperThumbs.controller.control = swiperSlider;
swiperSlider.controller.control = swiperThumbs;

var thumbsHeight = document.querySelector('.myThumbs').offsetHeight; //get the height of the thumbs div
document.querySelector('.mySlider').style.height = 100 - thumbsHeight; //set the height of the slider container

Node Server gives Status 500

My file, Database.py fetches information like User Id, Name, and Class from my Schools database website.

I used the following code to connect my node server with the python file in the Database directory:

// Execute the Python script in the background
const pythonScriptPath = path.join(__dirname, 'Database', 'Database.py');
const pythonProcess = spawn('python3', [pythonScriptPath], { stdio: 'inherit' });

pythonProcess.on('error', (err) => {
    console.error('Failed to start Python process:', err);
});

pythonProcess.on('exit', (code, signal) => {
    if (code === 0) {
        console.log('Python script executed successfully');
    } else {
        console.error(`Python script exited with code ${code} and signal ${signal}`);
    }
});

console.log('Python script execution initiated');

and I keep getting Status Code: 500 for each record fetched.

Running the code give Status Code: 500

computer is always winning, how do i fix it?

i made a ping pong game and I had a problem with the ball glitching out after a certain amount of hits, but @Keyboard Corporation fixed it by limiting the ball’s speed. The speed increasing was supposed to make the ball faster than the computer. But know since the speed is limited the computer will always bounce it back. How do I fix this?

P.S. I don’t want to make the computer level less, because than it is too easy

i have a html file and Javascript file heres the code for both:

html:

!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Pong Game JavaScript</title>

    <style>

        body{

            background-color: dimgray;

        }

        #pong{

            border: 2px solid #FFF;

            position: absolute;

            margin :auto;

            top:0;

            right:0;

            left:0;

            bottom:0;

        }

    </style>

</head>

<body>
        <audio id="background-music-for-video-short-blog-era-of-cyborgs-54-second-199951.mp3" loop>
 
  <source src="background-music-for-video-short-blog-era-of-cyborgs-54-second-199951.mp3" type="audio/mp3">
  Your browser does not support the audio element.
</audio>

<p>Click the buttons to play or pause the audio.</p>

<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button> 

<script>
var x = document.getElementById("background-music-for-video-short-blog-era-of-cyborgs-54-second-199951.mp3"); 

function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 
</script>

   <canvas id="pong" width="600" height="400"></canvas>

   <script src="pong.js"></script>
        
</body>

</html>

Javascript:

// select canvas element

const canvas = document.getElementById("pong");

// getContext of canvas = methods and properties to draw and do a lot of thing to the canvas

const ctx = canvas.getContext('2d');

// load sounds

let hit = new Audio();

let wall = new Audio();

let userScore = new Audio();

let comScore = new Audio();

hit.src = "sounds/hit.mp3";

wall.src = "sounds/wall.mp3";

comScore.src = "sounds/comScore.mp3";

userScore.src = "sounds/userScore.mp3";

// Ball object

const ball = {

    x : canvas.width/2,

    y : canvas.height/2,

    radius : 10,

    velocityX : 5,

    velocityY : 5,

    speed : 7,

    color : "WHITE"

}

// User Paddle

const user = {

    x : 0, // left side of canvas

    y : (canvas.height - 100)/2, // -100 the height of paddle

    width : 10,

    height : 100,

    score : 0,

    color : "WHITE"

}

// COM Paddle

const com = {

    x : canvas.width - 10, // - width of paddle

    y : (canvas.height - 100)/2, // -100 the height of paddle

    width : 10,

    height : 100,

    score : 0,

    color : "WHITE"

}

// NET

const net = {

    x : (canvas.width - 2)/2,

    y : 0,

    height : 10,

    width : 2,

    color : "WHITE"

}

// draw a rectangle, will be used to draw paddles

function drawRect(x, y, w, h, color){

    ctx.fillStyle = color;

    ctx.fillRect(x, y, w, h);

}

// draw circle, will be used to draw the ball

function drawArc(x, y, r, color){

    ctx.fillStyle = color;

    ctx.beginPath();

    ctx.arc(x,y,r,0,Math.PI*2,true);

    ctx.closePath();

    ctx.fill();

}

// listening to the mouse

canvas.addEventListener("mousemove", getMousePos);

function getMousePos(evt){

    let rect = canvas.getBoundingClientRect();

  

    user.y = evt.clientY - rect.top - user.height/2;

}

// when COM or USER scores, we reset the ball

function resetBall(){

    ball.x = canvas.width/2;

    ball.y = canvas.height/2;

    ball.velocityX = -ball.velocityX;

    ball.speed = 7;

}

// draw the net

function drawNet(){

    for(let i = 0; i <= canvas.height; i+=15){

        drawRect(net.x, net.y + i, net.width, net.height, net.color);

    }

}

// draw text

function drawText(text,x,y){

    ctx.fillStyle = "#FFF";

    ctx.font = "75px fantasy";

    ctx.fillText(text, x, y);

}

// collision detection

function collision(b,p){

    p.top = p.y;

    p.bottom = p.y + p.height;

    p.left = p.x;

    p.right = p.x + p.width;

  

    b.top = b.y - b.radius;

    b.bottom = b.y + b.radius;

    b.left = b.x - b.radius;

    b.right = b.x + b.radius;

  

    return p.left < b.right && p.top < b.bottom && p.right > b.left && p.bottom > b.top;

}

// update function, the function that does all calculations

function update(){

  

    // change the score of players, if the ball goes to the left "ball.x<0" computer win, else if "ball.x > canvas.width" the user win

    if( ball.x - ball.radius < 0 ){

        com.score++;

        comScore.play();

        resetBall();

    }else if( ball.x + ball.radius > canvas.width){

        user.score++;

        userScore.play();

        resetBall();

    }

  

    // the ball has a velocity

    ball.x += ball.velocityX;

    ball.y += ball.velocityY;

  

    // computer plays for itself, and we must be able to beat it

    // simple AI
    let computerLevel = 0.1;
    com.y += (ball.y - (com.y + com.height/2)) * computerLevel;

  

    // when the ball collides with bottom and top walls we inverse the y velocity.

    if(ball.y - ball.radius < 0 || ball.y + ball.radius > canvas.height){

        ball.velocityY = -ball.velocityY;

        wall.play();

    }

  

    // we check if the paddle hit the user or the com paddle

    let player = (ball.x + ball.radius < canvas.width/2) ? user : com;

  

    // if the ball hits a paddle

    if(collision(ball,player)){

        // play sound

        hit.play();

        // we check where the ball hits the paddle

        let collidePoint = (ball.y - (player.y + player.height/2));

        // normalize the value of collidePoint, we need to get numbers between -1 and 1.

        // -player.height/2 < collide Point < player.height/2

        collidePoint = collidePoint / (player.height/2);

      

        // when the ball hits the top of a paddle we want the ball, to take a -45degees angle

        // when the ball hits the center of the paddle we want the ball to take a 0degrees angle

        // when the ball hits the bottom of the paddle we want the ball to take a 45degrees

        // Math.PI/4 = 45degrees

        let angleRad = (Math.PI/4) * collidePoint;

      

        // change the X and Y velocity direction

        let direction = (ball.x + ball.radius < canvas.width/2) ? 1 : -1;

        ball.velocityX = direction * ball.speed * Math.cos(angleRad);

        ball.velocityY = ball.speed * Math.sin(angleRad);

      

        // speed up the ball everytime a paddle hits it.
        if(ball.velocityX > 0) {
            ball.x = player.x + player.width + ball.radius; // Adjust for right paddle
        } else {
            ball.x = player.x - ball.radius; // Adjust for left paddle
        }
       
        
        // speed up the ball everytime a paddle hits it.
        // ball.speed += 0.1;
        ball.speed = Math.min(ball.speed + 0.1, 10);
    }

}

// render function, the function that does al the drawing

function render(){

  

    // clear the canvas

    drawRect(0, 0, canvas.width, canvas.height, "#000");

  

    // draw the user score to the left

    drawText(user.score,canvas.width/4,canvas.height/5);

  

    // draw the COM score to the right

    drawText(com.score,3*canvas.width/4,canvas.height/5);

  

    // draw the net

    drawNet();

  

    // draw the user's paddle

    drawRect(user.x, user.y, user.width, user.height, user.color);

  

    // draw the COM's paddle

    drawRect(com.x, com.y, com.width, com.height, com.color);

  

    // draw the ball

    drawArc(ball.x, ball.y, ball.radius, ball.color);

}

function game(){

    update();

    render();

}

// number of frames per second

let framePerSecond = 50;

//call the game function 50 times every 1 Sec

let loop = setInterval(game,1000/framePerSecond);

It is good practice to use the setState callback to ensure that the state is updated

I have a situation where I am fetching a list from the backend. For each item in the list, I need to display a dropdown, which also needs to be fetched from the backend. I then need to check if the item is in the dropdown and select it. Additionally, when typing, I will display the typed value, and if it’s in the dropdown, I will show it as selected (which is why I also have the indexInSearchResults)

handleSearch(term, index, chooseGroup) {
apiCall('GET', null, `${SEARCH_URL}keyword=${term}&isActive=true`)
    .then(({ data }) => {
        this.setState(prevState => {
            const homeGroups = [...prevState.homeGroups];
            homeGroups[index].searchResults = data;

            if (chooseGroup) {
                homeGroups[index].indexInSearchResults = data.findIndex(result => result.name === homeGroups[index].searchTerm); // Here I am 
            }
            return { homeGroups };
        });
    })
    .catch(() => {
        this.setState(prevState => {
            const homeGroups = [...prevState.homeGroups];
            homeGroups[index].searchResults = [];
            homeGroups[index].indexInSearchResults = -1; // Set to -1 if no data is fetched
            return { homeGroups };
        });
    });

}

For example, in the case of handleInputChange, I change the value in the state, then make an API call to get the dropdown data. To ensure that the state is updated, I am using the setState callback function.

handleInputChange(name, index) {
this.setState(prevState => {
    const homeGroups = [...prevState.homeGroups];
    homeGroups[index].searchTerm = name;
    homeGroups[index].indexInSearchResults = -1; // Set to -1 when input changes
    return { homeGroups, isTouched: true };
}, () => {
    this.debouncedHandleSearch(name, index);
});

}

Similarly, for handleRateAdd, I create a new homeGroup object and add it to the state, then trigger a search with an empty string.

handleRateAdd() {
const newHomeGroup = {
    name: "",
    startDate: "",
    endDate: "",
    localID: uniqueID(),
    searchTerm: "",
    isSearchTermEmpty: false,
    indexInSearchResults: -1,
    searchResults: [],
    autoFocus: true
};

this.setState(prevState => ({
    homeGroups: [...prevState.homeGroups, newHomeGroup],
    isTouched: true,
}), () => {
    this.handleSearch("", this.state.homeGroups.length - 1, false);
});

}

And for handleBlur, I set the disabled state of the save button based on the search term and the availability of results.

handleBlur(index) {
const saveButton = document.getElementsByClassName('save-button')[0];

if (this.state.homeGroups[index].searchTerm === "") {
    const newHomeGroup = {
        name: "",
        startDate: "",
        endDate: "",
        localID: uniqueID(),
        searchTerm: "",
        searchResults: this.state.homeGroups[index].searchResults,
        isSearchTermEmpty: true,
        indexInSearchResults: -1,
    };
    this.setState(prevState => {
        const homeGroups = [...prevState.homeGroups];
        homeGroups[index] = newHomeGroup;
        return { homeGroups };
    });
    saveButton.disabled = true;
} else if (this.state.homeGroups[index].searchResults.length === 0) {
    this.setState(prevState => {
        const homeGroups = [...prevState.homeGroups];
        homeGroups[index].searchTerm = homeGroups[index].name;
        return { homeGroups };
    }, () => {
        this.handleSearch("", index, true);
    });
} else {
    this.setState(prevState => {
        const homeGroups = [...prevState.homeGroups];
        homeGroups[index].isSearchTermEmpty = false;
        return { homeGroups };
    });
    saveButton.disabled = false;
}
this.setState(prevState => {
    const isAnyHomeGroupEmpty = prevState.homeGroups.some(homeGroup => homeGroup.isSearchTermEmpty);
    console.log(prevState.homeGroups, "---test");
    saveButton.disabled = isAnyHomeGroupEmpty;
});

}

Are these code snippets clear, readable, and well-written, or do you think there’s room for improvement? It is good practice to use the setState callback to ensure that the state is updated before performing any subsequent actions, especially when relying on the updated state immediately after setting it. And additionally, I’m not using componentdidUpdate because I should pass arguments for my function

Looping Range Invalid array

In this challenge, you will build a function that creates an array for a given start, end, and step parameter.

  • The function takes three integer parameters: start, end, and step.
  • The function should return an array of numbers from start to end, counting by step.

The function checks for incorrect parameters by ensuring that;

  • start, end, or step are defined
  • start is not greater than end
  • step is greater than zero
    If any of these parameters are not met, the function should return an empty array [].

My code:

function range (start, end, step) {
  const result = [];
  for (let i = start; i <= end; i += step) {
    result.push(i);
  }
  return result;
}

console.log(range(0, 10, 2));

RangeError: Invalid array length

How can I find the key in object without resorting to a large number of cycles?

For example, there is an object with fields:

let Data: object = {
    one: "one",
    two: {
        home: "home",
        tree: "tree",
        gender: {
            m: "m",
            w: "w",
        },
    },
    thee: "thee",
    four: {
        flover: "rose"
    },
    five: "five",
    ....
}

How do I get the “w” and “flower” values with minimal effort?

I did this with a bunch of reversion and parsing. I’m even ashamed of it. Moreover, this affects performance quite strongly, as far as I am concerned.

Cesium Resource Proxy getUrl with AWS SDK v3 presigned url

We are using the Cesium Resource Proxy class to provide a presigned url from s3 for each of our resources. The getUrl method must return a string and is synchronous. When using the AWS SDK v2, this works because getPresignedUrl returns a string. How can I do the same thing using the entirely async AWS SDK v3?

Upload file issue by index of files object

I am using Vuejs to create an upload form.

Issue is that when I upload with key of object, backend server receives empty request:
like axios.postForm(app_url() + 'api/upload', { files: e.target.files[key] }, api_config())

But when I upload with following expression (Whole files together) It works correctly:
like axios.postForm(app_url() + 'api/upload', { files: e.target.files }, api_config())

What is reason of this problem? and how can I send files separate and simultaneous to server?

Here is then code:

<script setup>
import uploadIcon from '../assets/images/direct-inbox.png';
import axios from 'axios';
import app_url from '../customJavascript/app_url';
import api_config from '../customJavascript/api_config';

const changeFile = (e) => {

  const all = [];

  for (const key in e.target.files) {

    if (typeof e.target.files[key] == 'object') {
      all.push(axios.postForm(app_url() + 'api/upload', { files: e.target.files }, api_config()));
    }

  }

  axios.all(all)
    .then(axios.spread((data1, data2) => {
      console.log('data1', data1, 'data2', data2)
    }));

}
</script>

<template>
  <div class="main-card">
    <p class="main-card-title">upload file</p>

    <div class="mt-6 flex justify-center">


      <div class="upload-card clickable focus:shadow-none">

        <div class="relative text-center h-full flex flex-col justify-center align-center">
          <input type="file" @change="changeFile"
            class="rounded-2xl cursor-pointer absolute right-0 top-0 w-full h-full opacity-0" multiple />
        </div>

      </div>

    </div>
  </div>
</template>


<style>
.upload-card {
  @apply w-11/12 lg:w-5/12 h-60 lg:h-60 rounded-2xl border-2 border-lightblue bg-white hover:shadow-lg;
}
.upload-card:hover button {
  @apply bg-primary;
}
</style>

I put code out side of loop and send request with just a static index variable, I expected maybe loop caused this issue but It wasn’t.

Force Tab Event on WebView2

i am trying to automatize a process in one of our sites, i am using c# into an .net project with the WebView2 component. I was checking for a method or way to force the webview to do a tab. It’s like when I do a focus or a click by code in javascript, it doesn’t work. So i was trying to simulate the tab keyboard event.

I tried things like:

await webView.ExecuteScriptAsync($”document.querySelectorAll(‘.myclass input’)[0].focus()”);
await webView.ExecuteScriptAsync($”document.activeElement.dispatchEvent(new KeyboardEvent(‘keypress’,” + “{ key: ‘Tab’}))”);

Can you help me?