How can I compress a JSON file in NodeJS, upload it on a blockchain smart contract (web3) and then decompress it?

I managed to get the compression of the JSON working and then uploaded it on the smart contract I also wrote.

It all works fine when I try to compress and decompress the JSON, but when I compress, store on the blockchain, and then decompress, it doesn’t work anymore and throws unknown compression method.

Here is the function that writes onto the contract from the javascript API (unsing web3 and NodeJS)

async function writeContract(jsonstring){
    console.log("Writing value to contract...");
    
console.log("JSON string to write:", jsonstring);
    
    // compress
    jsonstring = pako.deflate(JSON.stringify(jsonstring));
    console.log("Compressed string:", jsonstring);

    const tx = await contract.methods.storeJson(jsonstring).send({from: userAddress});
}

And here is the code that reads the smart contract, and decompress the file:

async function readJSON(){
    console.log("Reading JSON string from contract...");
    var value = await contract.methods.JSONfile().call();

    // decompress
    console.log("Reading compressed JSON string from contract:", value);

    const decompressed = JSON.parse(pako.inflate(value, { to: 'string' }));

    console.log("Reading JSON output", decompressed);
    return decompressed;
}

The smart contract (written in Solidity):

contract Storage {

    bytes public JSONfile;

    event newStrIsStored(address indexed _from, bytes JSONfile, bytes32 JSONhash);

    function storeJson(bytes memory json_in_str) public {
        JSONfile = json_in_str;
        emit newStrIsStored(msg.sender, JSONfile, JSONhash);
    }

}

I tried to change the encoding, the parameters type of the function call in the smart contract, the type of of the input but nothing.

The expected output is the original JSON file.

Thank you for your help !

DOM Element Is Not Recognizing The HTML Element

