Datepicker not working on javascript generated html

With jquery, i append some html form inputs to my site on a button click, like these:

html  += '<div class="form-group my-4">';
    html += '<span class="left">Date of ending work <span class="carer_help">Required format: 01-01-2000</span></span>';
    html += '<span class="left"><input class="form-control datepicker" type="text" required="required" name="work_end[' + works_row_melleklet + ']" value="'+work_end+'" /></span>';
html += '</div>';

You can see, that the input have the datepicker class.
But my problem is, that the datepicker calendar isnt showing up. I think, because the html input, where i wanna use the calendar, is not in the site’s source, its just added by javascript on button click.

How can i fix this?

 $('.datepicker').datepicker({
        format: 'dd-mm-yyyy',
        language: 'en',
        autoclose: true,
        todayHighlight: true
    });

atleast one of the value’s in the array1 obj “data” array matches the “data” array in array2 object

at least one of the value’s in the array1 obj “data” array matches the “data” array in array2 object


> array1

array1 = [
  {
      id: '1',
      name: 'ron',
      data: ['p1']
  },
  {
      id: '2',
      name: 'lon',
      data: ['p2']
  },
{
      id: '3',
      name: 'voon',
      data: ['p4']
  }
];


> array2

array2 = [
  {
      id: '1',
      name: 'fgr',
      data:['p1','p2','p3']
  },
  {
      id: '2',
      name: 'gone',
      data:['p1','p2','p3']
  }
]


output: {
id: ‘1’,
name: ‘ron’,
data: [‘p1’]
},
{
id: ‘2’,
name: ‘lon’,
data: [‘p2’]
}

how to resolve the warning: AudioContext was not allowed to start. while playing songs in the loop

I’m trying to make loop options in the audio player (using wavesurfer.js) I have made a button for a loop. when use hits the button the loop mode turns on and after finishing the current song next, the next song plays itself. But the problem is that when next song has loaded the browser give me the following warning:

The AudioContext was not allowed to start. It must be resumed (or
created) after a user gesture on the page.

how can this issue be solved?

here is my jQuery code:

var playcounter = false;
      $("#playAll").click(function(){
        $(this).toggleClass('play-all-btn2');
        playcounter = !playcounter;
      });
      wavesurfer.on('finish', function () {
        if(!playcounter){
          wavesurfer.stop();
        }else{
          songAdrr++;
          songAdrr1 = songAdrr;
          songlinktest = $(".player-playlist .songlink").eq(songAdrr).attr('href');
          if (typeof songlinktest === 'undefined') { //if no song found, stop loading song
            wavesurfer.stop();
            wavesurfer.cancelAjax();
            songAdrr--;
            songAdrr1 = songAdrr;
          }else{
            $(".wavetest").show();
            $(".player-playlist .player-song-detail .wavetest").eq(songAdrr).hide();
            $(".player-playlist .player-song-detail #songwave").remove();
            $(".player-playlist .player-song-detail #testdiv").eq(songAdrr).append("<div id='songwave'> </div>");
            wavesurfer = WaveSurfer.create({
              container: '#songwave',
              waveColor: '#CCCCCC',
              progressColor: '#E64C51',
              barWidth:2,
              height:40,
              barGap:2,
              backgroundColor: 'transparent'
          });
            wavesurfer.load(songlinktest);
            wavesurfer.play();
            wavesurfer.stop();
          }
          
        }
        if (songAdrr > 0) {
          $("#preSong").prop('disabled', false);
        }
        if (songAdrr == totalSongs) {
          $("#nextSong").prop('disabled', true);
        }

      });

Django STATIC FILES not loading in actual Production

I have tried many things to solve this like adding whitenoise middleware, also added STATICFILES_DIRS = [], added mimetypes for css
in settings.py file CSS/JS Won’t load.

Here is my settings.py

from pathlib import Path
import environ
import mimetypes

mimetypes.add_type("text/css", ".css", True)

BASE_DIR = Path(__file__).resolve().parent.parent

env = environ.Env()
environ.Env.read_env()

STRIPE_PUB_KEY = env('STRIPE_PUB_KEY') 

DEBUG = True

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'users',
    'addresses',
    'orders',
    'feedback',
    'message',
    'gifts_coupons',
    'core',
    'product',
    'fulfillment',
    'cart',
    'discounts',
    'stripe_pay',
    
    'rest_framework',
    'rest_framework.authtoken',
    'phonenumber_field',
    'django_filters',
    'creditcards',
    'mptt',
    'corsheaders',
    'import_export',
    'django_inlinecss',
]

