Costumize Ema widget tradingview

could someone tell me where I’m going wrong? I have to change the color of the EMA5 to Red and EMA10 ro Yellow, but it doesn’t work.

    new TradingView.widget({
"container_id": "tradingview_widget",
"width": "100%",
"height": "400px",
"symbol": "BINANCE:BTCUSDT",
"interval": "D",
"timezone": "Etc/UTC",
"theme": "light",
"style": "1",
"locale": "en",
"toolbar_bg": "#f1f3f6",
        "enable_publishing": false
, "studies_overrides": {
    "moving average exponential.0.plot.color": "#FF0000",
    "moving average exponential.1.plot.color": "#FFFF00"
        },
        "studies": [
            {
                id: "MAExp@tv-basicstudies",
                inputs: {
                    length: 5
                }
            
            },
            {
            id: "MAExp@tv-basicstudies",
            inputs: {
                length: 10
            }
            }
        ]});

I need to change my Javascript forced patterns

Someone said I could ask this again with these new updates I need.

I need a code that will force the following input for 3 different inputs, 2 with the same patterns, the other an email.

Display Name & Real Name:

  • Force first character to be a letter
  • Capitalize first letter of all words (even single characters)
  • Force the rest of the letters in words lowercase
  • Allow single spaces (also prevent consecutive spaces)
  • Prevent all special characters
  • Allow all numbers

E-mail:

  • prevent all spaces
  • force all letters to be small
  • prevent multiple @’s
  • prevent consecutive .’s in a row (allow multiple .’s but not in a row)
  • prevent @ and . beside each other (both ways: @. and .@)
            function handleNameFieldKeypress(target, evt) {
            console.log('handleNameFieldKeypress ... target ...', target);

            const char = String.fromCharCode(evt.which);

            const { selectionStart } = target;

            const isNotValid = (selectionStart === 0 && (

                evt.code === 'Space' ||
                !/^[a-zA-Z]$/.test(char)

            )) || (

                char === ' ' &&
                target.value.charAt(selectionStart - 1) === ' '
            );
            if (isNotValid) {

                evt.preventDefault();
            }
            }
            function handleEmailFieldKeypress(target, evt) {
            console.log('handleEmailFieldKeypress ... target ...', target);

            const { selectionStart } = target;

            const isNotValid =
                (selectionStart === 0 && evt.code === 'Space') || (

                String.fromCharCode(evt.which) === '@' &&
                target.value.charAt(selectionStart - 1) === '@' ) || (    

                String.fromCharCode(evt.which) === '@' &&
                target.value.charAt(selectionStart - 1) === '.' ) || (   

                String.fromCharCode(evt.which) === '.' &&
                target.value.charAt(selectionStart - 1) === '@' ) || (   

                String.fromCharCode(evt.which) === '.' &&
                target.value.charAt(selectionStart - 1) === '.' 
                );

            if (isNotValid) {
                evt.preventDefault();

                return;
            }
            const key = evt.keyCode || evt.charCode || evt.which;

            return (key !== 32) && key;
            }

            function handleInputFieldKeypress(evt) {
            const { target } = evt;

            let result;

            if (target.matches('input[name="real_name"], input[name="display_name"]')) {

                result = handleNameFieldKeypress(target, evt);

            } else if (target.matches('input[name="email"]')) {

                result = handleEmailFieldKeypress(target, evt);
            }
            
            return result;
            }

            document
            .addEventListener('DOMContentLoaded', () => {

                document
                .querySelector('form')
                .addEventListener('keypress', handleInputFieldKeypress);
            });
<input type="text" name="email" placeholder="E-mail" id="email">
<input type="text" name="real_name" placeholder="Real Name" id="real_name">
<input type="text" name="display_name" placeholder="Display Name" id="display_name">

Your help would be greatly appreciated!

Losing context of ‘this’ in class after initializing service class

I’m trying to get this.appConstantsService inside of FileService. But the problem is when executing method this is undefined. All my application uses the same code style, and I can’t figure out, why methods of this class lose this, while others, in other classes, work fine?

Simplified code:

@Injectable()
export class FileService implements OnModuleInit, OnModuleDestroy {
    constructor(private readonly appConstantsService: AppConstantsService) {
        console.log(this.appConstantsService); // => ok, it shows env variables.
    }

    onModuleDestroy() {
        console.log("FileService destroy!"); // => it doesn't - fine
    }

    onModuleInit(): any {
        console.log("FileService init!"); // => ok
    }

    normalize(file: File): TFileToClient {
        const f = excludeSensitiveFields(file, [
            "path",
            "size",
        ]) as TFileToClient;

        console.log(this); // => undefined
        f.url =
            /*
             * ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'appConstantsService')
             * */
            this.appConstantsService.BACKEND_URL +
            "/api/s3/file/" +
            file.originalName +
            "?path=" +
            file.path;
        f.size = byteSize({
            sizeInBytes: file.size,
        });
        return f;
    }
}

Although I think it doesn’t matter, but both AppConstantsService and DatabaseService are @Global. And they are available in other classes. But, that’s not the point, because my problem is that this keyword is undefined.

I could understand if I was trying to pass the “this” keyword inside another function, but I didn’t do that.

