WalletPass Notification API Returns 200 but No Push Notification Received

Problem:
When using the WalletPass Notification API to push updates to a pass, the API returns a 200 OK response, indicating success. However, no push notification is actually delivered to the WalletPass app, and the pass does not update as expected.

Expected Behavior:
A notification should be sent to the WalletPass app, prompting the pass to refresh and display updated information.

Actual Behavior:
The API call returns a successful response (HTTP 200), but no notification appears, and the pass remains unchanged.

Steps to Reproduce:

Send a POST request to the WalletPass Notification API endpoint with a valid pushToken or serialNumber.

Observe that the response is 200 OK.

Check the WalletPass app — no notification or pass update occurs.

Additional Notes:

The issue is reproducible with multiple passes.

The payload and authentication are confirmed valid.

No error or failure message is returned by the API.

What causes the failure to display all article comments in my Laravel 8 blogging application?

I am working on a blogging application (link to GitHub pull request) in Laravel 8.

In appHttpControllersArticlesController.php I have methods for displaying article details, with comments included:

class ArticlesController extends FrontendController
{
    protected $per_page = 12;
    protected $comments_per_page = 10;
    protected $comments_orderby_direction = 'desc';

    public function show($slug)
    {
        $article = Article::visible()->where('slug', $slug)->firstOrFail();

        // Throttle views
        $sessionKey = 'article_viewed_' . $article->id;
        $lastViewedAt = session($sessionKey);
        if (!$lastViewedAt || Carbon::createFromTimestamp($lastViewedAt)->diffInMinutes(now()) >= 60) {
            $article->increment('views');
            session()->put($sessionKey, now()->timestamp);
        }

        // Older article
        $old_article = Article::visible()
            ->where(function ($q) use ($article) {
                $q->where('published_at', '<', $article->published_at)
                  ->orWhere(function ($q2) use ($article) {
                      $q2->where('published_at', $article->published_at)
                         ->where('id', '<', $article->id);
                  });
            })
            ->orderBy('published_at', 'desc')
            ->orderBy('id', 'desc')
            ->first();

        // Newer article
        $new_article = Article::visible()
            ->where(function ($q) use ($article) {
                $q->where('published_at', '>', $article->published_at)
                  ->orWhere(function ($q2) use ($article) {
                      $q2->where('published_at', $article->published_at)
                         ->where('id', '>', $article->id);
                  });
            })
            ->orderBy('published_at', 'asc')
            ->orderBy('id', 'asc')
            ->first();

        // Approved top-level comments with approved replies
        $comments = Comment::where('article_id', $article->id)
            ->where('approved', 1)
            ->whereNull('parent_id')
            ->with(['replies' => function ($query) {
                $query->where('approved', 1);
            }])
            ->orderBy('id', 'desc')
            ->get();

        $comments_count = $comments->count();

        return view(
            'themes/' . $this->theme_directory . '/templates/single',
            array_merge($this->data, [
                'categories'        => $this->article_categories,
                'article'           => $article,
                'old_article'       => $old_article,
                'new_article'       => $new_article,
                'comments'          => $comments,
                'comments_count'    => $comments_count,
                'comments_per_page' => $this->comments_per_page,
                'tagline'           => $article->title,
                'is_infinitescroll' => false
            ])
        );
    }

    public function get_comments_ajax(Request $request)
    {
        if (!$request->ajax()) exit();

        $article_id  = $request->post('article_id');
        $page_number = $request->post('page');
        $offset      = $this->comments_per_page * $page_number;
        $more_comments_to_display = true;

        $data['comments'] = $this->get_commentQuery($article_id, $this->comments_per_page, $offset)->get();
        $content = '';
        if ($data['comments']->count()) {
            $content .= view(
                'themes/' . $this->theme_directory . '/partials/comments-list',
                array_merge($data, [
                    'is_infinitescroll' => $this->is_infinitescroll,
                    'theme_directory'   => $this->theme_directory,
                    'article_id'        => $article_id
                ])
            );
        } else {
            $more_comments_to_display = false;
        }

        echo json_encode([
            'html' => $content,
            'page' => $page_number,
            'more_comments_to_display' => $more_comments_to_display,
            'article_id' => $article_id
        ]);
        exit();
    }

    private function get_commentQuery(int $article_id, int $limit = 0, int $offset = 0): object
    {
        $commentQuery = Comment::where(['article_id' => $article_id, 'approved' => 1])
            ->orderBy('id', $this->comments_orderby_direction)
            ->with(['replies' => function ($query) {
                $query->where('approved', 1);
            }]);

        if ($offset > 0) $commentQuery = $commentQuery->offset($offset);
        if ($limit > 0)  $commentQuery = $commentQuery->limit($limit);

        return $commentQuery;
    }
}

The comment model:

class Comment extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'article_id',
        'parent_id',
        'body',
        'approved'
    ];

        // Join users to comments
        public function user() {
            return $this->belongsTo(User::class);
        }

        // Join articles to comments
        public function article() {
            return $this->belongsTo(Article::class);
        }

        // Join comment replies to comments
        public function replies() {
          return $this->hasMany(Comment::class, 'parent_id');
        }
}

The Blade list of comments (and replies):

