Problem about website with multi-language with html, js and json [duplicate]

I’m writing my simple website page, and I want my page has multi-language. And here is what i got:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://trash1-stl.glitch.me/body.css">
        <link rel="stylesheet" href="https://trash1-stl.glitch.me/header.css">
    </head>
    <body>
        <div class="container">
            <header class="header">
                <div class="header-container">
                    <div class="header-left">
                        <a href="/" class="logo" id="hp"></a>
                        <div class="menu"></div>
                    </div>
                    <div class="header-right">
                        <div class="language">
                            <a class="logo" value="vi" style="cursor: pointer;">
                                <img src="https://cdn.glitch.global/fe903a6f-50b0-47e7-ac0b-5135afb92925/flag_vn.png?v=1670855949145" alt="Chuyển sang tiếng Việt" title="Chuyển sang tiếng Việt" class="logo-image">
                            </a>
                            <a class="logo" value="en" style="cursor: pointer;">
                                <img src="https://cdn.glitch.global/fe903a6f-50b0-47e7-ac0b-5135afb92925/flag_uk.png?v=1670855969176" alt="Switch to English" title="Switch to English" class="logo-image">
                            </a>
                        </div>
                    </div>
                </div>
            </header>
        </div>
    </body>
    <script src="jquery-3.7.1.min.js"></script>
    <script src="script.js"></script>
</html>

script.js:

document.addEventListener("DOMContentLoaded", function() {
    const languageManager = new LanguageManager();
    const initialLanguage = languageManager.getLanguage() || 'vi';
    loadContent(initialLanguage);
    
    const language = document.getElementsByClassName("language");
    language.addEventListener("change", function() {
        const selectedLanguage = language.value;
        languageManager.setLanguage(selectedLanguage);
        loadContent(selectedLanguage);
    });
});

function loadContent(language) {
    const header_logo = document.getElementsByClassName("logo");
    fetch("lang.json")
    .then(response => response.json())
    .then(data => {
        const content = data.all.header.logo[language];
        header_logo[0].innerHTML = `
        <img 
        src="https://cdn.glitch.global/fe903a6f-50b0-47e7-ac0b-5135afb92925/STL.png?v=1670131602976" 
        alt="${content.alt}" 
        title="${content.title}" 
        class="logo-left-image">
        `;
    })
    .catch(error => console.error("Lỗi tải giá trị!: ", error));
};

class LanguageManager {
    constructor() {
        this.storageKey = "selectedLanguage";
    };

    getLanguage() {
        return localStorage.getItem(this.storageKey);
    };

    setLanguage(language) {
        localStorage.setItem(this.storageKey, language)
    };
}

lang.json:

{
    "all": {
        "header": {
            "logo": {
                "vi": {
                    "alt": "Content[VN]",
                    "title": "Content [VN]"
                },
                "en": {
                    "alt": "Content [EN]",
                    "title": "Content [EN]"
                }
            }
        }
    }
}

