What is the most optimal way to create an if statement, or logic in general, in Nearley?

Using the Nearley module for NodeJS I want to create an if statement that looks like this:

if condition: /* code */ endif;

And so in Nearley, I wrote:

# grammar.ne
@builtin "whitespace.ne"

# Condition -> etc etc

IfStatement -> "if" __ Condition __ ":" (_ Logic:*):? __ "endif;"

I don’t know what to define Logic as. I want it to be used to describe any instance of variable declaration, an if statement (so probably using recursion, but I don’t know how), or calling a function.

Note that my project is not intended to be primarily a scripting language. I’m drifting it towards the style of Infocom’s ZIL. Logic as mentioned above can only be used in a function, so it would look like this:

(FunctionName OptionalParameter1 OptionalParameter2)
<Logic>
[Conclude]

/* Example:
 * (AddDigits x y z)
 * <set a = x + y + z;
 * return a;>
 * [Conclude]
 *
 * Functions begin with a header including its Name and Parameters (if any);
 * They include any code encased with <>;
 * They end with the [Conclude] tag.
 */
ConcludeTag -> "[Conclude]"
FunctionDeclare -> FunctionHeader "n" FunctionBody ConcludeTag
FunctionHeader -> "(" [a-zA-Z0-9_]:* ((__ [a-zA-Z0-9_]:*):*):? ")" 
FunctionBody -> # Logic needs to be defined first!!

My intial idea was to use recursion. However I am unsure if this is a good or even valid method. I wrote this:

# Define integers, strings and booleans as valid Value types
Value -> [0-9]:* 
       | """ . """
       | ("true" | "false")

# Define an extended Value type as anything listed above PLUS function calling e.g. myfunc()
ExtendedValue -> Value
               | [a-zA-Z0-9_]:* _ "(" (_ (Value | (Value "," _):* Value) _):? ")"

# I stopped here because I was stuck. There might be more to add but I do not know yet
Logic -> IfStatement 
       | [a-zA-Z0-9_]:* _ "=" _ ExtendedValue _ ";"

getting length of array within separate method in class JavaScript

My problem is that I get an error when I try to get the length of the sprites array in the for loop of my move function but not in the redraw function. It appears to properly draw the square using redraw but doesn’t like it when I use the move function. I’m kinda new to classes in JS(and posting on Stack Overflow) so I was hoping some of you could help me with this

class Canvas {
  init() {
    this.canvas = document.getElementById("canvas");
    this.ctx = canvas.getContext("2d");
    this.sprites = []; //array hold objects with each sprites x, y, and r
    this.active = false;
  }
  
  ball(r, clickMult, speed) {
    this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
    this.sprites.push({x: 0, y: 0, r: r, xVel: speed, yVel: speed});
    this.#redraw();
    if (!this.active) {
      setInterval(this.#move, 200);
      this.active = true;
    }
  }

  #redraw() {
    for (let i = 0; i < this.sprites.length; i++) {
      this.ctx.beginPath();
      this.ctx.fillRect(this.sprites[i].x, this.sprites[i].y, this.sprites[i].r, this.sprites[i].r);
      this.ctx.fill();
      this.ctx.closePath();
    }
  }

  #move() {
    for (let i = 0; i < this.sprites.length; i++) {
      this.sprites[i].x += this.sprites[i].xVel;
      this.sprites[i].y += this.sprites[i].yVel;
    }
    
    this.#checkCollision();
    this.#redraw();
  }

  #checkCollision() {
    for (let i = 0; i < this.sprites.length; i++) {
      if (this.sprites[i].x < 0) {
        this.sprites[i].x = 0;
        this.sprites[i].xVel *= -1;
      } else if (this.sprites[i].x + this.sprites[i].r > this.canvas.width) {
        this.sprites[i].x = this.canvas.width - this.sprites[i].r;
        this.sprites[i].xVel *= -1;
      }
  
      if (this.sprites[i].y < 0) {
        this.sprites[i].y = 0;
        this.sprites[i].yVel *= -1;
      } else if (this.sprites[i].y + this.sprites[i].r > this.canvas.width) {
        this.sprites[i].y = this.canvas.width - this.sprites[i].r;
        this.sprites[i].yVel *= -1;
      }
    }
  }
}

