timestamp Vs timestampz in database postgres

While creating backend of the systems i always store time in UTC that is when client side send any date time, i restrict to only accept UTC date time, the client side convert his local date time into UTC and then send it over the network using API.

I then store that utc date time into the database, i never cared about timezone. Then when the user ask for date time, i give them the UTC time which i stored, and then they convert it back to local time zone, this looks great to me.

My questions are,

  1. Why i need to store time zone in the database ?
  2. what is the real world use case where i need to store time zone as well, instead of just reallying on UTC ?
  3. Any resource i can explore which can explain me in detail when to use which approach ?

URL changes but components not rendered in Angular

I am new to angular I am mobile developer ,
I am using angular 17 but I have issue the only home page renders on the screen I can’t navigate to any other component the url changes but the same page appears

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
import { EmployeesComponent } from './employee/employees/employees-component/employees-component';
import { EmployeesService } from './employee/common/employees-service';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { MatTableModule } from '@angular/material/table';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoadingComponent } from './core/compnents/loading-component';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { AddEmployeeComponent } from './employee/add-employee.ts/add-employee-component';

@NgModule({
  declarations: [EmployeesComponent, LoadingComponent, AddEmployeeComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    MatTableModule,
    MatProgressSpinnerModule,
    BrowserAnimationsModule,
  ],
  providers: [EmployeesService, provideAnimationsAsync('animations')],
  bootstrap: [AddEmployeeComponent],
})
export class AppModule {}    

app router

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddEmployeeComponent } from './employee/add-employee.ts/add-employee-component';
import { EmployeesComponent } from './employee/employees/employees-component/employees-component';
export const routes: Routes = [
  {
    path: 'add',
    component: EmployeesComponent,
  },
  {
    path: '',
    component: AddEmployeeComponent,
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { enableTracing: true })],
  exports: [RouterModule],
})
export class AppRoutingModule {}

I added

but still networking
when I created my project I enabled option to use app modules

Can’t delete the session of another user in nodejs

I am using session based authentication for the first time. I have been reading and wathcing tutorials. I would like to know how to end the session of another user.
I know that I can use this line of code:

req.session.destroy();

to end the session of a user but this works if the user is the person carrying out the action on it own session. The session would be available in req object.
How ever I would like to have an admin who can end the session of any other user. According to what I found on express website, store.destroy(sid, callback) is explained this way:

This required method is used to destroy/delete a session from the store given a session ID (sid). The callback should be called as callback(error) once the session is destroyed.

I felt this is exactly what I am looking for since it has an argument for sessionId. But it didn’t work for me. I used it this way req.session.destroy('sessionId', );
I tried adding callback and it alerted me that it only expected one argument which is a callback.
So, how do I achieve my goal? I would like a user like an admin who can destroy the session of other users using their sessionId.
By the way, I am using redisStore via connect-redis package and my session is setup this way:

export const createSession = session({
store: new RedisStore({client: redisClient, }),
secret: sanitizedConfig.SESSION_SECRET,
resave: false,
saveUninitialized: false,
name: sanitizedConfig.SESSION_NAME,
cookie:{
maxAge: 1000 * 60 * 60,
secure: process.env.NODE_ENV === 'production' ? true: false,
httpOnly: process.env.NODE_ENV === 'production' ? true : false

}
});

Ajax data validation approach

I am working on a web app. Before saving, I want to be able to validate the data. One of the validations is a duplicate check.

I have a function called DupeCheck. It does a jQuery Ajax call which returns one of two values: “true” meaning it is a duplicate and “false” which is the opposite. I am running into the problem of synchronicity here. Since ajax is async, I can’t just wait for the return value from the server and then return true or false depending on what the server says. I do not want to turn it into Synchronous Ajax (and I believe that is deprecated anyway).

In pseudo code, I would like it to work something like this:

function save(){
   if(validate()){
      //Call routine that sends data to server
   }else{
      //Show error messages and go back to edit
   }
}

function validate(){
   bIsValid = dupeCheck();
   //Additional checks here
   return bIsValid;
}

function dupeCheck(){
   $.ajax{
      url:blahblah,
      success:function(data, status, jqXHR){
          //set a value based on data
      }
   }
   return value_based_on_data;
}

I know my dupeCheck code is wrong. I am just not sure how I can structure this to achieve what I want. Any thoughts appreciated.