This is a code about multi-lang and its keep that type language in other sites (when I choose English (Vietnamese is the defalut language) in index.html and its keep set English in example.html). And so that, I have a problem: It’s said that language.addEventListener is not a function`, and I have get correct class name and id in element.

React + Vite App Not Loading on iOS When Wrapped with Cordova (White Screen Issue)

I’m currently working on a React project using Vite and attempting to wrap it with Cordova for mobile deployment. Everything functions correctly on Android, but when running on iOS, I encounter a white screen and the app fails to load.

What I’ve Tried:

  1. Followed the standard Cordova approach: created a Cordova project, added Android and iOS platforms, moved build files to the www folder, and used cordova run .
  2. Tested with a Create React App (CRA) project in the same Cordova setup, which worked fine on iOS.
  3. Replaced the app’s build file with a basic JavaScript file, which loaded correctly.
  4. Modified the HTML to load this basic JavaScript file as type=”module” (as Vite sets it), which resulted in failure.
  5. Attempted to alter the Vite build process to generate a non-module JavaScript file, but this did not resolve the issue.

Observations:

  • It seems Cordova on iOS has trouble loading files with type=”module”.
  • Even after switching to a SystemJS-based build, the issue persisted.

Temporary Solution:

Successfully made it work using Capacitor instead of Cordova, but I’m interested in finding a Cordova-based solution.
Question:
Has anyone successfully integrated React, Vite, and Cordova, particularly for iOS deployment? Any insights or suggestions to resolve this module loading issue with Cordova on iOS would be greatly appreciated.

Environment:

  • React
  • Vite
  • Cordova

JavaScript Live Calculator [duplicate]

Im trying to make a live calculator in java script and html and by live I mean every time a number or a symbol changes the answer changes live time. So I wrote this code but every time I change the number or symbol the answer just goes away.

var num01 = document.getElementById("num01").value;
var num02 = document.getElementById("num02").value;
var calculation = document.getElementById("calculation");
var answer = document.getElementById("answer");

calculation.onchange = function() {
    calculationSelect = this.value
    if (calculationSelect = "") {
        answer.innerText = "0"
    } else if (calculationSelect = "+") {
        answer.innerText = num01 + num02
    } else if (calculationSelect = "-") {
        answer.innerText = num01 - num02
    } else if (calculationSelect = "x") {
        answer.innerText = num01 * num02
    } else if (calculationSelect = "/") {
        answer.innerText = num01 / num02
    }
}

document.getElementById("num01").onchange = function(){
    if (calculationSelect = "") {
        answer.innerText = "0"
    } else if (calculationSelect = "+") {
        answer.innerText = num01 + num02
    } else if (calculationSelect = "-") {
        answer.innerText = num01 - num02
    } else if (calculationSelect = "x") {
        answer.innerText = num01 * num02
    } else if (calculationSelect = "/") {
        answer.innerText = num01 / num02
    }
}

document.getElementById("num02").onchange = function(){
    if (calculationSelect = "") {
        answer.innerText = "0"
    } else if (calculationSelect = "+") {
        answer.innerText = num01 + num02
    } else if (calculationSelect = "-") {
        answer.innerText = num01 - num02
    } else if (calculationSelect = "x") {
        answer.innerText = num01 * num02
    } else if (calculationSelect = "/") {
        answer.innerText = num01 / num02
    }
}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <label id="answer">0</label>
    <input type="number" id="num01">
    <select id="calculation"> 
        <option value=""></option>
        <option value="+">+</option> 
        <option value="-">-</option> 
        <option value="x">x</option> 
        <option value="/">/</option> 
    </select>
    <input type="number" id="num02">
    <script src="script.js"></script>
</body>
</html>
#answer{
    display: block;
    text-align: center;
    font-size: 100px;
}

I tried to to change the if statements to be more direct with the imports from the html file but that still didn’t work.

Sending javascript array data to whatsapp contact via link

I have a javascript array.
Example

let newArrVal = [{"name" : "book",
"Price" : 18.99}, {"name" : "bag",
"Price" : 18.99}]

I have a html button and I want that html button to send this array of objects data to whatsapp, how do I do it? As if you want to send message to whatsapp, you should have &20 for space seperator.
For example wa.me/+1234455?text=hello%20world

from firebase google authentication emailid is not fetching

I am using firebase google authentication in my project. when iam hosting my project on local-host and login with my email the firebase token contains my emialid but when i try with other mails the firebase token contain emial as null and other things like photo, name is present in the token but iam only facing issue with emailid.

I have tried to pass email as parameter explicitly, also iam taking user permission (i saw this on documentation) but still its not solving.

Chart.js The second line in Chart.js is incorrectly positioned in X-axis

I have created multiple line chart, but the second line incorrectly positioned according X-axis, got the same starting point as first line, but by JsonData it has another starting point. How to fix it? No idea.

enter image description here

Function of creating chart:

function createEmployeeChart(chartId, xValues, datasets) {
                  var uniqueXValues = Array.from(new Set(xValues));
                
                  new Chart(chartId, {
                    type: "line",
                    data: {
                      labels: uniqueXValues,
                      datasets: datasets,
                    },
                    options: {
                      legend: {
                        display: false
                      },
                    },
                  });
                } 

Ajax request:

$.ajax({
                type: "GET",
                url: "/statistics/handlers/candidates/show_candidates_graph_by_employee.php",
                data: {
                  startDate: startDate,
                  endDate: endDate,
                  departments: departments,
                  stage: stage,
                  responsible_id: responsible_id,
                },
                success: function (data) {
                  var jsonData = JSON.parse(data);

                  if (responsible_id === undefined) {

                    var employeeIds = Object.keys(jsonData);

                    // Initialize startDateArray as an empty array
                    var startDateArray = [];

                    // Populate startDateArray inside the map function
                    var datasets = employeeIds.map(function (employeeId, index) {
                      var employeeData = jsonData[employeeId];

                      var firstName = employeeData[0].firstName;
                      var lastName = employeeData[0].lastName;

                      // Use push to add elements to the existing array
                      employeeData.forEach(function (item) {
                        var parsedStartDate = moment(item.startDate, 'YYYY-MM-DD H:i:s');
                        var parsedEndDate = moment(item.endDate, 'YYYY-MM-DD H:i:s');
                        
                        // Check if the time difference is less than one day
                        var timeDifferenceInDays = parsedEndDate.diff(parsedStartDate, 'days');
                        var dateFormat = (timeDifferenceInDays < 1) ? 'HH:mm' : 'DD.MM';
                        
                        var formattedDate = parsedStartDate.format(dateFormat);
                        startDateArray.push(formattedDate);
                    });                    

                      var stageCountArray = employeeData.map(function (item) {
                        return parseInt(item.stageCount);
                      });

                      return {
                        label: firstName + ' ' + lastName,
                        data: stageCountArray,
                        borderColor: getRandomColor(),
                        fill: false,
                      };
                    });

                    destroyChart("employeeChart");

                    if (startDate == endDate) {
                      $('#employeeChartTitle').text('График по сотруднику: ' + startDate);
                    } else {
                      $('#employeeChartTitle').text('График по сотруднику: ' + startDate + ' | ' + endDate);
                    }

                    createEmployeeChart("employeeChart", startDateArray, datasets, true);
                  } else {
                    // Display data for the selected responsible_id
                    var startDateArray = jsonData[responsible_id].map(function (item) {
                      var parsedDate = moment(item.startDate, 'YYYY-MM-DD H:i:s');
                      var dateFormat = (moment(item.endDate, 'YYYY-MM-DD H:i:s').diff(parsedDate, 'days') <= 0) ? 'HH:mm' : 'DD.MM';
                      return parsedDate.format(dateFormat);
                    });

                    var stageCountArray = jsonData[responsible_id].map(function (item) {
                      return parseInt(item.stageCount);
                    });

                    var firstNameArray = jsonData[responsible_id].map(function (item) {
                      return item.firstName;
                    });

                    var lastNameArray = jsonData[responsible_id].map(function (item) {
                      return item.lastName;
                    });

                    destroyChart("employeeChart");

                    if (startDate == endDate) {
                      $('#employeeChartTitle').text('График по сотруднику: ' + startDate);
                    } else {
                      $('#employeeChartTitle').text('График по сотруднику: ' + startDate + ' | ' + endDate);
                    }

                    createEmployeeChart("employeeChart", startDateArray, [{
                      label: firstNameArray[0] + ' ' + lastNameArray[0],
                      data: stageCountArray,
                      borderColor: 'green',
                      fill: false,
                    }], true); // Pass true to indicate that X-axis is startDateArray
                  }
                },
              });

Server script:

<?php
include($_SERVER['DOCUMENT_ROOT'].'/common/db_statistics.php');
include($_SERVER['DOCUMENT_ROOT'].'/common/db_auth.php');

$startDate = $_GET['startDate'];
$endDate = $_GET['endDate'];
$departments = $_GET['departments'];
$stage = $_GET['stage'];
$responsible_ids = isset($_GET['responsible_id']) ? explode(',', $_GET['responsible_id']) : [];

$data = array();

if (date('Y-m-d', strtotime($startDate)) == date('Y-m-d', strtotime($endDate))) {
    $startDate = date('Y-m-d 00:00:00', strtotime($startDate));
    $endDate = date('Y-m-d 23:59:59', strtotime($endDate));
    $increment = '+1 hour';
} else {
    $increment = '+1 day';
}

$currentStartDate = $startDate;

while ($currentStartDate <= $endDate) {
    $startPeriod = date('Y-m-d H:i:s', strtotime($currentStartDate));
    $endPeriod = date('Y-m-d 23:59:59', strtotime($startPeriod . $increment));

    if (!empty($responsible_ids)) {
        foreach ($responsible_ids as $responsible_id) {
            $whereClause = " AND date >= '$startPeriod' AND date <= '$endPeriod' AND responsible_id = '$responsible_id'";
            $query = "SELECT COUNT(*) as stageCount FROM `bitrix` WHERE departments = '$departments' AND stage = '$stage' $whereClause";
            $r_get_created_candidate = mysqli_query($link_bitrix_statistic, $query);
    
            while ($row = mysqli_fetch_assoc($r_get_created_candidate)) {
                // Fetch employee information inside the loop
                $employeeInfo = mysqli_query($link_auth, "SELECT name, surname FROM users WHERE bitrix_id = '$responsible_id'");
                $employeeData = mysqli_fetch_array($employeeInfo);
    
                $firstName = $employeeData['name'];
                $lastName = $employeeData['surname'];
    
                $data[$responsible_id][] = [
                    'firstName' => $firstName,
                    'lastName' => $lastName,
                    'startDate' => $startPeriod,
                    'endDate' => $endPeriod,
                    'stageCount' => $row['stageCount'],
                ];
            }
        }
    } elseif (empty($responsible_ids)) {
        // If responsible_id is empty, retrieve data for all responsible_id values
        $whereClause = " AND date >= '$startPeriod' AND date <= '$endPeriod'";
        $query = "SELECT responsible_id, COUNT(*) as stageCount FROM `bitrix` WHERE departments = '$departments' AND stage = '$stage' $whereClause GROUP BY responsible_id";
    
        $r_get_created_candidate = mysqli_query($link_bitrix_statistic, $query);
    
        while ($row = mysqli_fetch_assoc($r_get_created_candidate)) {
            // Fetch employee information inside the loop
            $employeeInfo = mysqli_query($link_auth, "SELECT name, surname FROM users WHERE bitrix_id = '$row[responsible_id]'");
            $employeeData = mysqli_fetch_array($employeeInfo);
    
            $firstName = $employeeData['name'];
            $lastName = $employeeData['surname'];
    
            $data[$row['responsible_id']][] = [
                'firstName' => $firstName,
                'lastName' => $lastName,
                'startDate' => $startPeriod,
                'endDate' => $endPeriod,
                'stageCount' => $row['stageCount'],
            ];
        }
    }
    

    $currentStartDate = date('Y-m-d H:i:s', strtotime($startPeriod . $increment));
}

echo json_encode($data);
?>

here’s example of jsonData:
347
:
[{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-06 00:00:00”,…},…]
0
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-06 00:00:00”,…}
1
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-07 00:00:00”,…}
2
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-08 00:00:00”,…}
3
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-09 00:00:00”,…}
4
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-10 00:00:00”,…}
5
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-12 00:00:00”,…}
6
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-13 00:00:00”,…}
7
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-14 00:00:00”,…}
8
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-15 00:00:00”,…}
9
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-16 00:00:00”,…}
10
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-17 00:00:00”,…}
11
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-22 00:00:00”,…}
12
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-23 00:00:00”,…}
13
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-24 00:00:00”,…}
14
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-26 00:00:00”,…}
15
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-27 00:00:00”,…}
16
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-28 00:00:00”,…}
17
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-29 00:00:00”,…}
18
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-11-30 00:00:00”,…}
19
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-12-03 00:00:00”,…}
20
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-12-04 00:00:00”,…}
21
:
{firstName: “Замира”, lastName: “Калиева”, startDate: “2023-12-05 00:00:00”,…}
6521
:
[{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-11-28 00:00:00”,…},…]
0
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-11-28 00:00:00”,…}
1
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-11-29 00:00:00”,…}
2
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-11-30 00:00:00”,…}
3
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-12-01 00:00:00”,…}
4
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-12-03 00:00:00”,…}
5
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-12-04 00:00:00”,…}
6
:
{firstName: “Аида”, lastName: “Жекенова”, startDate: “2023-12-05 00:00:00”,…}

I was trying to fix this issue by changing some option in function of creating chart, I guess there is problem.

For each object in array, how to resolve promises that retrieve DB data and populate dropdown in sequential order?

I have an array of objects called projects. Each project has a project_id. I need to retrieve all members assigned to a project from the DB using the project_id, check if each member is approved, and then populate a dropdown select with the project titles.

Since I need to wait for the GET request to complete before the other tasks, I wrapped the request in a promise. Unfortunately, I can’t use async await because our team uses promises as the standard. For each project object in the array, I need to execute this promise and chain it with .then() to check the approval statuses and fill the dropdown.

This is what I have so far:

projectArray.map(project => () => {        // map each project in array to a new promise
    getMembers(project.project_id)
        .then(members => {                 // pass in array of member objects returned from getMembers()

            if (members.every(member => member.approved)) {
                // populate dropdown with projects
            }
        }
})

function getMembers(project_id) {
    return new Promise((resolve, reject) => {
        // send AJAX GET request

        return resolve(memberData)
    }
}

The functions inside the .map() are not run so I’m not sure if I have to call them again. How do I run this promise and the following function in order? I want to complete those steps for the first project, before moving to the next project. I would appreciate any suggestions, thanks!

minify one of the files from the raw bundle

I have a configuration to bundle all raw vanilla js files

Copying/Dumping selective js code/files for 3 kinds of files.

  1. mylib.js
  2. mylib.min.js (same files as mylib.js + minify)
  3. mylib-test.js (test scripts)

Issues:

  1. Unable to minify the min.js version, the output file is non-minified.
  2. Ending up with a file named “main” in the bin directory.
  3. If there’s a better way of doing these things, lateral thinking?

Here’s the webpack configuration.

webpack.config.js

const path = require("path");
const RawBundlerPlugin = require("webpack-raw-bundler");
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    mode: "development",
    entry: ["./index.js"],
    output: {
        filename: "[name]",
        path: path.resolve(__dirname, "bin")
    },
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                include: /mylib-2.0.0.min.js$/,
            }),
        ],
    },
    module: {
        rules: [
            { test: /.txt$/, use: "raw-loader" }
        ]
    },
    plugins: [
        new RawBundlerPlugin({
            readEncoding: "utf-8",
            bundles: [ "mylib-2.0.0.js", "mylib-2.0.0.min.js", "mylib-2.0.0.test.js" ],
            "mylib-2.0.0.js": [
                "src/header.txt",
                "src/foo/Foo.js",
                "src/bar/Bar.js",
                "src/footer.txt"
            ],
            "mylib-2.0.0.min.js": [
                "src/header.txt",
                "src/foo/Foo.js",
                "src/bar/Bar.js",
                "src/footer.txt"
            ],
            "mylib-2.0.0.test.js": [
                "test/header.txt",
                "test/foo/FooTest.js",
                "test/bar/BarTest.js"
            ]
        })
    ],
    watchOptions: {
        ignored: /node_modules/
    }
};

How to increase the limit of 20 pages for Google Cloud Vision PDF text detection?

Hi I am trying to detect text in a 34 page PDF with Google Cloud Vision. I then save the text to Firebase Firestore from the JSON generated and saved to my Firebase Storage. All this using a Firebase Cloud function. When I loop through the pages in the JSON, I only get 20 pages and not all the 34 pages. The same thing happens with any PDF I use that is over 20 pages. I use the asyncBatchAnnotateFiles function which is supposed to have a 2,000 page limit. I have searched everywhere to learn how to increase the 20 page limit but failed to find any relevant info. Please help. Here’s my code:

if (contentType === "application/pdf") {  

    const orderUri = path.dirname(object.name);
    const fileName = path.basename(object.name)
    const outputPrefix = 'results';
    const gcsSourceUri = `gs://${object.bucket}/${object.name}`;
    const gcsDestinationUri = `gs://${object.bucket}/${orderUri}/${outputPrefix}/${fileName}/`;
    

    const inputConfig = {
    // Supported mime_types are: 'application/pdf' and 'image/tiff'
    mimeType: 'application/pdf',
    gcsSource: {
        uri: gcsSourceUri,
    },
    };

    const outputConfig = {
    gcsDestination: {
        uri: gcsDestinationUri,
    },
    };

    const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];

    const request = {
    requests: [
        {
        inputConfig: inputConfig,
        features: features,
        outputConfig: outputConfig,
        },
    ],
    };

    // OCR PDFs
    const [operation] = await client.asyncBatchAnnotateFiles(request);
    const [filesResponse] = await operation.promise();    
    // const destinationUri =
    // filesResponse.responses[0].outputConfig.gcsDestination.uri;
    // console.log('Json saved to: ' + destinationUri);    
    
    
}

