Why am I getting ‘user.matchPassword is not a function’ error when calling my API with bcryptjs in Node.js and Express?

const userAuth = asyncHandler( async (req,res)=>{
    const  { email , password } = req.body;

    const user = User.findOne({email});

    if(user && (await user.matchPassword(password))){
        generateToken(res,user._id)
        res.status(201).json({
            _id:user._id,
            name:user.name,
            email:user.email
        })
       }else{
        res.status(401);
        throw new Error('Incorrect Password or Email');
        }
});
{
    "message": "user.matchPassword is not a function",
    "stack": "TypeError: user.matchPassword is not a functionn    at file:///C:/Users/siroh/OneDrive/Desktop/MERN-Auth/server/Controllers/userControllers.js:45:28n    at asyncUtilWrap (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express-async-handler\index.js:3:20)n    at Layer.handle [as handle_request] (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\layer.js:95:5)n    at next (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\route.js:144:13)n    at Route.dispatch (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\route.js:114:3)n    at Layer.handle [as handle_request] (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\layer.js:95:5)n    at C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:284:15n    at Function.process_params (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:346:12)n    at next (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:280:10)n    at Function.handle (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:175:3)"
}

Displaying a div based on select element value with JavaScript and CSS

I was trying to display a div and hide other div when the select element hold the corresponding value.

I created a select element with 4 options, the default with empty value plus three others, lower, upper, higher. I placed three hidden div elements below containing the content for each of the 3 options: lower, upper and higher. I wanted to show and hide each div based on the values of the select element. Here is my code:

         <div class="">
            <div class="">
              <label class="">Department
                <select id="departments" name="departments">
                  <option value="" selected>Select Department...</option>
                  <option value="lower">Lower</option>
                  <option value="upper">Upper</option>
                  <option value="higher">Higher</option>
                </select>
              </label>
            </div>
          </div>

          <div class="lower-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

          <div class="upper-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

          <div class="higher-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

       From my css file:
       .lower-dep, .upper-dep, .higher-dep {
        display: none;
        }

          
  <script>
    const departments = document.querySelector("#departments");
    const lowerdep = document.querySelector(".lower-dep");
    const upperdep = document.querySelector(".upper-dep");
    const higherdep = document.querySelector(".higher-dep");

    if (departments.value = "") {
      lowerdep.style.display = "none";
      upperdep.style.display = "none";
      higherdep.style.display = "none";

    } else if (departments.value = "lower") {
      lowerdep.style.display = "block";

    } else if (departments.value = "upper") {
      upperdep.style.display = "block";

    } else {
      higherdep.style.display = "block";
    }

  </script>

login created token, but still get an error react

I have a react native application. And an login service call.

And if I trigger the login service call the token has been created. But I still get an login failed error. So this is the service call:

export const loginRequest = async (email, password) => {
    try {
        const response = await fetch("http://192.168.1.65:8000/api/user/token/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email: email,
                password: password,
            }),
        });

        const data = await response.json();
        console.log(data);

        if (response.ok) {
            await AsyncStorage.setItem("Token", data.access);

            return true;
        } else {
            throw new Error(data.detail);
        }
    } catch (error) {
        throw new Error("Login failed");
    }
};

And in the console I see that the token has created:

 Object {
  "token": "a608aa4c5c584f288c6afce37ef963985ec64f1c",
}


Question: how to proper login?

WebSocket connection to ‘wss://127.0.0.1:8080/’ failed

Problem Context

I have an express server serving my webpage with HTTPS via the following code:

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

const sslKey = fs.readFileSync(__dirname + "/certs/key.pem");
const sslCert = fs.readFileSync(__dirname + "/certs/cert.pem");

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/pages/index.html");
});

https
  .createServer(
    {
      key: sslKey,
      cert: sslCert,
    },
    app
  )
  .listen(3000);

The webpage is connecting to a Python websocket server running on my computer on port 8080 via the following code:

const server = "127.0.0.1";
const ws = new WebSocket(`wss://${server}:8080`);

And my Python websocket server is running based on the following code:

import asyncio
import websockets
import random
import string
import subprocess
import os
import logging
import ssl
import speech_recognition as sr
r = sr.Recognizer()