So, I spent a lot of time trying to find the answer, but I couldn’t. And I just tried to use the arrow method instead – and it also functions great.
But this.normalize.bind(this) in constructor couldn’t help.

Changed code:

@Injectable()
export class FileService implements OnModuleInit, OnModuleDestroy {
    constructor(private readonly appConstantsService: AppConstantsService) {
        console.log(this.appConstantsService); // => ok, it shows env variables.
    }

    onModuleDestroy() {
        console.log("FileService destroy!"); // => it doesn't - fine
    }

    onModuleInit(): any {
        console.log("FileService init!"); // => ok
    }

    normalize = (file: File): TFileToClient => {
        const f = excludeSensitiveFields(file, [
            "path",
            "size",
        ]) as TFileToClient;

        f.url =
            /*
            * now it works
            * */
            this.appConstantsService.BACKEND_URL +
            "/api/s3/file/" +
            file.originalName +
            "?path=" +
            file.path;
        f.size = byteSize({
            sizeInBytes: file.size,
        });
        return f;
    };
}

How is it possible? All my methods in other services use only trivial methods, not arrow methods, and this keyword is not lost.

Thanks for your answers

How to Pass Variables between Nested Includes in Gulp File Include?

I’m using gulp-file-include to build my HTML files and I’m running into an issue with passing variables between nested include files.

File Structure:

.
├── index.html
└── template-parts
    └── common
        ├── header.html
        └── headerMenuList.html

Problem:
I want to pass a variable (nav) from index.html to header.html and then pass it from header.html to headerMenuList.html. However, I’m getting the following error:

[21:14:05] Starting 'htmlConcat'...
[21:14:05] 'htmlConcat' errored after 11 ms
[21:14:05] Error in plugin "gulp-file-include"
Message:
    JSON5: invalid character 'a' at 1:11
Details:
    domainEmitter: [object Object]
    domainThrown: false

index.html:

<!-- siteHeader -->
@@include('template-parts/common/header.html', { "nav": "about" })

header.html:

<!-- I want to pass the nav variable to this file -->
<p>Navigation: @@nav</p>
<!-- Passing nav to headerMenuList.html -->
@@include('./headerMenuList.html', { "nav": nav })

headerMenuList.html:

<!-- Trying to access nav variable here -->
<p>Current Navigation: @@nav</p>

What I’ve Tried:
Direct Variable Passing: Using @@include('./headerMenuList.html', { "nav": nav }) but it throws the JSON5 error.
String Interpolation: Tried using <%= nav %> inside header.html but it outputs <%= nav %> as a string instead of the value.
Direct String Testing: When I change it to @@include('./headerMenuList.html', { "nav": "about" }), it works, indicating that the variable isn’t being passed correctly.
Question:
Is it possible to pass variables between nested include files in gulp-file-include? If so, what is the correct way to do this? If not, is there a workaround or alternative approach I can use to achieve this?

Thanks in advance for your help!

Encode text using base64 and AES

Im trying to decode data which is generated from this java script code:

    jeTV: (t, e, r) => {
        "use strict";
        r.d(e, {
            X: () => s
        });
        var n = r("wIp5")
          , i = r.n(n)
          , s = (r("4Whi"),
        function(t, e) {
            var r = i().lib.WordArray.random(12).toString(i().enc.Base64)
              , n = i().AES.encrypt(t, i().enc.Utf8.parse(e), {
                iv: i().enc.Utf8.parse(r)
            });
            return "".concat(r).concat(n.ciphertext.toString(i().enc.Base64))
        }
        )
    }

My code :

def decrypt(encrypted_data, key):
    # Extract the Base64 IV and ciphertext
    iv_base64 = encrypted_data[:16]  # First 16 characters (Base64-encoded IV)
    ciphertext_base64 = encrypted_data[16:]  # The rest is the ciphertext

    # Use the Base64 string directly as IV, without decoding it back to bytes
    iv_bytes = iv_base64[:16].encode('utf-8')  # Get the first 16 chars of the Base64-encoded IV

    # Decode the ciphertext
    ciphertext = base64_decode(ciphertext_base64)

    # Create AES cipher object for decryption
    cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv_bytes)

    # Decrypt and unpad the plaintext
    plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)

    return plaintext.decode('utf-8')

but i got this error when run the program:

    plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "DvenvLibsite-packagesCryptoUtilPadding.py", line 95, in unpad
    raise ValueError("PKCS#7 padding is incorrect.")
ValueError: PKCS#7 padding is incorrect.

I checked the key and the Base64-decoded IV/ciphertext, and they seem to match what was generated during encryption. I printed the raw decrypted bytes, but I’m not sure if they are binary data or not.Any insights or suggestions on how to resolve this issue would be appreciated. Thanks!

I’m trying to develop a VSCode extension, but the compilation doesn’t finish, and I can’t open the Extension Development Host window

I’m trying to develop a VSCode extension, but the compilation doesn’t finish, and I can’t open the Extension Development Host window.

