How can I respond to an input element’s value property being set?

I’m writing a user script which needs to respond to an <input> element’s value changing, no matter how the change was made.

For user interactions, this is easy — just add a listener for the input event. However, I haven’t yet found a way to respond to the input’s value being set directly by changing its .value property.

I’ve tried adding listeners for the change and input events (neither are triggered) and adding a MutationObserver for both the input’s attributes and the input’s parent’s child list (again, neither are triggered). There also doesn’t appear to be a property descriptor I can modify.

How can I trigger code to run when an <input> element’s .value property is set?

<!DOCTYPE html>
<html>
  <head>
    <title>Detect value change</title>

    <script type="module">
      const range = document.querySelector('input');

      range.addEventListener('change', (event) => console.log('Change:', event));
      range.addEventListener('input', (event) => console.log('Input:', event));

      const observer = new MutationObserver((mutations) => console.log('Mutation:', mutations));

      observer.observe(range, { attributes: true, attributeFilter: ['value'] });
      observer.observe(range.parentNode, { childList: true });

      console.log('Property descriptors:', Object.getOwnPropertyDescriptors(range));

      range.value = 7;
    </script>
  </head>

  <body>
    <input type="range" min="0" max="10" />
  </body>
</html>

Console output:

Property descriptors: {}

How to call this object and display it in HTML

I am not sure if my term is correct. I want to get the value that corresponds “spc1” under “alternatePrices”. Please refer from the image below. While I can successfully call the value of “addedOn” and the like, I don’t know how on those with arrays or object. I tried this code but nothing is appearing.

document.getElementById('demox').innerHTML = cartItem.alternatePrices[spcl]

enter image description here

undefined is not an object (evaluating ‘_navigator.dispatch’) on navigating to screen in react native

I’m trying to navigate to a certain screen when clicking on notification but I get above mentioned error. I have read oter questions and tried to solve it but I couldn’t find solution for my problem.

here is my MainApp.js

import {NavigationContainer, useNavigation} from '@react-navigation/native';
import {NavStack} from './src/RootNavigator/StackNavigation';
import {NavStack2} from './src/RootNavigator/MainNavigator';
import {useDispatch, useSelector} from 'react-redux';
import {
  navigate,
  setTopLevelNavigator,
} from './src/RootNavigator/MainNavigator/NavigationService';
import {dispatchFunc, saveToken, checkPopUps} from './src/Redux/action';
import messaging from '@react-native-firebase/messaging';
import Strings from './src/Translation';
import NavigationService from './src/RootNavigator/MainNavigator/NavigationService';
import {navigationRef} from './RootNavigation';

export default function App(props) {
  const dispatch = useDispatch();
  const login = useSelector(state => state.user.login);
  const language = useSelector(state => state.user.language);
  const [isAnimate, setAnimate] = useState(true);

  useEffect(() => {
    updateData();
  }, []);

  useEffect(() => {
    const unsubscribe = messaging().onNotificationOpenedApp(
      async remoteMessage => {
        console.log(
          'A new FCM message arrived!',
          JSON.stringify(remoteMessage),
        );
      },
    );
    return unsubscribe;
  }, []);
  const updateData = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      getFcmToken();
      console.log('Authorization status:', authStatus);
    }
    messaging().onMessage(async remoteMessage => {
      console.log('remoteMessage', JSON.stringify(remoteMessage));
    });
    messaging().setBackgroundMessageHandler(async remoteMessage => {
      console.log(
        'Message handled in the background!',
        JSON.stringify(remoteMessage),
      );
    });
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log(
        'Notification caused app to open from background state:',
        JSON.stringify(remoteMessage),
      );
      // Alert.alert('ap[iii', 'lolll');
      Alert.alert('Alert Title', 'My Alert Msg');
       NavigationService.navigate('MyBooking');
    });
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log(
            'Notification caused app to open from quit state:',
            remoteMessage.data,
          );
        }
      });
  };
  const getFcmToken = async () => {
    const fcmToken = await messaging().getToken();
    if (fcmToken) {
      console.log('Your Firebase Token is:', fcmToken);
      dispatch(saveToken(fcmToken));
    } else {
      console.log('Failed', 'No token received');
    }
  };
  return (
    <NavigationContainer ref={navigationRef}>
      <PopUpBox okClick={() => dispatch(dispatchFunc())} />
      {!login ? <NavStack /> : <NavStack2 />}
      </NavigationContainer>
  );
}

