How to set key_ops in generating JWK using java script?

I want to generate JWK with parameters using JavaScript. Following is the code I used to generate JWK

var JA = java.util;
var JWKgen = Packages.com.nimbusds.jose.jwk.gen;
var Keys = Packages.com.nimbusds.jose.jwk.KeyUse;
var ops = Packages.com.nimbusds.jose.jwk.KeyOperation;
var alg = Packages.com.nimbusds.jose.Algorithm;

var RSAKeyjwk = JWKgen.RSAKeyGenerator(3072)
.keyUse(Keys.SIGNATURE) 
.keyID(JA.UUID.randomUUID().toString())
.algorithm(alg("RS384"))
.issueTime(new Date()) 
.generate();

I have added the keyUse, KeyId, algorithm as per the following link
https://javadoc.io/static/com.nimbusds/nimbus-jose-jwt/6.7/com/nimbusds/jose/jwk/gen/JWKGenerator.html#keyOperations-java.util.Set-

I want to add “key_ops”:[“verify”],”ext”: true in the JWK. I tried following syntax

keyOperations(Set <KeyOperation) – Method in class com.nimbusds.jose.jwk.gen.JWKGenerator
Sets the operations (key_ops) of the JWK.

.keyOperations(Set(ops['VERIFY'])). 
.keyOperations(Set(ops.VERIFY))
.keyOperations(Set(ops("VERIFY")))

I am getting the following error

TypeError: Set objects may not be constructed using “new”.
TypeError: Set objects may not be constructed using “new”.

Java constructor for “com.nimbusds.jose.jwk.KeyOperation” with arguments “string” not found.

Please help me on how to add the key_ops parameter.

Thanks

Send email in Node.js

You can send mail using the nodemailer package.

npm i nodemailer

you can generate app password from your gmail account

[https://accounts.google.com/](https://accounts.google.com/) -> search (app password) -> Generate

Below is the code template for this:-

// SMTP server details
let transporter = nodeMailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: process.env.USER,
      pass: process.env.PASSWORD, // Generated app password
    },
    tls: {
      rejectUnauthorized: false, // Allows self-signed certificates
    },
  });

  // Message object
  let message = {
    from: process.env.USER,
    to: process.env.RECEIVER,
    subject: process.env.SUBJECT, ,
    text: process.env.BODY,
  };

  transporter.sendMail(message, (err, info) => {
    if (err) {
      console.log('Error occurred. ' + err.message);
      return process.exit(1);
    }

    console.log('Message sent: %s', info.messageId); 
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
  });

How to push a div (say div1) using another div(div2) if div1 is fixed in upper position until div2 come below it while scrolling

Have to seen the telegram web or app page. while scrolling the the old chats the date are sticked to the top . when chats with new date comes , The div of new date push the div of old date on upper side without going over it.

enter image description here

See, here the div of 18 april push the div of 16 push upper side and get fixed there.
How to get the exact same behaviour .
Can it be done using only CSS . Does it also require javascript. if yes please write the example code.

Why title is not align to items value using flex.?

Can you please help me Why title is not align to items value using flex. I am using flex box . In all rows we are using “align-self” : “flex-start” . still and header and rows are not align. Kindly help

[![export default function App() {
  return (
    <>
      <div
        style={{
          display: "flex",
          justifyContent: "space-around",
          alignContent: "flex-start",
        }}
      >
        <span style={{ alignSelf: "flex-start" }}>ooasdasd</span>
        <span style={{ alignSelf: "flex-start" }}>sss</span>
        <span style={{ alignSelf: "flex-start" }}>asasda</span>
      </div>

      <li
        style={{
          display: "flex",
          justifyContent: "space-around",
          alignContent: "flex-start",
          padding: 0,
          margin: 0,
        }}
      >
        <span style={{ alignSelf: "flex-start" }}>kaveennnn</span>
        <span style={{ alignSelf: "flex-start" }}>jakhdahdsk</span>
        <span style={{ alignSelf: "flex-start" }}>asdasd asdas</span>
      </li>

      <li
        style={{
          display: "flex",
          justifyContent: "space-around",
          alignContent: "flex-start",
          padding: 0,
          margin: 0,
        }}
      >
        <span style={{ alignSelf: "flex-start" }}>kaveennnn</span>
        <span style={{ alignSelf: "flex-start" }}>jakhdahdsk</span>
        <span style={{ alignSelf: "flex-start" }}>asdasd asdas</span>
      </li>
    </>
  );

}][1]][1]

here is my code
https://codesandbox.io/p/sandbox/testing-f5htxq?file=%2Fsrc%2FApp.js%3A3%2C1-47%2C2

enter image description here

I face one problem in my blogger please help to solve

