Why are you allowed to omit arguments from a JavaScript function?

In JavaScript, how come you are able to pass no arguments to a function that “requires” arguments?

For example:

function printName(name) {
    if (name) console.log(name);
    else console.log("No name");
}

printName();

However, if you try the same thing in Python you get an error:

def foo(name):
    if name: print(name)
    else: print("No name")

foo()
TypeError: foo() missing 1 required positional argument: 'name'

Original exception was:
Traceback (most recent call last):
  File "random.py", line 5, in <module>
    foo()
TypeError: foo() missing 1 required positional argument: 'name'

I can tell this relates to the undefined keyword: if you console.log() nothing, it logs undefined.

Can somebody explain what is going on when it does this/how this is allowed to work in relation to other languages that don’t allow it, such as Python?

Javascript button open function [duplicate]

I want to open the function make_table() on click the button, but I don’t find how to do this, this is my code:

var x = document.querySelectorAll("a");
var myarray = []
var alllinks = []
for (var i = 0; i < x.length; i++) {
  var nametext = x[i].textContent;
  var cleantext = nametext.replace(/s+/g, ' ').trim();
  var cleanlink = x[i].href;
  alllinks.push([cleantext, cleanlink]);
};

function make_table() {
  var table = '<table><thead><th>Name</th><th>Links</th></thead><tbody>';
  for (var i = 0; i < myarray.length; i++) {
    table += '<tr><td>' + myarray[i][0] + '</td><td>' + myarray[i][1] + '</td></tr>';
  };

  var w = window.open("");
  w.document.write(table);
}
var button = document.createElement("Button");
button.innerHTML = "Links AP y EP";
button.style = "position:absolute;z-index: 1;top: 85px;right: 60px;"
document.body.appendChild(button);
button.addEventListener("click", function() {});

How to penetrate or cut holes through a 2D foreground

I’m currently making a 2D game in Javascript, but I want to the game to have different lighting levels, for example, if I were to create a day and night cycle. However, I want to be able to cut holes in the lighting/foreground, or do something so that I can make certain parts of the screen lit up, for example like a flashlight or candle. Note: I’m also using the P5.js library.

The most obvious idea that came to mind for going about in creating a foreground is just creating a rectangle with some opacity that covers the entire screen. This is good, but how am I supposed cut through this? Obviously, the code below won’t work because I’m just layering on another element, and the rectangle is still obstructed and not perfectly clear.

function setup() {
  noStroke();
  createCanvas(400, 400);
}

function draw() {
  background(255); //white
  
  fill(255, 0, 0);
  rect(200, 200, 25, 25); //Example object
  
  fill(150, 150, 150, 100); //Gray with opacity
  rect(0, 0, 400, 400); //Darkness covering entire screen, foreground
  
  fill(255, 255, 255, 100)
  ellipse(mouseX, mouseY, 50, 50); //object that is supposed to penetrate foreground.
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

How would I go about doing this? I want this to work not only with just a plain background and simple shapes, but with images as well. Is there a way to cut holes in shapes, or do I need to use something else, like a shader or mask?

Thanks.

How can I programmatically select the select menu?

I have a select

<v-select dense outlined :items="attributes" item-text="name" item-value="id" v-model="rule.attribute" :rules="form.rules.attribute" label="Attribute"></v-select>

where this.attributes =

[ { "id": 1, "name": "Style name", "alias": null, "attribute": "STYLE_NAME", "category_id": 1, "data_type_id": 3, "data_type_name": "String" }, { "id": 2, "name": "Country", "alias": null, "attribute": "COUNTRY_NAME", "category_id": 2, "data_type_id": 3, "data_type_name": "String" }, { "id": 3, "name": "Serial number", "alias": null, "attribute": "scanstring", "category_id": 3, "data_type_id": 3, "data_type_name": "String" }, { "id": 4, "name": "Brand Name", "alias": null, "attribute": "BRAND_NAME", "category_id": 1, "data_type_id": 3, "data_type_name": "String" }, { "id": 5, "name": "Account/Customer Name", "alias": null, "attribute": "CUSTOMER_NAME", "category_id": 1, "data_type_id": 3, "data_type_name": "String" }, { "id": 6, "name": "Product UPC", "alias": null, "attribute": "PRODUCT_UPC", "category_id": 1, "data_type_id": 3, "data_type_name": "String" }, { "id": 7, "name": "Label batch", "alias": null, "attribute": "LABEL_HEADER_ID", "category_id": 3, "data_type_id": 1, "data_type_name": "Number" }, { "id": 8, "name": "Current time", "alias": null, "attribute": "time(convert_tz(now(),'UTC','${PARAM}'))", "category_id": 4, "data_type_id": 5, "data_type_name": "Time" } ]

Then that lead my select to look like this

enter image description here

As you can see that it has a

v-model="rule.attribute"

and rule.attribute = Serial number, why is my select is not selected Serial number on page load. It just show this

enter image description here

I was hoping to see sth like this :

enter image description here

How to combine arrays and repeat first array’s elments as many times as the length of the second array?

The challenge is to build a table. So, the first array is like to the following:

[1001,235689,1002,235690,1003,235691]

The second array is like this:

[
[tecido,1,Crepe Georgette,,,,mt,0.9,11.9,10.71],
[tecido,2,Forro,,,,kg,0.5,7.916666666666667,3.9583333333333335],
[aviamento,5,Tag Láureen Instrução Lavagem,,,,und,1,0.5,0.5],
[aviamento,3,Entretela malha,,,,und,1,10,10]
]

How can I concatenate them to be like:

[
[1001,235689,tecido,1,Crepe Georgette,,,,mt,0.9,11.9,10.71],
[1001,235689,tecido,2,Forro,,,,kg,0.5,7.916666666666667,3.9583333333333335],
[1001,235689,aviamento,5,Tag Láureen Instrução Lavagem,,,,und,1,0.5,0.5],
[1001,235689,aviamento,3,Entretela malha,,,,und,1,10,10]
]

I’ve tried looping over the first array and get the second in, but I get lost repeating the first array’s elements as many times as the elements count in the second.

Appreciate any help.

JavaScript store procedure to render REGEXP_REPLACE(variable1::string, ‘@|T|Z|\(GMT-04:00\))’,’ ‘)) >= timestamp

