express js app.all() throwing error for no apparent reason [duplicate]

this is the code im trying to run

const express = require("express");
const app = express()

app.all('*', (req, res) => {
  res.status(404).send('<h1>resource not found</h1>')
});

app.listen(5000, () => {
  console.log('server is listening on port 5000...')
});

and running node app.js shows this:

C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:73
            throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);
            ^

TypeError: Missing parameter name at 1: https://git.new/pathToRegexpError
    at name (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:73:19)
    at lexer (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:91:27)
    at lexer.next (<anonymous>)
    at Iter.peek (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:106:38)
    at Iter.tryConsume (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:112:28)
    at Iter.text (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:128:30)
    at consume (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:152:29)
    at parse (C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:183:20)
    at C:UsersuserDropboxPCDesktopnode-tutorialnode-express-course2-express-tutorialnode_modulespath-to-regexpdistindex.js:294:74
    at Array.map (<anonymous>)

the only thing ive installed using npm in this project is nodemon and express.js

ive tried using both the normal versions and the @latest ones

ES6 arrow functions this inside a class versus inside an object [duplicate]

I’m trying to get a better understanding of how the arrow functions work in modern JavaScript. I have the following example:

class Person {
    name = 'Max';
    printMyName () {
        console.log(this.name); // this is required to refer to the class!
    }
}
 
const person = new Person();
person.printMyName();

class Person2 {
  name = 'Max2';
  printMyName = () => {
    console.log(this.name);
  }
}

const person2 = new Person2();
person2.printMyName();
    
    
const user = {
    name: "John",
    logName () {
        console.log(this.name);
    },
    logNameArrow: () => {
            debugger;
        console.log(this.name);  //this is Window here
    },
};
user.logName(); // logs 'John'
console.log('===============================');
user.logNameArrow(); // logs result

Which I’ve put here: https://jsfiddle.net/52qy8fd6/1/

this works inside a JavaScript class, but not in a JavaScript object.

Can anyone explain why the scoping is different in these two cases? Maybe instantiating my class with a new statement is binding this?

JavaScript function not returning array [duplicate]