I use blogger for news website so in my blogger website i face onr problem i want to add nse and bse live score widget using below code .

<img align="left" alt="NSE Nifty Index" border="0" height="150" src="http://www.moneycontrol.com/gd/mail_indices.php" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; float: left; margin: 0px 0px 4px; padding-left: 0px; padding-right: 0px; padding-top: 0px;" width="300">

Output :
enter image description here

But i past above code in my blogger then above output photo i given like this it is not work . Show balnk see below :

In my blogger :
enter image description here

<img align="left" alt="NSE Nifty Index" border="0" height="150" src="http://www.moneycontrol.com/gd/mail_indices.php" style="background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; float: left; margin: 0px 0px 4px; padding-left: 0px; padding-right: 0px; padding-top: 0px;" width="300">

Please solved my problem.

how to render html code with style in ckeditor5 body? but I don’t want paste code in body but render it from code level in angular 15

I want to render html code in Ckeditor5 body with css on it. but dont want to copy-paste snippent in body and then render it. I want to render it from code level, where i can write code in my angular 15 project and then render it by click of button/plugin.

I tried some methods of it, but it only provided me the way by pasting the html code in body & then it will render it.

Why loading from http return different value then loading from https for same content?

I have modified script to get dictionary meaning for Chinese characters.

In following in loadDictData() method when localhost used to get dictionary data file then the search return correct result but when cdn used to get dictionary data file then the search method return different result.

This is result for all files loaded from localhost.

git clone https://github.com/cschiller/zhongwen.git
cd zhongwen
python -m http.server

Then open browser and paste below script the result will be similar.

enter image description here

This is result for dictionary data cedict_ts.u8 loaded from cdn. Open new tab with cdn url, then paste below script in dev console. The result is different.

enter image description here

let host = "http://127.0.0.1:8000";

async function loadDictData() {
    let wordIndex = fetch(`${host}/data/cedict.idx`).then(r => r.text());
    let grammarKeywords = fetch(`${host}/data/grammarKeywordsMin.json`).then(r => r.json());
    let vocabKeywords = fetch(`${host}/data/vocabularyKeywordsMin.json`).then(r => r.json());

    // comment and uncomment to test the result
    host = "https://cdn.jsdelivr.net/gh/cschiller/zhongwen@latest";

    let wordDict = fetch(`${host}/data/cedict_ts.u8`).then(r => r.text());

    return Promise.all([wordDict, wordIndex, grammarKeywords, vocabKeywords]);
}

class ZhongwenDictionary {

    constructor(wordDict, wordIndex, grammarKeywords, vocabKeywords) {
        this.wordDict = wordDict;
        this.wordIndex = wordIndex;
        this.grammarKeywords = grammarKeywords;
        this.vocabKeywords = vocabKeywords;
        this.cache = {};
    }

    static find(needle, haystack) {

        let beg = 0;
        let end = haystack.length - 1;

        while (beg < end) {
            let mi = Math.floor((beg + end) / 2);
            let i = haystack.lastIndexOf('n', mi) + 1;

            let mis = haystack.substr(i, needle.length);
            if (needle < mis) {
                end = i - 1;
            } else if (needle > mis) {
                beg = haystack.indexOf('n', mi + 1) + 1;
            } else {
                return haystack.substring(i, haystack.indexOf('n', mi + 1));
            }
        }

        return null;
    }

    hasGrammarKeyword(keyword) {
        return this.grammarKeywords[keyword];
    }

    hasVocabKeyword(keyword) {
        return this.vocabKeywords[keyword];
    }

    wordSearch(word, max) {

        let entry = { data: [] };

        let dict = this.wordDict;
        let index = this.wordIndex;

        let maxTrim = max || 7;

        let count = 0;
        let maxLen = 0;

        WHILE:
        while (word.length > 0) {

            let ix = this.cache[word];
            if (!ix) {
                ix = ZhongwenDictionary.find(word + ',', index);
                if (!ix) {
                    this.cache[word] = [];
                    continue;
                }
                ix = ix.split(',');
                this.cache[word] = ix;
            }

            for (let j = 1; j < ix.length; ++j) {
                let offset = ix[j];

                let dentry = dict.substring(offset, dict.indexOf('n', offset));

                if (count >= maxTrim) {
                    entry.more = 1;
                    break WHILE;
                }

                ++count;
                if (maxLen === 0) {
                    maxLen = word.length;
                }

                entry.data.push([dentry, word]);
            }

            word = word.substr(0, word.length - 1);
        }

        if (entry.data.length === 0) {
            return null;
        }

        entry.matchLen = maxLen;
        return entry;
    }
}