.vscode/tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "npm",
            "script": "watch",
            "problemMatcher": [
                "$ts-webpack-watch",
                "$tsc-watch"
            ],
            "isBackground": true,
            "presentation": {
                "reveal": "never",
                "group": "watchers"
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "runOptions": {
                "runOn": "folderOpen"
            }
        },
        {
            "type": "npm",
            "script": "watch-tests",
            "problemMatcher": "$tsc-watch",
            "isBackground": true,
            "presentation": {
                "reveal": "never",
                "group": "watchers"
            },
            "group": "build"
        },
        {
            "label": "tasks: watch-tests",
            "dependsOn": [
                "npm: watch",
                "npm: watch-tests"
            ],
            "problemMatcher": []
        }
    ]
}

I am stuck on this screen.

I tried to run it using the F5 key. I expected the Extension Development Host window to appear, but it seems that the window does not show up because the compilation is not finished.

How to prevent webpack from tree shaking specific functions?

I have problem and cannot find any solution. How can i use javascript functions after bundling by webpack but in html?

I have file app.js that contains: import qs from 'query-string' (from npm install query-string) and some my code. After i run npm run dev that conatins webpack --mode production it creates another bundle file with my function and query-string. Now i need to use it in my html code like:

<p>some text</p>
<script>
  const someConst = someFunctionFromBundle();
</script>

But after bundling webpack removes someFunctionFromBundle() because of tree shaking. How to prevent webpack from tree shaking specific functions?

How would I correctly position elements based of their y position?

I’m creating a HTML/JS browser based game, and I’m trying to have any element that has a higher Y on the page to have a lower Z Index, making it appear behind elements with a lower Y, the code I’ve written seems to be doing just that, by setting the Z Index to the elements top positioning, but visually it doesn’t

The code for placing elements:

async start(xx, yy, p, sxx, syy) {
    document.getElementById("htmlIcon").href = `/media/misc/${p}/icon.png`;
    new Promise(async (resolve) => {
      const x = xx;
      const y = yy || xx;
      const sx = sxx || (x * 50) / 2;
      const sy = syy || (y * 50) / 2;
      this.mx = x;
      this.my = y;
      this.inventory.update();
      this.map.style.width = `${x * 50}px`;
      this.map.style.height = `${y * 50}px`;
      this.map.style.overflow = "hidden";
      document.body.style.width = `${x * 50}px`;
      document.body.style.height = `${y * 50}px`;
      this.map.innerHTML = "";
      this.rawMap = [];
      this.layerHandler();
      for (let i = 0; i < y; i++) {
        for (let j = 0; j < x; j++) {
          // Grass
          const tile = document.createElement("img");
          tile.src =
            this.data.tiles.grass.image[
              Math.floor(Math.random() * this.data.tiles.grass.image.length)
            ];
          tile.classList.add("tile");
          tile.style.left = `${i * 50}px`;
          tile.style.top = `${j * 50}px`;
          tile.style.width = `${this.vars(this.data.tiles.grass.size)}px`;
          tile.style.zIndex = 1;
          this.map.appendChild(tile);
        }
      }
      for (let i = 0; i < y; i++) {
        let layer = "";
        for (let j = 0; j < x; j++) {
          const tile = Math.floor(Math.random() * 100);
          if (tile <= 50) {
            // Air
            layer += "null/";
          }
          if (tile <= 75 && tile > 50) {
            // Flowers
            const div = document.createElement("img");
            div.src =
              this.data.tiles.flower.image[
                Math.floor(Math.random() * this.data.tiles.flower.image.length)
              ];
            div.classList.add("tile");
            div.classList.add("breakable");
            div.classList.add("layers");
            const offsetX = this.vars(this.data.tiles.flower.offsetX) * 1;
            const offsetY = this.vars(this.data.tiles.flower.offsetY) * 1;
            div.style.left = `${i * 50 + offsetX}px`;
            div.style.top = `${j * 50 + offsetY}px`;
            div.style.width = `${this.vars(this.data.tiles.flower.size)}px`;
            this.map.appendChild(div);
            layer += "flower/";
          } else if (tile <= 100 && tile > 75) {
            // Trees
            const div = document.createElement("img");
            div.src =
              this.data.tiles.tree.image[
                Math.floor(Math.random() * this.data.tiles.tree.image.length)
              ];
            div.classList.add("tile");
            div.classList.add("breakable");
            div.classList.add("layers");
            const offsetX = this.vars(this.data.tiles.tree.offsetX) * 1;
            const offsetY = this.vars(this.data.tiles.tree.offsetY) * 1;
            div.style.left = `${i * 50 + offsetX}px`;
            div.style.top = `${j * 50 + offsetY}px`;
            div.style.width = `${this.vars(this.data.tiles.tree.size)}px`;
            this.map.appendChild(div);
            layer += "tree/";
          }
        }
        this.rawMap.push(layer);
      }
      // Player
      const entity = this.data.entities.player[p];
      const player = document.createElement("img");
      player.classList.add("entity");
      player.classList.add("layers");
      player.style.left = `${sx}px`;
      player.style.top = `${sy}px`;
      player.style.width = `${entity.size}px`;
      player.id = `player`;
      this.playerSprites = [];
      // Get data URIs of each sprite
      function uri(blob) {
        return new Promise((resolve) => {
          const reader = new FileReader();
          reader.onload = () => {
            resolve(reader.result);
          };
          reader.readAsDataURL(blob);
        });
      }
      await fetch(entity.image + "up.png")
        .then((res) => res.blob())
        .then(async (blob) => this.playerSprites.push(await uri(blob)));
      await fetch(entity.image + "down.png")
        .then((res) => res.blob())
        .then(async (blob) => this.playerSprites.push(await uri(blob)));
      await fetch(entity.image + "left.png")
        .then((res) => res.blob())
        .then(async (blob) => this.playerSprites.push(await uri(blob)));
      await fetch(entity.image + "right.png")
        .then((res) => res.blob())
        .then(async (blob) => this.playerSprites.push(await uri(blob)));
      player.src = this.playerSprites[1];
      this.map.appendChild(player);
      this.track(player);
      this.movement(player, p);
      resolve();
    });
  }