I have an ESRI 3.46 JavaScript application. There are a couple of functions which return data from an API. I am looping through the results and creating an array to be returned to other areas of my application. The problem I am having is the function is returning
“undefined” instead of the array. If I send the results to the console before the return statement, the data is there. I am also using a little PHP in this.

        function requestDomains(layer){
          var dUrl = '<?php echo $emapFS; ?>/queryDomains';
          var domainRequest = new Request({
            "url" : dUrl,
            "content": {
              "f": "json",
              "layers": '['+layer+']',
            },
            async: false
          });
          //domainRequest.then(domainParse, requestFailed);
          domainRequest.then(function(response){
            var domains = response.domains
            var arr = [];
            //console.log(domains);
            jQuery.each(domains, function(key, value){
              var dname = value.name;
              arr[dname] = [];
              var cValues = value.codedValues;
              jQuery.each(cValues, function(k, v){
                var dcode = v.code.toString();
                var dvalue = v.name.toString();
                arr[dname][dcode] = dvalue;
              });
            });
            console.log(arr);  //<------------ This returns the array in console. Looks good
            return arr;

          });
        }

        function MainTabContent (results){
          var template = "";
          var wfeatures = results.features[0];
          //console.log("Main");
          var MainArray = <?php echo $mainFields; ?>;
          var layerid = mapLayers['Main Lines'];
          //console.log(layerid);
          var cDomains = requestDomains(layerid);
          console.log(cDomains); // <-----------------------This returns undefined
          template = "<i>Total features returned: " + wfeatures.length + "</i>";
          template += "<table border='1' style='width:1000px;'>";
          template += "<tr>"
          jQuery.each(MainArray, function(tkey, tvalue){
            template += "<th>"+tvalue+"</th>"
          });
          //template += "<th>Data</th>"
          template += "</tr>";
          for (var i = 0, il = wfeatures.length; i < il; i++)
          {
            template += "<tr>";
            jQuery.each(MainArray, function(key, value){

                switch(key)
                {
                  case "<?php echo $switchFields[4]; ?>":
                    template += '<td width="300">'+ wfeatures[i].attributes[key] +'</td>';
                  break;
                  case "<?php echo $switchFields[3]; ?>":
                    template += '<td width="100">'+ wfeatures[i].attributes['DIAMETER'] +' '+ wfeatures[i].attributes['MATERIAL'] + '<a href="#" onclick="showFeature(mainResults.features[0]['+ i +']); return false;">(show)</a></td>';
                  break;
                  case "<?php echo $switchFields[5]; ?>":
                    asbuilt = wfeatures[i].attributes[key];
                    //console.log(asbuilt);
                    if(asbuilt != 'Null')
                    {
                      template += '<td><a href="<?php echo base_url(); ?>gis/ab/' + asbuilt + '" target="_blank">' + asbuilt + '</a></td>';
                    } else {
                      template += '<td>&nbsp;</td>';
                    }
                  break;
                  case "<?php echo $switchFields[0]; ?>":
                    unitid = wfeatures[i].attributes[key];
                    template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                  break;
                  case "<?php echo $switchFields[1]; ?>":
                    unitid2 = wfeatures[i].attributes[key];
                    template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                  break;
                  case "<?php echo $switchFields[6]; ?>":
                    facilityID = wfeatures[i].attributes[key];
                    template += '<td><div class="csspointer" style="color:blue;text-decoration:underline;" onClick="window.open('/gis/HansenQuery/'+facilityID+'/COMPWMN', '',  'width=400,height=400,menubar=no,scrollbars=yes')">Asset Data</div></td>';
                  break;
                  case "<?php echo $switchFields[7]; ?>":
                    mLength = parseFloat(wfeatures[i].attributes[key]);
                    template += "<td>"+ Math.round(mLength) +"</td>";
                  break;
                  default:
                  template += "<td>"+ wfeatures[i].attributes[key] +"</td>";
                }

            });
            //template += '<td><div class="csspointer" style="color:blue;text-decoration:underline;" onClick="window.open('/gis/HansenQuery/'+unitid+'/COMPWMN/'+unitid2+'', '',  'width=400,height=400,menubar=no,scrollbars=yes')">Hansen</div></td>';
            template += "</tr>";
          }
          template += "</table>";

          return template;
        }

The above code was shortened a bit. I initially had the request for the data in one function and the parsing of the data into an array in another.

How to inspect why YouTube player onStateChange doesn’t trigger

On a web page, I created YouTube player objects with new YT.Player(id, {events: {'onStateChange': ...}}). The resulting players have players[i].options.events.onStateChange. The iframes have message event listeners.

But that onStateChange event doesn’t trigger for some of the players in one particular browser tab that is currently open. The line d.j.G(e,h) in www-widgetapi.js is not reached when those problematic players pause or play. It is reached for the other players.

When I open the same page in a new tab, all events get triggered. So it’s a rare error (possibly depending on the order of loaded content and/or user actions). I can’t replicate it consistently, let alone work towards a minimal example. So I want to inspect it in the currently open browser tab where it occurred.

How can I inspect why the existing onStateChange event doesn’t trigger for those players in that browser tab?

I’ve read a dozen of posts about onStateChange not triggering, but my code doesn’t have the same bugs that those posts describe.

How to disallow foreign characters in Gravity Forms / HTML / JS and allow English characters only? (Chinese, Russian, Arabic letters etc)

Using Gravity Forms in WordPress I created a contact form.

Now customers enter Chinese characters into the fields, such as Name, Message. But this information is being sent to another system which does not allow these characters and they are converted into question marks: ??????

I am looking for a type of functionality that disallows any foreign type of character sets other than English and all its special character variations to be typed into the input field.