async function loadDictionary() {
    const [wordDict, wordIndex, grammarKeywords, vocabKeywords] = await loadDictData();
    return new ZhongwenDictionary(wordDict, wordIndex, grammarKeywords, vocabKeywords);
}

let dict;
await loadDictionary().then(r => dict = r);

function search(text) {

    if (!dict) {
        return;
    }

    let entry = dict.wordSearch(text);

    console.log("entry", entry);

    if (entry) {
        for (let i = 0; i < entry.data.length; i++) {
            let word = entry.data[i][1];
            if (dict.hasGrammarKeyword(word) && (entry.matchLen === word.length)) {
                // the final index should be the last one with the maximum length
                entry.grammar = { keyword: word, index: i };
            }
            if (dict.hasVocabKeyword(word) && (entry.matchLen === word.length)) {
                // the final index should be the last one with the maximum length
                entry.vocab = { keyword: word, index: i };
            }
        }
    }

    return entry;
}

let res = search("你好");
console.log(res);

How to query indexedDB for value/s from specific key using Javascript?

In one of the projects we are using indexedDB as the database. We have about 6 keys, each of one has its own keys.
indexedDB is structure as follows:

{
    collegeInformation: [],
    courseInformation: [],
    teacherInformation: [],
    classRoomInformation: [],
    examInformation: [],
    gradeInformation: [
        {
            studentId: 1,
            examId: 11,
            courseId: 111,
            marks: 50
        }
        {
            studentId: 2,
            examId: 11,
            courseId: 111,
            marks: 40
        }
        {
            studentId: 3,
            examId: 11,
            courseId: 111,
            marks: 95
        }
        {
            studentId: 4,
            examId: 11,
            courseId: 111,
            marks: 70
        }
    ],
}

Without loading the indexedDB into Javascript variable, we would like to pull values from gradeInformation without getting complete indexedDB and pick the values of specific key.

and
Without loading the indexedDB into Javascript variable, we would like to pull values from gradeInformation for only the studentId: 2.

Currently we are getting complete indexedDB


let student_Id = 2;
request.onsuccess = function (e) {
    const db = e.target.result;
    const transaction = db.transaction(["college"], "readonly");
    const objectStore = transaction.objectStore("college");
    const getRequest = objectStore.getAll();

    getRequest.onsuccess = function (event) {
      const jsonDataArray = event.target.result;

      if (jsonDataArray && jsonDataArray.length > 0) {
        const collegeData= jsonDataArray[0];

        if (collegeData) {
          const gradeInfo= collegeData.gradeInformation;

          const studentGrade = gradeInfo.find(
            (item) => item.studentId=== student_Id
          );
        }
      }
   }
}

Any one who has working knowledge on indexedDB with Javascript please do respond. That would be great support for us to enhance the code.

Thank you in advance.

Filter 2-dim array based on string value that contain on 2nd array

so i have a bad bad logic for this assignment, i need to filter 2 Dimension Array that contains the value of string that input on 2nd array.

So this is the example of the 2-Dim Array

const roles = [ ['roles', 'admin', 'write'] ['roles' ,'admin', 'read'] ['roles', 'member', 'read']]

I need to filter the array that only containts ‘member’ and the result is like this

const result = ['roles', 'member', 'read']

How can i achieve this ?