How to wait for media element source to actually update with Async/Await?

I am using vanilla JS, webaudioAPI and canvas elements to create an audio visualizer.

When I update the audio element src with javascript, I need the audio element duration property to update two variables for my spectrogram visualizers. I want to use the duration property right after changing the src with javascript, but it returns NAN within the function.

Here is the code:

async function chooseTrack(trackTxt) {
  audioElem.src = `tracks/${trackTxt}`;
  await audioElem.load()
}

async function updateAudioContext(trackTxt) {
  await audioCtx.suspend()
  .then(() =>  chooseTrack(trackTxt))
  .then(() => {
      console.log(audioElem)
      console.log(audioElem.duration)
      frameLength = 360 / ((audioElem.duration * 1000)/ 3.2) ; 
      freqHeight = 250 / bufferLength;

  })
}


I can make it work with setTimeOut, but I would like a more elegant solution to access this property of the new source file within the function calls. This works:

setTimeout(() => {
      console.log(audioElem)
      console.log(audioElem.duration)
      frameLength = 360 / ((audioElem.duration * 1000)/ 3.2) ; /
      freqHeight = 250 / bufferLength;
    }, 50)

I’d rather not use setTimeOut to wait for the updated duration property in the function. What am I doing wrong?

How to convert a datetime string to another time zone

I have a string “2024-09-19 14:20:45” in given time zone say “America/Los_Angeles”.
In javascript how can I convert it to datetime string in another time zone “timezone2” say “America/New_York” (three hours earlier than Los Angeles)?

How can I get “2024-09-19 17:20:45” in the above example for “America/New_York” in Javascript ?

Mongoose/MongoDB throwing “Error [ERR_REQUIRE_ESM]: require() of ES Module /node_modules/mongoose/index.js not supported” with NodeJS usage

I’m trying to create a website that stores status values of different machines through mongoDB but it throws Error [ERR_REQUIRE_ESM]: require() of ES Module file:///C:/Users/mimic/OneDrive/Documents/GitHub/TAMU_Laundry/node_modules/mongoose/index.js not supported. whenever I try to run the index.js file despite there being no "type": "module" in the package.json. On another forum post there was mention of node-fetch only being compatible with ES but I tried to troubleshoot that and nothing worked so not sure if that is the cause. This is one of my first times doing web development and first time working with mongoDB so any help would be much appreciated!

main package.json:

{
  "name": "tamu_laundry",
  "version": "1.0.0",
  "description": "",
  "main": "node index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.1",
    "express": "^4.21.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.7.0",
    "node-fetch-native": "^1.6.4",
    "node-schedule": "^2.1.1",
    "twilio": "^5.3.2"
  },
  "devDependencies": {
    "nodemon": "^3.1.7"
  }
}

main index.js:


const express = require('express');
const connectDB = require('./config/db');
const authRoutes = require('./routes/auth');
const claimRoutes = require('./routes/claims');
const seedMachines = require('./config/seed');

const app = express();
const PORT = 3000;

connectDB();
app.use(express.json());

app.use('/auth', authRoutes);
app.use('/api', claimRoutes);

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
seedMachines()

mongoose package.json