The code for handling layers:

layerHandler(type = ".layers") {
    document.querySelectorAll(type).forEach((elm) => {
      const rect = elm.getBoundingClientRect();
      elm.style.zIndex = Math.floor(rect.top + window.scrollY);
    });
  }

This is also on GitHub here: https://github.com/QueenAka/barely-alive

Dynamic html and js

I’m creating a dynamic content loader with a menu for navigating between sections. Each tab loads its corresponding HTML and JavaScript file. However, I’m encountering redeclaration errors with variables in the JS files when switching tabs. when i try to go again in a section i was before i get this error

Uncaught SyntaxError: Identifier ‘parcours’ has already been declared (at script.js:1:1)”.

How can I dynamically load and unload these scripts without conflicts?

the main html

<body>
    <!-- MENU -->
    <div id="menuConteneur">
        <div class="menuIcon on" id="etudeTravail" onclick="loadContent('etudeTravail/etudeTravail.html', 'etudeTravail/script.js')"></div>
        <div class="menuIcon off" id="projets" onclick="loadContent('projets/projets.html', 'projets/script.js')"></div>
        <div class="menuIcon off" id="about" onclick="loadContent('about/about.html', 'about/script.js')"></div>
    </div>
    <!-- DIV CONTENUE DYNAMIQUE -->
    <div id="contenu"></div>
    <script src="script.js" defer></script>
</body>

the main script :

let lastScript = null;

function loadScript(scriptUrl) {
    if (lastScript) {
        document.body.removeChild(lastScript);
    }

    const script = document.createElement('script');
    script.src = scriptUrl;
    script.defer = true;
    document.body.appendChild(script);

    lastScript = script;
}

function loadContent(page, scriptUrl) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', page, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('contenu').innerHTML = xhr.responseText;
            if (scriptUrl) {
                loadScript(scriptUrl);
            }
        }
    };
    xhr.send();
}
loadContent('etudeTravail/etudeTravail.html', 'etudeTravail/script.js');

one of the js

let parcours = document.querySelectorAll(".parcour");
parcours.forEach(parcour => {
    parcour.addEventListener("mouseover", function () {
        console.log("test2");
    })
});
console.log("test");

his html

<div class="parcour">1</div>
<div class="parcour">2</div>
<div class="parcour">3</div>

I’ve implemented a dynamic content loader with a menu that switches between sections by loading different HTML and JavaScript files. I expected the scripts to load and unload without errors. However, I’m facing redeclaration issues with variables when switching tabs. What solutions can help resolve this?

doesn’t generate unique QR Code even the the data is dynamic using $linkcert

it’s possible that the QRCodeStyling library may not be handling each iteration correctly because the variable $linkcert inside the JavaScript block is always resolving to the last value in the loop. what can I do here is the code thanks

P.S whenever I scan the QR Code only the data of the last iteration loop is displaying

<?php
session_start();
include("../../../connection.php");
$user = $_SESSION['user'];
$btn = $_GET['btn'];
$id_encrypt = $_GET['link'];
$link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
include("../functions/control_query.php");

$decrypt = base64_decode(urldecode($id_encrypt));
$id=((($decrypt*54321)/12345)/6789);

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport" shrink-to-fit=yes>

  <!-- Header & Styles -->
  <?php include('../link/header-sublink.php');?>

  <style type="text/css">

    table.report-container {
      page-break-after:always;
    }
    thead.report-header {
      display:table-header-group;
    }
    tfoot.report-footer {
      display:table-footer-group;

    } 

    @media print {
      body{
        width:100%;
        height:auto;
        overflow: hidden;
        background-color:#fff;  
      }
      .footer{
          page-break-after:always; 
      }

      @page {
          height: 100%;
          margin:0mm,0mm,0mm,0mm;   
          size: portrait; 
          background-color: #fff;
      }
    }
    @media screen {
        .print{display:none !important;}
    }

  </style>

</head>