logging.basicConfig()

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)

ssl_cert = "certs/cert.pem"
ssl_key = "certs/key.pem"

ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)

async def server(websocket, path):
    await call_some_custom_irrelevant_function_with_the_socket(websocket, path)


start_server = websockets.serve(
    server, "127.0.0.1", 8080, ssl=ssl_context, origins="*")


asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

There are separate TLS/SSL certificates being used by both, the express server, and the Python websocket server. I generated them and granted them trust on my local computer using mkcert, a way to generate and automatically grant certificates trusted authority on your local device. Certificates for both are placed inside the certs directory of each’s project folder and appropriately referenced in the code.

I run the Python websocket server with python app.py in its directory successfully, and start my express app using nodemon app.js in its directory as well, being able to access https://localhost:3000 in a secure manner.

Problem

When I open my webpage and pull the trigger to connect to the websocket server (Irrelevant code as it’s just an event handler on a button that calls the websocket connection code I gave above and some other irrelevant socket event stuff), it waits for like 1 second and then gives out the following error:

WebSocket connection to 'wss://127.0.0.1:8080/' failed: 

I researched a bit regarding this and it seems that there may be some sort of problem with how I am integrating my TLS/SSL certificates, however, I am clueless as to exactly what. If someone could help me out in fixing this, or even point me in the right direction, I’d be grateful.

Jest & Supertest not working with Express middleware routers

I’m using Node v18.8.0 and Express v4.18.2.
Say I had this app where I wanted to get a list of all phone codes from each country. This is my model:

// models/misc/phoneCodeModel.js
const mongoose = require('mongoose');
const phoneCodeSchema = new mongoose.Schema({
    countryCodes: {
        type: [String],
        required: [true, `To add a phone code you must specify the 'countryCodes' array`]
    },
    countryName: {
        type: String,
        required: [true, `To add a phone code you must specify the 'countryName'`]
    }
});

const PhoneCode = mongoose.model(`PhoneCode`, phoneCodeSchema);
module.exports = PhoneCode;

This is the controller:

// controllers/misc/phoneCodeController.js
const PhoneCode = require(`./../../models/misc/phoneCodeModel`);

exports.getPhoneCodes = async (req, res, next) => {
    const phoneCodes = await PhoneCode.find();

    res.status(200).json({
        status: 'success',
        data: {
            phoneCodes
        }
    });
};

exports.getPhoneCode = async (req, res, next) => {
    const phoneCode = await PhoneCode.findById(req.params.id);

    res.status(200).json({
        status: 'success',
        data: {
            phoneCode
        }
    });
};

This is the router:

// routes/misc/phoneCodeRoutes.js
const express = require('express');

const phoneCodeController = require(`./../../controllers/misc/phoneCodeController`);

const router = express.Router();
router.route('/')
    .get(phoneCodeController.getPhoneCodes);
router.route('/:id')
    .get(phoneCodeController.getPhoneCode);
module.exports = router;

This is the app.js file:

const express =  require('express');
const app = express();
app.use(express.json()); // Parse request/response into JSON objects

const phoneCodeRouter = require(`./routes/misc/phoneCodeRoutes`);

app.use('/api/v1/phoneCodes', phoneCodeRouter);
app.get('/test', (req, res) => {
    res.send("test")
});

app.all('*', (req, res, next) => {
    res.status(404).json({
        status: 'fail',
        message: `Can't find ${req.originalUrl} on this server!`
    });
});

module.exports = app;

There’s a server.js file that starts the app on port 8080…
Now the real question, if I try to make a test using Jest and Supertest:

// tests/test.js
const request = require('supertest');
const app = require('./../app');

describe('Phone codes', () => {
    
    describe('GET /phoneCodes', () => {
        test('Should response with a 200 status code', () => {
            return request(app).get('/api/v1/phoneCodes').expect(200);
        });
    });
    
});