and here’s how I retrieve the JSON from Firebase Storage and loop through it to get the text:

if (path.basename(object.name).startsWith('output') && path.basename(object.name).split('.').pop() === "json") {       
        // Get references
        const fileBucket = object.bucket; // The Storage bucket that contains the file.
        const filePath = object.name; // File path in the bucket.       

         // Download JSON     
        const bucket = admin.storage().bucket(fileBucket);   
        const downloadResponse = await bucket.file(filePath).download();       
        const bufferToJson = downloadResponse.toString();
        const jsObject = JSON.parse(bufferToJson);

        // Text
        const textArray = jsObject.responses.map(async (response) => {
          return response.fullTextAnnotation.text;
        });
        const readyArray = await Promise.all(textArray);
        const fullTextReady = readyArray.join();

        // Count words
        function countWords(str) {
          return str.trim().split(/s+/).length;
        }
        const words = countWords(fullTextReady);       


        // Text confidence
        const textConfidenceArray = jsObject.responses.map(async (response) => {
          return response.fullTextAnnotation.pages.map((page) => {
            return page.confidence;
          })
        })
        const textConfidence = await Promise.all(textConfidenceArray);        
        const textConfidence2 = textConfidence.flat();
        const sum = textConfidence2.reduce((accumulator, currentValue) => {
          return accumulator + currentValue
        },0);
        const average = sum / textConfidence2.length;
        const textConfidence3 = Number(average).toFixed(2) * 100;      
        
        
        // Language and Language Confidence
        const pages = jsObject.responses.map((response) => {
          return response.fullTextAnnotation.pages.map((page) => {
            return page.property.detectedLanguages
          })
        });
        const pages2 = await Promise.all(pages);
        const detectedLanguages = pages2.flat(2);    

        const languageAndConfidenceArray = detectedLanguages.map((language) => {
               const langCode = language.languageCode;
               const confidence = Number((language.confidence).toFixed(1)) * 100;
                return {
                  languageCode: langCode,
                  languageConfidence: confidence
                }
        })

        const languages = await Promise.all(languageAndConfidenceArray);

             
        // Save to Firestore
        const jsonLocation = path.dirname(object.name);
        const fileName = path.basename(jsonLocation);
        const results = path.dirname(jsonLocation);
        const order = path.dirname(results);   
        const destination = `${order}/${fileName}`;
        const docRef = db.collection('Clients').doc(destination);
        await docRef.set({
          fullText: fullTextReady,
          textConfidence: textConfidence3,         
          type: "application/pdf",
          pageCount: jsObject.responses.length,
          languages: languages,
          fileName: fileName,
          location: jsonLocation,
          wordCount: words          
          }, { merge: true });
            
}

