Creating small screenshots in js using the bmp-js package

In my JS code, I need to save canvas screenshots. I do it with a package bmp-js (https://www.npmjs.com/package/bmp-js)

  data_GUI = await utilities.get_canvas(canvas_selector)
  arr_of_data_GUI = Object.values(data_GUI)
  arr_of_data_GUI = new Uint8Array(arr_of_data_GUI)
  temp = bmp.encode(
    {
      data: arr_of_data_GUI,
      width: canvas_width,
      height: canvas_height
    }
  )
  return fs.createWriteStream(file_path).write(temp.data)

My screenshots are about 3mb in size. I want to take smaller screenshots. The documentation for bmp-js has this code:

var bmp = require("bmp-js");
var rawData = bmp.encode(bmpData);//default no compression,write rawData to .bmp file

The comment to the code says “default no compression“, but I can’t find how to call this code with compression.

Please help me!

How to reduce JavaScript code when I’m trying to sum of table colums?

I have a table & I want to total of columns data, this is working fine but now I want to reduce JavaScript code how can I do that?

My Code:-

var TotalValue1 = 0;
        var currentRow1 = '';
        $("tr .loop1").each(function(index, value) {
            currentRow1 = parseFloat($(value).text());
            TotalValue1 += currentRow1
        });
        $('.total1').text(TotalValue1);
        
           var TotalValue2 = 0;
        var currentRow2 = '';
        $("tr .loop2").each(function(index, value) {
            currentRow2 = parseFloat($(value).text());
            TotalValue2 += currentRow2
        });
        $('.total2').text(TotalValue2);

        var TotalValue3 = 0;
        var currentRow3 = '';
        $("tr .loop3").each(function(index, value) {
            currentRow3 = parseFloat($(value).text());
            TotalValue3 += currentRow3
        });
        $('.total3').text(TotalValue3);
     
        var TotalValue4 = 0;
        var currentRow4 = '';
        $("tr .loop4").each(function(index, value) {
            currentRow4 = parseFloat($(value).text());
            TotalValue4 += currentRow4
        });
        $('.total4').text(TotalValue4);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>


  <table class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Store</th>
        <th>Sale</th>
        <th>Revenu</th>
        <th>Payout</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td class="loop1">20</td>
        <td class="loop2">34</td>
        <td class="loop3">65</td>
        <td class="loop4">26</td>
      </tr>
      <tr>
        <td>John</td>
        <td class="loop1">76</td>
        <td class="loop2">93</td>
        <td class="loop3">27</td>
        <td class="loop4">83</td>
      </tr>
      <tr class="font-weight-bold">
        <td>Total</td>
        <td class="total1"></td>
        <td class="total2"></td>
        <td class="total3"></td>
        <td class="total4"></td>
      </tr>
     
    </tbody>
  </table>

</body>
</html>

ThankYou!

Javascript for each spread operator refactor

This is my current situation,

const cleanString= string => {
  let city = getAccentedCity(string);
  if (city.toLowerCase().indexOf('%c3%9f') >= 0 ) return city.replaceAll('%c3%9f', 's');
  if (city.indexOf('%20') < 0) return city;
  return city.replaceAll('%20', ' ');
}

The cities containing these special characters i do a replaceAll with his pair assigned. It works fine

I am doing now a refactor like this

const replaceMap = [
  ['%20', ' '],
  ['%c3%9f', 's'],
];

const cleanString = (string) => {
  let city = getAccentedCity(string);
  replaceMap.forEach(pair => city = city.replaceAll(...pair));
  return city;
}

The code stopped working and i do not see the error, what is the problem here? How can i do this refactor better?

Vue: passing dynamic props to mixin

Is it possible to pass dynamic props to Vue mixin from its parent component?
Here are my codes.

This is the mixin receiving isActive as a prop.

mixin.ts

export default {
  props: {
    isActive: {
      type: Boolean,
      required: true
    }
  },
  watch: {
    isActive: {
      immediate: true,
      handler() {
        if (this.isActive) {
          // do something
        } else {
          // do something        
        }
      }
    }
  },
  methods: {
    // some methods
  }
}

This component calls the mixin above.
I want to pass the isActiveToBePassed to the mixin as isActive prop.

component.vue

<template>
 ....
</template>

<script lang="ts">
import mixin from 'mixin';

export default {
  name: "Sample",
  mixins: [mixin], <- ??? how to pass the isActiveToBePassed as a prop
  data() {
    return {
      isActiveToBePassed: false,
    }
  },
  ...
};
</script>

Thank you.

progressbar html tag change

I’am working on progressbar that change the level when reaching some point.
The code.
I want to change the text under the progressbar when the progressbar reach 100 or above 90.
I could change it once but I want to go to next level, like this.
silver ==> gold ==> diamond ==> and more

const step = 5;
var content=document.getElementById('mylevel').innerHTML;

const updateProgress = () => {
  const currentWidth = Number(document.getElementById("progressvalue").style.width.replace( "%", ""));
  
  if (currentWidth>=100) {
    return;
  }
  else {
    document.getElementById("progressvalue").style.width = `${currentWidth+step}%`;
  }

    if (currentWidth > 90) {
    
      document.getElementById("mylevel").textContent = "gold";
      document.getElementById("progressvalue").style.width = "0%";
    }
      if (currentWidth > 90 && content == "gold") {
    
      document.getElementById("mylevel").textContent = "diamond";
      document.getElementById("progressvalue").style.width = "0%";
    }
}

const restart = () => {
  document.getElementById("progressvalue").style.width = "0%";
}
.progress {
  background-color: #ededed;
  width: 100%;
  overflow: hidden;
}
#progressvalue {
  height: 40px;
  background-color: lightgreen;  
  width: 0%;
}
<div class="progress">
  <div id="progressvalue"></div>
  