App.js

import { Provider } from "react-redux";
import MAINAPP from "./MainApp";
import { Store, persistor } from "./src/Redux/store";
import { PersistGate } from "redux-persist/integration/react";
import RemotePushController from  './src/Service/RemotePushController'

export default class App extends React.Component {

  componentDidMount() {
    setTimeout(() => SplashScreen.hide() , 2000);
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <Provider store={Store}>
          <PersistGate loading={null} persistor={persistor}>
            <MAINAPP />
            <RemotePushController />
          </PersistGate>
        </Provider>
      </View>
    );
  }
}

RootNavigation.js

import React from 'react';

export const navigationRef = React.createRef();

const navigate = (name, params) =>
  navigationRef.current?.navigate(name, params);

export default {
  navigate,
};

NavigationService.js

import {NavigationActions} from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}
function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    }),
  );
}
export default {
  navigate,
  setTopLevelNavigator,
};

And if i update MainApp.js like this, then i get this error:

The action 'Navigation/NAVIGATE' was not handled by any navigator.

<NavigationContainer
      ref={navigatorRef => {
        NavigationService.setTopLevelNavigator(navigatorRef);
      }}>
      <PopUpBox okClick={() => dispatch(dispatchFunc())} />
      {!login ? (
        <NavStack
          ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef);
          }}
        />
      ) : (
        <NavStack2
          ref={navigatorRef => {
            NavigationService.setTopLevelNavigator(navigatorRef);
          }}
        />
      )}
..... remaining code as it is....

Property of ‘toLowerCase’ of undefined

That’s the code

const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});

let database = await lib.googlesheets.query['@0.3.0'].select({
  range: `A:D`,
  bounds: 'FULL_RANGE',
  where: [
    {
      ID__icontains: `${context.params.event.author.id}`,
    },
  ],
  limit: {
    count: 0,
    offset: 0,
  },
});
let initialLevel = 0;
let points = 10;
let level = 0;
if (database.rows.length !== 0) {
  initialLevel = database.rows[0].fields['Level'];
  points = parseInt(database.rows[0].fields['Points']) + parseInt(1);
  level = Math.floor(points / 50);
}
let timeout = await lib.utils.kv['@0.1.16'].get({
  key: `timeout`,
  defaultValue: false,
});
let zero = null;
let badWordList = process.env.UNWANTED_WORDS.split(', ').join('|');
let badWordsRegex = new RegExp(badWordList, 'gi');
let roleloc = zero || '';
let roleid = zero || '';
let role = zero || '';
console.log(context.params.event.content.match(badWordsRegex));
if (!context.params.event.content.match(badWordsRegex)) {
  if (!timeout) {
    if (database.rows.length === 0) {
      await lib.googlesheets.query['@0.3.0'].insert({
        range: `A:D`,
        fieldsets: [
          {
            ID: `${context.params.event.author.id}`,
            Username: `${context.params.event.author.username}`,
            Level: `0`,
            Points: `1`,
          },
        ],
      });
    } else {
      await lib.googlesheets.query['@0.3.0'].update({
        spreadsheetId: process.env.SPREADSHEET_ID,
        range: `A:D`,
        bounds: 'FULL_RANGE',
        where: [
          {
            ID__icontains: `${context.params.event.author.id}`,
          },
        ],
        limit: {
          count: 0,
          offset: 0,
        },
        fields: {
          Username: `${context.params.event.author.username}`,
          Level: level,
          Points: points,
        },
      });
      if (level > initialLevel) {
        await lib.discord.channels['@0.1.0'].messages.create({
          channel_id: context.params.event.channel_id,
          content: `Great job <@${context.params.event.author.id}>, you moved up a level! Your new level is: **${level}**! To get more details, type _${process.env.PREFIX}level_!`,
        });
      }
      await lib.utils.kv['@0.1.16'].set({
        key: `timeout`,
        value: true,
        ttl: 5,
      });
    }
  }
}
//if you would like, you can change the prefix of the following prefix command
if (context.params.event.content.startsWith(`${process.env.PREFIX}status`)) {
  if (database.rows.length === 0) {
    await lib.discord.channels['@0.1.1'].messages.create({
      channel_id: `${context.params.event.channel_id}`,
      content: '',
      tts: false,
      embed: {
        type: 'rich',
        title: `${context.params.event.author.username}#${context.params.event.author.discriminator}'s  Level:`,
        description: '',
        color: 0x9b21ff,
        thumbnail: {
          url: `https://cdn.discordapp.com/avatars/${context.params.event.author.id}/${context.params.event.author.avatar}.png`,
          height: 0,
          width: 0
        },
        fields: [
          {
            name: 'Level:',
            value: '0',
          },
          {
            name: 'Points:',
            value: '1',
          },
        ],
      },
    });
  } else {
    await lib.discord.channels['@0.1.1'].messages.create({
      channel_id: `${context.params.event.channel_id}`,
      content: '',
      tts: false,
      embed: {
        type: 'rich',
        title: `${context.params.event.author.username}#${context.params.event.author.discriminator}'s  Level:`,
        description: '',
        color: 0x9b21ff,
        fields: [
          {
            name: 'Level:',
            value: level,
          },
          {
            name: 'Points:',
            value: points,
          },
        ],
      },
    });
  }
}