@if ($comments && count($comments))
    <div class="comments mt-4" id="comments_container">
        @foreach ($comments as $comment)
            @if (is_null($comment->parent_id))
                <div x-data="{ showEdit: false, showReply: false }" class="card bg-light comment mb-3" id="comment-{{ $comment->id }}">
                    <h5 class="card-header">
                        <span class="row">
                            <span class="col-md-6 text-dark avatar">
                                <img src="{{ asset('images/avatars/' . $comment->user->avatar) }}"
                                    alt="{{ $comment->user->first_name }} {{ $comment->user->last_name }}"
                                    class="rounded-circle me-1">
                                {{ $comment->user->first_name }} {{ $comment->user->last_name }} says:
                            </span>
                            <span class="col-md-6 text-dark d-none d-md-flex align-items-center justify-content-end">
                                {{ date('jS M Y', strtotime($comment->created_at)) }}
                            </span>
                        </span>
                    </h5>

                    <div class="card-body bg-white p-2">
                        <p class="comment__text">{{ $comment->body }}</p>
                        <ul class="comment-actions list-unstyled">
                            @if (Auth::check() && $comment->user->id !== Auth::id())
                                <li>
                                    <a class="comment-reply" @click.prevent="showReply = !showReply">
                                        <i class="fa-regular fa-comments"></i>
                                        <span x-text="showReply ? 'Cancel' : 'Reply'"></span>
                                    </a>
                                </li>
                            @endif
                            @if (Auth::check() && $comment->user->id === Auth::id())
                                <li>
                                    <a class="comment-edit" @click.prevent="showEdit = !showEdit">
                                        <i class="fa-regular fa-pen-to-square"></i>
                                        <span x-text="showEdit ? 'Cancel' : 'Edit'"></span>
                                    </a>
                                </li>
                                <li>
                                    @include(
                                        'themes/' . $theme_directory . '/partials/comment-delete-form',
                                        ['commentOrReply' => $comment]
                                    )
                                </li>
                            @endif
                        </ul>

                        {{-- Edit form --}}
                        <div class="mt-2 comment-edit-form-wrapper" x-show="showEdit" x-transition>
                            @include('themes/' . $theme_directory . '/partials/comment-edit-form', [
                                'commentOrReply' => $comment,
                            ])
                        </div>

                        {{-- Reply form --}}
                        @if (Auth::check())
                            <div class="mt-2 reply-form" x-show="showReply" x-transition>
                                @include('themes/' . $theme_directory . '/partials/comment-form', [
                                    'article' => $article,
                                    'parent_id' => $comment->id,
                                ])
                            </div>
                        @endif
                    </div>

                    {{-- Replies --}}
                    @if ($comment->replies && count($comment->replies))
                        <div class="replies ps-4 mt-3">
                            @foreach ($comment->replies as $reply)
                                <div x-data="{ showEdit: false }" class="card bg-light comment mb-2 me-2"
                                    id="comment-{{ $reply->id }}">
                                    <h5 class="card-header">
                                        <span class="row">
                                            <span class="col-md-6 text-dark avatar">
                                                <img src="{{ asset('images/avatars/' . $reply->user->avatar) }}"
                                                    alt="{{ $reply->user->first_name }} {{ $reply->user->last_name }}"
                                                    class="rounded-circle me-1">
                                                {{ $reply->user->first_name }} {{ $reply->user->last_name }} says:
                                            </span>
                                            <span
                                                class="col-md-6 text-dark d-none d-md-flex align-items-center justify-content-end">
                                                {{ date('jS M Y', strtotime($reply->created_at)) }}
                                            </span>
                                        </span>
                                    </h5>

                                    <div class="card-body bg-white p-2">
                                        <p class="comment__text">{{ $reply->body }}</p>
                                        <ul class="comment-actions list-unstyled">
                                            @if (Auth::check() && $reply->user->id === Auth::id())
                                                <li>
                                                    <a class="comment-edit" @click.prevent="showEdit = !showEdit">
                                                        <i class="fa-regular fa-pen-to-square"></i>
                                                        <span x-text="showEdit ? 'Cancel' : 'Edit'"></span>
                                                    </a>
                                                </li>
                                                <li>
                                                    @include(
                                                        'themes/' .
                                                            $theme_directory .
                                                            '/partials/comment-delete-form',
                                                        ['commentOrReply' => $reply]
                                                    )
                                                </li>
                                            @endif
                                        </ul>

                                        {{-- Edit form --}}
                                        <div class="mt-2 comment-edit-form-wrapper" x-show="showEdit" x-transition>
                                            @include(
                                                'themes/' . $theme_directory . '/partials/comment-edit-form',
                                                ['commentOrReply' => $reply]
                                            )
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endif
                </div>
            @endif
        @endforeach
    </div>
@endif

The problem

When loading comments on page scroll via AJAX is disabled (I have an option in the “Settings” section of the CMS for that), for a reason I was unable to spot, not all the article comments and replies are loaded, although I have approved all comments related to the article I checked.

I suspect the bug is in the ArticlesController, but I was unable to spot it.

This pat seems redundant because there is a get_commentQuery method already:

// Approved top-level comments with approved replies
$comments = Comment::where('article_id', $article->id)
        ->where('approved', 1)
        ->whereNull('parent_id')
        ->with(['replies' => function ($query) {
            $query->where('approved', 1);
        }])
        ->orderBy('id', 'desc')
        ->get();
  1. What is the reason for this bug?
  2. What is the most robust way to fix it?

::whereUuid() is not defined in laravel php

I am trying to get the order that has the client and service as a foreignkey with whereUuid with this line of code:

$order = Order::whereUuid($order_id)->with(['client', 'service'])->first();

But the intellisense is showing me this error, although I did not see any error on the logs. Or I don’t know how to check for error logs in laravel that is running in a docker container.

Method Order::whereUuid() is not defined. The call is passed to the magic Model::__callStatic() method.PHP(PHP6615)

Please can you help me solve this or if there is a better approach to handle the matter, I will appreciate it. Thank you.

Not load animation when I click button

I want that When Click on Button. It will start loading an animation untill p.php is fetched values.

HTML CODE

<input type="text" id="myInput" placeholder="Enter something">
<button id="myButton">Send Data</button>
<div id="responseArea"></div>

Javascript code