</div>
<p id="mylevel">silver</p>
<br />
  
<button type="button" onclick="updateProgress()">
  Update Progress
</button>
  
<button type="button" onclick="restart()">
  Restart
</button>

When the updateprogress is above 90 the silver change to gold, but I need to change again to diamond when the updateprogress is again above 90.
Am I putting the if condition in a wrong place, I tried many times.
I don’t know what I’am missing and am new with JavaScript

I started the code but got help here to make it much better (80% of the code done by
teresaPap thanks)

How to add multiple markers in Maptiler map in Angular 13?

I have implemented maptiler in Angular 13, and I can add a single marker init but now as per my requirement I need to add multiple markers init. I did go through with their documents but I couldn’t able to find any reference regarding it. I have attached my code below please help me.

TS File

export class HomePage implements OnInit, AfterViewInit, OnDestroy {
  map: Map | undefined;
  @ViewChild('map')
  private mapContainer!: ElementRef<HTMLElement>;
  constructor(public platform: Platform) { }
  ngOnInit(): void {


  }
  ngAfterViewInit() {
    setTimeout(() => {
      const initialState = { lng: 72.778310, lat: 21.145640, zoom: 12 };

      this.map = new Map({
        container: this.mapContainer.nativeElement,
        style: `https://api.maptiler.com/maps/streets/style.json?key='API_Key'`,
        center: [initialState.lng, initialState.lat],
        zoom: initialState.zoom, dragPan: true, dragRotate: false
      });
      let controlOption = {
        showCompass: true,
        showZoom: true,
        visualizePitch: false,
      }
      this.map.addControl(new NavigationControl(controlOption), 'top-left');
      new Marker({ color: "#FF0000" })
        .setLngLat([initialState.lng, initialState.lat]).addTo(this.map)
      // marker.setLngLat([71.778310, initialState.lat]).addTo(this.map)
      // marker.setLngLat([71.758310, initialState.lat]).addTo(this.map)
    }, 500);
  }
  ngOnDestroy(): void {
    this.map?.remove();
  }
}

HTML File

<div class="map-wrap">
    <div class="map" #map></div>
</div>

How can I implement form validation on my title input and have it submit along with an image file that a user selects?