I am trying to render the following line in the stored procedure written in javascript –

------Expected output------ 
select val1 from tableName where REGEXP_REPLACE(var1, '@|T|Z|\(GMT-04:00\))',' ')) >= date1

At present the code looks like this in the stored procedure –

----Actual code--------
SELECT val1 from tableName where REGEXP_REPLACE(var1,''@|T|Z|\\\\(GMT-04:00\\\\))'', '' '')) >= date1

The above code does result in the expected output, however I am trying to optimize this solution, and looking for cleaner way to achieve this final result. Any suggestions are appreciated. TIA.

React import multiple components from a folder

I am trying to import 2 components from the components folder. Both components’ class are export default .

However, I got an error message that I should use the curly braces in my import statement. However, both components above are not using named export so curly braces is not needed when importing them.

How can I make this work?

Main app

Login component

Problem with a node.js recursive function (with pupeeter) – var not defined

I made a program with pupeteer that retrieves the list of button ids and their names.

I want to loop through these buttons then click on them and retrieve the ids and names…

So I created a recursive function which, with a list as input, allows you to browse and click.

Here is my code:

  return Array.isArray(a) &&
    Array.isArray(b) &&
    a.length === b.length &&
    a.every((val, index) => val === b[index]);
}

async function parcourt(liste, previousListe, path, page) {
                    console.log(liste)

 for (const bouton of liste) {
    if(!arrayEquals(liste, previousListe)){
        const id = await page.evaluate(el => el.id, bouton);
        const titres = await bouton.$$('div[class^="Cell_title"]')
        const titre = await page.evaluate(el => el.innerText, titres[0]);
        var Newpath = path + "/" + titre
        console.log(Newpath + " : " + id)
        await bouton.click()
        var Newliste = await page.$$('div[id^="catalog-"]')
        parcourt(await NewListe,liste,await Newpath,page)
    }
    return 0
 }
}



const getData = async () => {
  // 1 - Créer une instance de navigateur
  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()

  // 2 - Naviguer jusqu'à l'URL cible
await page.goto("xxxxxxx")
const liste = await page.$$('div[id^="catalog-"]')
parcourt(liste, [], '',page)

}

// Appel de la fonction getData() et affichage des données
getData().then(value => {
  console.log(value)
})

How to create a self stabilizing variable

I am trying to model the water level of a bucket. The bucket has a max Limit of 1000 m^3. The inflow rate is 50 m^3/s. Randomly, a known but variable amount of water is taken out of bucket.

bucket with water level

I have to keep track of the current volume of water present in the bucket.

I have written the following program to solve the problem.