<body onload="window.print(); window.focus()">

    <?php 
    
        $reqtype = mysqli_query($req,"SELECT tbl_request.request_id, tbl_request.request_type FROM tbl_request  WHERE tbl_request.request_id='$id'") or die (mysqli_connect_error());
        $rqt = mysqli_fetch_array($reqtype,MYSQLI_ASSOC);

        $request = $rqt['request_type'];

        $cert_type = 'Certificate of Leave Credits Balance';
        $division_type = 'Administrative Division';

        $decrypt = base64_decode(urldecode($id_encrypt));
        $id=((($decrypt*54321)/12345)/6789);

        //details
        $det = mysqli_query($req,"SELECT tbl_request.request_id, tbl_request.ctrl_no, tbl_request.`name`, tbl_request.position, tbl_request.place_assign, tbl_request.request_type, tbl_request.purpose, tbl_request.phone, tbl_request.requested_by, tbl_request.`status`, tbl_request.date_created, tbl_cert_leave.purpose, tbl_cert_leave.date_hired, tbl_cert_leave.vacation, tbl_cert_leave.sick, tbl_cert_leave.as_of_date, tbl_cert_leave.approve_by, tbl_cert_leave.date_created FROM tbl_request INNER JOIN tbl_cert_leave ON tbl_cert_leave.request_id = tbl_request.request_id WHERE tbl_request.request_type='Certificate of Leave Credits Balance' ") or die (mysqli_connect_error());
     
            //initialize index to keep track of certificates
             $index = 1;
              while ($det1 = mysqli_fetch_array($det,MYSQLI_NUM)) {

              
                if (empty($det1)) {

                    $det1 = NULL;
                    echo "<script>alert('Invalid URL');</script>";
                    header("Refresh:0; url=../error404?user=$user"); 
                  
                  }

            $qrDivId = "qrCodeDiv" . $index; //unique div ID for each QR Code

            

             //convert date format
            $originalDate = strtotime($det1[15]);
            $asofDate = date("F j, Y", $originalDate); 

            $date1 = strtotime($det1[17]);
            $day = date("jS", $date1);

            $date2 = strtotime($det1[17]);
            $month = date("F Y", $date2); 


            //Administrative Division Approval
            $adm_u = mysqli_query($req,"SELECT ctrl_user.ctrl_id, ctrl_user.`user`, ctrl_user.admin_user, ctrl_user.processing_user, ctrl_user.approval_user, ctrl_user.approval_user_ard, ctrl_user.end_user, ctrl_user.cashier_user, user_details.division, user_details.`name`,user_details.position, user_details.place FROM ctrl_user INNER JOIN user_details ON user_details.user_id = ctrl_user.`user` where ctrl_user.approval_user = '1' and user_details.division = '$division_type' ORDER BY ctrl_user.ctrl_id DESC LIMIT 1 ") or die (mysqli_connect_error());
            $adm_usr = mysqli_fetch_array($adm_u,MYSQLI_NUM);

            //logs
            $b = mysqli_query($req,"SELECT logs_approval.`user`, logs_approval.action_taken, logs_approval.date_action_taken, logs_approval.request_id FROM logs_approval WHERE logs_approval.request_id = '$id' and logs_approval.action_taken = 'Approved Request' and logs_approval.`user` = '$adm_usr[1]' ORDER BY logs_approval.date_action_taken DESC LIMIT 1 ") or die (mysqli_connect_error());
            $bb = mysqli_fetch_array($b,MYSQLI_NUM);


            //electronically signed & date
            $digitally_signed_by = 'ELECTRONICALLY SIGNED BY:';
            $chief_approval = strtoupper($adm_usr[9]);
            $date_signed = date('D, M j, Y/ h:i a', strtotime($bb[2]));
            $name = ucwords(strtolower($det1[3]));
            $name1 = strtoupper($det1[2]);

            // Dynamically generate the $linkcert using the request_id from $det1[0]
            $linkcert = 'http://localhost/r9_iis/main/spics/certificates/view_certificate?link=' . urlencode($det1[0]);

            
            echo"
            <div class='print'>
            <div class='col-md-6 override'>        
            <div class='card-body' style=' font-family: Times New Roman;'>
                    <!-- HEADER -->
                <div class='row mt-2 align-items-center d-flex justify-content-center'>
                <div class='col-2' style='margin-top: 0; position:absolute;top:0;left: 20px'>               
                    <img class='img-fluid indep-sub-image' src='../../../dist/img/admin_logo.png' width='100px' height='100px'> 
                
                </div>
            
                <div class='col-12' style=' color: black; text-align: center; text-justify:inter-word;'>
                    <div style = 'text-align:center; display: inline-block;' >
                    <div style='font-size:13px; color:green'>Republic of the Philippines<br></div>
                    <div class='mb-0' style='font-size: 14px; color: darkblue;'><b>DEPARTMENT OF ENVIRONMENT AND NATURAL RESOURCES</b></div>
                    <p class='mb-0' style='font-size:13px; color:red;'><b>Regional Office No. IX</b></p>
                    <p style='font-size:12px;'>PCCARGC, Balintawak, Pagadian City, 7016 Zamboanga del Sur<br>
                    Telefax No: (062) 945-0870 Website: r9.denr.gov.ph
                    </p>
                    </div>
                </div>

                
                <div class='col-2' style='margin-top:0; position:absolute;top:0;right: 20px'>               
                    <img class='img-fluid indep-sub-image' src='../../../dist/img/bagong_pilipinas.png' width='100px' height='100px'> 
                
                </div>

            <div class='row'>
            <div class='card-body' style='margin-right: 30px; margin-left: 30px;'>
              <div class='row justify-content-center'>
               <hr>                
              </div>

              <div class='row justify-content-center'>
                <div class='col-md-12'>
                  <h3 style='text-align: center; color: black; font-family: Times New Roman;'><b>C E R T I F I C A T I O N</b></h3>
                </div>
              </div>

              <div class='row mt-5'>
                <div class='col-md-12'>
                  <p style='text-align: justify; text-justify:inter-word; font-size: 12px; color: black;'><b>TO WHOM IT MAY CONCERN:</b></p>
                </div>
              </div>

              <div class='row mt-3'>
                <div class='col-md-12'>
                  <p style='text-align: justify; text-justify:inter-word; font-size: 12px;'>
                      <strong>&emsp; &emsp; &emsp; THIS IS TO CERTIFY</strong> that per records of this Office, <span><strong>$name $name1</strong></span>                     
                      has the following leave credit balance as of  $asofDate, to wit:
                    </p>

                    <div>
                      <table class='table table-borderless' style='font-size: 12px; text-align: justify; text-justify:inter-word;  margin-right: 50px; margin-left: 50px; line-height: 2px;'>                            
                        <tr>                                  
                          <td class='col-2' style='text-align: left;'>VACATION LEAVE</td>
                          <td class='col-2' style='text-align: center;'>-</td>
                          <td class='col-2' style='text-align: left;'>$det1[13] day(s)</td>
                        </tr>

                        <tr>
                          <td class='col-2' style='text-align: left;'>SICK LEAVE</td>
                          <td class='col-2' style='text-align: center;'>-</td>
                          <td class='col-2' style='text-align: left;'> $det1[14] day(s)</td>
                        </tr>";

                         $total = $det1[13] + $det1[14]; 
                         $tv = number_format($total,2);
                        echo"
                        <tr>
                          <td style='text-align: left;'><b>TOTAL</b></td>
                          <td class='col-2' style='text-align: center;'>-</td>
                          <td style='text-align: left;'><b> $tv day(s)</b></td>
                        </tr>                             
                      </table>
                    </div><br>

                    <p style='text-align: justify; text-justify:inter-word; font-size: 12px; color: black;'>
                      <strong>&emsp; &emsp; &emsp;THIS CERTIFICATION</strong> is issued to support the <span> $det1[2]</span> of Mr./ Ms.  $det1[2]. 
                    </p><br>
                    <p style='text-align: justify; text-justify:inter-word; font-size: 12px; color: black;'>
                        &emsp; &emsp; &emsp;Issued this $day day of $month, Pagadian City, Zamboanga del Sur Philippines.
                    </p><br><br>

                  <div class='wrap'>
                    <div class='row'>
                      <div class='table-responsive'>
                        <table class='table table-nowrap table-borderless align-bottom mt-0'>
                          <tbody>
                            <tr>          
                              <div class='content' style='text-align: center; text-justify:inter-word; color: black; font-size:7px; position: absolute; right:70px;'>";
                               

                                  if ($bb != null and $adm_usr != null) {

                                    echo "$digitally_signed_by<br>";
                                    echo "<b>$chief_approval</b><br>ON ";
                                    echo "$date_signed<br>";
                                    
                                  }

                              echo"
                              </div>        
                            </tr>
                            <tr>
                              <td>
                                <div class='col-6 text-end' style='text-align: center; text-justify:inter-word; color: black; font-size: 12px;'> 
                                  <div id='qrDivId-$index'></div> 
                                </div>
                                <div style='font-size:12px'>&emsp;&emsp;$det1[1]</div>
                              </td>
                              
                              <td>
                                <div class='col-md-12' style='text-align: center; text-justify:inter-word; color: black; font-size: 12px;'> 
                                  <div class='content' style='float:right; width:180px;'>";

                                    

                                      if ($bb != null and $adm_usr != null) {

                                      echo "

                                      <div class='content'>
                                        <img src='../../tops/esig/$adm_usr[1].png' alt='signature' width='80px' height='80px'>
                                      </div> ";

                                      } 

                                      echo "<b>$chief_approval</b><br>";
                                      echo $adm_usr[10];
                                    echo"
                                  </div>                             
                                </div>
                              </td>
                              <td></td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>

                  </div>";
            
                if ($det1[9] == 'Approved') {

                    echo "

                    <div class='row mt-4 fixed-bottom'>
                    <div class='content' style='text-align: center; text-justify: inter-word; font-size:9px; font-style: italic;'>
                        THIS IS AN OFFICIAL DOCUMENT APPROVED DIGITALLY AND GENERATED FROM THE DENR-IX INTEGRATED INFORMATION SYSTEM.<br>
                        NO ORIGINAL SIGNATURE IS REQUIRED
                    </div>
                    </div> ";

              }

          
              
              echo"
              <div class='footer'>
              
              </div>

              </div>
              </div>                                           
              </div>
              </div>        
              </div>
              </div>           
              </div>";

               // Generate unique QR Code container IDs
                $qrDivId = "qrDivId-$index";

                // Generate the QR code container for each iteration
                echo "<div id='$qrDivId' style='display: none;'></div>";

            
              $index++; //Increment the index for the next QR Code
            }

        
    ?>
    <!-- END OF CONDITION FOR REQUEST TYPE ----->

  <?php 

    //footer for view certificates
    
    //modal
    include('modal_view_cert.php');

  ?>

  </body>
  <!-- Footer -->
  <?php include('../link/footer-sublink.php');?>


