custom option of protocol buffer 3 in javascript

1、I declear one proto 3 file

syntax = "proto3";

import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
  optional string my_option = 51234;
}

message Ext {
  option (my_option) = "Hello world!";
}

2、And then I compile it, and use in google-protobuf runtime

import { Ext, myOption } from './ext_pb'
const ext = new Ext()

3、 And then, if I execute the following code

console.log(ext.getExtension(myOption))

I think it would output “Hello world!”, but it ouput “undefined”, why this happen;

4、If I execute the following code

ext.setExtension(myOption, 'se')
console.log(ext.getExtension(myOption))

It would output ‘se’ as my expected;

Firefox jumpiness involving CSS scale and canvas

In Firefox (121.0b9), when scaling canvas elements, I notice slight jitteriness. I don’t experience this in Safari or Chromium. Is there a way to work around this in Firefox?

Here’s an example (JSFiddle). (If you’re on macOS, activate “Use scroll gesture with modifier keys to zoom” to zoom in on the bottom right corner. On JSFiddle, when you’re zoomed in, use “Command + Enter” to rerun.)

<!DOCTYPE html>

<style>
  canvas {
    margin: 100px;
  }
</style>

<canvas width="400" height="400" />

<script>
  window.onload = function () {
    // make canvas
    const elem = document.querySelector("canvas");
    const ctx = elem.getContext("2d");
    ctx.fillStyle = "yellow";
    ctx.fillRect(0, 0, elem.width, elem.height);
    ctx.fillStyle = "black";
    ctx.fillRect(50, 50, 300, 300);

    // scale loop
    const start = performance.now();
    const end = start + 2000;

    const tick = () => {
      const now = performance.now();
      const t = Math.min(1, (now - start) / (end - start));
      const t2 = 1 - Math.pow(2, -10 * t); // easeOutExpo
      elem.style.transform = `scale(${1 - 0.5 * t2})`;
      if (now < end) {
        requestAnimationFrame(tick);
      }
    };

    tick();
  };
</script>

Possibly related: https://bugzilla.mozilla.org/show_bug.cgi?id=663776

Why isn’t autoplay working despite the video being loaded again? [duplicate]

I’ve a webpage which displays random videos on load. These random videos are being stored in an array.

function playVideo() {
  const videoEl = $('.video');
  const videoSrc = $('.video source');
  const vid = Math.floor(Math.random() * videos.length);
  console.log(vid, videos[vid]);

  videoSrc.attr('src', videos[vid]);
  videoEl[0].autoplay = true;
  // videoEl[0].controls = true;
  videoEl[0].load();
}

The src contains the right path and each time different video is added to the page, but the autoplay option doesn’t work. I’ve tried replacing it with play(), creating a new video tag and appending it to the body, but these methods haven’t worked either.

Why is the autoplay option being blocked? In Safari, when I click on spacebar for the first time, it plays. Could it be a browser related issue?

Vosk speech recognition for Flask app to recognize audio into CK Editor