IMPORT_EXPORT_USE_TRANSACTIONS = True

AUTH_USER_MODEL = 'users.User'

# If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect
CORS_ALLOW_ALL_ORIGINS = True 


# TODO: Change urls while going online

CORS_ALLOWED_ORIGINS = [
    'https://estreetmart.in',
    'https://estreetmart.sg',
    'https://ims.estreetmart.in',
    'http://localhost:8000',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'orders.middlewares.cart_middleware',
]

ROOT_URLCONF = 'estreetmart.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'estreetmart.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '5432',
    },
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_ROOT = BASE_DIR / 'media'

MEDIA_URL = '/media/'

STATIC_URL = '/static/'

STATIC_ROOT = BASE_DIR / 'static'

I also added following in my main urls.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

but still css/js is not loading so I inspected the code and found following:
403 Forbidden error for static file

and also sources is empty:
Sources are empty

nextjs: Warning: Prop `className` did not match. Server: “x” Client: “y”

This is my code:

export default function Nav() {
    const { userLogin } = useUser()
    console.log(userLogin)
    
    return (
        <nav className={styles.nav}>
            {!userLogin ? (
                <Link href={"/login"}><a className={`${styles.top}`}></a></Link>
            ) : (
                <Link href={"/profile"}><a className={`${styles.userLogged}`}></a></Link>
            )}
        </nav>
    )
}

And this is useUser:

export default function useUser(){
    var userLogin = false

    const cookies = parseCookies()
    if (cookies.token) {
        userLogin = true
    }

    return { userLogin }
}

So, if userLogin is false, everything is OK.

But if userLogin is true I get this error:

Warning: Prop `className` did not match. Server: "x" Client: "y"

This error show when I use cookies.

I don’t want to use next/dynamic. because dynamic reload component again on click.

Can’t place a background image in next JS and Tailwind CSS

I’m stuck and can’t place the background image on my next JS app
Here is My Code
globals.css

    padding: 0 2rem;
    background-image: url(../public/images/landing-page-illustration.svg);
}
```
**index.js**
```import Head from 'next/head'
import Image from 'next/image'
import Navbar from '../components/navbar';
import styles from '../styles/Home.module.css'

export default function Home() {
  
  return (
    <div className={styles.container}>
      
       
      <Navbar/>
    </div>
  );
}

I get this error trying to install canvas

I’ve been trying to install canvas for a NFT generator, but it everytime I try to do it, I get this error. what do you think is the problem? what am I supposed to do?

THE ERROR :

npm ERR! code 6
npm ERR! path C:UsersKeramDesktopgenerative-art-node-mainnode_modulescanvas
npm ERR! command failed
npm ERR! command C:Windowssystem32cmd.exe /d /s /c node-pre-gyp install –fallback-to-build
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using [email protected]
npm ERR! node-pre-gyp info using [email protected] | win32 | x64
npm ERR! node-pre-gyp info check checked for “C:UsersKeramDesktopgenerative-art-node-mainnode_modulescanvasbuildReleasecanvas.node” (not found)
npm ERR! node-pre-gyp http GET https://github.com/Automattic/node-canvas/releases/download/v2.9.0/canvas-v2.9.0-node-v93-win32-unknown-x64.tar.gz
npm ERR! node-pre-gyp info install unpacking Release/
npm ERR! node-pre-gyp info install unpacking Release/canvas.exp
npm ERR! node-pre-gyp info install unpacking Release/canvas.ilk
npm ERR! node-pre-gyp ERR! Completion callback never invoked!
npm ERR! node-pre-gyp ERR! System Windows_NT 6.1.7601
npm ERR! node-pre-gyp ERR! command “C:node jsnode.exe” “C:UsersKeramDesktopgenerative-art-node-mainnode_modules@mapboxnode-pre-gypbinnode-pre-gyp” “install” “–fallback-to-build”
npm ERR! node-pre-gyp ERR! cwd C:UsersKeramDesktopgenerative-art-node-mainnode_modulescanvas
npm ERR! node-pre-gyp ERR! node -v v16.6.2
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v1.0.5

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersKeramAppDataLocalnpm-cache_logs2022-01-29T08_29_22_396Z-debug.log
PS C:UsersKeramDesktopgenerative-art-node-main>

read response from redirection url using webView in flutter