Preferably a native feature already existing in Gravity Forms or another plugin that would add this feature. If this does not exist, I might go into the code to change it.

How do I achieve this please?

Convert ESC POS Command 24 dot double density into 8 dot single density

I need a function that return array of byte array 8 dots single density, this function running as expected however the printing speed is the issue, it takes quite long time to print the image even though the quality is not my priority. I’ve tried to change this code into bit-image-mode 8 dots single density to speed up the printing but the image ratio somehow becoming 2:3 instead of 1:1. Can anyone help me convert this code to support 8 dots single density?

Thanks!

function convertGSv0ToEscAsterisk(bytes) {
    // Extract header info
    const xL = bytes[4] & 0xFF;
    const xH = bytes[5] & 0xFF;
    const yL = bytes[6] & 0xFF;
    const yH = bytes[7] & 0xFF;
  
    const bytesByLine = xH * 256 + xL;
    const dotsByLine = bytesByLine * 8;
    const nH = Math.floor(dotsByLine / 256);
    const nL = dotsByLine % 256;
    const imageHeight = yH * 256 + yL;
    const imageLineHeightCount = Math.ceil(imageHeight / 24.0);
  
    // Pre-allocate the result array
    const returnedBytes = new Array(imageLineHeightCount + 2).fill(null).map((_, i) => {
      if (i === 0) return EscPosPrinterCommands.LINE_SPACING_24;
      if (i === imageLineHeightCount + 1) return EscPosPrinterCommands.LINE_SPACING_30;
      return new Uint8Array(6 + bytesByLine * 24);
    });
  
    // Process each image line
    for (let i = 0; i < imageLineHeightCount; i++) {
      const imageBytes = returnedBytes[i + 1];
      const pxBaseRow = i * 24;
  
      // Set command header
      imageBytes[0] = 0x1B;
      imageBytes[1] = 0x2A;
      imageBytes[2] = 0x21;
      imageBytes[3] = nL;
      imageBytes[4] = nH;
  
      // Pre-calculate bit masks for improved performance
      const bitMasks = Array.from({ length: 8 }, (_, idx) => 1 << (7 - idx));
  
      // Process image data
      for (let column = 0; column < dotsByLine; column++) {
        const byteOffset = 5 + column * 3;
        const bitColumn = bitMasks[column % 8];
        const srcByteOffset = Math.floor(column / 8) + 8;
  
        for (let byteRow = 0; byteRow < 3; byteRow++) {
          const dstIndex = byteOffset + byteRow;
          if (dstIndex >= imageBytes.length - 1) continue;
  
          for (let k = 0; k < 8; k++) {
            const pxRow = pxBaseRow + byteRow * 8 + k;
            if (pxRow >= imageHeight) continue;
  
            const srcIndex = bytesByLine * pxRow + srcByteOffset;
            if (srcIndex >= bytes.length) continue;
  
            if ((bytes[srcIndex] & bitColumn) === bitColumn) {
              imageBytes[dstIndex] |= bitMasks[k];
            }
          }
        }
      }
  
      imageBytes[imageBytes.length - 1] = EscPosPrinterCommands.LF;
    }
    return returnedBytes;
  }

Custom Mathjs unit

I would like to use mathjs in order to ease unit conversion. To do so, I introduce new units as following :

import { unit, createUnit, evaluate } from 'mathjs';
createUnit('gCO2eq');
createUnit('kgCO2eq', unit(1000, 'gCO2eq'));

const a = evaluate('10000 gCO2eq');
console.log(a.toString());

This outputs:

10000 gCO2eq

But I expected it to be

10 kgCO2eq

Any idea why I got this result instead?

When is chosen only display partial value of in – HTML

I have a SELECT that is pulling in 2 db fields (TYPE and DESCRIPTION) to form the displayed OPTION values (option example: ft - full-time, pt - part time, sl - seasonal, etc.).
When the drop-down options are displayed, I want to see both TYPE and DESCRIPTION (as detailed in my example) but I only want the TYPE displayed on the form/page after it is selected.