Create document with byte array: Cannot read properties of undefined (reading ‘fromUint8Array’

I’m trying to set a byte array as a Firestore document field.

Based on suggestions elsewhere, it should be as simple as using fromUint8Array(), as below:

const bytes = [72, 73];
const test = firestore.Blob.fromUint8Array(
   new Uint8Array(bytes)
);

But I get the error

TypeError: Cannot read properties of undefined (reading
‘fromUint8Array’)

I am completely new to Firebase/Firestore and I don’t know where I’m going wrong, so any pointers would be much appreciated.

My set-up:

  • firebase: “^9.9.2”
  • “https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js”
  • using the webhost, firestore emulators

Is there a way to alter the size of an image in an array in javascript?

I’m new to coding so this might be a really simple question, but I can’t figure out how to change the png stimulus to be 50% of it’s size. Is there a way to do this in an array, rather than using a function. Here’s my code for reference:

var test_s= [
{ stimulus: "doc/blue.png",  correct_response: 'h'},
{ stimulus: "doc/orange.png",  correct_response: 'f'}
];

var test = {
type: jsPsychImageKeyboardResponse,
stimulus: jsPsych.timelineVariable('stimulus'),
choices: ['f', 'j'],
data: {
    task: 'response',
    correct_response: jsPsych.timelineVariable('correct_response')
  },
  on_finish: function(data){
    data.correct = jsPsych.pluginAPI.compareKeys(data.response, data.correct_response);
  }
 };

I tried to do it this way, but it didn’t work
{ stimulus: “doc/orange.png”, correct_response: ‘f’, width: 50 }

How to count markdown tables with a given text?

code should be something like this:

const mdtext = `some blabla text
Here is a table:

| a | b |
|---|---|
| 1 | 2 |
| ^ | 3 |

more text outside

Here goes another table

| apples | oranges | bananas |
|--------|---------|---------|
| 11 | 24 | 22 |
| 84 | 32 | 23 |

- some bullets
- more bullets


`;

const count = countTables(mdtext)
console.log(count); // it should output 2


This regex https://stackoverflow.com/a/29616512/865220 matches single header only, I need with multiple.

Angular: How to refresh a div inside component on assets file modification

I have an external JSON file stored in assets folder of the angular app. This config is used to show an image in a component based on the expiration date provided in JSON. I’ve developed the logic to show the image by fetching data from the file.

Problem:

After deploying the prod build in server, if I change the content in the JSON (inside assets), the view automatically doesn’t refresh. So I created a setInterval function to call the API after every N seconds. This works somewhat perfectly The issue that appears here is on first load sometimes the setInterval doesn’t get triggered or sometimes if I change the value in JSON, the interval function doesn’t work. This issue doesn’t happen in DEV server as because when changing data in assets the angular server refreshes as a whole.

Code I wrote for interval:

time: NodeJS.Timer;

ngOnInit() { this.getPassDetails() }

ngOnDestroy() { this.time = null }

private getPassDetails() {
  this.time = setInterval(() => this._ymcaform.fetchPassDetails().subscribe(response => this.CONFIG = response), 1000);
}

What’s the problem here? Is there any other way to refresh UI when JSON inside assets changes?

How to block/remove Youtube Share, Download buttons in a content script like how uBlock does it?

Removing said buttons with code below works however it doesn’t update the UI in a way that displays the other buttons in the sub-menu. The other buttons remain hidden in the sub-menu, while the ones that were originally displayed(i.e. Thanks, Clip) just collapse to the right towards sub-menu button.

document.querySelector('button[aria-label="Download"]').remove();
document.querySelector('button[aria-label="Share"]').remove();

I expect that the other buttons like Save which is inside the sub-menu to be displayed after removing Share and Download buttons.

I tried to block it via uBlock Origin extension and it does work the way I expect to. But I’m looking for a way to do via my own content script. My understanding is it should be possible since uBlock, as a browser extension, is somehow able to do it.

Custom uBlock filter:

www.youtube.com##.ytd-download-button-renderer.style-scope > yt-button-shape
www.youtube.com###top-level-buttons-computed > ytd-button-renderer.ytd-menu-renderer.style-scope > yt-button-shape > .yt-spec-button-shape-next--icon-leading.yt-spec-button-shape-next--size-m.yt-spec-button-shape-next--mono.yt-spec-button-shape-next--tonal.yt-spec-button-shape-next > yt-touch-feedback-shape > .yt-spec-touch-feedback-shape--touch-response.yt-spec-touch-feedback-shape > .yt-spec-touch-feedback-shape__fill
www.youtube.com###top-level-buttons-computed > ytd-button-renderer.ytd-menu-renderer.style-scope

Docker – dist file disappeared after running docker-compose up -d

I have a nestJS application using Dockerfile to build

backend/Dockerfile

FROM node:18-alpine

# Reuse the old commits if dependencies are not changed
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /app && cp -a /tmp/node_modules /app

WORKDIR /app
COPY . .

RUN npm run build // dist file is supposed to be generated in this step

CMD [ "npm", "run", "dev" ]

I use Docker Compose for bootstrap my entire applications
docker-compose.yml

version: '3.5'

services:
  backend:
    build: 
      context: ./backend
      dockerfile: Dockerfile
    container_name: backend
    ports: 
      - '3001:3001'
    volumes:
      - ./backend:/app
    depends_on:
      - database

  database:
    image: mongo:6.0
    container_name: mongodb
    restart: always
    ports:
      - '27017:27017'
    environment:
      MONGO_INITDB_ROOT_USERNAME: 'XXX'
      MONGO_INITDB_ROOT_PASSWORD: '1234'

However when I run docker-compose up -d, the dist file is not generated in the docker container. Below is the result of docker logs -f backend

> nest start --watch -b swc

>  SWC  Running...
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Bindings not found.
Failed to compile 20 files with swc.
Watching for file changes.
Error: Cannot find module '/app/dist/main'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
    at Function.Module._load (node:internal/modules/cjs/loader:975:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)
    at node:internal/main/run_main_module:28:49

I tried to run npm run build locally to manually build a dist file to sync to the container, but whenever I run docker-compose up -d it just disappeared.

How to fix it?