Dynamic endpoint with express

I’m trying to generate a dynamic URL that will change everytime an endpoint is called
So I have this simple function in Node.js to create a dynamic url:

var path = crypto.createHash('md5').update(`${Date.now()}`).digest("hex");

function createNewPath(){
  path = crypto.createHash('md5').update(`${Date.now()}`).digest("hex");
}

and this simple code to receive the request:

app.use('/'+path, function(req,res){
  createNewPath();
  res.send("<h1>Welcome!<h1>");
});

The problem is that app.use does not reload the value in “path” so the initial url asigned stays the same, any ideas?

Been breaking my head and got nothing

Fixing Type incompatibility issues (TypeScript React)

I am receiving this build error:

Type '{ executionTime: number; schema: { [k: string]: { name: string; index: number; type: string; }; }; values: Document[][]; }' is not assignable to type 'DataGridData'.
Types of property 'schema' are incompatible.
Type '{ [k: string]: { name: string; index: number; type: string; }; }' is not assignable to type 'Schema'.
'string' index signatures are incompatible.
Type '{ name: string; index: number; type: string; }' is not assignable to type '{ name: string; index: number; type: SchemaDataType; }'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type 'SchemaDataType'.

It boils down to type ‘string’ not being compatible with explicitly defined type SchemaDataType. Here is that defined type:

export type SchemaDataType =
| 'DateTime'
| 'Decimal'
| 'Guid'
| 'Int32'
| 'String';

‘string’ is not being recognized as ‘String’.

function mapKeys() {
  const docKeys = Object.keys(items);
  const result = Object.fromEntries(
    docKeys.map((el, index) => {
      return [el, { name: el, index, type: el.constructor.name }];
    }),
  );
  return result;
}

This function I created transforms the json response in the DB to a palitable structure for a custom DataGrid that I am trying to implement. I attemted a fix by capitalizing the first letter of ‘type’ like so but this did not fix the issue:

function mapKeys() {
  const docKeys = Object.keys(items);
  const result = Object.fromEntries(
    docKeys.map((el, index) => {
      return [
        el,
        {
          name: el,
          index,
          type:
            el.constructor.name.charAt(0).toUpperCase() +
            el.constructor.name.slice(1),
        },
      ];
    }),
  );
  return result;
}

TypeError: json.push is not a function while addending json objects

I would like to store JSON in a textfile. Using:

let obj = {'column':empty,'ppas':ppa}; 
await myFunctions.addToStorage(obj);

async function addToStorage(obj) {
  const fs = require("fs");
  fs.readFile("storage.json", function (err, data) {
    var json = JSON.parse(data);
    json.push(obj);
    fs.writeFile("storage.json", JSON.stringify(json), function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });
  });
}

storage.json contains:

{"column":"0:lubbock:LW2-4$","ppas":[{"ppa":50000,"url":"/"},{"ppa":51724.137931034486,"url":"/lubbock"}]}

when I run the program I get:

  json.push(obj);
         ^
  TypeError: json.push is not a function
    at /home/....functions.js:5:10

I can see that, the problem is that the I’m trying to stored item in storage.json is a stringified object not a stringified array of objects.

How do I set up the project so for the first object you create an array (like if storage.json does not exist)and subsequent objects are added to the array. Is there a commonly used approach to this?

Cant push to UnionType array

I am playing around with UnionTypes in TS and I thought that I could create a valid scenario where they could be used, but I do not understand why this is breaking with the error of:

Argument of type ‘{ name: string; }’ is not assignable to parameter of type ‘string & { name: string; }’

I know ways to “force” this partical approach, but I want to understand why this does not work.

let newArray: string[] | { name: string }[] = new Array();

//just a boolean to know when is one type or the other
    if (isMultiple) {
      otherArray.forEach((item: { name: string }) => {
        newArray.push(item)
      })
    }
    else {
      otherArray.forEach((item: { name: string }) => {
        newArray.push(item.name)
      });
    }

    return newArray

Discord.js (v13) Uncaught TypeError TypeError: Cannot read properties of undefined (reading ‘members’)

I’m attempting to access all members of a given guild, the code I wrote (which should work) no longer works

async function getMembers(id){
const list = client.guilds.cache.get(id)

const members = await list.members.fetch()
members.each((member) => {

console.log(member.user.id);
})

}

I expected this function to console log the ID’s of all given members of a guild

Keep items in cart shopping using localstorage. After refreshing page or navigating to other pages

I have created a web commercial website with a cart, where i stock my items, my problem is that i don’t know how to keep items in the cart even after refreshing page or navigating to other pages.
I know that one solution is to use the local storage but i never used it before can anyone help me where and how can i add this function on my JS code so that can work.

My JavaScript Code :

$("#open-cart").click(function () {
  $(".cart").addClass("active");
});