What scale factor did CSS use? Or what was the original image size?

I’m displaying an image using the technique in this question, but using 100dvb and 100dvi to limit the image to fit the screen.

How do I calculate what scale factor was used? I don’t know the original size of the image, or the size of the screen, but I can obtain the latter. I was hoping this question would help figure the scale factor, but I get the same results for offsetWidth/Height and getBoundingClientRect, which are the size after scaling.

If I could obtain the original image size, I could obviously calculate the scale factor. If I could obtain the scale factor, I could calculate (at least within a few pixels) the original image size. I’m most interested in getting or calculating the scale factor.

onLoadedMetadata doesn’t work in next.js

Hello I have this little component over here.

{srcs.map((src, index) =>
                <video
                    key={"mediaPlayer" + index}
                    src={src}
                    onLoadedMetadata={(e) => console.log(e.currentTarget.duration)}
                />
            )}

I want to have access to e.currentTarget.duration as soon as it is available to me and log it into the console but for whatever reason onLoadedMetadata doesn’t run the function does anyone have any clue why? My assumption is that this is because of server side rendering preformed by next.js but I’m really not sure.

Error when i install ssl cert on my server,, ERROR: net::ERR_SSL_PROTOCOL_ERROR

HTML:

<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="farmapp.css"> 

</head>