I am trying to implement a user image post that allows a user to choose an image and add a title to that image within my React application and am having some trouble. I have used formik in the past but since I need a user to select an image, need to implement my own version. I was able to make it so that a user is able to select an image, I just need help with the title input. I want both the image and the title to get passed into my backend, and I also want to add form validation on the title so that when it is left empty, an error message displays and doesn’t allow it to be uploaded. Does anyone know how I can go about doin this? I have a sandbox with my attempts, but I am getting a blank screen when attempting to add the validation. https://codesandbox.io/s/peaceful-frog-ui4413?file=/src/App.js

enter image description here

Changing select2_ajax to text field but keeping the funtionality on WordPress

I need some help with a WordPress site, I am a beginner at javascript/ajax so any advice would be brilliant, it uses the Noo JobMonster theme and uses select2_ajax field when creating a job for selecting a company from the company list built into the site and uses this information to display the company details on the job page, is there any way to change this field to a text field but keep the functionality of it searching and selecting the company from the company list and displaying it as long as the names match, this is because we are going to be importing an xml file of jobs from a different site and not sure if the field will connect up and will work the current way.

Here is a link to one of the job pages: https://www.edijobs.co.uk/jobs/customer-service-administrator-tpcsa150322/

job company screenshot

Thanks

id is undefined in function

i have a global id then i want to use it in onSubmit function

export default function EditColorModal(props) {
  const dispatch = useDispatch();

  const [color, setColor] = useState({});

  const onSubmit = async () => {
    console.log(color);
    await axios.patch(`/admin/color/${color._id}`, {
      name,
      title,
      code,
    });
    const id = color._id;
    dispatch(adminActions.updateColor({ id, title, name, code }));
  };
 return (
    <div>
      <button
        type="button"
        class="btn btn-primary"
        data-bs-toggle="modal"
        data-bs-target="#EditColorModal"
        onClick={() => {
          setColor(props.color);
        }}
      >
        <Edit />
      </button>
</div>

console.log(color) in onSubmit function is undefined but up the function get me value

Firebase realtime db limitToFirst(10) doesnt working

i am facing issue i am trying to get only 10 data from firebase but how can i achieve that if ref(database, “messages/”).limitToFirst(10) is throwing:

ref(…).limitToFirst is not a function

My code:

const newMsg = ref(database, 'messages/').limitToFirst(10);
onChildAdded(newMsg, (data) => {
    if(data.val().name != name){
        var divData = '<div class="message"><div class="others">'+data.val().name+': </div><div>'+data.val().message+'</div></div>'; 
        //oponent message
        $("#chat-history").append(divData);
    }else{
        var divData = '<div class="message"><div class="user">'+data.val().name+': </div><div>'+data.val().message+'</div></div>'; 
        //sent message
        $("#chat-history").append(divData);
    }
});

Where database is

const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

And my imports look like this:

import {initializeApp} from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
import {
    getDatabase,
    set,
    ref,
    push,
    child,
    onValue,
    onChildAdded
} from "https://www.gstatic.com/firebasejs/9.6.6/firebase-database.js";

local storage problem when trying to fetch data from localstorage using useEffect() in ReactJS

I am trying to fetch data in localstorage using ReactJS. Can some one please help me here is my sample code.


let [rows,setRows] = useState([]);

    React.useEffect(() => {
        rows = localStorage.getItem("my_tier_list");
        if(rows){
            setRows(JSON.parse(rows));
        }
  
      },[]);
  
      React.useEffect(() => {
        localStorage.setItem("my_tier_list", JSON.stringify(cart));
      });

Can some one please help me and thanks in advance

HtmlWebpackPlugin: index.html does not include index.js scripts

I am trying to build with webpack and the HtmlWebpackPlugin. When I do so and open my newly generated index.html, it seems that all changes done inside the index.js to the template index.html are not being reflected. For example when clicking on buttons that have been assigned to an onclick event, I get errors like: Uncaught ReferenceError: selectAccount is not defined. Also, buttons that should simply modify the display property of divs don’t react at all.

webpack.config.js:

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const config = {
  entry: { script: "./src/index.js" },
  output: {
    path: __dirname + "/dist",
    filename: "index_bundle.js",
  },

  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"],
      },
      {
        test: /.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /.html$/,
        use: "html-loader",
      },
      {
        test: /.txt|docx$/,
        use: "raw-loader",
      },
    ],
  },
  resolve: {
    extensions: ["*", ".js"],
  },
  devServer: {
    static: "./dist",
    port: 8000,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers":
        "X-Requested-With, content-type, Authorization",
    },
  },
  plugins: [
    new MiniCssExtractPlugin(),

    new HtmlWebpackPlugin({
      title: "Project Title",
      template: "index.html",
      inject: true,
      // excludeChunks: ["script"],
    }),
  ],
};