$("#close-cart").click(function () {
  $(".cart").removeClass("active");
});

//cart working JS
if (document.readyState == "loading") {
  document.addEventListener("DOMContentLoaded", ready);
} else {
  ready();
}

function ready() {
  //Remove items from cart
  var reomveCartButtons = document.getElementsByClassName("cart-remove");
  console.log(reomveCartButtons);
  for (var i = 0; i < reomveCartButtons.length; i++) {
    var button = reomveCartButtons[i];
    button.addEventListener("click", removeCartItem);
  }
  //Quantity changes
  var quantityInputs = document.getElementsByClassName("cart-quantity");
  for (var i = 0; i < quantityInputs.length; i++) {
    var input = quantityInputs[i];
    input.addEventListener("change", quantityChanged);
  }
  //Add to cart
  var addCart = document.getElementsByClassName("add-cart");
  for (var i = 0; i < addCart.length; i++) {
    var button = addCart[i];
    button.addEventListener("click", addCartClicked);
  }
  //Buy button Work
  document
    .getElementsByClassName("btn-buy")[0]
    .addEventListener("click", buyButtonClicked);
  document
    .getElementsByClassName("btn-buy")[1]
    .addEventListener("click", resetButtonClicked);
}

//reset button
function resetButtonClicked() {
  var cartContent = document.getElementsByClassName("cart-content")[0];
  while (cartContent.hasChildNodes()) {
    cartContent.removeChild(cartContent.firstChild);
  }
  updatetotal();
}

//Buy Button
function buyButtonClicked() {
  alert("Votre commande a été placée");
  var cartContent = document.getElementsByClassName("cart-content")[0];
  while (cartContent.hasChildNodes()) {
    cartContent.removeChild(cartContent.firstChild);
  }
  updatetotal();
}

//Remove items from cart
function removeCartItem(event) {
  var buttonClicked = event.target;
  buttonClicked.parentElement.remove();
  updatetotal();
}

//Quantity changes
function quantityChanged(event) {
  var input = event.target;
  if (isNaN(input.value) || input.value <= 0) {
    input.value = 1;
  }
  updatetotal();
}

//Add to cart
function addCartClicked(event) {
  var button = event.target;
  var shopProducts = button.parentElement;
  var title = shopProducts.getElementsByClassName("product-title")[0].innerText;
  var price = shopProducts.getElementsByClassName("price")[0].innerText;
  var productImg = shopProducts.getElementsByClassName("product-img")[0].src;
  addProductToCart(title, price, productImg);
  document.cookie="produit="
  updatetotal();
}

function addProductToCart(title, price, productImg) {
  var cartShopBox = document.createElement("div");
  cartShopBox.classList.add("cart-box");
  var cartItems = document.getElementsByClassName("cart-content")[0];
  var cartItemsNames = cartItems.getElementsByClassName("cart-product-title");
  for (var i = 0; i < cartItemsNames.length; i++) {
    if (cartItemsNames[i].innerText == title) {
      alert("Vous avez déjà ajouté ce produit au panier");
      return;
    }
  }

  var cartBoxContent = `
          <img src="${productImg}" alt=""  class="cart-img">
            <div class="detail-box">
          <div class="cart-product-title">${title}</div>
          <div class="cart-price">${price}</div>
          <input type="number" value="1" class="cart-quantity">
          </div>
          <!--Remove cart-->
          <i class="bi bi-trash-fill cart-remove"></i>`;

  cartShopBox.innerHTML = cartBoxContent;
  cartItems.append(cartShopBox);
  cartShopBox
    .getElementsByClassName("cart-remove")[0]
    .addEventListener("click", removeCartItem);
  cartShopBox
    .getElementsByClassName("cart-quantity")[0]
    .addEventListener("change", quantityChanged);
}
//Update Total
function updatetotal() {
  var cartContent = document.getElementsByClassName("cart-content")[0];
  var cartBoxes = cartContent.getElementsByClassName("cart-box");
  var total = 0;
  var totalApresTaxes = 0;
  var montanttTPS = 0;
  var montantTVQ = 0;

  for (var i = 0; i < cartBoxes.length; i++) {
    var cartBox = cartBoxes[i];
    var priceElement = cartBox.getElementsByClassName("cart-price")[0];
    var quantityElement = cartBox.getElementsByClassName("cart-quantity")[0];
    var price = parseFloat(priceElement.innerText.replace("$", ""));
    var quantity = quantityElement.value;
    total = total + price * quantity;
    montanttTPS = total * 0.05;
    montantTVQ = total * 0.1;
    totalApresTaxes = total + montantTVQ + montanttTPS;
  }
  //If price contain some Cents Value
  total = Math.round(total * 100) / 100;
  totalApresTaxes = Math.round(totalApresTaxes * 100) / 100;
  console.log(totalApresTaxes);
  document.getElementsByClassName("total-price")[0].innerText = "$" + total;
  document.querySelectorAll(".total-price-apres-taxes")[0].innerText =
    "$" + totalApresTaxes;
}