<script type="text/javascript">
document.getElementById('myButton').addEventListener('click', function() {
    const inputValue = document.getElementById('myInput').value;
    const data = { inputData: inputValue }; // Create an object to send

    fetch('p.php', { // Replace with your PHP script path
        method: 'POST',
        headers: {
            'Content-Type': 'application/json', // Specify content type
        },
        body: JSON.stringify(data), // Convert data to JSON string
    })
    .then(response => response.text()) // Or .json() if PHP returns JSON
    .then(responseText => {
        document.getElementById('responseArea').innerHTML = responseText;
    })
    .catch(error => {
        console.error('Error:', error);
    });
});
    </script>

Can anyone do it?

Axios request fails with error status code 500: Internal Server error

I’m try to create code for downloading template file in my project so after click on button I wand to download file throw this code:

axios({
  url: url,
  method: 'POST',
  responseType: 'blob',
  headers: {
    authorization: `Bearer ${token}`,
  },
//  data: postData
}).then((response) => {
  const href = URL.createObjectURL(response.data);
  const link = document.createElement('a');
  link.href = href;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(href);
  //if (onDownloaded) onDownloaded(postData);
}).catch((err) => {
  console.error("Download failed:", err.message);
});

but I face to 500: Internal Server error for axios line.

I check my URL and it was true

Are there linters for TypeScript code that check if all expressions involving a int32 are followed by a bitwise “OR” operator?

I like that JavaScript and TypeScript allow for hardware-accelerated 32-bits integers (instead of the 64-bits floating point that is the default) if one uses the bit-wise “OR” operator like this:

let a: int32 = 1234;

// hardware-accelerated integral division by 3
a = (a / 3) | 0; 

However, the problem is that it’s easy for software developers to overlook that and forget to add the bit-wise operator when required (leading to the loss of the implied 32-bits integer type and it becomes promoted to a 64-bits floating type). It would be convenient if there were linters that would enforce that. Does such a linter exists?

I’m expecting that a tool for enforcing code style (linter) exists but the ones I’m aware of (eslint, rslint) do not seem to have the feature that I expect.

Generating Key & Nonce Pairs from Web Crypto API vs from Word List. Is entropy the same?

I want to find out if the 2 methods shown below achieve the same level of entropy.

For this first secure method, a 32 byte / 256 bit key and a 12 byte / 96 bit nonce are generated using the JavaScript Web Crypto API which is guaranteed to generate cryptographically strong random values.

Therefore we can affirm that the key & nonce contain maximum entropy for their respective sizes.

function generateSecureKeyNoncePair() {

  const keyBytes = new Uint8Array(32); // Buffer for random values
  crypto.getRandomValues(keyBytes);

  const nonceBytes = new Uint8Array(12); // Buffer for random values
  crypto.getRandomValues(nonceBytes);

  return {
    keyBytes,
    nonceBytes
  };

}

const { keyBytes, nonceBytes } = generateSecureKeyNoncePair();

console.log(keyBytes);
console.log(nonceBytes);

Next, inspired by https://developer.blockchaincommons.com/bytewords/, we have another function which selects 11 four letter words from a wordlist and slices the first 8 words for the key and the remaining 3 words for the nonce.

The reason for a wordlist of 256 four letter words is that these words can be converted to Uint8Array and then the Uint8Array can be converted to Uint32Array which can be used in a ChaCha20 state.

// wordList (256 four-letter words)
const wordList = [
  "able", "acid", "also", "apex", "aqua", "arch", "atom", "aunt", "away", "axis",
  "back", "bald", "barn", "belt", "beta", "bias", "blue", "body", "brag", "brew",
  "bulb", "buzz", "calm", "cash", "cats", "chef", "city", "claw", "code", "cola",
  "cook", "cost", "crux", "curl", "cusp", "cyan", "dark", "data", "days", "deli",
  "dice", "diet", "door", "down", "draw", "drop", "drum", "dull", "duty", "each",
  "easy", "echo", "edge", "epic", "even", "exam", "exit", "eyes", "fact", "fair",
  "fern", "figs", "film", "fish", "fizz", "flap", "flew", "flux", "foxy", "free",
  "frog", "fuel", "fund", "gala", "game", "gear", "gems", "gift", "girl", "glow",
  "good", "gray", "grim", "guru", "gush", "gyro", "half", "hang", "hard", "hawk",
  "heat", "help", "high", "hill", "holy", "hope", "horn", "huts", "iced", "idea",
  "idle", "inch", "inky", "into", "iris", "iron", "item", "jade", "jazz", "join",
  "jolt", "jowl", "judo", "jugs", "jump", "junk", "jury", "keep", "keno", "kept",
  "keys", "kick", "kiln", "king", "kite", "kiwi", "knob", "lamb", "lava", "lazy",
  "leaf", "legs", "liar", "limp", "lion", "list", "logo", "loud", "love", "luau",
  "luck", "lung", "main", "many", "math", "maze", "memo", "menu", "meow", "mild",
  "mint", "miss", "monk", "nail", "navy", "need", "news", "next", "noon", "note",
  "numb", "obey", "oboe", "omit", "onyx", "open", "oval", "owls", "paid", "part",
  "peck", "play", "plus", "poem", "pool", "pose", "puff", "puma", "purr", "quad",
  "quiz", "race", "ramp", "real", "redo", "rich", "road", "rock", "roof", "ruby",
  "ruin", "runs", "rust", "safe", "saga", "scar", "sets", "silk", "skew", "slot",
  "soap", "solo", "song", "stub", "surf", "swan", "taco", "task", "taxi", "tent",
  "tied", "time", "tiny", "toil", "tomb", "toys", "trip", "tuna", "twin", "ugly",
  "undo", "unit", "urge", "user", "vast", "very", "veto", "vial", "vibe", "view",
  "visa", "void", "vows", "wall", "wand", "warm", "wasp", "wave", "waxy", "webs",
  "what", "when", "whiz", "wolf", "work", "yank", "yawn", "yell", "yoga", "yurt",
  "zaps", "zero", "zest", "zinc", "zone", "zoom"
];