<label>Employee Type</label>
<select>
  <Option value="" disabled selected hidden>--Select Type--</Option>
  @if (Model.DropDownItems != null) {
    @foreach (var item in Model.DropDownItems) {
      <option value="@item.Type">@item.Type - @item.Desc</option>
    }
  }
  else {
    <option value="" disabled>No data available</option>
  }
</select>

Any assistance with this would be greatly appreciated.

REGEX: How to get substring from nested braces using regular expressions [duplicate]

Is there a way to get a substring from a string with nested curly braces where the nesting level is not fixed using regular expressions with pure javascript?

For example we need to get the some text substring from all this strings:

"error: {error: {error: {some text}; at 'aaa', line 11;} at 'bbb', line 22'} at 'ccc', line 33';"
"error: {error: {some text}; at 'aaa', line 11;} at 'bbb', line 22';"
"error: {some text}; at 'aaa', line 11;"

Is there an API to check the status of the free OCR.space API? [closed]

I’ve been having trouble with the OCR.space API. I use the free API’s OCR Engine 2, and sometimes it is down. I know I can check it manually via. the OCR.space API Status Page, however I need an API that can be used to check it directly in the client-side javascript.

I’ve tried simply using fetch() on the page, but it gets blocked by CORS. Below is the error I got:

Access to fetch at ‘https://status.ocr.space/‘ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

GET https://status.ocr.space/ net::ERR_FAILED 200 (OK)

The reason I need this is to disable a button on my page that uses the API.

Thanks in advance.

Kombinizin Ömrünü Uzatın, Tasarrufu Hissedin [closed]

Kış aylarında evinizin sıcak kalmasını sağlamak için kombinizin düzenli olarak kontrol edilmesi şarttır. Birçok kişi sadece cihaz arızalandığında teknik servis çağırmayı tercih eder. Oysa ki düzenli olarak yapılan kombi bakımı, hem cihazınızın ömrünü uzatır hem de ani arızaların önüne geçer. Üstelik sadece konfor değil, enerji tasarrufu açısından da büyük fayda sağlar.

Empati Teknik olarak Ankara genelinde verdiğimiz hizmetlerde müşteri memnuniyetini ön planda tutuyoruz. Deneyimli teknisyenlerimizle gerçekleştirdiğimiz detaylı kombi bakımı, cihazınızın iç aksamlarının temizlenmesini, gaz ayarlarının kontrolünü ve genel çalışma performansının test edilmesini kapsar. Böylece cihazınız güvenli, verimli ve sessiz bir şekilde çalışır.

Kombi kadar önemli olan bir diğer konu da petek temizliği. Isıtma sistemlerinde zamanla oluşan tortu, çamur ve kireç tabakası, suyun petekler içerisinde rahat dolaşmasını engeller. Bu durum odaların yeterince ısınmamasına, kombinin daha fazla çalışmasına ve doğalgaz tüketiminin artmasına neden olur. İşte tam da bu nedenle düzenli petek temizliği, daha iyi bir ısınma ve daha düşük fatura anlamına gelir.

Empati Teknik olarak kullandığımız özel ekipmanlarla ve kimyasal destekli temizlik sistemlerimizle, peteklerinizin ilk günkü verimliliğine kavuşmasını sağlıyoruz. İşlem sonrası tüm peteklerin eşit ısındığını fark edecek, ısınma süresinin kısaldığını hemen hissedeceksiniz.

Detaylı bilgi almak ya da hemen servis randevusu oluşturmak isterseniz Ankara kombi servisi sayfamıza göz atabilirsiniz. Web sitemiz üzerinden birkaç adımda kolayca başvuru yapabilir, servis ekiplerimizin sizi arayarak yönlendirmesini sağlayabilirsiniz.