<!-- Separate Script to Initialize QR Codes -->
<script src='qr-code/qrcode.min.js'></script>
<script type='text/javascript'>
    document.addEventListener('DOMContentLoaded', function() {
        // Iterate through all QR code containers and initialize
        for (let i = 1; i <= <?php echo $index - 1; ?>; i++) {
            const qrCodeContainerId = `qrDivId-${i}`;
            const qrCodeData = '<?php echo $linkcert ?>'.replace(/\/g, '');

             // Ensure the container exists
             const container = document.getElementById(qrCodeContainerId);
            if (container) {
                // Clear any previous content in the container
                container.innerHTML = '';
         
              const qrCode = new QRCodeStyling({
                width: 150,
                height: 150,
                type: 'png',
                data: qrCodeData,
                image: 'qr-code/logo_denr.png',
                backgroundOptions: {
                    color: '#ffffff',
                },
                imageOptions: {
                    crossOrigin: 'anonymous',
                    margin: 0,
                }
            });

            qrCode.append(container);
          }
        
        }
    });
</script>


<script>
    window.addEventListener('load', function() {
  
       
    // Event listener for after the print dialog is closed (either print or cancel)
    window.onafterprint = function() {
    // Redirect to the previous page
    window.history.back();  // Go back to the previous page
    };

   // Fallback in case 'onafterprint' doesn't work on some browsers
   setTimeout(function() {
  window.location.href = 'http://localhost/r9_iis/main/spics/certificates/view_certificate?link=<?php echo $id_encrypt; ?>';
  }, 1000);
  });