//autorole part
let roles = process.env.LEVEL_ROLE_IDS.split(', ');
let lev10 = roles[0];
let lev25 = roles[1];
let lev50 = roles[2];
if (points === 500) {
  await lib.discord.guilds['@0.1.0'].members.roles.update({
    role_id: `${lev10}`,
    user_id: `${context.params.event.author.id}`,
    guild_id: `${context.params.event.guild_id}`,
  });
}
if (points === 1250) {
  await lib.discord.guilds['@0.1.0'].members.roles.update({
    role_id: `${lev25}`,
    user_id: `${context.params.event.author.id}`,
    guild_id: `${context.params.event.guild_id}`,
  });
}
if (points === 2500) {
  await lib.discord.guilds['@0.1.0'].members.roles.update({
    role_id: `${lev50}`,
    user_id: `${context.params.event.author.id}`,
    guild_id: `${context.params.event.guild_id}`,
  });
}

And the error says:
{
“error”: {
“message”: “Cannot read property ‘toLowerCase’ of undefined (googlesheets/[email protected]/select)”,
“stack”: “Error: Cannot read property ‘toLowerCase’ of undefined (googlesheets/[email protected]/select)n at IncomingMessage. (/bundled_node_modules/lib/lib/request.js:116:21)n at IncomingMessage.emit (events.js:412:35)n at endReadableNT (internal/streams/readable.js:1333:12)n at processTicksAndRejections (internal/process/task_queues.js:82:21)”
}
}
Error completing request

I tried to fix it but I don’t know what to do :C Help please
I’m using autocode.com for discord bot and for the database is google sheets.

Part of a cancel swipe function added to an HTML5 based eBook is breaking the text input field for a note taking input

I’m working on developing the process for creating HTML5 based eBooks intended for both desktop and mobile use made with Adobe Indesign and exported with a plugin called In5, that allows for appending html, css, and javascript on export. The issue I’ve encountered is that part of the smooth swipe JS/JQuery code i found on the In5 forums breaks the text input field on desktop browsers (though for some reason not on iPad.)