The result that continues popping up is that length is undefined but it does this in the move function but not the redraw function despite them appearing to be the same

Add “checked” to radio button on load with javascript

Based on Bootstrap 5’s dark mode switch javascript (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript) I’m trying to set a radio button to “checked” on page load, as well as when the colour mode is changed.

Using the following javascript:

    <script>
      (() => {
        'use strict'

        const getStoredTheme = () => localStorage.getItem('theme')
        const setStoredTheme = theme => localStorage.setItem('theme', theme)

        const getPreferredTheme = () => {
          const storedTheme = getStoredTheme()
          if (storedTheme) {
            return storedTheme
          }

          return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
        }

        const setTheme = theme => {
          if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.documentElement.setAttribute('data-bs-theme', 'dark')
          } else {
            document.documentElement.setAttribute('data-bs-theme', theme)
          }
        }

        setTheme(getPreferredTheme())

        const showActiveTheme = (theme, focus = false) => {
          const themeSwitcher = document.querySelector('#bd-theme')

          if (!themeSwitcher) {
            return
          }

          const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)

          document.querySelectorAll('[data-bs-theme-value]').forEach(element => {
            element.classList.remove('checked')
          })

          btnToActive.classList.add('checked')

          if (focus) {
            themeSwitcher.focus()
          }
        }

        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
          const storedTheme = getStoredTheme()
          if (storedTheme !== 'light' && storedTheme !== 'dark') {
            setTheme(getPreferredTheme())
          }
        })

        window.addEventListener('DOMContentLoaded', () => {
          showActiveTheme(getPreferredTheme())

          document.querySelectorAll('[data-bs-theme-value]')
            .forEach(toggle => {
              toggle.addEventListener('click', () => {
                const theme = toggle.getAttribute('data-bs-theme-value')
                setStoredTheme(theme)
                setTheme(theme)
                showActiveTheme(theme, true)
              })
            })
        })
      })()
    </script>

I’m trying to control the button group:

  <div class="btn-group" id="bd-theme" role="group">
    <input autocomplete="off" checked class="btn-check" data-bs-theme-value="light" id="btnradio1" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio1">
      Light
    </label>
    <input autocomplete="off" class="btn-check" data-bs-theme-value="dark" id="btnradio2" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio2">
      Dark
    </label>
    <input autocomplete="off" class="btn-check" data-bs-theme-value="auto" id="btnradio3" name="btnradio" type="radio">
    <label class="btn btn-outline-dark" for="btnradio3">
      Auto
    </label>
  </div>

By default, ‘Light’ mode is “checked”, but if a different ‘theme’ is already stored then that other radio button should be “checked” instead.

I think the code that needs changing in particular is:

        const showActiveTheme = (theme, focus = false) => {
          const themeSwitcher = document.querySelector('#bd-theme')

          if (!themeSwitcher) {
            return
          }

          const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)

          document.querySelectorAll('[data-bs-theme-value]').forEach(element => {
            element.classList.remove('checked')
          })

          btnToActive.classList.add('checked')

          if (focus) {
            themeSwitcher.focus()
          }
        }

How to move IFrame scrollbars from another IFrame

I recently ran into a problem where I have an Index page in which there are 3 IFrames.

1th IFrame : Views the photo (photo name)

2th IFrame : A simple list of all links (list name)

3th IFrame : Views the a big photo (pag name)

-Index.htm


<table border="0" align="center" height=100% width="100%" height=150  >
  <tr>
   <td valign="top" width=300 align=center bgcolor=#aaaaaa> 
    <iframe frameBorder="1" width=300 height=300 id="photo" name="photo" src=""></iframe>
    <iframe frameBorder="0" width=300 name="list" height=300 src="list.htm"></iframe> <p>
  </td>
  <td valign="top" colspan="2">
    <iframe frameBorder="0" id="pag" name="pag" src="pag.htm" width=100% height=100%>
    </iframe>
  </td>
 </tr>