// Encode String Array to Uint8Array
const enc = new TextEncoder();
const stringArray2bytes = (words) => enc.encode(words.join(""));

function generateAsciiKeyNoncePair() {
  const selected = new Set();
  const randomBytes = new Uint8Array(22); // Buffer for random values
  
  crypto.getRandomValues(randomBytes);
  let byteIndex = 0;
  
  while (selected.size < 11) {
    if (byteIndex >= randomBytes.length) {
      crypto.getRandomValues(randomBytes);
      byteIndex = 0;
    }
    selected.add(randomBytes[byteIndex++]);
  }
  
  const indices = Array.from(selected);
  
  return {
    keyAscii: indices.slice(0, 8).map(i => wordList[i]),
    nonceAscii: indices.slice(8, 11).map(i => wordList[i])
  };
}

const { keyAscii, nonceAscii } = generateAsciiKeyNoncePair();

console.log("Ascii Key:", keyAscii);
console.log("Ascii Nonce:", nonceAscii);

console.log("Ascii Key:", stringArray2bytes(keyAscii));
console.log("Ascii Nonce:", stringArray2bytes(nonceAscii));

My question is, regardless of how user friendly this function is, am I naive to assume it achieves the same level of entropy as the first function? I ask because I can’t help but to think the word list contains words which are part of the English alphabet which is 26 letters in total unlike Uint8Array filled by crypto.getRandomValues() which is 256 bytes long.

Embed YouTube Videos With No Ads

I am attempting to develop a robust, custom client-side LoFi Music player for live-streaming YouTube content (like 24/7 radio streams) that is guaranteed ad-free, without relying on browser extensions like uBlock Origin.
The Challenge
Standard YouTube embeds (youtube-nocookie.com/embed/) are unreliable for 100% ad-free playback, as ads (especially pre-rolls or mid-rolls on live streams) can still be served through the iframe or loaded via the YouTube API.
I have observed a specific implementation—for example, on sites like lofimusic.app (which streams the Lofi Girl channel)—that successfully loads the YouTube stream and plays it in a custom, minimal UI.
My hypothesis is that this approach bypasses the official player entirely by finding and loading the underlying HLS/DASH manifest URL, filtering out the ad segments at the manifest level, and playing the content stream directly in a library like video.js.

What I’ve Tried

  • Standard youtube-nocookie.com embed: This reduces tracking but still allows ads served from the video creator/YouTube.

  • YouTube IFrame Player API: Using the official API gives control but honors all ad settings, making it impossible to block pre-rolls/mid-rolls client-side.

  • Client-Side Stream Sniffing (Developer Console): Attempted to monitor network traffic for the .m3u8 or .mpd manifest files when the stream loads, but the player obscures the URL and the initial manifest request is often signed/ephemeral.
    The Core Question
    For an established live-stream YouTube channel (e.g., Lofi Girl), what is the most reliable, modern client-side technique—primarily using JavaScript and/or a custom media library—to:

  • Retrieve the current, non-expiring video ID (or stream ID) from the live channel page.

  • Generate or retrieve the specific HLS (.m3u8) or DASH (.mpd) manifest URL for the raw media stream.

  • Filter/Proxy this manifest client-side (e.g., in a Service Worker or WebAssembly component) to strip out ad-related segments (SSAI or CSAI markers) before playback begins in a custom player (e.g., Video.js or hls.js)?
    I am specifically looking for insights into the first two steps: how to programmatically get the raw stream URL from a YouTube live video on the client-side without a persistent server-side proxy.

Capacitor Firebase Firestore onSnapshot returning Promise breaks React useEffect cleanup with “TypeError: e is not a function”

I’ve been banging my head against the wall for days on this one. I have a React app that works perfectly in the browser, but when I build it for iOS using Capacitor, I keep getting this error: TypeError: e is not a function in the minified production code.

I’m using Firebase Firestore real-time listeners to display live data updates in my app. The issue is with how Capacitor’s Firebase plugoin handles the onSnapshot cleanup function.n React, you’re supposed to return a cleanup function from useEffect, right? Like this:

useEffect(() => {
  const unsubscribe = onSnapshot(query, (snapshot) => {
    // handle data
  });
  
  return () => unsubscribe();  // cleanup when component unmounts
}, []);

This works great with the regular Firebase web SDK. But the Capacitor Firebase plugin (@capacitor-firebase/firestore) doesn’t return a function – it returns a Promise that eventually gives you a callback ID. I’ve been trying to wrap this in a way that React will accept, but something breaks during the minification process.

My Wrapper Code
Here’s what I’ve been trying:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';
import { onSnapshot as webOnSnapshot } from 'firebase/firestore';

export function onSnapshot(queryRef, callback, errorCallback) {
  if (isCapacitor()) {
    // This is where things get tricky...
    const unsubscribeHolder = { callbackId: null, isUnsubscribed: false };
    
    // Start the listener (this returns a Promise)
    FirebaseFirestore.addCollectionSnapshotListener(
      {
        reference: queryRef._path,
        compositeFilter: queryRef._compositeFilter
      },
      (event) => {
        if (!unsubscribeHolder.isUnsubscribed) {
          callback(processSnapshot(event));
        }
      }
    ).then(listener => {
      // Store the callback ID for cleanup
      unsubscribeHolder.callbackId = listener.callbackId;
    }).catch(errorCallback);
    
    // Return a function that uses the holder
    return function() {
      unsubscribeHolder.isUnsubscribed = true;
      if (unsubscribeHolder.callbackId) {
        FirebaseFirestore.removeSnapshotListener({ 
          callbackId: unsubscribeHolder.callbackId 
        });
      }
    };
  }
  
  // Browser version works fine
  return webOnSnapshot(queryRef, callback, errorCallback);
}