<body onload="loadimg()">

    <div id="sitehead">
        
    <div class="leftsection" onclick="location.href = 'mainsite.html';">
            <div>
            <img class="left-sunriseIMG" src="thumbnails/sunrise.jpg">
            </div>
            <div>
            <h1 class="sitetitle">FARM</h1>
            </div>
        </div> 

        <div class="middlesection">
            <div>
        <!--
            <input class="search-box" type="text" placeholder="Search District">
            <label>Search using DISTRICT : </label>
        -->

        
            <button type="button" class="clearsearch" value="" onclick="location.href = 'mainsite.html';">x</button>
            </div>
            <div>
            <button type="submit" class="search-button" onclick="SearchWithDistrict()">Search</button>
            </div>
        </div>     
    </div>

    <div id="deals-box">
        <div class="about" onclick="location.href = 'About.html';">About</div>
        <div class="contact" onclick="location.href = 'contact.html';">contact</div>
        <div class="post" onclick="location.href = 'FishImageUpload.html';">Post-AD</div>
        <div class="edit" onclick="location.href = 'edit.html';">Edit-AD</div>
    </div>

    <div id="cimages"></div>

    <div id="FullImageView">
        <img id="FullImage" />
        <button id="CloseButton" onclick="CloseFullView()">Close</button>
    </div>

    <div id="FullDetailsView">
        <div id="ViewDetails"></div>
        <button id="DetailsCloseButton" onclick="CloseDetailsView()">Cancel</button> 
    </div>
    