Appreciate your help.

How to get selected row using ReactDataGrid?

This is a very simple example of a ReactDataGrid component. I’m trying to get the selected row, but I am unsure of the syntax to get that out when calling my function.

I don’t think this is the correct syntax to call, onSelectionChange to print out the selected row. What is the correct syntax?
onSelectionChange={({ selected }) => this.onSelectionChange(selected)}

import React, { PropTypes, Component } from 'react';
import ReactDataGrid from 'react-data-grid';

class DataGridExample extends Component {

  static propTypes = {
    columns: PropTypes.array,
    rows: PropTypes.array
  };

  constructor (props) {
    super(props)
    this.state = {
      columns: [],
      rows: []
    }
    this.rowGetter = this.rowGetter.bind(this);
  }

  componentDidMount() {
    this.setState((prevState, props) => ({
      rows: [
        {key: 'd1', lname: 'Doe', quantity: 3},
        {key: 'd2', lname: 'Simmons', quantity: 97},
        {key: 'd3', lname: 'Walters', quantity: 6}
      ],
      columns: [
        {name: "Quantity", key: "quantity"},
        {name: "Last Name", key: "lname"}
      ]
    }));
  }

  rowGetter(i) {
    return this.state.rows[i];
  }

  onSelectionChange = (selected) => {
      console.log(`selected:${selected}`)
  }

  render() {
    return  (
    <ReactDataGrid
      columns={this.state.columns}
      rowGetter={this.rowGetter}
      rowsCount={this.state.rows.length}
      minHeight={400} 
      onSelectionChange={({ selected }) => this.onSelectionChange(selected)}
      />);
  }
}

export default DataGridExample;

How i can print this in one?

I would like to know, how I can write this in one line with the symbol of dollar($) separating ech word and with this symbol in the end?I’ve tried to change ” ” to $ with replace – no success. In this example it is printing $ before eery word but still in a column :/

class Add {
  constructor(...words) {
      this.words = words;
  }
  print () {
  var a = this.words;

  for (let v of a) {
  v = "$" + v;
      console.log(v);    
  }
  }
}

var x = new Add("hehe", 
"hoho", "haha", "hihi", 
"huhu");
var y = new Add("this", "is", 
"awesome");
var z = new Add("lorem", 
"ipsum", "dolor", "sit", 
"amet", "consectetur", 
"adipiscing", "elit");
x.print();
y.print();
z.print();

JavaScript – Implementing and call asynchronous functions without async and await in [duplicate]

I have a case that I cannot modify my function (using async keyword) to be asynchronous and I need to await another function inside that function. Of course await here will throw an error.

So, I thought of calling the function need to be awaited like any other function is called but in addition to that I tried to pass an object as a flag (need to be reference variable) and then after that function, I have an empty loop to check for that flag as bellow:

firstFn(){

const obj= {done:false};

secondFn(obj);

// need to pause the execution here until I get the result

while (!obj.done)

{
  // the problem here that, this while loop is blocking the execution and the browser is freezing

// I want to have the line below, but that will not work because await keyword is needed here but I cannot use it

//   await new Promise(resolve => setTimeout(resolve, 2000));

}

// only reach this point after the secondFn is executed, for example, a user clicks ok in a custom modal popup.

alert("done")

}

I remember I implemented something similar and it was working perfectly, but do not remember the trick to avoid this blocking behavior.

your help is appreciated. Thanks.

React Form | button outside of form component

In the application, I am building I want the following functionality. I have a form that is there to edit some text content. I have buttons (in fact 2 buttons), but each of them is displayed one at a time. When I press the “Edit” button, the state change occurs onClick and the different button with type=”submit” is shown. I want the functionality above because initially the form itself is not shown and is only displayed when “Edit” is pressed.
I am using react in my project and this is a code snippet of how I have decided to solve my problem:

 ...some code...
<Form id="markerEditForm" onSubmit={()=>alert("submitted")}>
         <Form.Group>
                      <Form.Label>
                                   My form
                      </Form.Label>
         </Form.Group>
 </Form>
...some code...
 {someState ?
 <Button form="markerEditForm"type="submit" variant="success">
        Save
 </Button>
 :
 <Button onClick={()=>onEdit()} variant="warning">
        Edit
 </Button>}

The problem I am facing is that when I press “Edit” button, I still get an alert with text “submitted”, though my “Edit” button has no references to my form and is not of type “submit”.
I am rather new to react and I am possibly doing something silly or unnecessary hence why I would appreciate any advice on how to fix this.

¿What is the problem here with material Ui table?