In development and production, for the browser mode, everything works perfectly. But on iOS in dev mode: Listener starts but cleanup errors, and on iOS in production, it completely breaks with that cryptic TypeError: e is not a function error.

The error happens when the component unmounts and React tries to call the cleanup function. It’s like React’s minifier is doing something to the code that breaks the Promise-to-function bridge I’m trying to create.

I’ve tried:

  1. Returning the unsubscribe function synchronously (still breaks after minification)
  2. Checking typeof unsubscribe === ‘function’ before calling it (the check passes but it still errors!)
  3. Multiple variations of the holder pattern
  4. Different Promise wrappers

I think the problem is that Capacitor’s addCollectionSnapshotListener is inherently async (returns a Promise), but React’s useEffect expects a synchronous function return. When React Scripts minifies everything for production, something about that conversion breaks in a way I can’t debug because it’s all minified.

My questions…

  1. Has anyone actually gotten real-time Firestore listeners working with Capacitor + React in production?
  2. Is there a proper way to bridge Capacitor’s async API to React’s synchronous cleanup pattern?

*Edit:
Environment is:

  {
      "@capacitor-firebase/firestore": "^7.3.1",
      "@capacitor/core": "^7.4.3",
      "firebase": "^11.2.0",
      "react": "^19.0.0",
      "react-scripts": "5.0.1"
    }

**Edit:
The error specifically happens at component unmount when React tries to call the returned cleanup function. The console shows the listener starting fine, but then TypeError: e is not a function when the component unmounts.

Javascript, Radios And Checkbox: How to make a “checked” item work upon opening

Javascript

function changeBorder() {
    const monitor = document.querySelector(".Screen");
    const border = document.getElementById("ScreenBorder");

    border.addEventListener("change", () => { border.checked ? monitor.style.border = "5px solid purple" : monitor.style.border = "1px solid black"; });
}

function changeBG() {
    const screen = document.querySelector(".Screen");
    const screenbackground = document.querySelectorAll('INPUT[name="r"]');

    screenbackground.forEach(radio => {
        radio.addEventListener('click', () => {
            const bgColor = radio.value;
            screen.style.background = bgColor;
        });
    });
}

changeBorder();
changeBG();

CSS

DIV.Screen {
    border: 1px solid black;
    width: 256px;
    height: 256px;
}

HTML

<DIV class="Screen">
</DIV>

<P>
<INPUT type="radio" name="r" value="red" checked>Red
<INPUT type="radio" name="r" value="blue">Blue
<INPUT type="radio" name="r" value="green">Green
</P>

<P><INPUT id="ScreenBorder" type="checkbox" name="checkbox" />Violet Border</P>

This code is a demonstration of two features, the checkboxes and the radios. A black-bordered box appears with two ways for you to change its style. Check on the checkbox to change the border to a 5px solid purple, uncheck it to go back to its initial 1px solid black. Use the radio buttons to change the background color of the box to either red, green or blue.

Pay special attention to the radio buttons. Red is set to “checked”, meaning the box’s color should have been set to red by default upon opening or refreshing this ask page, but it’s not. Instead, there is no color, and in order to make the box turn red, you have to force it by clicking on the red radio dial. Compare that to the checkbox input, where the behavior of toggling between checked and unchecked parameters works as intended.

I’ve always thought that whatever item is labelled “checked” is automatically active, provided the check declarations are made within your Javascript. In the border checkbox toggle example (see border.addEventListener), the original fallback option was set to “initial,” and in this case the box would go back to its 1px solid black style. However, the “initial” keyword did not work, for the entire border disappeared during my test, so I had to explicitly state “1px solid black” in that same line as an insurance measure.

My initial question was on why the “checked” feature works better on checkboxes instead of radios, but to be blunt, I need a better grasp on how the “checked” feature works when it comes to Javascript. How do I rewrite this code so that when I open this web page, the box will have automatically changed color to whatever value was set? If red was “checked”, the box is already red, and so on.

How to render MathJax inside of an SVG