</script>

i even ask in chatgpt and is not helping

Surrounding impact the reading of text with colored background

I am using OpenCV & tesseract to read the text from the image. But something weird is happening. I have a CTA with text on it with a background color:

[![enter image description here][1]][1]

When I run the code it’s read the text. Now if the CTA is a part of a UI like this:
[![enter image description here][2]][2]

Then the code didn’t read the CTA text.
here is the output:[![enter image description here][3]][3]

I didn’t now what to do. Here is the code snippet:

document.getElementById('process').addEventListener('click', async () => {
  if (!imageFile) {
    alert("Please upload an image first.");
    return;
  }

  const img = new Image();
  img.src = URL.createObjectURL(imageFile);

  img.onload = function() {
    // Set canvas dimensions to match the uploaded image
    canvas.width = img.width;
    canvas.height = img.height;

    // Draw the uploaded image onto the canvas
    ctx.drawImage(img, 0, 0);

    // Get image data from canvas for OpenCV processing
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    // Convert to BGR using OpenCV
    const src = cv.matFromImageData(imageData);
    const gray = new cv.Mat();
    const clahe = new cv.Mat();
    const thresh = new cv.Mat();

    // Convert to grayscale
    cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY, 0);

    // Apply CLAHE to improve contrast
    const claheObj = new cv.CLAHE(2.0, new cv.Size(8, 8));
    claheObj.apply(gray, clahe);
    
    // Adjust thresholding to better handle colored backgrounds
    cv.threshold(clahe, thresh, 150, 255, cv.THRESH_BINARY); // Adjust threshold value as needed

    // Convert thresholded image to RGBA for canvas
    const rgbaImageData = new Uint8ClampedArray(thresh.cols * thresh.rows * 4);
    for (let i = 0; i < thresh.rows; i++) {
      for (let j = 0; j < thresh.cols; j++) {
        const binaryValue = thresh.ucharPtr(i, j)[0]; // Binary value
        const index = (i * thresh.cols + j) * 4;
        rgbaImageData[index] = binaryValue;     // R
        rgbaImageData[index + 1] = binaryValue; // G
        rgbaImageData[index + 2] = binaryValue; // B
        rgbaImageData[index + 3] = 255;         // A (Fully opaque)
      }
    }

    // Create ImageData object with the RGBA data and put it back onto the canvas
    const processedImageData = new ImageData(rgbaImageData, thresh.cols, thresh.rows);
    ctx.putImageData(processedImageData, 0, 0);

    // Release memory used by OpenCV
    src.delete();
    gray.delete();
    clahe.delete();
    thresh.delete();
    claheObj.delete();

    // Convert the processed canvas image to a Blob URL and pass it to Tesseract
    canvas.toBlob((blob) => {
      const processedImageURL = URL.createObjectURL(blob);
      Tesseract.recognize(processedImageURL, 'eng', {
        logger: (m) => console.log(m),
        // Add the Tesseract options here
        tessedit_pageseg_mode: 6, // --psm 6
        oem: 3                     // --oem 3
      }).then(({ data: { text } }) => {
        // Send the extracted text back to the Figma plugin
        parent.postMessage({ pluginMessage: { type: 'text-extracted', text } }, '*');
      }).catch((error) => {
        console.error("Error extracting text:", error);
        alert("Failed to extract text from the image.");
      });
    }, 'image/png');
  };
});

I am didn’t know python that’s I used there CDN links
[1]: https://i.sstatic.net/BfLMehzu.png
[2]: https://i.sstatic.net/TLMRswJj.png
[3]: https://i.sstatic.net/8MMlKCtT.png

Loading dependencies