$(function(){
  $("#container").swipe("destroy");
  var pageWidth = parseInt($(".page").width());
  var pageChangeThreshold = pageWidth*.001;
  var pageWrap = $('.pages'), startPos, vertMode = false,
  nextProp = 'left', backProp = 'right', moveProp = 'left';
  
var cancelSwipe = function(){                                       //This Function breaks the note taking for some reason, changing name does not fix. removing the function totally breaks the swiping
pageWrap.animate({left:startPos+'px'}, 'fast');
};


  $("#container").swipe({
          allowPageScroll: (vertMode ? 'horizontal' : 'vertical'), fingers:1, 
          excludedElements:$.fn.swipe.defaults.excludedElements+',.mejs-overlay-button,map,[onclick],[data-useswipe="1"],[data-tapstart="1"], .panzoom,.scroll-horiz',
        swipeStatus:function(event, phase, direction, distance, duration, fingers) {
            switch(phase){
                case 'start':
                    startPos = parseInt(pageWrap.css(moveProp));
                    break;
                case 'end':
                    if(distance > pageChangeThreshold){
                        switch(direction){  
                            case nextProp:
                                if(nav.current < nav.numPages) nav.next();
                                else cancelSwipe();
                                break;
                            case backProp:
                                if(nav.current > 1) nav.back();
                                else cancelSwipe();
                                break;
                        }

                    } else {
                        cancelSwipe();
                    }

                    break;

                case 'move':            
                    switch(direction){
                        case nextProp:
                            pageWrap.css(moveProp, (startPos-distance)+'px');
                            break;
                        case backProp:
                            pageWrap.css(moveProp, (startPos+distance)+'px');
                            break;
                    }

                    break;

                case 'cancel':          //These lines of code seem to break the pop-out menu on iOS, renamed from 'cancel' to 'cancelSwipe' seems to have fixed this
                    cancelSwipe();
                    break;
            }
        },
        
        threshold:4,
        maxTimeThreshold:4000
    });
})

The specific line in question seems to be:

pageWrap.animate({left:startPos+'px'}, 'fast');

Here is the code we created for the note taking app:

    <div class="allnotes">
    <input type="text" id="textInput"><button id="add" class="addButton"></button>
        <hr>
        <div id="notes" class="notes"></div>
        <script>
            function get_notes() {
                var notes = new Array;
                var notes_str = localStorage.getItem('note');
                if (notes_str !== null) {
                    notes = JSON.parse(notes_str);
                }
                return notes;
            }
            function add() {
                var textInput = " <button id="goto" +$('.page').attr('data-name')+"" class="gotopagebutton">pg. "+$('.page').attr('data-name')+"</button>"+document.getElementById('textInput').value;
                var notes = get_notes();
                notes.push(textInput);
                localStorage.setItem('note', JSON.stringify(notes));
                shownotes();
                return false;
            }
            function remove() {
                var id = this.getAttribute('id');
                var notes = get_notes();
                notes.splice(id, 1);
                localStorage.setItem('note', JSON.stringify(notes));
                shownotes();
                return false;
            }
            function gotopage(destinationpageNumber) {
                var currentpagenumber = $('.page').attr('data-name');
                currentpagenumber = parseInt(currentpagenumber);
                destinationpageNumber = parseInt(destinationpageNumber.split(' ')[1]);
                var distance = destinationpageNumber - currentpagenumber;
                var offset = currentpagenumber - nav.current;
                nav.to(nav.current+distance);
                // if (distance == 0) {
                //     go(event,[{n:1,id:96334,act:'reverse'},{n:1,id:96324,act:'reverse'}]);
                // }
            }
            function shownotes() {
                var notes = get_notes();
                var html = '<ul>';
                for (var i = 0; i < notes.length; i++) {
                    html += '<li>' + notes[i] + " " + '<button class="remove" id="' + i + '">x</button></li>';
                };
                html += '</ul>';
                document.getElementById('notes').innerHTML = html;
                var removebuttons = document.getElementsByClassName('remove');
                for (var i = 0; i < removebuttons.length; i++) {
                    removebuttons[i].addEventListener('click', remove);
                };
                var gotopagebuttons = document.getElementsByClassName('gotopagebutton');
                for (var i = 0; i < gotopagebuttons.length; i++) { 
                    gotopagebuttons[i].addEventListener('click', gotopage.bind(null, gotopagebuttons[i].innerHTML));
                };
                
            }
            document.getElementById('add').addEventListener('click', add);
            shownotes();
        </script>
</div>

Could anyone help diagnose why the .animate function would break the selecting or focus of the text input field or provide another method to cancel a swipe on a touch screen device (i.e. iPad or windows tablet)?

Heres a sample page exported showing the issue.

Iterating over array of objects using forEach