/**
 * An extended version of redux store, that constantly restores a numeric value
 * unitll the provided max value is reached.
 */

export function createStore(reducer, options) {
  const {
    maxLevel = 1000,
    restoreRate = 50, // per second
    restoreAction = "increment",
  } = options || {};

  let state = maxLevel;
  let isRestoring = false;

  const getState = () => state;

  const dispatch = (action) => {
    state = reducer(state, action);

    if (state < 1000 && !isRestoring) {
      restore();
    }
  };

  const restore = async () => {
    isRestoring = true;
    await wait(1000);
    isRestoring = false;
    dispatch({
      type: restoreAction,
      payload: Math.min(restoreRate, maxLevel - state),
    });
  };

  const wait = async (milliseconds) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, milliseconds);
    });
  };

  return {
    getState,
    dispatch,
  };
}

export function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return state + action.payload;
    case "decrement":
      return state - action.payload;
    default:
      return state;
  }
}

Looking for suggestions to improve the above mentioned solution and also alternate approaches to model this behaviour.

How to populate select element while iterating through javascript object [duplicate]

I want this inside select element for all languages using iteration through the languages object using javaScript.

const languages = {
    option1: 'English',
    option2: 'Hindi',
    option3: 'Tamil',
    option4: 'Kannada',
    option5: 'Malayalam',
}

<select>
   <option value="English">"English"</option>
</select>

I tried this but it is not working at all using JavaScript:

<select>
   for(const language in languages) {
      <option value=`${languages[language]}`>`${languages[language]}`</option>
   }
</select>

Thanks for the help !!

How to avoid re-initializing component when multiple linked routes use same component

I have a react-router-dom component that was all working fine in v5, and I have since upgraded to v6. In the below router structure, I have a single component that is accessed via different routes. This view has a playback feature that updates the URL when playback is stopped resulting in a foo/<fooId>/<time> url structure, and a means to link to something in the list with bar/<barId>. Both of these render the same component, that uses the params as need be and can handle both entry points.

The issue I’m seeing since moving to v6 is it will refresh if switching from foo/<fooId>/<time> to bar/<barId> or viceversa. Same happens if I click a link to bar/<barId> while on foo/<foodId>/time. It’s the same component, and simply updated the browser URL in the past (used to use history.pushState and now use navigate (from useNavigate), I tried adding a replace param, etc., but it still re-mounts the entire component.

How can I avoid this? I can only think to re-structure the pages, but there’s a bunch of bookmarks out there that will be very unhappy, haha.

      <Route
        path="/foo"
        element={<AuthedRoute authState={authState} element={<Bar />} />}
      >
        <Route
          path=":fooId"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
        <Route
          path=":fooId/:timestamp"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
      </Route>
      <Route path="/bar">
        <Route
          path=":barId"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
      </Route>

AuthRoute:

function AuthedRoute({ authState, element }) {
  const location = useLocation()
  const { isLoggedIn } = authState
  return isLoggedIn ? (
    element
  ) : (
    <Navigate
      to="/login"
      state={{
        from: location,
      }}
    />
  )
}

Similar structure to the example here

How do you find the 10 indexes of a javascript array that have the highest numeric values?

I am counting the frequency of numbers between 0 and 256 found in a sequence using a javascript array.

If I see the number 74 pop up I am storing it in the 74th index value (i.e. mysequence[74] = mysequence[74] + 1)

I can see the results tallied and its easy when scanning it visually to see that certain numbers (for example 65) has appeared much more often than others. I want to find the 10 numbers that appear most often.

I am concerned a simple sort will not retain the index value which is what I am using to track which number is associated with the counted frequency.

The only thought that comes to mind would be a brute force approach. Creating a function to look through all values one by one keeping the highest and ignoring all indexes that are part of an ignore list. Then running that function 10 times, each subsequent time passing the values of the indexes that have been assigned the top values.

Is there a way to get the numeric keys associated with the top 10 values without resorting to the approach above? (i.e. maybe converting my data to a different format and some fancy map sorting functions?)

Print name of variable as string without sending curly braces

I’ve made a function for my own convenience that displays a log of the variable name and what it equals. The only way I’ve found to do this while retaining its original variable name is to send it with the curly braces, but is there a way to leave that out on the function call, and instead have it somewhere inside the function? I’m asking this because I simply want to type clog(myObj) and not clog({myObj}).

clog({myObj})

function clog(obj)
{
    const varToString = Object.keys(obj)[0];
    console.log(varToString + " = " + obj[varToString])
}