google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error

I am trying to add Google place auto suggest, I copied the code from the developer’s website to try it out but got the error :
google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead.
Also I am not getting any place suggestions.

https://developers.google.com/maps/documentation/javascript/places-autocomplete

google.maps.event.addDomListener(window, 'load', initializeAutocomplete);

i have also added script
<script src="https://maps.googleapis.com/maps/api/jskey=api_key&libraries=places"></script>

I have implemented the same thing in one html it worked successfully, but when I used it on click button which opens a popup (form which has place-input), it gave me this error.

Note : I have also tried addEventListener but that’s giving me an error : google.maps.event.addEventListener is not a function

Do you have any idea why I am getting this error, and how can I fix this?

Accessing property in an object

Consider this code snippet

class A {
  constructor() {
    this._elem = 5;
  }

  get elem() {
    return this._elem;
  }
}

class B {
  constructor() {
    this._elem = 6;
  }
}

class C extends A {
  constructor() {
    super();
  }
}

class D {
  constructor() {}
}

const a = new A();
const b = new B();
const c = new C();
const d = new D();

function foo(obj, name) {
  const val = 'elem' in obj ? obj.elem : 42;
  const val2 = obj.elem ? obj.elem : 42;
  console.log(`For ${name} val: ${val}, val2: ${val2}`);
}

foo(a, 'a');
foo(b, 'b');
foo(c, 'c');
foo(d, 'd');

I was trying to figure out if there ever could be a case where directly using obj.elem when the property elem doesn’t exist on obj could lead to incorrect logic vis-à-vis doing a check for "elem" in obj and access it only if it exists and use the value. It seems like val and val2 would always be the same. Are both equivalent?

Globals from jest-preset are not available in tests

I’m trying to upgrade jest from v27 to v28. In my test files when I try to access GLOBAL_VARIABLE that is specified in jest-preset file I have this error

ReferenceError: GLOBAL_VARIABLE is not defined

package.json

"jest": "~28.0.0",
"ts-jest": "~28.0.0-next.3"

my jest-preset file looks like this

module.exports = {
    verbose: true,
    transform: {
        '^.+\.(ts|tsx)$': 'ts-jest/legacy',
    testEnvironment: 'node',
    globals: {
        'ts-jest': {
            tsconfig: '<rootDir>/scripts/jest/tsconfig.json',
            isolatedModules: true,
        },
        GLOBAL_VARIABLE: true
    },
},

When running this with jest v27 it works as expected

Regex for parsing filter expressions

I am trying to build a helper class that can parse filter expressions as defined here https://developer.sas.com/reference/filtering/

Some examples would be:

eq(name,"item 1")

or(eq(name,"item 1"),eq(published,"1"))
or(eq(name,"item 1"),eq(published,"1"),neq(foo,"bar"))

and(or(eq(name,"item 1"),eq(published,"1"),neq(foo,"bar")))

I am struggling to figure out the regex pattern. So far I have [a-zA-Z]+(([^)]*)) but this doesn’t pick up on the first nested expression

EG if I use this funciton to get all matches:

function getRegexMatches(regex, str) {
  const matches = [];
  let match;
  while ((match = regex.exec(str))) {
    matches.push(match[0]);
  }
  return matches;
}

console.log(
  getRegexMatches(
    /[a-zA-Z]+(([^)]*))/gm,
    'eq(foo,"bar")'
  ),
  getRegexMatches(
    /[a-zA-Z]+(([^)]*))/gm,
    'or(eq(name,"item 3"),eq(published,"1"))'
  )
);

Output

[ 'eq(foo,"bar")' ]
[ 'or(eq(name,"item 3")', 'eq(published,"1")' ]

Should be

[ 'eq(foo,"bar")' ]
[ 'or(eq(name,"item 3"),eq(published,"1"))', 'eq(name,"item 3")', 'eq(published,"1")' ]

How do I add a onclick event listener to all of my dynamically created rows?

I am creating some dynamic rows in my table and attaching onclick listener to them:

var i=0;

while(i!=5){
    var row=table.insertRow(table.rows.length);
    var cell=row.insertCell(0);
    var cell1=row.insertCell(1);
    var cell2=row.insertCell(2);
    var cell3=row.insertCell(3);
    var cell4=row.insertCell(4);
    var cell5=row.insertCell(5);

    row.style.cursor="pointer";
    row.addEventListener("click",f1);

    i+=1;
}

function f1(){
    console.log(true);
}

But no matter how many times I click on the row, the event never gets triggered. Where am I going wrong here? Please help me

Load Page using AJAX in Oxygen Builder WordPress

I currently using Oxygen Builder in WordPress, I wanna make link when I click on that, the right column div is loaded with another page using AJAX, and I very very noob in AJAX (sorry for it). So, I follow the tutorial

from this site :
https://sridharkatakam.com/how-to-dynamically-load-posts-on-click-using-ajax-in-genesis/
and this site : https://wpmudev.com/blog/load-posts-ajax/.