This is HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PlanItt</title>
    <link rel="stylesheet" href="../src/style.css" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Comfortaa:[email protected]&display=swap"
      rel="stylesheet"
    />
  </head>
  <body>
    <div class="header-container">
      <header>
        <h1>Plan.itt</h1>
      </header>
    </div>
    <div class="content-container">
      <div class="navbar-container">
        <div class="first-set-container">
          <ul>
            <li class="nav-item-list">Running</li>
            <li class="nav-item-list">Completed</li>
          </ul>
        </div>
        <h2>Projects</h2>
        <div class="second-set-container">
          <ul class="second-set-container-ul">
            <li class="nav-item">University</li>
            <li class="nav-item">School</li>
          </ul>
        </div>
        <div class="add-project-button">
          <button class="add-project-btn">+ Add Project</button>
        </div>
      </div>
      <div class="main-list-container">
        <!-- <div class="list-heading-and-button">
          <div class="list-heading"></div>
          <div class="add-task-button">
            <button class="add-task-btn">+ Add Task</button>
          </div>
        </div> -->
        <div id="tasks-display"></div>
      </div>
    </div>

    <!-- Add Project Pop Up -->

    <dialog id="add-project-pop-up">
      <form class="add-project-form" method="dialog">
        <label for="project-name">Project Name</label>
        <input
          type="text"
          id="project-name"
          name="project-name"
          placeholder="Enter Project Name"
          required
        />
        <div class="add-proj-pop-btns">
          <div class="pop-add-btn">
            <button type="submit" id="pop-up-save" class="">Add</button>
          </div>
          <div class="pop-cancel-btn">
            <button type="submit" id="pop-up-delete">Cancel</button>
          </div>
        </div>
      </form>
    </dialog>

    <!--  -->

    <!-- Add Task Pop Up -->

    <dialog id="add-task-pop-up">
      <form class="add-task-pop-up-form" method="dialog">
        <label for="task-name">Task Name</label>
        <input type="text" id="task-name" name="task-name" required />
        <label for="task-desc">Task Description</label>
        <textarea id="task-desc"> </textarea>
        <label for="task-date">Task Date</label>
        <input type="date" id="task-date" name="task-date" required />
        <label for="task-priority">Task Priority</label>
        <select id="task-priority" name="task-priority">
          <option value="high">High</option>
          <option value="medium">Medium</option>
          <option value="low">Low</option>
        </select>
        <div class="add-task-pop-up-btns-task">
          <div class="pop-add-btn-task">
            <button type="submit" id="pop-up-save-task-btn">Add</button>
          </div>
          <div class="pop-cancel-btn-task">
            <button type="submit" id="pop-up-delete-task-btn">Cancel</button>
          </div>`your text
        </div>
      </form>
    </dialog>

    <!--  -->
  </body>
  <!-- <script src="../src/index.js"></script> -->
  <script src="main.js"></script>
</html>

This is the JS, It is properly connected to the Index.js

export class AddTask {
  constructor(pageName) {
    this.pageName = pageName;

    this.popUpTaskDialog = document.querySelector("#add-task-pop-up");
    this.taskName = document.querySelector("#task-name");
    this.taskDescription = document.querySelector("#task-desc");
    this.taskDate = document.querySelector("#task-date");
    this.saveTaskBtn = document.querySelector("#pop-up-save-task-btn");
    this.cancelTaskBtn = document.querySelector("#pop-up-delete-task-btn");
    this.taskPriority = document.querySelector("#task-priority");

    this.saveTaskBtn.addEventListener("click", (event) => this.saveTask(event));
    this.cancelTaskBtn.addEventListener("click", (event) =>
      this.closeTaskDialog(event)
    );

    this.render();
  }

  render() {
    this.popUpTaskDialog.showModal();
  }

  saveTask(event) {
    event.preventDefault();
    if (this.taskName.value.trim() === "") {
      //this.alertLog("Please enter a task name");
    } else {
      try {
        const taskCardDisplay = document.querySelector("#tasks-display");
        const contentCard = this.createTaskCard();
        taskCardDisplay.appendChild(contentCard);
      } catch (error) {
        console.log(error);
        console.log("No task display found");
      }

      try {
        const taskMainPage = document.querySelector(".main-list-container");
        taskMainPage.innerHTML = "";
        taskMainPage.appendChild(this.taskCardDisplay);
      } catch (error) {
        console.log(error);
        console.log("No main list container found");
      }
      this.closeTaskDialog(event);
    }
  } 
}



This is a MERN project and all the relevant files are created, also the project worked well before addition of this function.
All the other required methods are created and they were all working

When I try to add a new task, I get the following error in the console

TypeError: Cannot read properties of null (reading 'appendChild')
    at n.saveTask (main.js:1:11774)
    at HTMLButtonElement.<anonymous> (main.js:1:11479)
main.js:1 No task display found
main.js:1 TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at n.saveTask (main.js:1:11926)
    at HTMLButtonElement.<anonymous> (main.js:1:11479)
main.js:1 No main list container found

What should I do to resolve this?

Translate website in other languages using PHP, ajex, jQuery, JavaScript

I have a dynamic website in which I want a drop-down in my website with 15 languages options, when I click an option my website should be translate in that language.

According to my research their are two ways to do this task first is using APIs which are paid I don’t want to go for that and second way is we create a function in JS and store my complete webpage content in all languages in variables or array and than that variable will call on drop down options this way is too much length and complicated.

Is their any other why which will be easy and free to translate my website? Any function or logic ?

How to handle/catch keycloak.js ERR_CONNECTION_TIMED_OUT

I use keycloak-js to check sso on load. The problem is, when the server is down or whatever, The browser (web view) redirects to the website not available (ERR_CONNECTION_TIMED_OUT) page.

How to prevent keycloak-js from redirecting when sso server is not available (connection timed out).

await keycloak.init({
 checkLoginIframe: false,
 flow: 'standard',
 onLoad: 'check-sso',
});

I see keycloak.onAuthError, but how to do something like preventDefault? Navigating to the offline page? I just want to catch this and manually show an error without redirecting.

Mocking 2 or more modules in jest doesnt mocking values

i am mocking 2 module one is react-library and other one is simple file but when i try to test it gives error and doesnt run but when i do it one by one by commenting first jest.mock and running second one or commenting second one and running first then it works perfectly

jest.mock('@web3modal/ethers/react')
jest.mock('../../helper/Api', () => ({
   fetchBtcPrice: jest.fn().mockResolvedValue(10),
   getTotalBtc: jest.fn().mockResolvedValue([5, true]),
 }))

then how to deal with 2 or multiple module mocking in same test file??

example –

jest.mock('@web3modal/ethers/react')

jest.mock('../../helper/Api', () => ({
  fetchBtcPrice: jest.fn().mockResolvedValue('10'),
  getTotalCostakedBtc: jest.fn().mockResolvedValue([5, true]), // Assuming you want to simulate 'true' for show notification
}))
describe('Dashboard without connecting wallet', () => {
it('renders TVL value correctly', async () => {
    await act(async () =>
      render(
        <ErrorBoundary>
          <RecoilRoot>
            <App>
              <Dashboard />
            </App>
          </RecoilRoot>
        </ErrorBoundary>,
      ),
    )
    await act(async () => {
      const tvlElement = await waitFor(() => screen.getByTestId('loaded-TVL'), { timeout: 3000 })
      // screen.debug()
      const tvlText = tvlElement.textContent
      const expectedTotalValue = 5 * 10
      expect(tvlText).toEqual(`TVL$${expectedTotalValue}`)
    })
  })
})

it wont pass the test case
but if i jest.mock('@web3modal/ethers/react') comment this line
then it passes the code and give me expected as 50. else it gives me 0 only.
similarly
if i do

jest.mock('@web3modal/ethers/react')

jest.mock('../../helper/Api', () => ({
  fetchBtcPrice: jest.fn().mockResolvedValue('10'),
  getTotalCostakedBtc: jest.fn().mockResolvedValue([5, true]), // Assuming you want to simulate 'true' for show notification
}))
describe('Dashboard web3 after connecting wallet', () => {
  let mockOpen, mockSetThemeMode, mockAddress, mockIsConnected, mockWalletProvider, mockDisconnect

  beforeEach(() => {
    mockOpen = jest.fn()
    mockSetThemeMode = jest.fn()
    mockAddress = '0x9e0569'
    mockIsConnected = true

    mockWalletProvider = {
      request: jest.fn(),
      send: jest.fn(),
      on: jest.fn(),
      removeListener: jest.fn(),
      disconnect: jest.fn(),
      isMetaMask: true, // assuming you are using MetaMask
      _events: {}, // required by some ethers.js methods
    }
    mockDisconnect = jest.fn()

    // // If you need to mock specific responses from the provider
    // mockWalletProvider.request.mockResolvedValue('0x123') // mock response for request method
    // mockWalletProvider.send.mockResolvedValue('0x456') // mock response for send method

    useWeb3Modal.mockReturnValue({ open: mockOpen })
    useWeb3ModalTheme.mockReturnValue({ setThemeMode: mockSetThemeMode })
    useWeb3ModalAccount.mockReturnValue({ address: mockAddress, isConnected: mockIsConnected })
    useWeb3ModalProvider.mockReturnValue({ walletProvider: mockWalletProvider })
    useDisconnect.mockReturnValue({ disconnect: mockDisconnect })
  })
it('renders clicking arrow button navigating to costake page', async () => {
    const { getByTestId } = render(
      <ErrorBoundary>
        <RecoilRoot>
          <App>
            <Dashboard />
          </App>
        </RecoilRoot>
      </ErrorBoundary>,
    )
    fireEvent.click(getByTestId('arrow-img'))
    expect(window.location.pathname).toBe('/costake')
  })
})

then it also failed but if i comment

// jest.mock('../../helper/Api', () => ({
//   fetchBtcPrice: jest.fn().mockResolvedValue('10'),
//   getTotalCostakedBtc: jest.fn().mockResolvedValue([5, true]), // Assuming you want to simulate 'true' for show notification
// }))

then it passes the test case.
so its like,the jest is overlapping the mock modules.
how to solve this?

How would I implement Operational Transformation with a js client and python server?

I’m currently looking into Operational Transformation to get a textarea block sharing between multiple users fluidly. I’ve been looking at existing implementation libraries such as ShareDB, but I’ve noticed that all the systems I can find assume that both client and server are using the same language.

I, however, have been using Python as my server side while javascript handles the browser client-side.

Are there any good server-side implementations for python that will work alongside ShareDB’s client side, or will I need to rewrite my server code in js to be able to implement?

JSON, cart, and editing the quantity, JAVASCRIPT [closed]

hey, i need help!

please

fails/errors:

  • cant add anything when the cart is empty
  • cant add more than one item at a time
  • payment works not properly

goals:

  • i want to add multiple items
  • i want after payment a nice clean cart with a h2 and the p-tag
  • i want to add item even when the cart is empty

what i did:

talk with colleagues&Co.
goggle&Co., ask-the-debugger
help from KI (asked for checks and reviewing of code)

.. sitting here for days now..

[addItemToBasket](https://i.sstatic.net/WmgAjfwX.png)
[addItem-plus](https://i.sstatic.net/A2WjJJJ8.png)
[delItem](https://i.sstatic.net/9lZwgUKN.png)
[payment](https://i.sstatic.net/9Xm5yfKN.png)
[showBasket](https://i.sstatic.net/V1IkSGth.png)
[render](https://i.sstatic.net/2fLSqBxM.png)

“Print” PDF file in PHP/JS to get a flattened PDF File

I’m working on a workflow tool in PHP and JS where coworkers are able to send PDF documents and edit them (add annotations) in any webbrowser by using the build in PDF viewer. The problem with this is that the made annotations are editable.
The solution for this would be to flatten the PDF, but I didn’t find anything, except for expensive APIs, that would be able to achieve this. If anyone knows how to do it in PHP or JS that would be amazing.

Another approach I was thinking about is to “print” the PDF file and save the printed file on my webserver. I don’t know anything about printers or printservers, that’s why I just want to know if this may be possible.
The reason I think this could be possible is that we a function at work to “print as PDF”. This sends you an email with a flattened PDF. Would it be possible to achieve something similar on a webserver?

I tried to use different PHP and JS libraries to solve my problem.

How I can load my library function in my custom service worker?

I am making a custom library (file src/mylib.js):


export function myfunc(){
  // do stuff here
}

Where I use rollup to build it as umd module:

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { babel } from '@rollup/plugin-babel';

export default [
  {
    input: 'src/mylib.js',
    output: [
      {
        file: 'dist/mylib.js',
        format: 'umd',
        name: 'firebaseLibServiceWorker',
        sourcemap: true
      }
    ],
    plugins: [
      resolve(),
      commonjs(),
      babel({
        exclude: 'node_modules/**',
        babelHelpers: 'bundled',
        presets: [
          ['@babel/preset-env', {
            targets: {
              browsers: ['> 0.25%', 'not dead', 'ie 11']
            }
          }]
        ]
      }),
    ],
  },
];

And I export it as a module into npm:

{
  "name": "mylib",
  "version": "1.0.0",
  "description": "blahblahblag",
  "type": "module",
  "scripts": {
    "build": "rollup -c",
    "start": "rollup -c --watch",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "TechInsSoftware",
  "license": "MIT",
  "dependencies": {
  },
  "devDependencies": {
    "@babel/core": "^7.24.5",
    "@babel/preset-env": "^7.24.5",
    "@rollup/plugin-babel": "^6.0.4",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "rollup": "^4.17.2"
  }
}

And what I want to achieve it to use it via importScripts whenever I want to use it:

importscripts('https://mydnb.example.com/dist/mylib.js');

But I am unable to do so:

importscripts('https://mydnb.example.com/dist/mylib.js');
myfunc()

Cause I get:

Uncaught ReferenceError: myfunc is not defined

How I can fix this?

How to compress images client side before uploading with Livewire

I’m working on a project using Livewire 3 and I’m encountering issues with large image files from modern cell phones, as these high-megapixel images are too heavy to be handled efficiently on slow connections.

I want to compress images on the client side before uploading them via Livewire. Additionally, I’d love to see an example of integrating JavaScript with Livewire for this purpose, as such examples are quite rare or outdated.

I’m comfortable with the “Laravel way” of uploading and previewing images with Livewire 3, but I’m not familiar with the JavaScript integration part, so I’m having a hard time uploading and previewing the JavaScript-compressed files with Livewire.

I know that there are some popular JS packages for this purpose, like Compressor.js or Browser Image Compression or that we can also achieve this with plain old JS – I would just like a working example, no matter which JavaScript compression method is used.

Has anyone dealt with this issue before? How can I achieve client-side image compression and upload the compressed image using Livewire?

Any guidance or examples would be greatly appreciated!

Thanks in advance for your help!

How to make TypeScript see variable reassignments in lambdas?

I am running a lambda function predicate over a list of values to find the first value matching the predicate. However, in addition to finding the right value, I want to store the result of an internal calculation in the lambda function for later.

Simplified example:

let helper: number | undefined = undefined;
const array = [1, 2, 3];

const result = array.find((v) => {
  helper = v % 2;
  return helper === 0;
});

console.log({ helper, result });
if (helper !== undefined) {
  console.log(helper.toExponential());
}

Here, result should be the first value matching the predicate and helper should store the internal calculation, which I want to do something with later on. In order to consider the case where no value matches the predicate, I defined the type of helper to be number or undefined and check afterwards, if helper is a number before I do anything with it.

At runtime everything works as expected and the output is:

{ "helper": 0, "result": 2 }
"0e+0"

However, TypeScript complains:

Property 'toExponential' does not exist on type 'never'.

That is, TypeScript does not see the reassignment of helper within the lambda function. Because it does not see it, it deduces that the type of helper can be simplified to undefined.

How can I make TypeScript aware that I am reassigning a variable in a lambda function?

TypeScript Playground Link

Add Rows to grid layout via d3

I am fairly new to d3, so I consider this a newbie question, b/c I still could not wrap my head around data joins. I am trying to add rows to a grid layout. Each row is represented as an object with several slots and the rows are stored in an array.

In my .join I want to add several elements to the selection (content determined by the slots of the object, here simply the .text). I have difficulties to specify the .selectAll call before the .data call. I understand why this strange behaviour is occuring (basically) it tries to match the data to all divs in the selection (which are all cells).

How would I need to change m code, that each click on the button simply adds a new row?

Bonus question: as you cna see the cells are all mixed up. How would I add the data by row and not by column?

const data = [
  {cell1: '1/1', cell2: '1/2', cell3: '1/3', id: 1},
  {cell1: '2/1', cell2: '2/2', cell3: '2/3', id: 2}
];


function update(data) {
  d3.select('#grid')
    .selectAll('div')
    .data(data, (d) => d.id)
    .join((enter) => {
      enter.append('div')
        .classed('cell1', true)
        .text((d) => d.cell1);
      enter.append('div')
        .classed('cell2', true)
        .text((d) => d.cell2)
      enter.append('div')
        .classed('cell3', true)
        .text((d) => d.cell3);
  })
}

update(data)

function addRow() {
  const n = data.length + 1;
  const newRow = {cell1: n + '/1', cell2: n + '/2', cell3: n + '/3', id: n};
  data.push(newRow);
  update(data);
}
#grid {
  display: inline-grid;
  grid-template-columns: repeat(3, 200px);
}

#grid > div:nth-of-type(3n+2) {
  background-color: orange;
}

#grid > div:nth-of-type(3n+1) {
  background-color: purple;
}


#grid > div:nth-of-type(3n+0) {
  background-color: forestgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<div id="grid">
</div>
<button id="add" onclick="addRow()">Add Row</button>

Use query string parameters on Word add-in SourceLocation(manifest.xml)

I want to use query string parameters on SourceLocation on a Office add in(Word add in). I can add the query string parameters inside the manifest.xml file. How can I read them inside taskpane.html file

The query string parameters I used are stripped and not usable from taskpane.html file.

When I use Window location.search it does not have the query string parameters I added.

Is there any configuration on manifest.xml file or Office to enable query string parameters on SourceLocation

Imported function and class is undefined

Facing a weird issue maybe with importing,
after the imports the class and function imported from a module is undefined

Below is the Scenario:

In file.js

// file.js
function someFunction() {
  // ... function logic
}

class A {
  constructor() {
    // ... constructor logic
  }
}

module.exports = { A, someFunction };

In other file.js

// other-file.js
const { A, someFunction } = require('./file.js'); // Destructure imports

// This will correctly create an instance of A
const instanceA = new A();

added break point right after the require statement, it showed that A and someFunction both are undefined.

PS: this code was working fine before until now, also the same is imported in other files I can see its importing correctly over there.

  • Checked for circular imports, no circular imports found.
  • Checked for naming issues and even path issues, everything was correct.
  • Checked for function and class correctly present in module.exports, found everything correctly exported.