{
  "name": "mongoose",
  "description": "Mongoose MongoDB ODM",
  "version": "8.7.0",
  "author": "Guillermo Rauch <[email protected]>",
  "keywords": [
    "mongodb",
    "document",
    "model",
    "schema",
    "database",
    "odm",
    "data",
    "datastore",
    "query",
    "nosql",
    "orm",
    "db"
  ],
  "license": "MIT",
  "dependencies": {
    "bson": "^6.7.0",
    "kareem": "2.6.3",
    "mongodb": "6.9.0",
    "mpath": "0.9.0",
    "mquery": "5.0.0",
    "ms": "2.1.3",
    "sift": "17.1.3"
  },
  "devDependencies": {
    "@babel/core": "7.24.7",
    "@babel/preset-env": "7.25.4",
    "@typescript-eslint/eslint-plugin": "^8.4.0",
    "@typescript-eslint/parser": "^8.4.0",
    "acquit": "1.3.0",
    "acquit-ignore": "0.2.1",
    "acquit-require": "0.1.1",
    "assert-browserify": "2.0.0",
    "axios": "1.1.3",
    "babel-loader": "8.2.5",
    "broken-link-checker": "^0.7.8",
    "buffer": "^5.6.0",
    "cheerio": "1.0.0",
    "crypto-browserify": "3.12.0",
    "dotenv": "16.4.5",
    "dox": "1.0.0",
    "eslint": "8.57.0",
    "eslint-plugin-markdown": "^5.0.0",
    "eslint-plugin-mocha-no-only": "1.2.0",
    "express": "^4.19.2",
    "fs-extra": "~11.2.0",
    "highlight.js": "11.10.0",
    "lodash.isequal": "4.5.0",
    "lodash.isequalwith": "4.4.0",
    "markdownlint-cli2": "^0.13.0",
    "marked": "14.1.0",
    "mkdirp": "^3.0.1",
    "mocha": "10.7.3",
    "moment": "2.30.1",
    "mongodb-memory-server": "10.0.0",
    "ncp": "^2.0.0",
    "nyc": "15.1.0",
    "pug": "3.0.3",
    "q": "1.5.1",
    "sinon": "18.0.0",
    "stream-browserify": "3.0.0",
    "tsd": "0.31.1",
    "typescript": "5.5.4",
    "uuid": "10.0.0",
    "webpack": "5.94.0"
  },
  "directories": {
    "lib": "./lib/mongoose"
  },
  "scripts": {
    "docs:clean": "npm run docs:clean:stable",
    "docs:clean:stable": "rimraf index.html && rimraf -rf ./docs/*.html  && rimraf -rf ./docs/api && rimraf -rf ./docs/tutorials/*.html && rimraf -rf ./docs/typescript/*.html && rimraf -rf ./docs/*.html && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp",
    "docs:clean:5x": "rimraf index.html && rimraf -rf ./docs/5.x && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp",
    "docs:clean:6x": "rimraf index.html && rimraf -rf ./docs/6.x && rimraf -rf ./docs/source/_docs && rimraf -rf ./tmp",
    "docs:copy:tmp": "mkdirp ./tmp/docs/css && mkdirp ./tmp/docs/js && mkdirp ./tmp/docs/images && mkdirp ./tmp/docs/tutorials && mkdirp ./tmp/docs/typescript && mkdirp ./tmp/docs/api && ncp ./docs/css ./tmp/docs/css --filter=.css$ && ncp ./docs/js ./tmp/docs/js --filter=.js$ && ncp ./docs/images ./tmp/docs/images && ncp ./docs/tutorials ./tmp/docs/tutorials && ncp ./docs/typescript ./tmp/docs/typescript && ncp ./docs/api ./tmp/docs/api && cp index.html ./tmp && cp docs/*.html ./tmp/docs/",
    "docs:copy:tmp:5x": "rimraf ./docs/5.x && ncp ./tmp ./docs/5.x",
    "docs:copy:tmp:6x": "rimraf ./docs/6.x && ncp ./tmp ./docs/6.x",
    "docs:generate": "node ./scripts/website.js",
    "docs:generate:sponsorData": "node ./scripts/loadSponsorData.js",
    "docs:test": "npm run docs:generate",
    "docs:view": "node ./scripts/static.js",
    "docs:prepare:publish:stable": "git checkout gh-pages && git merge master && npm run docs:generate",
    "docs:prepare:publish:5x": "git checkout 5.x && git merge 5.x && npm run docs:clean:stable && npm run docs:generate && npm run docs:copy:tmp && git checkout gh-pages && npm run docs:copy:tmp:5x",
    "docs:prepare:publish:6x": "git checkout 6.x && git merge 6.x && npm run docs:clean:stable && env DOCS_DEPLOY=true npm run docs:generate && mv ./docs/6.x ./tmp && git checkout gh-pages && npm run docs:copy:tmp:6x",
    "docs:prepare:publish:7x": "env DOCS_DEPLOY=true npm run docs:generate && git checkout gh-pages && rimraf ./docs/7.x && mv ./tmp ./docs/7.x",
    "docs:check-links": "blc http://127.0.0.1:8089 -ro",
    "lint": "eslint .",
    "lint-js": "eslint . --ext .js --ext .cjs",
    "lint-ts": "eslint . --ext .ts",
    "lint-md": "markdownlint-cli2 "**/*.md"",
    "build-browser": "(rm ./dist/* || true) && node ./scripts/build-browser.js",
    "prepublishOnly": "npm run build-browser",
    "release": "git pull && git push origin master --tags && npm publish",
    "release-5x": "git pull origin 5.x && git push origin 5.x && git push origin 5.x --tags && npm publish --tag 5x",
    "release-6x": "git pull origin 6.x && git push origin 6.x && git push origin 6.x --tags && npm publish --tag 6x",
    "mongo": "node ./tools/repl.js",
    "publish-7x": "npm publish --tag 7x",
    "test": "mocha --exit ./test/*.test.js",
    "test-deno": "deno run --allow-env --allow-read --allow-net --allow-run --allow-sys --allow-write ./test/deno.js",
    "test-rs": "START_REPLICA_SET=1 mocha --timeout 30000 --exit ./test/*.test.js",
    "test-tsd": "node ./test/types/check-types-filename && tsd",
    "tdd": "mocha ./test/*.test.js --inspect --watch --recursive --watch-files ./**/*.{js,ts}",
    "test-coverage": "nyc --reporter=html --reporter=text npm test",
    "ts-benchmark": "cd ./benchmarks/typescript/simple && npm install && npm run benchmark | node ../../../scripts/tsc-diagnostics-check"
  },
  "main": "./index.js",
  "types": "./types/index.d.ts",
  "engines": {
    "node": ">=16.20.1"
  },
  "bugs": {
    "url": "https://github.com/Automattic/mongoose/issues/new"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/Automattic/mongoose.git"
  },
  "homepage": "https://mongoosejs.com",
  "browser": "./dist/browser.umd.js",
  "config": {
    "mongodbMemoryServer": {
      "disablePostinstall": true
    }
  },
  "funding": {
    "type": "opencollective",
    "url": "https://opencollective.com/mongoose"
  },
  "tsd": {
    "directory": "test/types",
    "compilerOptions": {
      "esModuleInterop": false,
      "strict": true,
      "allowSyntheticDefaultImports": true,
      "strictPropertyInitialization": false,
      "noImplicitAny": false,
      "strictNullChecks": true,
      "module": "commonjs",
      "target": "ES2017"
    }
  }
}