Trying to return a new array of objects that have the name and index from the original array. The solution should be as follows:

[{name: 'Jane', index: 1}, {name: 'mark', index: 3}, {name: 'sophia', index: 4}]

—

let array = [
        {a: 2},
        {name: "jane"},
        {},
        {name: 'mark'},
        {name: 'sophia'},
        {b: 1}
    ]

function somefunction (somearr) {
    newarray = [];
    somearr.forEach(element, index => {
        if (element.name != null) {
            let newobj = {}
            newobject.name = element.name
            newobject.index = index
            newarray.push(newobj)
        }
    })
    console.log(newarray)
}

somefunction(array)

I am getting the following error:

Process exited with code 1
Uncaught ReferenceError ReferenceError: element is not defined
    

why getIntExtra() is always default value

at first my declaration is:

     public static final String EXTRA_TEXT="com.example.application.example.EXTRA_TEXT";
    public static final String EXTRA_NUMBER="com.example.application.example.EXTRA_NUMBER";
**my MainActivity get number and text:**

        public void openActivity2(){
            EditText editText1 = (EditText) findViewById(R.id.edittext1);
            String text = editText1.getText().toString();
            EditText editText2 = (EditText) findViewById(R.id.edittext2);
            String number = (editText2.getText().toString());

          
          Intent intent = new Intent(this, Activity2.class);
            intent.putExtra(EXTRA_TEXT, text);
            intent.putExtra(EXTRA_NUMBER, number);
            startActivity(intent);
        }
    }