module.exports = (env, argv) => {
  process.env.NODE_ENV = argv.mode;

  if (argv.mode === "development") {
    //
  }

  if (argv.mode === "production") {
    //
  }

  return config;
};

package.json:

{
  "name": "abc",
  "version": "1.0.0",
  "description": "abc",
  "main": "index.js",
  "scripts": {
    "start": "webpack serve --config ./webpack.config.js --mode development",
    "dev": "webpack serve --config ./webpack.config.js --mode development",
    "build": "webpack --config ./webpack.config.js --mode production",
  },
  "repository": {},
  "keywords": [
    "javascript",
    "code",
    "node.js"
  ],
  "author": "",
  "license": "MIT",
  "homepage": "",
  "dependencies": {
    "angular-expressions": "^1.1.5",
    "docxtemplater": "^3.29.0",
    "express": "^4.17.1",
    "file-saver": "^2.0.5",
    "file-system": "^2.2.2",
    "install": "^0.13.0",
    "lodash": "^4.17.21",
    "morgan": "^1.10.0",
    "npm": "^8.5.0",
    "pizzip": "^3.1.1",
    "survey-creator": "^1.9.13",
    "survey-jquery": "^1.9.7",
    "vis-data": "^7.1.2",
    "vis-network": "^9.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.17.8",
    "babel-loader": "^8.2.4",
    "css-loader": "^6.7.1",
    "html-inline-css-webpack-plugin": "^1.11.1",
    "html-inline-script-webpack-plugin": "^3.0.0",
    "html-loader": "^3.1.0",
    "html-webpack-inline-source-plugin": "^0.0.10",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.6.0",
    "nodemon": "^2.0.3",
    "path": "^0.12.7",
    "raw-loader": "^4.0.2",
    "replace-in-file-webpack-plugin": "^1.0.6",
    "webpack": "^5.70.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  }
}

project structure:

dist-folder
- index_bundle.js
- index.html
- ...
node_modules-folder
src-folder
- index.js
- ...
index.html (template)
package.json
style.css
webpack.config.js

How can I open a JavaScript or CSS file from .html, which is in a different Gitlab repository on the same Server

I am currently working on a presentation platform hosted by Gitlab. The JavaScript code and the CSS templates shall be in one repository. The user shall open then a new repository based on a template and use the JavaScript code from the “main” repository for the individual presentation webpage. Everything works if its all together in one repository, but I do not know how to call a JavaScript file from another repository without a workaround which is to complicated for the users.
So the question is, how can I use other files from another repository in Gitlab.
Something like this:

<link rel="stylesheet" href="path_to_main_repo/dist/theme/black.css" id="theme">

Best regards,
Jonas

Third-party Voice-to-Text Services for UI Integration

I am looking for a Voice-to-Text Service for a UI search bar. The idea is that the application should allow the user to enter short phrases (2-5 words) using Voice. We want the Voice-to-Text service to be integrated with the UI application for better performance. We also want to have the capability to monitor and tweak the Voice-to-Text service.

We looked into the following services,

  1. JavaScript Web Speech API: Limited browser support, No way to enhance/tweak the service.
  2. Google Speech to Text: No JavaScript client.
  3. Azure Speech to Text: API Token is exposed when used on UI.

Are there any other Voice-To-Text services that integrate well with the UI?