I get the following error:

 FAIL  test/test.js (10.776 s)
  Phone codes
    GET /phoneCodes
      × Should response with a 200 status code (5016 ms)

  ● Phone codes › GET /phoneCodes › Should response with a 200 status code

    thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

       5 |
       6 |      describe('GET /phoneCodes', () => {
    >  7 |              test('Should response with a 200 status code', () => {
         |              ^
       8 |                      return request(app).get('/api/v1/phoneCodes').expect(200);
       9 |              });
      10 |      });

      at test (test/test.js:7:3)
      at describe (test/test.js:6:2)
      at Object.describe (test/test.js:4:1)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        11.652 s
Ran all test suites.

Meanwhile from Postman I get the list correctly, and if I try to make the test on the ‘/test’ endpoint it works correctly:

const request = require('supertest');
const app = require('./../app');

describe('Phone codes', () => {
    
    describe('GET /phoneCodes', () => {
        test('Should response with a 200 status code', () => {
            return request(app).get('/test').expect(200);
        });
    });
    
});
 PASS  test/test.js
  Phone codes
    GET /phoneCodes
      √ Should response with a 200 status code (46 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.003 s, estimated 11 s
Ran all test suites.

Am I missing something? Why is it not working with my Express routes? I’m using Jest v29.5.0 and Supertest v6.3.3

I looked up the Supertest docs on NPM and used it’s default methods and chained them like in their examples (with and without the ‘done’ parameter), but no luck. I tried making async functions myself and evaluating the response later, same result. I don’t know what else to do. I tried increasing the timeout value as the error says but it doesn’t work either.

Date and time will need to display on click in the input field

I have the rest of the JavaScript code on how to upload it to view this error and get a solution for it. Can anyone tell me how to upload arrowed 70000 character lines of bootstrap-datetimepicker JavaScript code?

(function(factory){
 if (typeof define === 'function' && define.amd)
      define(['jquery'], factory);
    else if (typeof exports === 'object')
      factory(require('jquery'));
    else
      factory(jQuery);

}

(function($, undefined){
var DPGlobal = {
    modes:            [
      {
        clsName: 'minutes',
        navFnc:  'Hours',
        navStep: 1
      },
      {
        clsName: 'hours',
        navFnc:  'Date',
        navStep: 1
      },
      {
        clsName: 'days',
        navFnc:  'Month',
        navStep: 1
      },
      {
        clsName: 'months',
        navFnc:  'FullYear',
        navStep: 1
      },
      {
        clsName: 'years',
        navFnc:  'FullYear',
        navStep: 10
      }
    ],
    isLeapYear:       function (year) {
      return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth:   function (year, month) {
      return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    getDefaultFormat: function (type, field) {
      if (type === 'standard') {
        if (field === 'input')
          return 'yyyy-mm-dd hh:ii';
        else
          return 'yyyy-mm-dd hh:ii:ss';
      } else if (type === 'php') {
        if (field === 'input')
          return 'Y-m-d H:i';
        else
          return 'Y-m-d H:i:s';
      } else {
        throw new Error('Invalid format type.');
      }
    },
    validParts: function (type) {
      if (type === 'standard') {
        return /t|hh?|HH?|p|P|z|Z|ii?|ss?|dd?|DD?|mm?|MM?|yy(?:yy)?/g;
      } else if (type === 'php') {
        return /[dDjlNwzFmMnStyYaABgGhHis]/g;
      } else {
        throw new Error('Invalid format type.');
      }
    },
    nonpunctuation: /[^ -/:-@[-`{-~tnrTZ]+/g,
    parseFormat: function (format, type) {
     
      var separators = format.replace(this.validParts(type), '').split(''),
        parts = format.match(this.validParts(type));
      if (!separators || !separators.length || !parts || parts.length === 0) {
        throw new Error('Invalid date format.');
      }
      return {separators: separators, parts: parts};
    },
    parseDate: function (date, format, language, type, timezone) {
      if (date instanceof Date) {
        var dateUTC = new Date(date.valueOf() - date.getTimezoneOffset() * 60000);
        dateUTC.setMilliseconds(0);
        return dateUTC;
      }
      if (/^d{4}-d{1,2}-d{1,2}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd', type);
      }
      if (/^d{4}-d{1,2}-d{1,2}[T ]d{1,2}:d{1,2}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd hh:ii', type);
      }
      if (/^d{4}-d{1,2}-d{1,2}[T ]d{1,2}:d{1,2}:d{1,2}[Z]{0,1}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd hh:ii:ss', type);
      }
      if (/^[-+]d+[dmwy]([s,]+[-+]d+[dmwy])*$/.test(date)) {
        var part_re = /([-+]d+)([dmwy])/,
          parts = date.match(/([-+]d+)([dmwy])/g),
          part, dir;
        date = new Date();
        for (var i = 0; i < parts.length; i++) {
          part = part_re.exec(parts[i]);
          dir = parseInt(part[1]);
          switch (part[2]) {
            case 'd':
              date.setUTCDate(date.getUTCDate() + dir);
              break;
            case 'm':
              date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
              break;
            case 'w':
              date.setUTCDate(date.getUTCDate() + dir * 7);
              break;
            case 'y':
              date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
              break;
          }
        }
        return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
      }
      var parts = date && date.toString().match(this.nonpunctuation) || [],
        date = new Date(0, 0, 0, 0, 0, 0, 0),
        parsed = {},
        setters_order = ['hh', 'h', 'ii', 'i', 'ss', 's', 'yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'D', 'DD', 'd', 'dd', 'H', 'HH', 'p', 'P', 'z', 'Z'],
        setters_map = {
          hh:   function (d, v) {
            return d.setUTCHours(v);
          },
          h:    function (d, v) {
            return d.setUTCHours(v);
          },
          HH:   function (d, v) {
            return d.setUTCHours(v === 12 ? 0 : v);
          },
          H:    function (d, v) {
            return d.setUTCHours(v === 12 ? 0 : v);
          },
          ii:   function (d, v) {
            return d.setUTCMinutes(v);
          },
          i:    function (d, v) {
            return d.setUTCMinutes(v);
          },
          ss:   function (d, v) {
            return d.setUTCSeconds(v);
          },
          s:    function (d, v) {
            return d.setUTCSeconds(v);
          },
          yyyy: function (d, v) {
            return d.setUTCFullYear(v);
          },
          yy:   function (d, v) {
            return d.setUTCFullYear(2000 + v);
          },
          m:    function (d, v) {
            v -= 1;
            while (v < 0) v += 12;
            v %= 12;
            d.setUTCMonth(v);
            while (d.getUTCMonth() !== v)
              if (isNaN(d.getUTCMonth()))
                return d;
              else
                d.setUTCDate(d.getUTCDate() - 1);
            return d;
          },
          d:    function (d, v) {
            return d.setUTCDate(v);
          },
          p:    function (d, v) {
            return d.setUTCHours(v === 1 ? d.getUTCHours() + 12 : d.getUTCHours());
          },
          z:    function () {
            return timezone
          }
        },
        val, filtered, part;
      setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
      setters_map['dd'] = setters_map['d'];
      setters_map['P'] = setters_map['p'];
      setters_map['Z'] = setters_map['z'];
      date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
      if (parts.length === format.parts.length) {
        for (var i = 0, cnt = format.parts.length; i < cnt; i++) {
          val = parseInt(parts[i], 10);
          part = format.parts[i];
          if (isNaN(val)) {
            switch (part) {
              case 'MM':
                filtered = $(dates[language].months).filter(function () {
                  var m = this.slice(0, parts[i].length),
                    p = parts[i].slice(0, m.length);
                  return m === p;
                });
                val = $.inArray(filtered[0], dates[language].months) + 1;
                break;
              case 'M':
                filtered = $(dates[language].monthsShort).filter(function () {
                  var m = this.slice(0, parts[i].length),
                    p = parts[i].slice(0, m.length);
                  return m.toLowerCase() === p.toLowerCase();
                });
                val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
                break;
              case 'p':
              case 'P':
                val = $.inArray(parts[i].toLowerCase(), dates[language].meridiem);
                break;
              case 'z':
              case 'Z':
                timezone;
                break;

            }
          }
          parsed[part] = val;
        }
        for (var i = 0, s; i < setters_order.length; i++) {
          s = setters_order[i];
          if (s in parsed && !isNaN(parsed[s]))
            setters_map[s](date, parsed[s])
        }
      }
      return date;
    },
    formatDate:       function (date, format, language, type, timezone) {
      if (date === null) {
        return '';
      }
      var val;
      if (type === 'standard') {
        val = {
          t:    date.getTime(),
         
          yy:   date.getUTCFullYear().toString().substring(2),
          yyyy: date.getUTCFullYear(),
        
          m:    date.getUTCMonth() + 1,
          M:    dates[language].monthsShort[date.getUTCMonth()],
          MM:   dates[language].months[date.getUTCMonth()],
          
          d:    date.getUTCDate(),
          D:    dates[language].daysShort[date.getUTCDay()],
          DD:   dates[language].days[date.getUTCDay()],
          p:    (dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
        
          h:    date.getUTCHours(),
         
          i:    date.getUTCMinutes(),
          
          s:    date.getUTCSeconds(),
         
          z:    timezone
        };

        if (dates[language].meridiem.length === 2) {
          val.H = (val.h % 12 === 0 ? 12 : val.h % 12);
        }
        else {
          val.H = val.h;
        }
        val.HH = (val.H < 10 ? '0' : '') + val.H;
        val.P = val.p.toUpperCase();
        val.Z = val.z;
        val.hh = (val.h < 10 ? '0' : '') + val.h;
        val.ii = (val.i < 10 ? '0' : '') + val.i;
        val.ss = (val.s < 10 ? '0' : '') + val.s;
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
      } else if (type === 'php') {
      
        val = {
     
          y: date.getUTCFullYear().toString().substring(2),
          Y: date.getUTCFullYear(),
       
          F: dates[language].months[date.getUTCMonth()],
          M: dates[language].monthsShort[date.getUTCMonth()],
          n: date.getUTCMonth() + 1,
          t: DPGlobal.getDaysInMonth(date.getUTCFullYear(), date.getUTCMonth()),
          
          j: date.getUTCDate(),
          l: dates[language].days[date.getUTCDay()],
          D: dates[language].daysShort[date.getUTCDay()],
          w: date.getUTCDay(), 
          N: (date.getUTCDay() === 0 ? 7 : date.getUTCDay()),       
          S: (date.getUTCDate() % 10 <= dates[language].suffix.length ? dates[language].suffix[date.getUTCDate() % 10 - 1] : ''),
         
          a: (dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
          g: (date.getUTCHours() % 12 === 0 ? 12 : date.getUTCHours() % 12),
          G: date.getUTCHours(),
          
          i: date.getUTCMinutes(),
        
          s: date.getUTCSeconds()
        };
        val.m = (val.n < 10 ? '0' : '') + val.n;
        val.d = (val.j < 10 ? '0' : '') + val.j;
        val.A = val.a.toString().toUpperCase();
        val.h = (val.g < 10 ? '0' : '') + val.g;
        val.H = (val.G < 10 ? '0' : '') + val.G;
        val.i = (val.i < 10 ? '0' : '') + val.i;
        val.s = (val.s < 10 ? '0' : '') + val.s;
      } else {
        throw new Error('Invalid format type.');
      }
      var date = [],
        seps = $.extend([], format.separators);
      for (var i = 0, cnt = format.parts.length; i < cnt; i++) {
        if (seps.length) {
          date.push(seps.shift());
        }
        date.push(val[format.parts[i]]);
      }
      if (seps.length) {
        date.push(seps.shift());
      }
      return date.join('');
    },
    convertViewMode:  function (viewMode) {
      switch (viewMode) {
        case 4:
        case 'decade':
          viewMode = 4;
          break;
        case 3:
        case 'year':
          viewMode = 3;
          break;
        case 2:
        case 'month':
          viewMode = 2;
          break;
        case 1:
        case 'day':
          viewMode = 1;
          break;
        case 0:
        case 'hour':
          viewMode = 0;
          break;
      }

      return viewMode;
    },
    headTemplate: '<thead>' +
                '<tr>' +
                '<th class="prev"><i class="{iconType} {leftArrow}"/></th>' +
                '<th colspan="5" class="switch"></th>' +
                '<th class="next"><i class="{iconType} {rightArrow}"/></th>' +
                '</tr>' +
      '</thead>',
    headTemplateV3: '<thead>' +
                '<tr>' +
                '<th class="prev"><span class="{iconType} {leftArrow}"></span> </th>' +
                '<th colspan="5" class="switch"></th>' +
                '<th class="next"><span class="{iconType} {rightArrow}"></span> </th>' +
                '</tr>' +
      '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
    footTemplate: '<tfoot>' + 
                    '<tr><th colspan="7" class="today"></th></tr>' +
                    '<tr><th colspan="7" class="clear"></th></tr>' +
                  '</tfoot>'
  };
  DPGlobal.template = '<div class="datetimepicker">' +
    '<div class="datetimepicker-minutes">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-hours">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-days">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    '<tbody></tbody>' +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-months">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-years">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '</div>';
  DPGlobal.templateV3 = '<div class="datetimepicker">' +
    '<div class="datetimepicker-minutes">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-hours">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-days">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    '<tbody></tbody>' +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-months">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-years">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '</div>';
  $.fn.datetimepicker.DPGlobal = DPGlobal;



  $.fn.datetimepicker.noConflict = function () {
    $.fn.datetimepicker = old;
    return this;
  };



  $(document).on(
    'focus.datetimepicker.data-api click.datetimepicker.data-api',
    '[data-provide="datetimepicker"]',
    function (e) {
      var $this = $(this);
      if ($this.data('datetimepicker')) return;
      e.preventDefault();
      
      $this.datetimepicker('show');
    }
  );
  $(function () {
    $('[data-provide="datetimepicker-inline"]').datetimepicker();
  });
}));

$('.form_datetime').datetimepicker({        
        language:  'fr',
        weekStart: 1,
        todayBtn:  0,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        
    });
.datetimepicker table tr td.active:active,
.datetimepicker table tr td.active:hover:active,
.datetimepicker table tr td.active.disabled:active,
.datetimepicker table tr td.active.disabled:hover:active,
.datetimepicker table tr td.active.active,
.datetimepicker table tr td.active:hover.active,
.datetimepicker table tr td.active.disabled.active,
.datetimepicker table tr td.active.disabled:hover.active {
    background-color: #039;
}

.datetimepicker table tr td span {
    display: block;
    width: 23%;
    height: 54px;
    line-height: 54px;
    float: left;
    margin: 1%;
    cursor: pointer;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.datetimepicker .datetimepicker-hours span {
    height: 26px;
    line-height: 26px;
}

.datetimepicker .datetimepicker-hours table tr td span.hour_am,
.datetimepicker .datetimepicker-hours table tr td span.hour_pm {
    width: 14.6%;
}

.datetimepicker .datetimepicker-hours fieldset legend,
.datetimepicker .datetimepicker-minutes fieldset legend {
    margin-bottom: inherit;
    line-height: 30px;
}

.datetimepicker .datetimepicker-minutes span {
    height: 26px;
    line-height: 26px;
}

.datetimepicker table tr td span:hover {
    background: #eee;
}

.datetimepicker table tr td span.disabled,
.datetimepicker table tr td span.disabled:hover {
    background: 0;
    color: #999;
    cursor: default;
}

.datetimepicker table tr td span.active,
.datetimepicker table tr td span.active:hover,
.datetimepicker table tr td span.active.disabled,
.datetimepicker table tr td span.active.disabled:hover {
    background-color: #006dcc;
    background-image: -moz-linear-gradient(top, #08c, #04c);
    background-image: -ms-linear-gradient(top, #08c, #04c);
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));
    background-image: -webkit-linear-gradient(top, #08c, #04c);
    background-image: -o-linear-gradient(top, #08c, #04c);
    background-image: linear-gradient(to bottom, #08c, #04c);
    background-repeat: repeat-x;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0);
    border-color: #04c #04c #002a80;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
    color: #fff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<input class="form-control form_datetime" data-date-format="dd-MM-yyyy hh:mm" data-link-field="dtp_input1" type="text" required autocomplete="off" data-link-format="dd-mmm-yyyy hh:mm" >

On the time selection, only one time will always be selected instead of the relative time. For example, if I select today’s date and go to the time, i.e., 11 hours and 30 minutes, that needs to get selected, and the same will need to appear on the input field, but that is not going to happen. What it is getting to display on the inenter code hereput field is 23-May-2023 23:05 instead of 23-May-2023 23:30. It will work in the am and pm sections relatively the same.

Promises resolving in different order than added

I am creating a PDF with jsPDF. In the code I have some loops, where I create promises to add images to the document.
Now I want to add a new page in between the other promises if certain conditions are met. But the page is always added before every other promise. Here is my code:

var docPromises = [];

for (var i = 0; i < usedMonths.length; i++){

  if(checkColumnPage(startPos)){
    var addPagePromise = new Promise((resolve, reject) => {
      doc.addPage();
      resolve();
    });
    docPromises.push(addPagePromise);
  }



  var imgSourceMonth = eval("img_months_" + currentMonth);

  (function(imgSrc, position) {
    var clonedStartPos = position.slice();

    var addImagePromiseMonth = calculateImageWidth(imgSrc, 20)
      .then(function(width) {
        doc.addImage(imgSrc, 'PNG', clonedStartPos[0], clonedStartPos[1], width, 20);
      })
      .catch(function(error) {
        console.error(error);
      });

    docPromises.push(addImagePromiseMonth);
  })(imgSourceMonth, startPos);

}

checkColumnPage(startPos) returns true if a new page has to be added and false if not.

I resolve the promises like this:
Promise.all(docPromises)

The second part in the loop works perfectly. The order of the image is correct.

I logged every promise action to the console and it appeared that the page was always added first, followed by every other promise.
I can’t figure out the problem… In my mind it should work like this:

Iteration 1 (checkColumnPage = false): add image promise
Iteration 2 (checkColumnPage = false): add image promise
Iteration 3 (checkColumnPage = true): add page promise, add image promise
Iteration 4 (checkColumnPage = false): add image promise

But the page always comes first. Can anyone help me with this problem? Thanks in advance.

Intersection of 3 circles with lat long center and meter radius

I have a question related to the intersection of circle.
I’ve spent some time on Google already but none of the solution seems to work for now.

I need to get the intersection of three circle. Each of them has a center given in latitude and longitude, and their radius in Meter.

The thing is for now every conversion I’ve done were not working.

Does anyone have an idea what should I do ?

Integración de avatar realista a mi app creada en android studio [closed]

Tienes idea de cómo fue desarrollado esa animación y aparentar que deadpool pudo manipular la tienes, ejemplos más detallado, a la hora de estar en la tienda de fortnite aparece deadpool saludando en una esquina y aparenta tocar la pantalla y desaparece luego sale en en la tienda y la empuja, como si la vieja…. Esa clase de animación la puedo realizar en mi app, y como, tengo una app simple crea que solo tiene un inicio de usuario, como puedo crear una animación así y integrarla a mi app para que haga esa clase de movimientos y no solo eso manipule mi entorno, tengo ya ideas en la mente pero no tan detalladas del como lograrlo,

Quiero que mi avatar creador con movimiento ya definido en unity o blender salte, a hora quiero que esa animación pueda importalos a mi app de android studio, pero quiero que a la hora de saltar golpeó con un botón y el botón se mueva.. Se qke el avatar no vera el botón ni nada pero ese movimiento del botón será una funcionalidad aparte, en android studio..

Slide is skiping in swiper with loop: true or without it

I don’t understand what’s wrong here.
but when I want to make the next slide active, this slide is skipped
loop: true is also not working correctly
Also, I want to add the ability to click on a slide and make it active

new Swiper(".mySwiperPhotos", {
    grabCursor: true,

    mousewheel: true,
    keyboard: true,

    centeredSlides: true,
    slidesPerView: 'auto',
    slidesPerGroup: 1,
    spaceBetween: 16,
    initialSlide: 1,

    loop: true,

    breakpoints: {
    600: {
        slidesPerView: 2,
        slidesPerGroup: 2,
        spaceBetween: 37,
    },
    },
});

I tried to do this, but it didn’t work out

let mySwiperPhotos = new Swiper(".mySwiperPhotos", {
    grabCursor: true,
    mousewheel: true,
    keyboard: true,
    centeredSlides: true,
    slidesPerView: 'auto',
    slidesPerGroup: 1,
    spaceBetween: 16,
    initialSlide: 1,
    loop: true,
    loopAdditionalSlides: 1,

    breakpoints: {
      600: {
        slidesPerView: 2,
        slidesPerGroup: 2,
        spaceBetween: 37,
      },
    },
  });

mySwiperPhotos.on('click', function() {
    var activeSlideIndex = mySwiperPhotos.clickedIndex;
    if (activeSlideIndex !== mySwiperPhotos.activeIndex) {
        mySwiperPhotos.slideToLoop(activeSlideIndex);
    }
});

Why is my model getting stuck at the PPO(‘MultiInputPolicy’) line when testing my javascript version of JumpKing using stable-baselines3 and PyTorch?

In the code below, I am trying to test my model for a javascript version of JumpKing, and its getting stuck on the line model = PPO(“MultiInputPolicy”, env, verbose=1)
basically, when I use the debugger and try to step over that line, I get this in the output, and it just gets stuck:
Using cuda device
Wrapping the env with a Monitor wrapper
Wrapping the env in a DummyVecEnv.

import numpy as np
import os

from stable_baselines3.common.env_checker import check_env
from stable_baselines3 import PPO

import asyncio

from env import JumpKingEnv
from game import Game
import time




models_dir = f"models/{int(time.time())}"
logdir = f"logs/{int(time.time())}"

if not os.path.exists(models_dir):
    os.makedirs(models_dir)
if not os.path.exists(logdir):
    os.makedirs(logdir)

game = Game()
asyncio.get_event_loop().run_until_complete(game.startGame(True))

env = JumpKingEnv(game)
obs = env.reset()

model = PPO("MultiInputPolicy", env, verbose=1)
TIMESTEPS = 20000
model.learn(total_timesteps=TIMESTEPS, reset_num_timesteps=False, tb_log_name="PPO", tensorboardlog = logdir)
print("done learning")
#model.save(f"{models_dir}/{TIMESTEPS*i}")
    #model.save("ppo_jumpking")
time.sleep(3)

for i in range(1000):
    action, _states = model.predict(obs, deterministic=True)
    obs, reward, done, info = env.step(action)
    env.render()
#obs = env.reset()
asyncio.get_event_loop().run_until_complete(game.terminate())

I used some test code earlier, and didn’t have any problem with it:

from stable_baselines3.common.env_checker import check_env
from env import JumpKingEnv
from game import Game
import asyncio

game = Game()
asyncio.get_event_loop().run_until_complete(game.startGame(True))

env = JumpKingEnv(game)
check_env(env)
asyncio.get_event_loop().run_until_complete(game.terminate())

I looked through the constructor for the model, but I couldn’t find any reason why it would get stuck like that.

Azure Data factory Pipeline faliure integration with service now incident

I want to integrate my azure data factory having multiple pipelines if any pipeline fails it should create the service now incident

What I have tried is

  • I created one action group with having a webhook pointed to scripted rest api URL created in service now.

But above way is not working, incident is getting created but I am getting empty json so not having data to use and request.body is empty

Tell me where I am missing or give me rest api Java script code

Discord bot not opening

My discord bot does not open when I press f5 in visual studio code, can someone help me?
When I press f5, the blue bar below turns orange for a few seconds and turns blue again.
My discord.js version is 13.16.0
I’d be glad if anyone could help me out on this subject.

url not being redirected to when starts with www

In my application I’ve got a method for redirecting to a url like so:

openURL() {
  window.open(this.url, '_blank').focus();
}

This will work fine if the URL starts with a http, so for example, if this.url is set to: https://www.example.com/...
this will work fine.

However if it does not have the https:// and just wwww.example.com/....., then what happens is that when it opens the new tab, the url becomes http://localhost:4200/...

I’m just not sure why the www is being replaced with http://localhost:4200/, what could be causing this?

How can I get the time difference in hh:mm:ss format between two Date objects in JavaScript? [duplicate]

I have two date object and am trying to get the time difference in hh:mm:ss format. Everything I have seen trying to look it up only shows getting it in seconds like below. Is it possible to get it in the format that I want?

var test = new Date('2023-05-22 03:08:00')
var test1 = new Date('2023-05-22 01:00:00')

var result = (test.getTime() - test1.getTime()) / 1000