my Activity2 should get the number and text:

 protected void onCreate(Bundle savedInstanceState) {
        .......
        Intent intent=getIntent();
        String text = intent.getStringExtra(MainActivity.EXTRA_TEXT);
        int num=intent.getIntExtra(MainActivity.EXTRA_NUMBER,0);

The text is well received,
but the number value is always 0.

when using svg in react its gives me error everytime

I created an SVG using adobe illustrator But when trying to add to the project it just gives an error and the same goes with SVG I created with SVGator in short every single SVG gives me an error but using in bare HTML project its runs perfectly.

can anyone guide me on how to use SVG to react

errors I got

  1. SVG with Adobe

    <style>.cls-1{fill:url(#a);}</style>
    

after adding {} as it suggested gives me this

Private names are only allowed in property accesses (`obj.#a`) or in `in` expressions 
 <style>.cls-1{{fill:url(#a)}}</style>
  1. Error when SVG is downloaded from the website

    Compiled with problems:

     ERROR
    
     [eslint]
     srccomponentscommonRegisterSvg.js
       Line 8:32256:  Parsing error: Unexpected token (8:32256)
    
  2. When Adding Animated SVG this is just a part of an error

How to convert obtuse string to a javascript Date in Angular 12?

While using Angular 12 I have a date as a string in a very custom format, from which I need to produce a Date object. An example of the date strings I have are:

20280328
20271201

To the human eye, these are obviously in the format yyyyMMdd however none of the standard parse functions appear to understand this (not unexpected.)

Other than simply breaking the string using substring, is there a better way to interpret these strings into a Date object?

I was hoping to be able to provide a custom input format for the .parse() function, but this does not appear to be available.

Mongoose convert field before find

In my mongodb database I have a collection named Bookings in the model there is a field named periodFrom (representing a date in a string) which is of type String.

I need to find the documents in this collection which have a periodFrom greater than today’s date. I tried using virtuals but it did not work.

Here is an example of a few documents in my Bookings collection :

{"name": "A", "periodFrom": "29.04.2022 10:00", "place": "Tokyo"},
{"name": "B", "periodFrom": "30.06.2022 10:00", "place": "Paris"}  
{"name": "C", "periodFrom": "28.04.2022 10:00", "place": "Berlin"},
{"name": "D", "periodFrom": "01.07.2022 10:00", "place": "London"}

My bookingSchema :

const bookingSchema = new Schema({
name: {type: String}, 
periodFrom: {type: String},
place: {type: String}
})

I tried virtuals by adding at the end of my model booking.js

bookingSchema.virtual('periodFromDate').get(function () {
    return new Date(this.periodFrom.split(' ')[0].split('.')[2].toString() + "-" + this.periodFrom.split(' ')[0].split('.')[1].toString() + "-" + this.periodFrom.split(' ')[0].split('.')[0].toString())

const Booking = mongoose.model("Booking", bookingSchema);
});

I tried the request by doing the following :

let allCrew = await Booking.find({ periodFromDate: { $gte: Date.now() } })

I also tried this way but it was not working either:

let allCrew = await Booking.find({ periodFrom: { $gte: '2022.07.01 00:00' } })

So any ideas how I could find the documents that have a periodFrom greater than today’s date if periodFrom is a string of a date in mongoose?

How to convert Nodejs counter readable stream example to simplified construction version?

I refer to this doc

https://nodejs.org/api/stream.html#simplified-construction

The _construct() method is never called in my version. Why?

This is a working class version of a readable stream counter example:

const { Readable } = require('stream');

class Counter extends Readable {
  constructor(options) {
    super(options);
    this._max = 10;
    this._index = 1;
  }

  _read() {
    const i = this._index++;
    if (i > this._max) {
      this.push(null);
    } else {
      const str = String(i);
      const buf = Buffer.from(str, 'utf-8');
      this.push(buf);
    }
  }
}

const readable = new Counter();

readable.on('readable', function() {
  console.log('readable');

  let data;

  while ((data = this.read()) !== null) {
    console.log(String(data));
  }
});

readable.on('close', function() {
  console.log('close');
});

This is my not working simplified construction version:

const { Readable } = require('stream');

const counter = new Readable({

  construct() {
    this._max = 10;
    this._index = 1;
    console.log(this._max); // This is never executed
  },

  read() {
    console.log(this._max); // This is undefined
    this.push(null);
  }

  // read() {
  //   const i = this._index++;
  //   if (i > this._max) {
  //     this.push(null);
  //   } else {
  //     const str = String(i);
  //     const buf = Buffer.from(str, 'utf-8');
  //     this.push(buf);
  //   }
  // }

});

counter.on('readable', function() {
  let data;

  while ((data = this.read()) !== null) {
    console.log(String(data));
  }
});

counter.on('close', function() {
  console.log('close');
});

The docs say:

const { Writable } = require('node:stream');

const myWritable = new Writable({
  construct(callback) {
    // Initialize state and load resources...
  },
  write(chunk, encoding, callback) {
    // ...
  },
  destroy() {
    // Free resources...
  }
});

Now I’m confused. Thought initialization code belongs into the _construct() method?

Remove core-js from nextjs bundle

I am trying to reduce nextjs project’s bundle sizes. There is a core-js bundle for polyfills. I want to remove this core-js from the main bundle size. It has 50KB of size.

I tried to use custom babel configuration like this:

    {
        "presets": [
            [
                "next/babel",
                {
                    "useBuiltIns": "usage",
                    "corejs": "3"
                }
            ]
        

]
}

But it didn’t help.

How can I remove the corejs from a NextJS project?

Any help will be appreciated.

Thanks

debounce closure shared by two functions

i am implementing debounce function. and i was able to successfully write the function then a confusing thought came to mind.

    function debounce(fn, timeout) {
        let timeoutRef;
        return function (...args) {
            const context = this;
            function cb() {
                fn.apply(context, args);
            }
            clearTimeout(timeoutRef);
            timeoutRef = setTimeout(cb, timeout);
        };
    }
    
    function foo() {
        console.log('foo is called');
    }
    function bar() {
        console.log('bar is called');
    }
    const debouncedFoo = debounce(foo, 10000);
    const debouncedBar = debounce(bar, 2000);
    
    debouncedFoo();  
    debouncedBar();

in the above code, don’t debouncedFoo and debouncedBar share same colsure variable timeoutRef ?

if that’s the case when debouncedFoo() it assigns setTimeout call reference to timeoutRef variable.
And later when debouncedBar() called previous timeoutRef set by debouncedFoo() call should be be cleared and new setTimeout call reference should be assigned.

in conclusion,

expected result:

bar is called

actual result:

foo is called
bar is called 

can someone please help me understand this ?