Error => material-table.js:872 Uncaught TypeError: Cannot read properties of undefined (reading ‘direction’)

Code:

  useState
} from 'react'
import './App.css';
import MaterialTable from 'material-table'

function App() {

  const [rows, setRows] = useState([])

  const columns = [
    {title: 'Name',field: 'name'},
    {title: 'Email',field: 'email'},
    {title: 'Phone Number',field: 'phoneNumber'},    
  ]
  return (
    <div className="App">
      <MaterialTable
          columns={columns}
          data={rows}
        />
    </div>
  );
}

export default App;

As you can see its really SUPER BASIC code but I dont understando whats the problem, any help will be really appreciated!

Issue with uploading a file through the multer package

I’m using multer to upload a file through node.js.
The file object that is sent from our FE is:

file: FileList
    0: File
    lastModified: 1647806297845
    lastModifiedDate: Sun Mar 20 2022 21:58:17 GMT+0200 (Israel Standard Time) {}
    name: "Example Docx.docx"
    size: 12143
    type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    webkitRelativePath: "

With the input’s name attribute 'cv'.
My usage of multer is:

const uploadSingleFile = multer.single('cv');

uploadSingleFile(req, res, (err) => {
    if (err) {
        next(err);
    }
    next();
});

Yet I don’t get any file in req.file

What am I missing?

How can I use spatialization in Web Audio API?

Web Audio’s PannerNode is supposed to allow placement of the sound source with the positionX, positionY and positionZ parameters, but I can’t seem to get things to work consistently.

I’ve tested things using two different hardware setups: a four-speaker quadraphonic system (created with an aggregate device in Audio/MIDI Setup) and with AirPods Pro, which can mimic 11.1 surround. I’ve confirmed working surround sound using Dolby Atmos-enabled test videos and surround mixes created in Adobe Audition, so the speakers shouldn’t be the problem. I’m using Safari 15.4 on macOS 11.6.4.

In the code below, which I’ve setup as a JSFiddle here, the sound starts centered but moving even slightly to the left or right moves it all the way to that side. In the quadraphonic setup, everything seems to come from the rear speakers no matter what the settings are. Moving along the Y axis seems to have no affect (expected with the quadraphonic setup, but it should come through on the AirPods).

I’m sure I’m missing something obvious, but I can’t seem to figure it out. Can anyone tell me what I’m doing wrong?

var AudioContext = window.AudioContext || window.webkitAudioContext;
var ctx = new AudioContext();
// create a gain node to gate the sound on and off
var g = ctx.createGain();
g.connect(ctx.destination);
g.gain.setValueAtTime(0, ctx.currentTime);
// create a panner to handle sound location
var p = ctx.createPanner();
p.connect(g);
p.positionX.setValueAtTime(0, ctx.currentTime)
// create oscillator to generate the sound
var o = ctx.createOscillator();
o.type = 'sine';
o.frequency.setValueAtTime(440, ctx.currentTime);
o.connect(p);

function startOsc() {
  // start oscillator; we "play" the sound by turning volume up and down
  o.start(0);
}

function moveSound(x,y,z) {
  // move the sound by x, y, and z units
  // first, update displayed values (rounding is to avoid floating-point math)
  document.querySelector('#xVal').innerHTML = Math.round((p.positionX.value + x)*10)/10;
  document.querySelector('#yVal').innerHTML = Math.round((p.positionY.value + y)*10)/10;
  document.querySelector('#zVal').innerHTML = Math.round((p.positionZ.value + z)*10)/10;
  // now position the sound
    p.positionX.value = Math.round((p.positionX.value + x)*10)/10;
    p.positionY.value = Math.round((p.positionY.value + y)*10)/10;
    p.positionZ.value = Math.round((p.positionZ.value + z)*10)/10;
  // now turn volume up and then down 1/2 second later to make a tone
  g.gain.setTargetAtTime(1, ctx.currentTime, 0.02);
  g.gain.setTargetAtTime(0, ctx.currentTime+0.5, 0.02);
}
<button onclick="startOsc();">start</button>

<button onclick="moveSound(0,0,0);">play in current location</button>

<table>
<tr>
<td><button onclick="moveSound(-0.1,0,0);">move left</button></td>
<td><div id=xVal>0</div></td>
<td><button onclick="moveSound(0.1,0,0);">move right</button></td>
</tr>
<tr>
<td><button onclick="moveSound(0,-0.1,0);">move down</button></td>
<td><div id=yVal>0</div></td>
<td><button onclick="moveSound(0,0.1,0);">move up</button></td>
</tr>
<tr>
<td><button onclick="moveSound(0,0,-0.1);">move backward</button></td>
<td><div id=zVal>0</div></td>
<td><button onclick="moveSound(0,0,0.1);">move forward</button></td>
</tr>