I have a website which includes svg-images which themselves include mathematical formulas that should be rendered using MathJax. As far as I know, this isn’t supported natively (i.e., by just putting the LaTeX-formulas within the SVG.

In the past, I have used the javascript code from this answer by Freddie Page which worked quite nicely for MathJax 2. However, I would now like to switch to MathJax 4 and can’t quite get this code to work again. The following code is my current best try of adapting it:

<!DOCTYPE html>
<html>
    <head>
    <script>
      MathJax = {
        tex: {
            inlineMath: {'[+]': [['$', '$']]}
        }
        startup: {
            ready: () => {
                MathJax.startup.defaultReady();
                MathJax.startup.promise.then(() => {
                    generateTeXinSVGs();
                });
            }
        }
      };
    </script>
    
    <script id="MathJax-script" defer src="https://cdn.jsdelivr.net/npm/[email protected]/tex-svg.js"></script>
        
    </head>
    <body>
    <p>
           An SVG with the formula $a^2+^2=c^2$ inside it:
    </p>
 
    <svg width="360" height="170" viewbox="0 0 360 170">
        <circle cx="80" cy="80" r="40" stroke-width="10" fill="None" stroke="red" />
        <text x="80" y="60">a^2+b^2=c^2</text>          
        <svg class="TeXinSVG" x="80" y="80"><text>a^2+b^2=c^2</text></svg>
    </svg> 
    
    <script type="text/javascript">
        // adapted from: https://stackoverflow.com/a/52011013
        // Define a function that takes LaTeX source code
        // and places the resulting generated SVG in a target SVG element.
        const mathSVG = async function (latex, target) {
          // First create a new element to hold the initial Latex code
          // and eventual MathJax generated SVG. 
          let mathBuffer = document.createElement("div");
          document.body.appendChild(mathBuffer);
        
          // Update the buffer with the source latex.
          mathBuffer.textContent = latex;
          // Get MathJax to process and typeset.
          await MathJax.typeset([mathBuffer]);
        
          var svg = mathBuffer.childNodes[0];
          svg.setAttribute("y", "0pt");
          // Move the generated svg from the buffer to the target element
          target.appendChild(svg);
        };
        
        async function generateTeXinSVGs() {
            listOfSVGs = document.getElementsByClassName("TeXinSVG");
            var i;
            for (i = 0; i < listOfSVGs.length; i++) {
                svgElement = listOfSVGs[i];
                latex = svgElement.children[0].textContent;
                svgElement.innerHTML = "";
                await mathSVG("$" + latex + "$", svgElement);
            }
        }
        </script>   
    </body>
</html>

It works insofar as it adds the output of MathJax to the SVG – however, nothing is displayed. As far as I can see, (part of) the problem seems to be that MathJax 2 created an SVG as top-level element which could then be placed within the SVG, whereas MathJax 4 creates a mjx-container as top-level element which, I guess, cannot be part of an SVG?

If one changes the line

var svg = mathBuffer.childNodes[0];

in the above code to

var svg = mathBuffer.childNodes[0].childNodes[0];

then the first part of the formula (the a^2) gets added to the SVG (and displayed – though slightly cropped). But adding the formula piece-by-piece does not feel like the right direction to me.

Can you help me adapt this code to MathJax 4?
(or maybe there are now better ways of achieving what I want in MathJax 4? Then I am of course also happy to hear about those)

Send array of objects to .NET controller action

I am trying to pass a javascript array of objects to a .NET controller action List<> parameter. Below is my C#

    [HttpPost]
    public bool Import([FromBody]List<Element> element)
    {

        uint srcAddrInt = ConvertIpAddressToUInt(element.SRC_Addr);
        Console.WriteLine($"The IP address {element.add} as an integer is: {int}");

        return true;
    }

Below is the variable I am passing and the ajax call

importData.push({
 ACLId: 11,
 DeviceId: 2,
 ACLGroupId: 5,
 ProtocolId: 27,
 LiftDate: liftDate,
 ActionDate: actionDate,
 RemedyTckt: remedyTicket,
 ITSMTckt: itsmTicket,
/* CommandView: cleanCmdVar,*/
 SRC_Addr: srcAddr,
 SRC_Mask: "0.0.0.0",
 DST_Addr: "0.0.0.0",
 DST_Mask: "255.255.255.255",
 ArinInfo: arin,
 FlagLogInput: 1,
 FlagLog: 0,
 Active: 0

});

var jsonData = JSON.stringify(importData);

$.ajax({
url: '/GAM/ACE/Import',
type: 'POST',             
data: jsonData,
contentType: "application/json; charset=utf-8",
success: function (result) {
    if (result) {                   
        $('#loading-overlay').fadeOut();
    } else {
        alert("Error. Import unsuccessful.");
        $('#loading-overlay').fadeOut();
    }
},
error: function (jqXHR, textStatus, errorThrown) {
    $('#loading-overlay').fadeOut();
    alert("Unable to import data. Error with /GAM/ACE/ImportAce ." + errorThrown);;
}

});

I am not sure what I am doing wrong. The element parameter for the controller is received and shows the objects in the list. But each object’s values are null. None of the data is coming through. I can see the payload coming through correctly. Any suggestions are appreciated

OSM Buildings viewer.remove() and viewer.destroy() not working propperly

Kinda newbie at programming so please bear withe me…

So I am trying to dynamically add and remove objects from the OSMBuildings 3dviewer using Java Script.

Short explaination:
I tried using the .remove() method to no avail… then found the .destroy() method but it also didnt work (In almost all scenarios that i tested i get 0 errors/a completely silent fail and everything just continues without removing the object)

Then after that tried to use the .destroy method + clearing the html div to clear the whole map and just reload all objects except the one that i want to remove but the map starts flashing red when i create a new one (probably because the old one is not cleared completely).

Detailed explaination/rant:
The “documentation” (https://osmbuildings.org/documentation/viewer/api) mentions the .remove() method which doesnt seem to be working no matter what i try (i tried viewer.remove(object itself), i tried using viewer.remove(‘id’ of object), i tried object.remove() etc etc). I even went through the source code just to find:

remove(object) {
   if (object.destroy) {
       object.destroy()
   }
}

i then tried the object.destroy method which also did NOTHING… I didnt even get any error message in any of these tests except for object.remove().

after that i tried to use a rather unsatisfying workaround (as described in the seconnd half of my short explaination) by clearing the div and destroying the map and creating a new one without the object that i want to remove. But that just makes the new map flash red and glitch… I then tried to just delete the div and create a new div with the same name but then OSMBuildings does not seem to find the div at all (my guess since the error message is not really helpful) despite the div definitely existing….

Any advice is highly appreciated.

I am working with Html, JS, and CSS on windows 11 pro using Chrome and Opera to test my page.

i tried too many things to go into detail on all of them but ill attach my current attempt at removing an object.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3D Map with OSM Buildings</title>
  
  <link href="https://cdn.osmbuildings.org/4.1.1/OSMBuildings.css" rel="stylesheet">
  <script src="https://cdn.osmbuildings.org/4.1.1/OSMBuildings.js"></script>

  <style>
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>

  <div id="map3D" style="width: 950px; height: 450px;"></div>

  <script>
    var map = new OSMBuildings({
      container: 'map3D',
      position: { latitude: 53.111212, longitude: 8.857276 }, 
      zoom: 16,
      minZoom: 13,
      maxZoom: 19,
      attribution: '© Data <a href="https://openstreetmap.org/copyright/">OpenStreetMap</a> © Map <a href="https://osmbuildings.org/copyright/">OSM Buildings</a>'
    });

    map.addMapTiles('https://tile-a.openstreetmap.fr/hot/{z}/{x}/{y}.png');
    map.addGeoJSONTiles('https://{s}.data.osmbuildings.org/0.2/59fcc2e8/tile/{z}/{x}/{y}.json');

  </script>
  <script>

    //var for custom building
    var buildings = [];
    let lon = 53.111;
    let lat = 8.857;
    droneSize = 2;
    let lat1 = lat + 0.00005;
    let lon1 = lon + 0.00005;
    let lat2 = lat + 0.00005;
    let lon2 = lon - 0.00005;
    let lat3 = lat - 0.00005;
    let lon3 = lon - 0.00005;
    let lat4 = lat - 0.00005;
    let lon4 = lon + 0.00005;

    let customBuilding = {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
            "height": 15,
            "minHeight": 11,
            "color": "#cc0000"
          },
          "geometry": {
            "type": "Polygon",
            "coordinates": [[
              [lat1, lon1],
              [lat2, lon2],
              [lat3, lon3],
              [lat4, lon4],
              [lat1, lon1]
            ]]
          }
        }
      ]
    };

    //add custom building and store object in buildings array
    buildings.push(map.addGeoJSON(customBuilding, { id: '1' }));
    //remove custom buildings that are in array from map
    for(const building of buildings) {
      console.log(building);
      //different tries to remove building from map
      map.remove(building);
      map.remove({id: '1'});
      map.remove('1');
      map.remove(1);
      building.destroy();
    }
  </script>