mongoose index.js:

/**
 * Export lib/mongoose
 *
 */

'use strict';

const mongoose = require('./lib/');

module.exports = mongoose;
module.exports.default = mongoose;
module.exports.mongoose = mongoose;

// Re-export for ESM support
module.exports.cast = mongoose.cast;
module.exports.STATES = mongoose.STATES;
module.exports.setDriver = mongoose.setDriver;
module.exports.set = mongoose.set;
module.exports.get = mongoose.get;
module.exports.createConnection = mongoose.createConnection;
module.exports.connect = mongoose.connect;
module.exports.disconnect = mongoose.disconnect;
module.exports.startSession = mongoose.startSession;
module.exports.pluralize = mongoose.pluralize;
module.exports.model = mongoose.model;
module.exports.deleteModel = mongoose.deleteModel;
module.exports.modelNames = mongoose.modelNames;
module.exports.plugin = mongoose.plugin;
module.exports.connections = mongoose.connections;
module.exports.version = mongoose.version;
module.exports.Aggregate = mongoose.Aggregate;
module.exports.Mongoose = mongoose.Mongoose;
module.exports.Schema = mongoose.Schema;
module.exports.SchemaType = mongoose.SchemaType;
module.exports.SchemaTypes = mongoose.SchemaTypes;
module.exports.VirtualType = mongoose.VirtualType;
module.exports.Types = mongoose.Types;
module.exports.Query = mongoose.Query;
module.exports.Model = mongoose.Model;
module.exports.Document = mongoose.Document;
module.exports.ObjectId = mongoose.ObjectId;
module.exports.isValidObjectId = mongoose.isValidObjectId;
module.exports.isObjectIdOrHexString = mongoose.isObjectIdOrHexString;
module.exports.syncIndexes = mongoose.syncIndexes;
module.exports.Decimal128 = mongoose.Decimal128;
module.exports.Mixed = mongoose.Mixed;
module.exports.Date = mongoose.Date;
module.exports.Number = mongoose.Number;
module.exports.Error = mongoose.Error;
module.exports.MongooseError = mongoose.MongooseError;
module.exports.now = mongoose.now;
module.exports.CastError = mongoose.CastError;
module.exports.SchemaTypeOptions = mongoose.SchemaTypeOptions;
module.exports.mongo = mongoose.mongo;
module.exports.mquery = mongoose.mquery;
module.exports.sanitizeFilter = mongoose.sanitizeFilter;
module.exports.trusted = mongoose.trusted;
module.exports.skipMiddlewareFunction = mongoose.skipMiddlewareFunction;
module.exports.overwriteMiddlewareResult = mongoose.overwriteMiddlewareResult;