</table>

-List.htm

<script type="text/javascript">

function movePic() {

//  works but only on current window 
//  window.scrollTo(0,170);
// not even that works
// window.parent.document.getElementById("pag").focus();
      }

</script>

<body topmargin=0 bgcolor="#ffffff" link="#0000FF" text="#000000" alink="#FF0000" vlink="#FF00FF">
<a href="pic/aa27.jpg" target="photo" onclick="movePic()">Requested Point</a> 

-Pag.htm

A big photo which needs to be moved throughout scrollbars to a certain point.

I tried in many ways, but I can’t from the 2th IFrame (list name) pass its focus to the 3th IFrame (map name)

Is there a way to highlight a specific set of words in TinyMCE editor?

I am using TinyMCE editor in my Angular project . I’m looking for a way to highlight words in TinyMCE editor if they are part of an array .

Example,

countries: string[] = ['india', 'england', 'argentina'];

If user types any of the item from above array , I want to highlight them in bold font . Let’s say user types the below line . Only the items that are part of the array are made bold .

Some countries are india , bangladesh , argentina and england .

Kindly let me know if there is a way to achieve this . Thanks in advance.

Here is the Stackblitz link

I need help making pokemon types show up when building a randomizer using a pokemon Api in Javascript

I’m still pretty new to programming and I’m building a random pokemon generator in javascript using a pokemon Api, I’m having trouble making the pokemon type show up in a fetch request because it is nestled in an array in the API.

I can fetch the name, pokemon id and base experience values just fine, because they are listed as their own individual values within the API, but types show up as [object Object] because they are listed in an array and I’m not quite sure how to retrieve them. Here is my code and a link the the API I’m using text

<body>
    
    <div id="name"></div>
    <div id="id"></div>
    <div id="type"></div>
    <div id="baseexperience"></div>

    <button class="myButton">Catch 'em all</button>
    



    <script>
        const name = document.getElementById('name')
        const id = document.getElementById('id') 
        const type = document.getElementById('type') 
        const baseexperience = document.getElementById('baseexperience') 
        const button = document.querySelector('.myButton');

        button.addEventListener('click', (e) => {
            e.preventDefault()
            const randomPokemon = Math.ceil(Math.random() * 1017)
        fetch(`https://pokeapi.co/api/v2/pokemon/${randomPokemon}`)
            .then(response => response.json())
            .then(pokemon => {
                console.log(pokemon)
                name.innerHTML = pokemon['name']
                id.innerHTML = pokemon['id']
                type.innerHTML = pokemon['types']
                baseexperience.innerHTML = pokemon['base_experience']

            })  

        })

       
    </script>
</body>

Moving a local scoped variable to global scope so I can import it to another JS file

Im trying to convert an excel sheet into a json object in javascript and Im having problems retrieving the final data as it is scoped locally. I would like to take the variable labelled as “inputData” and export it to another JS file however in order to do that it has to be at the top level of a file, which I assume means it has to be global scope. I cant for the life of me figure out how to get it from its local scope though. Any help would be appreciated.

Take a look at the code:

let selectedFile;

document.getElementById('input').addEventListener('change', (event) => {
    selectedFile = event.target.files[0];
})
document.getElementById('button').addEventListener('click', () => {

    if (selectedFile) {
        let fileReader = new FileReader();
        fileReader.readAsBinaryString(selectedFile);
        fileReader.onload = (event) => {
            let data = event.target.result;
            let workbook = XLSX.read(data, { type: "binary" })
            let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets.Grid);
            let newData = rowObject.filter((item, index) => {
                return index === rowObject.findIndex((obj) => {
                    return JSON.stringify(item) === JSON.stringify(obj)
                })
            })

            newData.pop()

            inputData = JSON.stringify(newData, undefined, 4)
            console.log(inputData)
        }
    }
})

How to enable lazy load videos in owl carousel 2

I have a carousel powered by Owl carousel v2 with lazy load enabled , it is working for imgs
in JS :