</body>
</html>

I have written the jsp,js and servlet for my program but the data is not passed from js to servlet. Below are the code snippet

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>New User Sign Up</title>
    <!-- Bootstrap CSS CDN -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="loginNewUserSignUp.css" />
</head>
<body>
    <div class="signup-container">
        <div class="signup-header">NEW USER SIGN UP DETAILS</div>
        <form id="signupForm" novalidate>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="userName" class="label-field col-4">Enter User Name</label>
                <input type="text" id="userName" name="userName" autocomplete="off" class="input-field col-7" />
                <span class="asterisk">*</span>
            </div>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="userId" class="label-field col-4">Enter User ID</label>
                <input type="text" id="userId" name="userId" autocomplete="off" class="input-field col-7" />
                <span class="asterisk">*</span>
            </div>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="password" class="label-field col-4">Enter User Password</label>
                <input type="password" id="password" name="password" autocomplete="off" class="input-field col-7" />
                <span class="asterisk">*</span><br>
                
            </div>
            <span class="password-msg">(Atleast one Capital Letter, One Number and One Special Character should be in Password)</span>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="confirmPassword" class="label-field col-4">Confirm User Password</label>
                <input type="password" id="confirmPassword" name="confirmPassword" autocomplete="off" class="input-field col-7" />
                <span class="asterisk">*</span>
            </div>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="email" class="label-field col-4">Enter User Email ID</label>
                <input type="email" id="email" name="email" autocomplete="off" class="input-field col-7" />
                <span class="asterisk">*</span>
            </div>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="mobile" class="label-field col-4">Enter User Mobile No.</label>
                <input type="text" id="mobile" name="mobile" autocomplete="off" maxlength="10" class="input-field col-7" />
                <span class="asterisk">*</span>
            </div>
            <div class="form-row d-flex align-items-center mb-2">
                <label for="address" class="label-field col-4">Enter User Address</label>
                <textarea id="address" name="address" class="input-field col-7" rows="4" wrap="soft"></textarea>
                <span class="asterisk">*</span>
            </div>
            <div class="button-row d-flex justify-content-center mt-3">
                <button type="submit" class="submit-btn">SUBMIT</button>
                <button type="reset" id="resetBtn" class="reset-btn">RESET</button>
                <button type="button" id="closeBtn" class="close-btn">CLOSE</button>
            </div>
        </form>
    </div>

    <script src="loginNewUserSignUp.js"></script>
</body>
</html>

My js file code is —

// 
// Disable right-click on the page
document.addEventListener('contextmenu', event => event.preventDefault());

// Disable tab key and enable enter key to move focus
document.addEventListener('keydown', function(event) {
    if (event.key === 'Tab') {
        event.preventDefault();
    }
    if (event.key === 'Enter') {
        const formElements = Array.from(document.querySelectorAll('#signupForm input, #signupForm textarea'));
        const index = formElements.indexOf(document.activeElement);
        if (index > -1 && index < formElements.length - 1) {
            formElements[index + 1].focus();
            event.preventDefault();
        }
    }
});

const form = document.getElementById('signupForm');

function showError(input, message) {
    alert(message);
    input.focus();
}

function validateNotBlank(input, fieldName) {
    if (!input.value.trim()) {
        showError(input, `The field cannot be Blank: ${fieldName}`);
        return false;
    }
    return true;
}

function validatePassword(input) {
    const value = input.value;
    const hasCapital = /[A-Z]/.test(value);
    const hasNumber = /[0-9]/.test(value);
    const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value);
    if (!hasCapital || !hasNumber || !hasSpecial) {
        showError(input, "Password must contain at least one Capital Letter, One Number and One Special Character.");
        return false;
    }
    return true;
}

function validateConfirmPassword(passwordInput, confirmInput) {
    if (passwordInput.value !== confirmInput.value) {
        alert("The Password and Confirm Password are not same.");
        confirmInput.focus();
        return false;
    }
    return true;
}

function validateEmail(input) {
    const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
    if (!emailRegex.test(input.value.trim())) {
        showError(input, "Enter valid Email ID");
        return false;
    }
    return true;
}

function validateMobile(input) {
    const mobileRegex = /^[0-9]{10}$/;
    if (!mobileRegex.test(input.value.trim())) {
        showError(input, "Enter a valid Mobile Number");
        return false;
    }
    return true;
}