// The following properties are not exported using ESM because `setDriver()` can mutate these
// module.exports.connection = mongoose.connection;
// module.exports.Collection = mongoose.Collection;
// module.exports.Connection = mongoose.Connection;

I’ve tried to convert the index.js file to ES but then the error just passes down to another .js file throwing the same error.

Bootstrap form not showing validation when used browser saved data

In the below code the bootstrap validation which is the green tick does not show when the data saved in the browser, but it works fine when the data is entered manually.

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags and Bootstrap CSS -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Registration Form</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    /* Optional: Adjust form width on larger screens */
    .registration-form {
      max-width: 500px;
      margin: auto;
    }

    /* Remove autofill background color in Chrome */
    input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0 1000px white inset !important; /* Changes background to white */
    -webkit-text-fill-color: #000 !important; /* Ensures text remains black */
  }
  </style>
</head>
<body>

<div class="container mt-5">
  <div class="registration-form">
    <div class="card">
      <div class="card-body">
        <h3 class="card-title text-center mb-4">Register</h3>
        <form class="needs-validation" novalidate>
          <!-- First Name and Last Name -->
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="firstName" class="form-label">First Name</label>
              <input type="text" class="form-control" id="firstName" pattern="^[A-Za-z]+$" placeholder="First Name" required>
              <div class="invalid-feedback">
                Please enter your first name (letters only).
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <label for="lastName" class="form-label">Last Name</label>
              <input type="text" class="form-control" id="lastName" pattern="^[A-Za-z]+$" placeholder="Last Name" required>
              <div class="invalid-feedback">
                Please enter your last name (letters only).
              </div>
            </div>
          </div>
          <!-- Email -->
          <div class="mb-3">
            <label for="emailAddress" class="form-label">Email</label>
            <input type="email" class="form-control" id="emailAddress" placeholder="Email" required>
            <div class="invalid-feedback">
              Please enter a valid email address.
            </div>
          </div>
          <!-- Password -->
          <div class="mb-3">
            <label for="password" class="form-label">Password</label>
            <input type="password" class="form-control" id="password" minlength="6" placeholder="Password" required>
            <div class="invalid-feedback">
              Please enter a password with at least 6 characters.
            </div>
          </div>
          <!-- Confirm Password -->
          <div class="mb-3">
            <label for="confirmPassword" class="form-label">Confirm Password</label>
            <input type="password" class="form-control" id="confirmPassword" minlength="6" placeholder="Confirm Password" required>
            <div class="invalid-feedback">
              Passwords do not match.
            </div>
          </div>
          <!-- Terms and Conditions -->
          <div class="form-check mb-3">
            <input type="checkbox" id="terms" class="form-check-input" required>
            <label class="form-check-label" for="terms">I agree to the terms and conditions</label>
            <div class="invalid-feedback">
              You must agree to the terms and conditions.
            </div>
          </div>
          <!-- Submit Button -->
          <div class="d-grid">
            <button class="btn btn-primary" type="submit">Register</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Bootstrap JS and custom validation script -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
(() => {
  'use strict';

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  const forms = document.querySelectorAll('.needs-validation');

  // Trigger validation for autofilled fields on page load
  const triggerAutofillValidation = () => {
    const autofillFields = document.querySelectorAll('input:-webkit-autofill');

    // Dispatch an input event for each autofilled field to trigger validation
    autofillFields.forEach(field => {
      field.dispatchEvent(new Event('input', { bubbles: true }));
    });
  };

  // On window load, trigger autofill validation
  window.addEventListener('load', triggerAutofillValidation);

  // Loop over each form and prevent submission if invalid
  Array.from(forms).forEach(form => {
    // Password and Confirm Password fields
    const password = form.querySelector('#password');
    const confirmPassword = form.querySelector('#confirmPassword');

    // Event listener to validate password match
    confirmPassword.addEventListener('input', function () {
      if (confirmPassword.value !== password.value) {
        confirmPassword.setCustomValidity('Passwords do not match');
      } else {
        confirmPassword.setCustomValidity('');
      }
    });

    // Form submission event
    form.addEventListener('submit', event => {
      // Check for validity
      if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
      }

      // Add Bootstrap validation classes
      form.classList.add('was-validated');
    }, false);

  });
})();
</script>