I was trying to add a payment gateway using WebView flutter library.On successful completion of payment, the gateway redirects to a return url or webhook with transaction response. Now instead of redirection to some outside url, I want redirection to my app and want to read the status of transaction from response that is sent.
All I want to know whether transaction is success or fail.

”’

WebView(
  navigationDelegate: (action) {
    return NavigationDecision.navigate;
  },
  onPageStarted: (url) => _onPageStart(url),
  onPageFinished: (url) => _onPageFinish(url),
   gestureNavigationEnabled: true,
  debuggingEnabled: true,
  javascriptMode: JavascriptMode.unrestricted,
  initialUrl: url,
  onWebViewCreated: (WebViewController webcontroller) {
    _controller = webcontroller;
  },
),

void _onPageStart(url) {
  Future<String> future = _controller
      .runJavascriptReturningResult("window.document.body.outerHTML");
  future.then((data) {
    print("ONpage start $data");
  });
}


Future<void> _onPageFinish(url) async {
    Future<String> future = _controller
        .runJavascriptReturningResult("window.document.body.outerHTML");
    future.then((data) {
      print(data);
    });
  }

”’

My Discord bot repeats messages but only related to music bot

My code is this
require(‘dotenv’).config();

module.exports = (client, Discord, message) =>{
const prefix = process.env.BOT_PREFIX;

    if(!message.content.startsWith(prefix) || message.author.bot) return;
    

    const args = message.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();


    

    const command = client.commands.get(cmd);

    if(command) command.Execute(client, message, args, Discord);
    if (!command) return
    if (command.inVoiceChannel && !message.member.voice.channel) {
        return message.channel.send(`${client.emotes.error} | You must be in a voice channel!`)
    }
    const status = queue =>
    `Volume: `${queue.volume}%` | Filter: `${queue.filters.join(", ") || "Off"}` | Loop: `${
        queue.repeatMode ? (queue.repeatMode === 2 ? "All Queue" : "This Song") : "Off"
    }` | Autoplay: `${queue.autoplay ? "On" : "Off"}``
    client.distube
    .on("playSong", (queue, song) =>
        queue.textChannel.send(
            `${client.emotes.play} | Playing `${song.name}` - `${song.formattedDuration}`nRequested by: ${
                song.user
            }n${status(queue)}`
        )
    )
    .on("addSong", (queue, song) =>
        queue.textChannel.send(
            `${client.emotes.success} | Added ${song.name} - `${song.formattedDuration}` to the queue by ${song.user}`
        )
    )
    .on("addList", (queue, playlist) =>
        queue.textChannel.send(
            `${client.emotes.success} | Added `${playlist.name}` playlist (${
                playlist.songs.length
            } songs) to queuen${status(queue)}`
        )
    )
    .on("error", (channel, e) => {
        channel.send(`${client.emotes.error} | An error encountered: ${e.toString().slice(0, 1974)}`)
        console.error(e)
    })
    .on("empty", channel => channel.send("Voice channel is empty! Leaving the channel..."))
    .on("searchNoResult", (message, query) =>
        message.channel.send(`${client.emotes.error} | No result found for `${query}`!`)
    )
    .on("finish", queue => queue.textChannel.send("Finished!"))
    
    try {
        
    } catch (e) {
        console.error(e)
        message.channel.send(`${client.emotes.error} | Error: `${e}``)
    }
    }

My console looks like this
C:UsersadminDesktopmadhvanDiscord bot>node .
Mady Bot Is Online
(node:11012) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use node --trace-deprecation ... to show where the warning was created)
[DisTube] Updated youtube-dl to 2022.01.21!
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 playSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 addSong listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 addList listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 error listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 empty listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 searchNoResult listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit
(node:11012) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 finish listeners added to [DisTube]. Use emitter.setMaxListeners() to increase limit

Getting TypeError: Cannot set properties of null (setting ‘textContent’)

I am building a 2 Player shooter game. Each player has a health of 100. Players can shoot at each other with a random power (0-5) which will reduce the opponent’s health.

I am trying to reduce the currentScore by random health as given below. But its showing the TypeError.
textContent is showing null value. What should I do solve this error?

"use strict";

const player1El = document.querySelector(".player-1");
const player2El = document.querySelector(".player-2");
const score1El = document.querySelector("#score--1");
const score2El = document.querySelector("#score--2");
const current1El = document.querySelector("#current--1");
const current2El = document.querySelector("#current--2");