I’ve made a web application using Flask (screenshot attached)(https://github.com/MusabbinJamil3/vosk-flask-app.git), I am trying to recognize audio using Vosk and route that text into my CK Editor. The problems that I am trying to solve are,

Flask app with Audio Recognition

  1. My editor is being updated every time the model recognizes audio and it is not keeping previously written text

  2. I have placed my fetch data function into a setInterval function in my html page. But this I feel like, is too intensive for any sort of website. Making an api call every second to reterive data from server (maybe it is common, I’m just a beginner). My interval is also running when I am not recognizing audio.

Usually my first go to is ChatGPT, but this seems to be what breaks it. It keeps giving the same answer by saying change this when that is already what it is…

I’ve tried using sockets to decrease the number of api calls, but that to no end. I’ve tried to make a new variable to store previous data and append data but I’m not sure how to do that. Even a link to a good tutorial on how to use routing with CK Editor would be appreciated.

Node JS: Loop round grouped by array

I’ve got data like this

[
  [ '@test','1.2.6-unstable' ],
  [ '@test','1.3.2-unstable' ],
  [ '@test','1.4.6-unstable' ],
  [ '@test2','4.0.1-unstable' ],
  [ '@test2','4.0.2-unstable' ],
  [ '@test2','4.0.3-unstable' ],
  [ '@test3','2.2.0-unstable' ],
  [ '@test3','2.2.3-unstable' ],
  [ '@test3','2.2.9-unstable' ],
...
]

and I’m trying to group them by name @test then loop round the values and apply an action on each, ignoring the first value.
My output should be

[
  [ '@test','1.3.2-unstable' ],
  [ '@test','1.4.6-unstable' ]
]
[
  [ '@test2','4.0.2-unstable' ],
  [ '@test2','4.0.3-unstable' ]
]
[
  [ '@test3','2.2.3-unstable' ],
  [ '@test3','2.2.9-unstable' ]
]

I have looked at these questions and I’m unable to apply the right combination to get what I need
break array of objects into separate arrays based on a property
Can’t loop over grouped array in JS
JS loop through array and group with map
I’ve also tried .shift() and .slice(1) but this only takes the 1st one off the whole original array

My code looks like this:

const response = await axios.get(reportURL, { headers });
const mystuff = response.data.value.reduce((acc, next) => {
  acc.push(...next.versions.map((v) => [next.name, v.version]));
  return acc;
}, []);
const filteredArray = mystuff.filter(([_, version]) => version.includes('-unstable'));
const map = filteredArray.reduce((acc, { name, version }) => {
  if (acc.has(name)) {
    acc.get(name).versions.push(version);
  } else {
    acc.set(name, { name, versions: [version] });
  }
  return acc;
}, new Map());

const result = [...map.values()];

// Loop round the array and fire off the axios
result.forEach(([name, version]) => {
  const URL = `https:URL/${name}/versions/${version}?api-version=7.1-preview.1`;

Onclick is not working over the element in React

Using a library to make a navbar , i am clicking the logout button but it displays homepage after clicking and not the log inside the callback function passed in onClick .

import hcOffcanvasNav from "hc-offcanvas-nav";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import {
  DarkHomeInviteFriendsIcon,
  DarkHomeLogoutIcon,
  DarkHomeMenuIcon,
  DarkHomeNotificationsIcon,
  DarkHomeSettingsIcon,
  DarkHomeTripIcon,
  DarkHomeWalletIcon,
  DarkImgProfileImage,
  HomeInviteFriendsIcon,
  HomeLogoutIcon,
  HomeMenuIcon,
  HomeNotificationsIcon,
  HomeSettingsIcon,
  HomeTripIcon,
  HomeWalletIcon,
  ImgProfileImage,
} from "../../../assets/TaxiModeImage";
import { Link } from "react-router-dom";

const Navigation = ({ setLogoutModal }) => {
  const themeGetter = useSelector((state) => state.theme);

  const [isMenuOpen, setIsMenuOpen] = useState(false);
  console.log("in navigation");
  useEffect(() => {
    const Nav = new hcOffcanvasNav("#main-nav", {
      customToggle: ".toggle",
      open: isMenuOpen,
      swipeGestures: false,
    });

    return () => Nav.close();
  }, [isMenuOpen]);

  const toggleMenu = () => {
    setIsMenuOpen((prev) => !prev);
  };

  const handleClick = () => {
    console.log("Logout button clicked");
  };
  return (
    <nav id="main-nav">
      <ul className="second-nav">
        <li>
          <Link className="sidebar-user d-flex align-items-center p-3 border-0 mb-0    rounded-4">
            <img
              src={themeGetter ? DarkImgProfileImage : ImgProfileImage}
              className="rounded-pill me-3 ch-50"
              alt="#"
            />
            <div>
              <h4
                className={`mb-0 ${
                  themeGetter ? "txt-white-dark" : "tm-secondary-txt-color"
                } roboto-text`}
              >
                Hello, Brayden
              </h4>
              <small className="tm-primary-txt-color roboto-text">
                Edit account
              </small>
              <br />
            </div>
          </Link>
        </li>
...
      <ul className="bottom-nav">
        <li>
          <Link
            className="txt-logout"
            onClick={() => {
              console.log("click");
            }}
          >
            {themeGetter ? (
              <DarkHomeLogoutIcon className="me-3" />
            ) : (
              <HomeLogoutIcon className="me-3" />
            )}
            <span className="txt-logout" onClick={handleClick}>
              &nbsp;Logout
            </span>
          </Link>
        </li>
      </ul>
    </nav>
  );
};

export default Navigation;

i tried to log the ‘click’ but it didn’t happened , i want to know that is this the library or css or code problem because if the code is normal then it should be logged but it doesn’t.

An import map is added after module script load was triggered

I have a Rails app, and my custom javascript doesn’t work.
In Chrome console I can see the following errors:

An import map is added after module script load was triggered.

Uncaught TypeError: Failed to resolve module specifier “application”. Relative references must start with either “/”, “./”, or “../”.

Uncaught TypeError: Failed to resolve module specifier “@hotwired/turbo-rails”. Relative references must start with either “/”, “./”, or “../”.

I cannot uderstand why there are these errors, I moved the importmap before the script with type module, but I’m still getting this error.
In my application.html.erb I have

<%= csrf_meta_tags %>
<%= csp_meta_tag %>

<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_importmap_tags %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true, type: "module" %>

This is my importmap.rb file:

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

This is my app/javascript/application.js file:

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"

This is the app/javascript/cotrollers/application.js

import { Application } from "@hotwired/stimulus"

const application = Application.start()

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

This is the content of the app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .

And I cannot see the custom javascript in the app/assets/javascripts/ folder.
What am I missing? thanks

Video don’t load in Firefox unless the page is refreshed

I am trying to build my very first website. Everything work fine but I notice that my video won’t load in Firefox unless I refresh the page containing that video. These videos are in webm format that Firefox supports, and they work fine in both Chrome and Safari (albeit in Safari the autoplay does’t work. Not ideal, but can live with it for now). The following are my html tag for the video

{entry.data.vid ? (     
   <video poster="/assets/video/Loading.gif" preload="auto" controls loop muted autoplay>
      <source src={entry.data.vid + ".webm"} type="video/webm">
      Opps. Something went wrong with my video.
   </video>
) : (entry.data.img && (
   <img src={entry.data.img} alt={entry.data.img_alt || ''} />)
)}

As you can see, some pages have videos, the rest only have images (This website is build using Astro framework with animations between pages btw). This same problem persist both on my local machine or hosted on the server. This is a newly installed Firefox with no add-ons.

I tried with other video format (mp4), that doesn’t work either. I tried removing preload=”auto” and autoplay attribute, that doesn’t work as well.
I check the console in Firefox (with control-shift-j) and see the following errors in Parent process whenever I refresh a page (regardless of it containing a video or just an image). Not sure if it is relevant or not.

NS_ERROR_FAILURE: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIFaviconService.replaceFaviconDataFromDataURL] loadFavicon resource:///modules/PlacesUIUtils.sys.mjs:213 loadFavicon resource:///modules/PlacesUIUtils.sys.mjs:644 setIconFromLink resource:///actors/LinkHandlerParent.sys.mjs:139 receiveMessage resource:///actors/LinkHandlerParent.sys.mjs:60 LinkHandlerParent.sys.mjs:148:17 setIconFromLink resource:///actors/LinkHandlerParent.sys.mjs:148 receiveMessage resource:///actors/LinkHandlerParent.sys.mjs:60 

When I look at Multiprocess section of the console though, I see the “All candidate resources failed to load. Media load paused.” warning only on page that contains video and only before page refresh Image showing the warning.

Sorry for such a simple question, I am sure this is some very basic problem that only a novice would ask, but I would really appreciate any suggestions that you guys can give.

uneven number of data points on each trial_data collection

I have a task where peole see a dot moving and then disappearing. When that happens they need to indicate with the mouse where it started and where it vanished. The motion trajectory can be 1 line, 2 lines, or 3 lines.
The data I collect is the actual initial position of the dot (in both axes), the actual vanishing position (both axes), the trial number, the condition, the perceived position of the dot (start, vanish both axes), the direction of the first line, and if there is a 2nd line the direction of it.
Because there are uneven data points, my values are not correctly placed under the right header at the csv file that I “send” the data to.
I would appriciate it if anyone could help with making the headers align with the data.

I tried to create a loop when I push the headers. It works for the 3 lines trajectory but not with the others.

Fullcalendar non-gregorian months

I am looking for a way to display a fullcalenar month grid divided by Hebrew calendar months.

I managed to display the hebrew date within the cells of the month grid view usign dayCellContent (including bootstrap classes):

//Array of letters representing the day of the month
const hebDateLetters = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'יא', 'יב', 'יג', 'יד', 'טו', 'טז', 'יז', 'יח', 'יט', 'כ', 'כא', 'כב', 'כג', 'כד', 'כה', 'כו', 'כז', 'כח', 'כט', 'ל',]; 

...

dayCellContent: (info)=>{
        var hebDate = new Intl.DateTimeFormat('he-IL-u-ca-hebrew', {day: 'numeric'}).format(info.date);
        var hebMonth = new Intl.DateTimeFormat('he-IL-u-ca-hebrew', {month: 'long'}).format(info.date);

        //Container element
        const container = document.createElement("div");
        container.setAttribute("class", "container p-1"); 

        //First row element
        const elRow1 = document.createElement("div");
        elRow1.setAttribute("class", 'row m-0 w-100');
        const elCol1 = document.createElement("div");
        elCol1.setAttribute("class", 'col p-0');
        elCol1.innerText = hebDate !=1 ? hebDateLetters[hebDate-1] : hebDateLetters[hebDate-1] + " " + hebMonth; // Condition to display Hebrew month name on first day of the month
        elRow1.appendChild(elCol1);

        //Second row element
        const elRow2 = document.createElement("div");
        elRow2.setAttribute("class", 'row m-0 w-100');
        const elCol2 = document.createElement("div");
        elCol2.setAttribute("class", 'col p-0 c-date');
        elCol2.innerText = info.date.getDate();
        elRow2.appendChild(elCol2);

        container.appendChild(elRow1);
        container.appendChild(elRow2);
        return {html: container.outerHTML};
      }

This is what I achived

Calendar Image

My next step would be to display the months according to the Hebrew calendar. I’ve been trying to build a custom view as discribed here: Custom view with JS, but I’m not fully sure how to use this to achive what I’m looking for.

How to make this code synchronous by blocking the execution thread?

I have a piece of code with an API call in the topmost JS import which I need to use everywhere else in the project.
How to make this asynchronous?

My HTML file looks like:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="src/style.css">
  </head>
  <body>
    <h1 id="header"></h1>

    <script src="src/script1.js"></script>
    <script src="src/script2.js"></script>
  </body>
</html>

First JS file:

const fetchData= async () => {
    const configUrl = 'https://jsonplaceholder.typicode.com/todos/1';

    try {
        const response = await fetch(configUrl);

        if (!response.ok) {
            throw new Error(`Network response was not ok: ${response.status} - ${response.statusText}`);
        }

        const res = await response.json();
        console.log('data 0:',res)
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

window.data = fetchData();

console.log("data 1:",data);

Second JS file:

console.log("data 2:",window.data)

Basically I want window.data with the data from the endpoint to be accessible everywhere. I want to continue the program execution only after the api call is done. That is, the thread should be blocked for the API call and rest of the program (js files) should execute only after the api call.
Im not ready to move other JS file code to first 1 nor import it inside first using @import in .then block of first.

Is there any clean approach for this?

Live example: https://playcode.io/1696111

In the example I want console.log inside script2.js to print the API data.

`RecipientsDisplay` component using react/ vue

  • This functionality should work on any screen size and when the screen is resized. For simplicity, this will only be tested in a recent version of a Chromium browser.

  • If all the recipient email addresses fit in the available space, we can simply display them delimited by a comma and space (e.g. a, b).

  • When there is not enough space to display all recipients, we trim the text. However, to prevent showing clipped email addresses that are hard to read, we trim entire email addresses. If we cannot fit the entirety of a recipient email address, it shouldn’t be shown at all.

  • When at least one recipient is trimmed, we put a comma, space, and ellipsis after the last fitting recipient (e.g. a, b, ...). Furthermore, the rightmost end of the column should show a “badge” with the number of trimmed recipients (+N).

  • If there is not enough space to show even the first recipient, the badge should show the number of trimmed recipients excluding the first recipient, and the recipient should be truncated with an ellipsis only. If there is only one recipient, there will be no badge, and the recipient should still be truncated by an ellipsis.

Trim recipients that do not fit in the column. Show , ... after the last fitting recipient and a badge with +N at the end of the column.

If there is not enough space to show the ellipsis and the extra space, trim that recipient as well.

If there is not enough space to show the first recipient, the badge should show the number of trimmed recipients excluding the first recipient, and the recipient should be truncated with an ellipsis only. If there is only one recipient, there should be no badge.

Measurements

  • Font size: 16px
  • Foreground color: #f0f0f0
  • Background color: #666666
  • Border radius: 3px
  • Top padding: 2px
  • Bottom padding: 2px
  • Left padding: 5px
  • Right padding: 5px
  • Font size: 16px
  • Foreground color: #333333
  • Top padding: 5px
  • Bottom padding: 5px
  • Left padding: 10px
  • Right padding: 10px

onmouseover event suddenly not working in Edge browser

I have the following code throughout my site to swap images on hover:

<img class="rounded-lg object-cover shadow-lg transition hover:scale-[1.05]"
src="/assets/profiles/leadership/volker-photo-detail-hover.png"
onmouseover="this.src='/assets/profiles/leadership/volker-photo-detail-hover.png';"
onmouseout="this.src='/assets/profiles/leadership/volker-photo-detail.png';">

which has been working fine for the last year, but suddenly it won’t work correctly in Microsoft Edge browser. It works fine in Chrome and Firefox. You can test here: https://jwmdrc.org/ (work in progress so not really accessible on smaller screens/mobiles yet) in different browsers and see that it’s only Edge that is affected.

Maybe this is due to a recent update? Has anyone else encountered this and/or know of a solution?

Thanks

Edit: built with Statamic and Tailwind

Loading of script tag is slower in Chrome than Firefox

I want to load large amounts of data from a local file in an html application.

At the moment my strategy is to keep the data as javascript arrays in separate .js files and load them by dynamically adding elements to the header of the page, like so:

const head = document.getElementsByTagName['head'][0]
const js = document.createElement('script')
js.async = true
js.src = "localDataFile.js"
head.appendChild(js)

The contents of localDataFile.js look like the following, where dataString contains the data encoded as a base64 string.

const base64DataString = "..."
globalFunction(base64DataString)

An example .js file I am using has a size of 300 MiB.
This file takes ~40 seconds to load in Chrome v112, and ~17 seconds in Firefox v102.

My question:
Is there any way to speed up parsing of this javascript file for Chrome, or both?
More generally, are there any better strategies in getting the data to the html application without using a web server?