<script src="main.js"></script>
</body>

</html>

javascript:

function loadimg() {

    options = {
      method: 'POST',
    }
    
    fetch('https://apfarmsite.com:8000/FarmSite', options)
    .then(res => res.json())
    .then(cust_data => {  // Handle the response from the server
      console.log(cust_data);
}

app.js

app.post('/FarmSite', (req, res) => {
  console.log(req.body);
})

I am unable to connect to my api when i do post request. it gives me ssl error.. This happens only when i use ssl cert on my server(HTTPS). IT is working when i use HTTP. I am using nginx. i have allowed full traffic in security groups for this ec2 instance. Do i have adjust any SSL/TLS protocol settings.

How to set ChromePicker to go outside the Polaris Card border?

I have this in my child component

     
          <div
            ref={colorPicker}
            style={{
              position: "absolute",
              zIndex: 9999,
              top: "38px",
            }}
          >
              <ChromePicker
                  color={
                      backgroundColor?.length === 7
                          ? backgroundColor
                          : backgroundColorBackUp
                  }
                  onChangeComplete={handleChangeSetColor(nameKey)}
              />
          </div>
   

and in parent component, i display it like this

      <Card>
     <BlockStack>
      <FormLayout>
            <CustomColorPicker
              title="Group name color"
              nameKey="groupNameColor"
              handleChangeSetColor={handleChangeSetColor}
              backgroundColorBackUp={formik.values.groupNameColor}
              handleOpenSetColor={handleOpenSetColor}
              colorPagination={colorPagination}
              backgroundColor={dataBackUp.groupNameColor}
            />
          </FormLayout>
        </BlockStack>
      </Card>

and here is the problem

enter image description here

I already try

 style={{
          position: "absolute",
          zIndex: 9999,
          top: "38px",
        }}

but it does not work.

i want to make ChromePicker to go outside the Polaris Card border

Return fn function not returning value [duplicate]

Return fn statement returns undefined

from my furnace controller:

dbController.getFurnaceSettings(furnaceSettings.state, function (tempFurnaceSettings){
console.log("* * * in furnace controller just back from getting settings");
console.log(tempFurnaceSettings.state);
    ...
})

// over in the db controller:
// called by the furnace controller
exports.getFurnaceSettings = function (HomeState, fn){
   console.log("Current state - " + HomeState);

   var sqltest = "SELECT * FROM furnaceSettings WHERE state IN ('" + HomeState + "')";
       connection.query (sqltest, function (err, result) {
         if (err) throw err;
         console.log(result);
         return ( fn (result) )
     });
};

the console log in the db controller shows the correct data, so I know my sql is good,
but over in the furnace controller I’m getting undefined.
This used to work, but I recently converted from Windows to Linux (Ubuntu 22.04.3) not sure if that’s relevant…

lots of searches didn’t help

Why am I getting an error for JavaScript atob when it is working on btoa?

I am working on a Straight up transcriptor for practice and fun, But It works by having two sets of object: Input, Label, And a paragraph for the output, The one translating binary to ascii is working just fine, But the other way around keeps giving me errors.

Here is the whole code I threw together:

//Adding comments for clarity.

//First we need to get the elements we will use for input.
const Bin = document.getElementById("binary");
const Ascii = document.getElementById("ascii");

//I will update their value, My first attempt to rectify the errors.
Bin.value = "Binary here."
Ascii.value = "Ascii here."

//These are the paragraphs that I made for the output,
//In the original, I just used the opposite input,
//But... I forgot how to work the proper event...
const BinOut = document.getElementById("Binary Output");
const AsciiOut = document.getElementById("Ascii Output");

//Dedicated function to do the work upon receiving events...
function Transcript(changingBin = false) {
  //If changingBin is true, We are reading from Ascii, Otherwise from Binary.
  let valueRead = changingBin ? Bin : Ascii;
  //Choosing the output paragraph right under it...
  let toChange = !changingBin ? BinOut : AsciiOut;
  //If we are reading from Ascii, We should use atob, Otherwise, Btoa
  let output = changingBin ? btoa(valueRead.value) : atob(valueRead.value)

  //Change the corresponding paragraph tag to include outputted results.
  return toChange.innerText = output;
}

//Makeshift event...
document.addEventListener("Tick", () => {
  Transcript(false)
})
document.addEventListener("Tick2", () => {
  Transcript(true)
})

setInterval(() => {
  //Dispatch the events to the inputs...
  let e = new CustomEvent("Tick", {});
  document.dispatchEvent(e)
  //There are two because I thought it might off somehow overwritten,
  //Not convinced, But better safe then sorry.
  let e2 = new CustomEvent("Tick2", {});
  document.dispatchEvent(e2)
  //Lovely side effect where they update as you type.
}, 60)
<h1>Transcriptor: Ascii &lt;=&gt; Binary</h1>
<div>
  <label for="binary">Binary =&gt;</label>
  <input type="text" name="binary" id="binary" placeholder="Binary input here">
  <br>
  <p id="Ascii Output"></p>

  <br>

  <label for="ascii">Ascii =&gt;</label>
  <input type="text" name="ascii" id="ascii" placeholder="Ascii input here">
  <br>
  <p id="Binary Output"></p>
</div>

Here is the error I get, Directly copied and pasted:
transcript.html:64 Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. at Transcript (http://127.0.0.1:5500/transcript.html:64:60) at HTMLDocument.<anonymous> (http://127.0.0.1:5500/transcript.html:69:48) at http://127.0.0.1:5500/transcript.html:74:22
But I am not using it for the Dom at all beyond a value of am input…
the frustrating thing is that I’ve done this before, But the phone it’s on is iffy, If I get it back, I’ll try to update this with the other code and the solved version of this if I get it…

I tried making the output separate from the inputs, This worked to get the events functioning without overwriting what I was actively typing.
I tried making the events seperate in hopes of getting it to work both ways, It did not…
I tried mapping both to the btoa in expectation that it might give me insight, But it didn’t,
I mapped them both to atob hoping they would work, But then neither did.
Even when I gvot them both working, The atob won’t accept pasted text nor the originally placed text as seen in the script tag on lines 61 and 62…
I tried looking it up, But all that came up was a question that asked how to set the html to reload once the user returned, To resume their session and the like.
To elaborate my intentions, I wish to encode the strings so that the caan be directly returned into btoa without need for further decryption.