owlLazyClass = "owl-lazy owlLazy";
        // image
        var mediaHtml = '<div class="oclzm-post-inner">' +
                        '   <div class="oclzm-img-holder">' +
                        '       <img class="oclzm-image ' + owlLazyClass + '" ' + srcClass + '="' + thumb_url + '" data-full-image="' + image_url + '"  alt="' + image_alt_text +'">' +
                        '   </div>' +
                        '</div>';

i tried to apply on videos like so :

mediaHtml = '<div class="oclzm-post-inner">' +
                            '   <div class="vid-holder">' +
                            '       <video class="video owl-lazy">' +
                            '           <source src="' + video_url + '#t=2" type="video/mp4">' + // show thumbnail at 2s
                            '           Your browser does not support the video tag.' +
                            '       </video>' +
                            '       <div class="video-icon"></div>' +
                            '   </div>' +
                            '</div>';

which didn’t work. Any ideas how to enable it for videos too?

Tailwind CSS: How do I stop child divs from going beyond the height of a parent div?

<div className='block justify-center flex flex-col h-screen py-8 px-48'>
    <div className='flex'>
        <Form />
    </div>
    <div className='flex-1'>
        <div className='shadow-md flex flex-col'>
            <div className='flex'>
                <div className='flex w-full py-2 px-2 bg-white border-0'>
                    <div className='flex-1'>
                        <Searchbar />
                    </div>
                    <div className='flex'>
                        <Button />
                    </div>
                </div>
            </div>
            <div className='overflow-auto flex-1'>
                <Table />
            </div>
        </div>
    </div>
</div>

Here is what my React page component looks like (using Form, Searchbar, Button, Table as other components). My issue is that the Table element is exceeding the height of the parent block, and the overflow-auto is not triggering to keep it contained withing the block bounds.

After alot of research I stumbled into using flex and flex-1 to have items take up remaining space of the parent div. To my (limited) knowlege, I do not see how the flex, flex-1, flex-col setup I have here is not leading to the table being overflowed correctly, unless flex does not work the way I think it does. Unfortunately, other answers that tried to calculate the height of the remaining children seemed to hinge o nthe fact that the other children have a static size and are not flexed, like mine are.

Honestly, I am pretty new to React and javascript in general, so any help is appreciated. Thanks!

This is what it currently looks like, and this is what I want it to look like. The table, form, and searchbar/button combo all behave and look exactly how I want them too, with the exception that when there is too much table data, the overflow does not work, as I described

Javascript: date.setDate is broken for a very specific date

I was looping dates in a while loop and noticed that one of my dates did not increment properly (making the loop go over the same date twice)

More specifically: “2024-03-10”

I then tried to replicate this issue in the dev tools console (in chrome) using this function:

(() => {
    let d = new Date("2024-03-10")
    console.log("current day", d.toISOString())
    d.setDate(d.getDate() + 1)
    console.log("next day", d.toISOString())
})()

And the output I receive is:

current day 2024-03-10T00:00:00.000Z
next day 2024-03-10T23:00:00.000Z

As you can see, it only added 23h to the date so we are still in 2024-03-10.
Is anyone else able to reproduce this error? I get this problem in both NodeJS and Chrome Console…

Stop Vitest from attempting to build test files

I added Typescript to an older vue2/vite/JS for very narrow static type checking. I’ve noticed now that when I run vitest basically every test fails. I’m guessing this has something to do with the availability of tsc and/or a tsconfig added to the project.

  • tsconfig is configured to exclude any test files
  • vitest is configured NOT to perform type checking, also ignoreSourceErrors is true
  • the command I’m running is vitest

I’ve read through documentation on vitest, but I’m not finding a solution

https://vitest.dev/guide/testing-types.html

Trigger a Javascript function with Nodejs

I want to trigger a client side function Javascript, with Nodejs
I’m trying to get a response from the Nodejs to display data on my website

A program will send an API to my Nodejs Api example(htpp://localhost:3000/apiResponse) containing some data
I want to get the API data to my frontend

How can i do this, or is there another way to trigger a function o value when a API send to me?