I’m trying to load classes in order of dependency, so extensible classes are loaded before classes that extend them.

The below approach works, but seems a bit convoluted to do something which seems like it would be a common enough ask. Am I missing a more standard way of achieving this?

    depends = new depends(LoadDepends);
    depends.add("markerClass.js",[]);
    depends.add("zcla_clusters.js",["markerClass.js"]);
    depends.add("users.js",["markerClass.js"]);
    depends.add("zcla_wkcomsh.js",["markerClass.js"]);
    depends.chain();

And the depends class, that is referenced.

class depends {
/**
 * Constructs a new instance of the Depends class.
 * @param {Function} onHasDepends - The callback function to be executed when all dependencies are loaded.
 */
constructor(onHasDepends) {
    this._depends = [];
    this._loaded = [];
    this._loading = [];
    this._onHasDepends = onHasDepends;
}

/**
 * Adds a dependency to the list of dependencies.
 * @param {string} name - The name of the dependency.
 * @param {Array<string>} dependencies - An array of dependency names.
 */
add(name, dependencies) {
    if(!this._depends.includes(name)) {
        this._depends.push(name)
        this._depends[name] = dependencies;
        for(let i in dependencies) {
            if(!this._depends.includes(dependencies[i])) {
                alert("Dependency ["+ dependencies[i] +"] not found for ["+ name +"]");
            }
        }
    }
}

/**
 * Checks if all dependencies of a given module are loaded.
 * @param {string} name - The name of the module.
 * @returns {boolean} - True if all dependencies are loaded, false otherwise.
 */
depLoaded(name) {
    let f = true;
    for (let d = 0; d < this._depends[name].length; d++) {
        if (!this._loaded.includes(this._depends[name][d])) {
            f = false;
            break;
        }
    }
    return f;
}

/**
 * Checks if all dependencies are loaded.
 * @returns {boolean} Returns true if all dependencies are loaded, false otherwise.
 */
allLoaded() {
    let f = true;
    for (let i = 0; i < this._depends.length; i++) {
        if (!this._loaded.includes(this._depends[i])) {
            f = false;
            break;
        }
    }
    return f;
}

/**
 * Executes a chain of dependent scripts.
 */
chain() {
    var ch = this
    for (let i = 0; i < this._depends.length; i++) {
        if (!this._loading.includes(this._depends[i]) && this.depLoaded(this._depends[i])) {
            var script = document.createElement('script');
            script.src = 'javascripts/' + ch._depends[i];
            script.onload = function(){
                ch._loaded.push(this.src.split('/').pop());
                if (ch.allLoaded()) {
                    ch._onHasDepends()
                } else {
                    ch.chain()
                }
            };
            ch._loading.push(ch._depends[i]);
            document.head.appendChild(script);
        }
    }
}

}

combining capture once passive and signal

I’ve been working on a complex event-driven system where I’m using various options within the addEventListener() method to handle form submissions and control event propagation. Specifically, I’m combining the following options: capture, once, passive, and signal for a custom form handler.

Here is the code im working on

const formData = function () {
  const nameLabel = document.getElementById("element1");
  const countryLabel = document.getElementById("element2");
  const btnHandle = document.getElementById("btn");
  const dataBase = [];
  
  const controller = new AbortController();
  const signal = controller.signal;

  const handleClick = function (event) {
    event.preventDefault();  // Prevent form submission
    
    const formEntry = {
      name: nameLabel.value,
      country: countryLabel.value
    };
    
    dataBase.push(formEntry);
    console.log('Form Data Submitted:', dataBase);
    
    // Abort listener after event triggered if `once` is true
    if (options.once) {
      controller.abort();
    }
  };

  const options = {
    capture: true,   // Event captured before DOM propagation
    once: true,      // Event listener removed after being triggered once
    passive: false,  // Allows preventDefault() to be called
    signal: signal,  // Aborts event listener when controller.abort() is called
    useCapture: true // Ensures event is handled in the capturing phase
  };

  btnHandle.addEventListener("click", handleClick, options);
  
  // Abort the listener programmatically after 10 seconds
  setTimeout(() => {
    controller.abort();
  }, 10000);
};

formData();

How do subtle interactions between capture, passive, once, and signal manifest in complex event-driven architectures, particularly when dealing with nested components, asynchronous event handling, and reactivity frameworks (e.g., React or Vue)?

I’m particularly interested in understanding how these edge cases might lead to performance bottlenecks, event handling inconsistencies, or missed cleanup actions in applications using virtual DOMs or reactive data bindings. Have there been observed real-world cases where these configurations resulted in unexpected behavior, such as listeners being prematurely removed or default actions being inconsistently triggered across nested elements?

Can’t use type-fest GreaterThan as parameter type

I tried using type-fest GreaterThan type for the function parameter and got an error

when I write the following function:

import type {GreaterThan} from 'type-fest'

function printNumberOfBooks <N extends number> (numberOfBooks: GreaterThan<N, 0>): void {
    console.log(numberOfBooks)
}

and… :

printNumberOfBooks(2)

I get the following typescript error:

Argument of type ‘number’ is not assignable to parameter of type ‘never’

It took me hours… I didn’t find a solution

Official documentation of type-fest GreaterThan type

Official documentation of typescript Generics