Combined their code together because it might be appropriate with my goal, because in sridhar’s site load the post not page. FYI, in the oxygen builder, I load the page title (link) and the whole page using Easy Post which is same to a repeater. Then, the Easy Post is inside the Column which divided 2 into 50:50 of size. The left column shows the link which when clicked the right column is loading the whole page.

Here’s the screenshot :

screenshot

Then here’s my goal looks like :

https://www.youtube.com/watch?v=UZRiiVQN3d4

So, here’s the code i wrote :

PHP (inside the left column of easy post)

printf( '<div><a href="%s" class="post-link" data-id="%s">%s</a></div>',
    esc_url( get_the_permalink() ),
    get_the_ID(),
    esc_html( get_the_title() )
);

PHP (inside the left column of easy post)

wp_enqueue_script(
    'ajax-loadpage',
    get_stylesheet_directory_uri() . '/js/ajax-loadpage.js',
    array( 'jquery' ),
    '1.0',
    true
);

wp_localize_script(
    'ajax-loadpage',
    'ajaxloadpage',
    array(
        'ajaxurl'       => admin_url( 'admin-ajax.php' ),
    )
);

Function.php

add_action( 'wp_ajax_nopriv_ajax-loadpage', 'ajax-load-page' );
add_action( 'wp_ajax_ajax-loadpage', 'ajax-load-page
function ajax-load-page() {
echo get_bloginfo( 'title' );
die();
}

AJAX-loadpage.js (I put in the JS folder according to the Tutorial)

(function ($) {

$(document).on('click', 'div a', function (event) {
    event.preventDefault();

    $.ajax({
        // URL to which request is sent.
        url: ajaxloadpage.ajaxurl,

        // specifies how contents of data option are sent to the server.
        // `post` indicates that we are submitting the data.
        type: 'post',

        // data to be sent to the server.
        data: {
            // a function defined in functions.php hooked to this action (with `wp_ajax_nopriv_` and/or `wp_ajax_` prefixed) will run.
            action: 'ajax-loadpage',
            
            query_vars: ajaxloadpage.query_vars,
            
            page: page

        },
        
        beforeSend: function() {
            $(document).scrollTop();

        },
        
        // function to be called if the request succeeds.
        // `response` is data returned from the server.
        success: function (response) {
            $('.content > .entry .entry-content').hide().html(response).fadeIn('slow');
        }
    })
})

})(jQuery);

Then, the formula returned to :

Uncaught ReferenceError: page is not defined
  at HTMLAnchorElement.<anonymous> (ajax-loadpage.js?ver=1.0:21:17)
  at HTMLDocument.dispatch (jquery.min.js?ver=3.6.0:2:43064)
  at HTMLDocument.v.handle (jquery.min.js?ver=3.6.0:2:41048)

after inspected in chrome and when i click to the link, it didn’t load the targeted Page at all 🙁

Does any webmaster here know how to save my insomnia? Thank you so much.

blogs.map is not a function error in next.js app

import Head from 'next/head'
import { useState } from 'react'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

const Home = (props) => {
  const [blogs, setblogs] = useState(props.data);

  return <div className={styles.container}>
    <Head>
      <title>BlogsWap</title>
      <meta name="description" content="New App" />
      <link rel="icon" href="/favicon.ico" />
    </Head>

    <main className={styles.main}>
      <h1 className={styles.title}>
        Welcome to <a href="https://nextjs.org">BlogsWap!</a>
      </h1>

      <p className={styles.description}>
        An all time blog for coders!
      </p>
      {blogs.map((blogitem) => {
        return <div className={styles.grid}>
          <a href="https://nextjs.org/docs" className={styles.card}>
            <h2>{blogitem.title} &rarr;</h2>
            <p>{blogitem.content}</p>
          </a>

        </div>
      })}

    </main>

    <footer className={styles.footer}>
      <a
        href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
        target="_blank"
        rel="noopener noreferrer"
      >
        &copy; BlogsWap
        <span className={styles.logo}>
        </span>
      </a>
    </footer>
  </div>

}
export async function getServerSideProps(context) {
  let totalBlogs = await fetch('http://localhost:3000/api/blogs');
  // console.log(totalBlogs)
  let data = await totalBlogs.json();
  return {
    props: { data }, // will be passed to the page component as props
  }
}

export default Home

I am getting error like:

TypeError: blogs.map is not a function

What should I do? I have no idea why it appeared because,
recently I have used similar method but it all was fine
now it throwing such error!
Please help me in to get the error out!

Here is the photo of the error 🙁

Photo of the error occured

How do you use functions in a different js file in phaser 3?

Im trying to create a js file with functions relevant to my game but i get an error message saying

Uncaught TypeError: Cannot read properties of undefined (reading ‘add’)

when i try to use phaser functions outside of the main file.

I have 2 files one called game.js and one called test.js. I am also using the matter physics engine.

game.js :

class bootScene extends Phaser.Scene {
    
    //Preloading assets for later use
    preload() {
                this.load.image('linus', 'assets/linus.png');
        this.load.script('t','test.js')

    }

    create() {
        

    }

    update() {
        //launch game scene
        this.scene.launch('game').stop();
    }
}


class playScene extends Phaser.Scene {

    constructor() {
        super('game');
        
    }

    create() {


        test('test',1,1,'linus')

    };


    update() {

}

// set the configuration of the game
let config = {
    type: Phaser.WEBGL, // Phaser will use WebGL if available, if not it will use Canvas
    width: 1280,
    height: 720,
    pixelArt: true,
    transparent: false,
    autoCenter: true,
    backgroundColor: '#000000',
    physics: {
        default: 'matter',
        matter: {
            restingThresh: 2,
            // debug: {
            //     renderFill: false
            // },
            gravity: {
                y: 0
            }
        }
    },
    scene: [bootScene, playScene]

};

// create a new game, pass the configuration
let game = new Phaser.Game(config);

test.js:

function test(msg,x,y,texture)
{
    console.log(msg)
    this.matter.add.image(x,y,texture)
}

I have tried trying to put t.test(etc.) and adding the load script in preload. I tried looking up examples but I couldnt find any.

Sorry if this is a really obvious fix or im just terrible

Webpack – Bundling multiple js files with respect to resusable methods and variable from one another

I am trying to bundle around 10+ javascript files of my application which are loaded as scripts in the index.html file. They are properly sequenced as per their dependencies with one another.

<script src="/js/main.js"></script>
<script src="/js/user.js"></script>
<script src="/js/contact.js"></script>
...

The code inside each file looks like this:

// main.js
const _main = {};
_main.MethodOne = function(){
  ...
}

// user.js
const _user = {};
_user.MethodTwo = function(){
  // Can access the method from main.js file
  _main.MethodOne();
}

// contact.js
const _contact = {};
_contact.MethodThree = function(){
  // Can access the methods from main.js & user.js file
  _user.MethodTwo();
  _main.MethodOne();
}

Now, when bundling them through webpack, the constant variables _main, _contact & _user gets renamed to some random letters. However, the names used to invoke those methods from other files remain the same in each case i.e. _user.MethodTwo(), _main.MethodOne() doesn’t change.

This is my webpack.config.js

entry: {
    vendors: [
        './public/js/colorpicker.js',
        ...
    ],
    app: [
        './public/js/main.js',
        './public/js/user.js',
        './public/js/contact.js'
    ]
},
mode: 'production',
output: {
    filename: 'js/[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
    publicPath: 'auto',
    assetModuleFilename: 'img/[hash][ext][query]'
},

I read the webpack documentation however didn’t get any clue about this problem.

Python Scrapy Web Scraping : problem with getting URL inside the onclick element which has ajax content

I am beginner for the web scraping with scrapy . I try to scrape user reviews for specific book from goodreads.com . I want to scrape all of the reviews about book so i must parse every review page . There is a next_page button below the every review page , content of the next_page button embedded in the onclick element but there is a problem . This onclick link include the ajax request and i dont know how to handle this situation . Thanks for your help in advance.

Picture of the next_page button

Its the content of onclick button

Its the remaining part of the onclick button

I am also beginner for the posting stackoverflow and i am sorry if i have any mistake. 🙂

Trigger Mutation observer CB function?

I am writing a user script that requires a mutation observer but also requires the CB function to execute at least once. I hate that I have to write code like

const mut = new MutationObserver(foo);
foo();
// My foo/0 doesn't return anything so I can also write
const mut = new MutationObserver(foo() || foo);

But is there a better way to write this code without triggering a mutation or calling the function directly?

How to track when all elements of a webpage have been viewed, clicked or changed

I am fairly new to react and i’m trying to implement some code in my application which will track when a user has interacted with any of the elements in the webpage. Any clicks, views or changes in value must be captured and stored.

I have tried adding event-listeners to all the elements in the page but surely there has to be a more efficient way of achieving this? Any ideas?

Need help to Write an efficient algorithm function

Need help with Write an efficient algorithm function:
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. the small frog always jumps a fixed distance, D.

Count the minimal number of jumps that the small frog must perform to reach its target.

Write a function:

class Solution { public int solution(int X, int Y, int D); }

That, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

For example, given:

X = 10
Y = 85
D = 30

The function should return 3, because the frog will be positioned as follows:

  • after the first jump, at position 10 + 30 = 40
  • after the second jump, at position 10 + 30 + 40 = 70
  • after the third jump, at position 10 + 30 + 30 + 30 = 100

Write an efficient algorithm for the following assumptions:

* X,Y and D are integers within the range [1..1,000,000,000];
* X <_ Y.

Thank you for the help.