const healthEl = document.querySelector(".health");
const btnNew = document.querySelector(".btn--new");
const btnShoot = document.querySelector(".btn--shoot");

let wins, currentScore, activePlayer, playing;
// Initializing
const init = function () {
  wins = [0, 0];
  currentScore = 100;
  activePlayer = 0;
  playing = true;

  score1El.textContent = 0;
  score2El.textContent = 0;
  current1El.textContent = 100;
  current2El.textContent = 100;

  healthEl.classList.add("hidden");
  player1El.classList.remove("player--winner");
  player2El.classList.remove("player--winner");
  player1El.classList.add("active");
  player2El.classList.remove("active");
};
init();
// console.log(currentScore);

// Switching Players
const switchPlayer = function () {
  document.getElementById(`current--${activePlayer}`).textContent = 0;
  currentScore = 100;
  activePlayer = activePlayer === 1 ? 2 : 1;
  player1El.classList.toggle("player--active");
  player2El.classList.toggle("player--active");
};

// Shooting Functionality
btnShoot.addEventListener("click", function () {
  // 1. Generating random number
  const health = Math.trunc(Math.random() * 6);

  // 2. Display health
  healthEl.classList.remove("hidden");
  healthEl.src = `imgs/Num-${health}.png`;

  // 3. Decrease health
  currentScore -= health;
  console.log(currentScore);

  document.querySelector(`current--${activePlayer}`).textContent = currentScore;
});

Socioboard-login/signup error” Sorry some Error occurred , Please reload the page”

I am working in a existing project that has a socioboard setup. I have been assigned to solve the login/sign up issue. The project is remotely hosted. The issue when someone tries to sign up with google,facebook or other social medias it is displaying “some errors occurred, reload the page”. sign in email is also giving a red image notification. In the console it giving the following errors.

Failed to load resource: the server responded with a status of 404 (Not Found)
plugins/custom/intl-tel-input/build/css/intlTelInput.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
login:611 Uncaught ReferenceError: reset is not defined
    at login:611:45
(anonymous) @ login:611
login:1 [DOM] Found 2 elements with non-unique id #emailId:
<input class=​"form-control form-control-solid h-auto py-7 rounded-lg font-size-h6" type=​"text" name=​"email" id=​"emailId" autocomplete=​"off" placeholder=​"Email">​ <input class=​"form-control form-control-solid h-auto py-7 rounded-lg font-size-h6" type=​"text" name=​"emailId" id=​"emailId" autocomplete=​"off" placeholder=​"Email">​
plugins.bundle.js:3841 jQuery.Deferred exception: SBAppSettings is not defined ReferenceError: SBAppSettings is not defined
    at HTMLDocument.<anonymous> (http://smm.grit0.com/js/main.js:328:16)
    at mightThrow (http://smm.grit0.com/plugins/global/plugins.bundle.js:3557:29)
    at process (http://smm.grit0.com/plugins/global/plugins.bundle.js:3625:12) undefined
jQuery.Deferred.exceptionHook @ plugins.bundle.js:3841
process @ plugins.bundle.js:3629
plugins.bundle.js:3850 Uncaught ReferenceError: SBAppSettings is not defined
    at HTMLDocument.<anonymous> (main.js:328:16)
    at mightThrow (plugins.bundle.js:3557:29)
    at process (plugins.bundle.js:3625:12)
(anonymous) @ main.js:328
mightThrow @ plugins.bundle.js:3557
process @ plugins.bundle.js:3625
build/js/utils.js?1613236686837:1 Failed to load resource: the server responded with a status of 404 (Not Found)
intlTelInput.min.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)

I am not sure where to start. Any help would be much appreciated.

Why bracket notation is working here but not the dot notation?

var recordCollection = {
  2548: {
    albumTitle: 'Slippery When Wet',
    artist: 'Bon Jovi',
    tracks: ['Let It Rock', 'You Give Love a Bad Name']
  },
  2468: {
    albumTitle: '1999',
    artist: 'Prince',
    tracks: ['1999', 'Little Red Corvette']
  }
};


console.log(recordCollection[2548])

//This is giving error
console.log(recordCollection.2548)

does indexOf() in js searches all the elements of an array to execute?

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(char);
}

I believe that time complexity of code above is O(n).

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(arr.indexOf(char);
}

However, does indexOf() search all the elements?
If does so, I believe time complexity of code above may be O(n^2)

I want to know whether indexOf() searches all the components as for loop.