Unutmayın: kombi bakımı yılda en az bir kez, petek temizliği ise iki yılda bir mutlaka yapılmalıdır. Hem güvenliğiniz hem de bütçeniz için bu işlemleri aksatmamak büyük önem taşır. Empati Teknik olarak biz buradayız; siz sıcak, güvenli ve tasarruflu bir kış geçirin diye!

Inheriting constructor documentation in JSDoc with ES6 classes

I am writing documentation for some classes written using the ES6 class syntax. I have some classes which inherit their constructor from their parent class, as below:

/**
 * @class
 */
class Parent {
    /**
     * the inherited constructor
     * @param {*} someAttribute - an attribute of the parent class
     */
    constructor(someAttribute) {
        this.someAttribute = someAttribute
    }

    /**
     * does nothing
     * @method
     */
    someMethod() {
        return;
    }
}

/**
 * @class
 * @extends Parent
 */
class Child extends Parent {
}

This mostly does exactly what I need, documenting Parent exactly as I expect in the generated website, and showing that Child extends Parent. It also documents someMethod within both Parent and Child as I expected. Additionally, I see the documentation exactly as expected in the popups that show on VSCode when typing, for example, new Child(

However, in the generated website, the constructor documentation is displayed only for Parent and not for Child, even though the constructor is also inherited.

Is there any way to inherit the constructor documentation from Parent in Child. As well as the above, I have also tried using @augments in place of @extends, @constructor or @method above the constructor function, and @inheritdoc in the Child class

Not able to create a POST data : MongoDb + Express + CRUD [closed]

User.js

import express from 'express';
import connectDB  from '../db.js';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.json());

const router = express.Router();

//Create User
router.post('/create-data',async(req,res)=>{
    const db = await connectDB();
    const Bodydata = {age:req.body.age,gpa:req.body.gpa}
    const result = await db.collection('students').insertOne({Bodydata})
    console.log(Bodydata)
    res.status(201).json(result);
})
export default router;

Index.js (Express connection)

import express from 'express';
import router from './routes/user.js';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.json());

app.use(express.json());
app.use('/', router);

const PORT = 8000;
app.listen(PORT, () => {
    console.log(`Server running at Port: ${PORT}`);
});

db.js (Mongo Connection)

import { MongoClient } from 'mongodb';

const uri = 'mongodb://0.0.0.0:27017';
const client = new MongoClient(uri);
let db;

const connectDB = async () => {
  if (!db) {
    await client.connect();
    db = client.db('school'); // your DB name
    console.log('Connected to MongoDB');
  }
  return db;
};

export default connectDB;

Note: I am not using moongoose Postman & Error Message Image

I am trying to perform a CRUD Operation with Mongo + Express but I am facing this error not sure what it is? I am not able to create data it is throwing the error which I have attached to the Image. Let me know where I am going wrong

Эффект полностраничной поблочной прокрутки wordpress [closed]

I would like to create a full-page scroll effect (block-by-block scrolling) on a WordPress site using the DIVI theme. I have a code that works only on desktop, but if I activate it, the site doesn’t work on mobile Safari and shows an error.
I would like to know if it’s possible to make the code work only on desktop and disable it on mobile?

The CSS code is applied to the block section.

.fullpage-section{
height:100vh; 
display: flex; 
flex-direction: column; 
justify-content: center;}

JavaScript code added to the head of the site

<script>
 ( function( $ ) {
 $( document ).on( 'mousewheel DOMMouseScroll', function( event ) {
 if ( ( $( '.et_pb_side_nav' ).length === 0 ) || $( 'html, body' ).is( ':animated' ) ) return;
 event.preventDefault();
 var direction = event.originalEvent.wheelDelta || -event.originalEvent.detail;
 var $position = $( '.et_pb_side_nav' ).find( '.active' );
 var $target;
 if( direction < 0 ) {
 $target = $( $position ).parent().next();
 } else {
 $target = $( $position ).parent().prev();
 }
 if ( $( $target.length ) !== 0 ) {
 $( $target ).children( 'a' ).trigger( "click" );
 }
 } );
 } )( jQuery );
 </script>