function validateAddress(input) {
    const words = input.value.trim().split(/s+/).filter(word => word.length > 0);
    if (words.length === 0 || words.length > 4500) {
        showError(input, "Please enter proper Address not more than 4500 words.");
        return false;
    }
    return true;
}

form.addEventListener('submit', function(event) {
    event.preventDefault();
alert("Entering Data");
    const userName = document.getElementById('userName');
    const userId = document.getElementById('userId');
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    const email = document.getElementById('email');
    const mobile = document.getElementById('mobile');
    const address = document.getElementById('address');

    if (!validateNotBlank(userName, 'User Name')) return;
        if (!validateNotBlank(userId, 'User ID')) return;
        if (!validateNotBlank(password, 'Password')) return;
        if (!validatePassword(password)) return;
        if (!validateNotBlank(confirmPassword, 'Confirm Password')) return;
        if (!validateConfirmPassword(password, confirmPassword)) return;
        if (!validateNotBlank(email, 'Email')) return;
        if (!validateEmail(email)) return;
        if (!validateNotBlank(mobile, 'Mobile')) return;
        if (!validateMobile(mobile)) return;
        if (!validateNotBlank(address, 'Address')) return;
        if (!validateAddress(address)) return;
        alert("Entering Transfer");
        const servletUrl = 'http://localhost:8081/MyTransactionDetails/Servlets/loginNewUserData';
    // Send data to servlet
    fetch(servletUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            userName: userName.value,
            userId: userId.value,
            password: password.value,
            confirmPassword:confirmPassword.value,
            email: email.value,
            mobile: mobile.value,
            address: address.value
        })
        
    })
    
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Data entered successfully');
            // Clear form
            form.reset();
            // Focus on userName
            userName.focus();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred during sign up.');
    });
});

My servlet code is as shown below

package Servlets;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;



import java.sql.ResultSet;
import java.sql.SQLException;
import jakarta.servlet.*;


@WebServlet("/loginNewUserData")
public class loginNewUserData extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // Database connection details
    private static final String DB_URL = "jdbc:mysql://localhost:3306/mytransactiondetails";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "Devi@27032009";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // CORS headers
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        StringBuilder sb = new StringBuilder();
        String line;
        try (BufferedReader reader = request.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        String requestBody = sb.toString();

        JSONObject jsonRequest = new JSONObject(requestBody);
        String userName = jsonRequest.getString("userName");
        String userId = jsonRequest.getString("userId");
        String password = jsonRequest.getString("password");
        String confirmpwd=jsonRequest.getString("confirmPassword");
        String email = jsonRequest.getString("email");
        String mobile = jsonRequest.getString("mobile");
        String address = jsonRequest.getString("address");

        JSONObject jsonResponse = new JSONObject();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn =null;
            conn=DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            
            String newUserIDNo = null,sqlSearchID;
            sqlSearchID="select count(qr_New_User_ID) as totalID from qr_new_user_details";
            PreparedStatement pstmt= conn.prepareStatement(sqlSearchID);
            ResultSet rs=pstmt.executeQuery();
            while (rs.next())
            {
                newUserIDNo=rs.getString("totalID");
                newUserIDNo=newUserIDNo+1;
            }
            
            Date CurDate=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("dd/mm/yyyy");
            String getCurDate=sdf.format(CurDate);

            String sql = "INSERT INTO qr_new_user_details (qr_New_User_ID, qr_New_User_Name, qr_New_UID, qr_New_UPWD, qr_New_UCPWD, qr_New_User_Email,qr_New_User_Mobile,"
                    + "qr_New_User_Address,qr_New_User_Status,qr_New_User_Create_Date) VALUES (?, ?, ?, ?, ?, ?,?,?,?,?)";
            java.sql.PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, newUserIDNo);
            stmt.setString(2, userName);
            stmt.setString(3, userId);
            stmt.setString(4, password);
            stmt.setString(5, confirmpwd);
            stmt.setString(6, email);
            stmt.setString(7, mobile);
            stmt.setString(8, address);
            stmt.setString(9, "Active");
            stmt.setString(10, getCurDate);
            
            int rowsAffected = stmt.executeUpdate();

            if (rowsAffected > 0) {
                jsonResponse.put("success", true);
                jsonResponse.put("message", "Data entered successfully");
            } else {
                jsonResponse.put("success", false);
                jsonResponse.put("message", "Failed to insert data");
            }

            stmt.close();
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "Database error: " + e.getMessage());
        }

        out.print(jsonResponse.toString());
        out.flush();
    }
    
    protected void doOptions(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Handle CORS preflight
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

<———————————————————->
The above is the code which I wrote for new user details to be entered in the jsp file and validated in js file. After validation the data should be transferred fron js file to the servlet. I am using eclipse ide for the coding. The issue is that the data is not transferred from js file to the servlet.

Google Sign In popup not showing (only showing in FireFox)

I am trying to implement Google Sign In on my page. I am following this documentation.

Here is my code:

function loginWithGoogle() {
  if (!otherUtils.notNullEmptyOrUndefined(cookieUtils.getAuthToken())) {
    google.accounts.id.initialize({
      client_id: "xxxxxx",
      callback: (response) => handleCredentialResponse(response),
      ux_mode: "popup",
    });
    google.accounts.id.prompt();
  }
}

NOTE: Don’t mind the if(...) part – the code goes through it, I checked.

And here is HTML part:

<template>
  <div class="options-container">
    <div id="google-login-button">
      <button @click="loginWithGoogle">google</button>
    </div>
  </div>
</template>

I am using Nuxt 4 btw.

I have a problem where the popup that should appear doesn’t show on Brave, Chrome and Opera. It only shows on Firefox.

enter image description here

What can be the problem?