</body>
</html>  

See below images for reference

When data entered manually

When using browser saved data

I what to get the tick when the browser saved data is also used.

How to pass data from ajax sucess to other method in javascript?

Sorry, I am new to javascript and cannot understand how to pass the needed data.

Here is my ajax call:

$(document).ready(function (){
    loadSkiResortData();
});

function loadSkiResortData(){
    $.ajax({
       method: 'GET',
       url: '/admin/sknowed/loadSkiResortData',
       success: function(response){
           console.log(typeof response.weatherData);
           const obj = JSON.parse(response.weatherData);
           console.log(obj.hourly.temperature_2m);
           console.log(obj.hourly.time);
       }
    });
}

The above returns the “temperature” (obj.hourly.temperature_2m) and the data/time (obj.hourly.time). The temperature and date/time need to be passed to chart.js as follows;

const ctx = document.getElementById('myChart');

new Chart(ctx, 

{
    type: 'line',
    data: 
        {
            labels: // I want to replace this array with obj.hourly.time
                [
                    'Red', 
                    'Blue', 
                    'Yellow', 
                    'Green', 
                    'Purple', 
                    'Orange'
                ],
            datasets: 
                [
                    {
                        label: 'My chart label',
                        data: [12, 19, 3, 5, 2, 3], // I want to replace this array with obj.hourly.temperature_2m
                        borderWidth: 1
                    }
                ]
        },
}

I want to make the labels array equal to I want to obj.hourly.time and the data array equal to obj.hourly.temperature_2m.

Sorry but I would appreciate any pointers please.

Understanding Disabling Controls JavaSCript vs Code Behind

First time for any web dev, so this might be a really silly question because I don’t know something very basic.

This JQuery disables all the input controls in the PanlDL panel:

$('#PanlDL *').attr('disabled', true);

This JQuery will find those disabled controls:

var NumDisabled = $('#PanlDL :disabled');

However, when I run this code in the form’s LoadComplete event (which seems like the same thing) the 2nd JQuery above doesn’t find the controls as disabled:

ScriptManager.RegisterStartupScript(Page, Page.GetType, "DiablTestKey", "$('#PanlDL *').attr('disabled', true);", True)

I’ve tried using Page.ClientScript.RegisterStartupScript and also an Ajax Update Panel but they both have the same result. Similarly this line of code doesn’t find the someCtrl as being disabled if that control was disabled in the code behind using the ScriptManager line above:

var isDisabld = $(someCtrl).is('[disabled]');

What is the difference between running the Javascript from code behind? Does it have something to do with the “key” parameter used in the ScriptManager call?

Thanks for any help,
Ken

How to add a border around a masked image using canvas in JavaScript?

I am trying to mask an image using another image (acting as a mask) and add a border around the shape defined by the mask using the element in JavaScript.

Here’s the code I’m using:

function applyFiltersAndConvertToBase64(imageUrl, materialImage) {
    return new Promise((resolve, reject) => {
        const maskImg = new Image();
        const mainImg = new Image();
        maskImg.crossOrigin = "anonymous"; // Important for cross-origin images
        mainImg.crossOrigin = "anonymous";

        let imagesLoaded = 0;

        const onLoad = () => {
            imagesLoaded++;
            if (imagesLoaded === 2) {
                // Create a canvas element
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // Set canvas dimensions to the size of the mask image
                canvas.width = maskImg.width;
                canvas.height = maskImg.height;

                // Draw the mask image
                ctx.drawImage(maskImg, 0, 0);

                // Change composite mode to use the mask for clipping
                ctx.globalCompositeOperation = 'source-in';

                // Draw the main image to be clipped
                ctx.drawImage(mainImg, 0, 0, maskImg.width, maskImg.height);

                // Reset composite operation
                ctx.globalCompositeOperation = 'source-over';

                // Convert canvas to Base64
                const base64Image = canvas.toDataURL('image/png');
                resolve(base64Image);
            }
        };

        maskImg.onload = onLoad;
        mainImg.onload = onLoad;

        maskImg.onerror = reject;
        mainImg.onerror = reject;

        // Set the sources
        maskImg.src = imageUrl; // Mask image
        mainImg.src = materialImage; // Main image
    });
}

This function works fine for applying the mask and clipping the main image, but I’m struggling to add a border around the mask’s shape. The border either appears as a rectangle or does not appear at all, depending on the approach I’ve tried.

How can I add a border that follows the shape defined by the mask, rather than the canvas’ rectangular boundaries? I want the border to trace the exact edges of the mask.

Any help would be appreciated!

How can I add a border that follows the shape defined by the mask, rather than the canvas’ rectangular boundaries? I want the border to trace the exact edges of the mask.

MIME Type Errors. JS files being rendered like html

I have a website that I created a while back. Recently, I built a languages switching feature locally, and pushed it up through GitHub and into Vercel, expecting it to work just fine.

The page should have looked like this:

Web Page
Instead, I got this result:
Broken Page

Now, this result is telling, when you look at the code. Here, let me send you the code directly connected with this page:

<!-- index.html -->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Contact</title>
        <meta name="description" content="Do you want your child to grow up knowing what really matters? If so, we will gladly teach them!">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://cdn.tailwindcss.com"></script>
        <script type="module" src="/languageSwitch.js"></script>
        <script src="/indexComponent.js"></script>
        <link rel="icon" href="/logo.svg">
    </head>
    <body class=" bg-slate-200">
        <index-content></index-content>
        <img id="close" src="/close.svg" class="h-5 fixed top-14 right-5 -mr-2 mt-1 border border-red border-solid bg-slate-300 rounded-xl z-10 hover:bg-slate-400">
        <div id="btnsDiv" class="fixed right-2 top-14 bg-slate-800 pt-7 pb-4 pl-3 pr-5 rounded-sm grid gap-2 sm:flex">
            <button id="Spanish" class="text-sm bg-slate-300 px-2 py-1 mx-1 rounded-xl hover:bg-slate-400 text-slate-950">Español</button>
            <button id="English" class="text-sm bg-slate-300 px-2 py-1 rounded-xl hover:bg-slate-400 text-slate-950">English</button>
        </div>
    </body>
</html>
//indexComponent.js
class IndexContent extends HTMLElement {
  connectedCallback() {
      this.updateContent();  // Initialize with default content
  }

  updateContent(content = {}) {
      const { header = {}, main = {} } = content;

      const htmlContent = `
      <header class="shadow-md shadow-slate-700 w-screen py-2 bg-slate-800 flex justify-center items-center content-center">
        <nav class="w-fit flex justify-around items-center content-center">
          <p class="hover:bg-slate-700 px-2 py-1 rounded-sm text-slate-400 border-r border-solid border-slate-300/50"><a href="/good-news/gospel.html${window.location.search}">${header.linkOne || 'Good News'}</a></p>
          <p class="hover:bg-slate-700 px-2 py-1 rounded-sm text-slate-400 border-l border-solid border-slate-300/50"><a href="/index.html${window.location.search}">${header.linkTwo || 'Sign Up'}</a></p>
        </nav>
      </header>
      <main class="w-screen m-0 py-6 flex items-center justify-center">
        <div class="w-9/12">
          <h1 class="text-center font-bold h-5 text-2xl text-slate-900 py-2">${main.title || 'Contact Us'}</h1>
          <form action="https://getform.io/f/bejyndga" method="POST" class="grid justify-center p-8 gap-4">
            <div class="grid justify-center items-center content-center">
              <input class="mb-4 px-2 rounded-sm bg-slate-100 sm:w-60 md:w-80 w-52 text-sm py-1" type="text" name="Parent_Name" placeholder="${main.fields?.parentName || 'Parent Name'}">
              <input class="mb-4 px-2 rounded-sm bg-slate-100 w-52 sm:w-60 md:w-80  text-sm py-1" type="text" name="Child's Name'" placeholder="${main.fields?.childName || 'Child/Children's First Name(s)'}">
              <p class="text-xs pb-4 -mt-3 text-slate-900 w-52 sm:w-60 md:w-80">${main.fields?.fieldComment?.comment || '(if you have more than one child, separate their names with commas.)'}</p>
              <input class="mb-4 px-2 rounded-sm bg-slate-100  text-sm py-1" type="number" name="Phone_Number" placeholder="${main.fields?.phoneNumber || 'Phone Number'}">
              <input class="px-2 rounded-sm bg-slate-100  text-sm py-1" type="text" name="Address" placeholder="${main.fields?.address || 'Address'}">
            </div>
            <textarea class="px-2 rounded-sm bg-slate-100  text-sm py-1" name="Additional_Info" placeholder="${main.fields?.additInfo || 'If you need to give us additional information, feel free!'}" rows="6" cols="20"></textarea>
            <button type="submit" class="bg-slate-900 py-2 text-slate-50 rounded-3xl hover:bg-slate-800 active:bg-slate-950">${main.button || 'Send'}</button>
          </form>
          <p class="text-center py-4 -mt-8 italic text-sm">${main.alt || '(Or text us at (210) 549-6522)'}</p>
        </div>
      </main>
      `;
      this.innerHTML = htmlContent;
  }
}

customElements.define("index-content", IndexContent);

If you examine the code, you will see that only the html that is directly inside the index.html file is rendering. While the Web Component, along with the interpolated data is not displaying.

I’m getting three errors:
enter image description here

Details:

You can view the code on GitHub: https://github.com/QualityWebDev/Sunday_School

Thank you in advance!

Is it possible to return an empty slot from JavaScript’s map() function?

This site has a similar question: Possible to push empty slot to an array? I want to know if it’s possible for the Array.prototype.map callback to return an empty slot.

I tried this but it returns undefined instead:

console.log([1, 2, 3].map(() => {}));

I want to return empty slots so that I can simply call flat() on the return value to remove them. flat() does not remove undefined or null values.

I’m aware of the .filter(Boolean) trick, but I don’t like that solution because 0 is falsey, and I’ve never intended to remove that as a side effect of removing null/undefined elements: in my experience, .filter(Boolean) is a ticking time bomb in one’s code.

Svelte: Times New Roman Font Not Applying to Mathematical Expressions in OpenWebUI [duplicate]

I’m customizing the OpenWebUI project, which uses Svelte for the frontend, and I want to display mathematical expressions (numbers, variables, and operators) in Times New Roman font. However, despite making changes to the CSS and Svelte components, the font is not applying correctly to the mathematical content.

What I’ve Tried:

CSS: I’ve added a .math-content CSS class with font-family: 'Times New Roman', Times, serif; to ensure the font applies to all mathematical expressions. The class is intended to be used for numbers, variables, and operators in the LLM’s responses.

Svelte Modifications: In the relevant Svelte components (like MessageInput.svelte and Messages.svelte), I used JavaScript to wrap mathematical expressions in tags with the .math-content class using a regular expression.

The formattedMessage logic is applied using innerHTML, but the .math-content class is not being consistently applied to the expressions.

Font Installation: I’ve ensured that Times New Roman is installed on my system and also added a Google Fonts fallback link, but the math expressions still don’t display in the correct font.

Goal: My goal is for all mathematical expressions (numbers, variables like x, and operators such as +, -, *, /, ^) in the LLM’s responses to be displayed in Times New Roman font. Currently, the font is not rendering properly for the math expressions, and I’m unsure why the .math-content class isn’t being applied as expected.

getting error as “home.models.Cart.DoesNotExist: Cart matching query does not exist.”

Views.py code:

def plus_cart(request):
    if request.method == "GET":
        pk = request.GET.get('prod_id')
        c = Cart.objects.get(pk=pk, user=request.user)
        c.quantity+=1
        c.save(update_fields=['quantity'])
        user = request.user
        cart = Cart.objects.filter(user=user)
        amount = 0
        for p in cart:
            value = p.quantity * p.product.dp
            amount = amount + value
        totalamount = amount + 40
        data={
            'quantity':c.quantity,
            'amount':amount,
            'totalamount':totalamount,
        }
        return JsonResponse(data)

in urls.py, following url is added:
path(‘pluscart/’, views.plus_cart),

in the static folder, myscript.js has following code:

$('.plus-cart').click(function(){
    var id=$(this).attr("pid").toString();
    var eml=this.parentNode.children[2]
    console.log("pid= ", id)
    $.ajax({
        type:"GET",
        url:"/pluscart",
        data:{
            prod_id:id
        },
        success:function(data){
            console.log("data= ", data);
            eml.innerText=data.quantity 
            document.getElementById("amount").innerText=data.amount 
            document.getElementById("totalamount").innerText=data.totalamount
        }
    })
    })

while querying the database the python manage.py shell, user and cart_item with the required prod_id checked and found ok. but error is generated while executing the code. Please help.