How to define a static constructor within a JS class?

How do you define a static constructor within a JS class?

I managed to write something that somehow works but it requires to write a specific codepath in constructor for when an IngredientsDB object is instantiated from the static method IngredientsDB.fromXML():

class IngredientsDB {
  constructor(...args) {
    if (arguments.length === 0) {
      this.document = null;
    } else {
      this.document = new DOMParser().parseFromString("<ingredients/>", "text/xml");
      // ... process args
    }
  }
  static fromXML = function fromXML(xmlString) {
    const db = new this;
    db.document = new DOMParser().parseFromString(xmlString, "text/xml");
    return db;
  }
  toString() { // concise output for testing
    const ingredientsNode = this.document.firstChild;
    let str = ingredientsNode.tagName + ":";
    let childNode;
    for (childNode of ingredientsNode.children)
      str += " " + childNode.tagName;
    return str;
  }
}

const xml = document.getElementById("ingredients").textContent.trimStart();
console.log(IngredientsDB.fromXML(xml).toString());
<script id="ingredients" type="text/xml">
<ingredients>
  <tomato/>
  <meat/>
  <cheese/>
</ingredients>
</script>

Acces to django context to html js

I’m trying to access to my django context from my views.py to my index.html page but something wrong and I need help.

My context from django called in my html template is working fine with:

{% for i in links %}
            <li><a>{{i.id}}; {{i.sequence}}; {{i.category}};{{i.link}}; {{i.description}}; {{i.image}}</a></li>
{% endfor %}

out of that give me:

2; 0; OUTILS DU QUOTIDIEN – DIVERS;https://safran.fabriq.tech/login; La solution tout-en-un pour le QRQC Digitalisé ! Détectez, escaladez, résolvez vos problèmes plus rapidement et améliorez votre performance.; Logos/Fabriq_0ER4lsy.png
3; 0; OUTILS DU QUOTIDIEN – DIVERS;https://improve.idhall.com/; Improve est la plateforme collaborative de Safran pour piloter toutes les initiatives de progrès du Groupe (de l’idée au projet d’amélioration).; Logos/Improve_lFlB5pY.png
4; 0; OUTILS DU QUOTIDIEN – DIVERS;https://portal.bi.group.safran/reports/powerbi/REPORTS/Safran%20Aircraft%20Engines/Develop/Innovation-Participative-SAE/IP-FULL-SAE?rs:Embed=true; PowerBI IP Safran Aircraft Engines.; Logos/Gestor_gVEU0RR.png

but in my js:

        <script>
            var linksData = '{{links}}';

            for(let j=0;j< linksData.length;j++)
            {
                document.writeln('<p class="card-text">"'+String(linksData[j].category)+'"</p>');
            }          

        </script>

give me :

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

"undefined"

...

My attempt was also with

 var linksData = JSON.parse('{{links|escapejs}}');

but still not working and return nothing, could you help me please?

Thanks a lot
Philippe

how to find an entry in an array based on two conditions [duplicate]

Say I have the following:

const allowedDomains=[
    {"domain":"abc.com","apiKey":"1","from":"Goofy"},
    {"domain":"def.com","apiKey":"2","from":"Mickey Mouse"},
    {"domain":"chi.com","apiKey":"3","from":"Donald Duck"},
];

I have two values in my code that are:

let domain = 'abc.com';
let apiKey = '1';

I want to check if there is an entry in the array that satisfies both conditions. So the above should return true.

If the values are:

let domain = 'abc.com';
let apiKey = '2';

it should return false.

I thought to use find but don’t know how to use it with two conditions. What is the quickest way to do it?
With one condition it could be:

let from = allowedDomains.find(a => a.domain === domain)?.from;

What for two conditions?

How to filter metadata where data inside the metadata is having multpile id’s stored as giant string with comma seperated

I am using Chroma from langchain.vectorstores import Chroma According to chroma’s doc, it only allows $eq, $in etc for metadata filed.

the metadata is structured as

 {
    userids: '217cdc91-dssd-fasd,3850d-sdsw-150, 217cdc91-dssd-fasd',
    created: 1725908639288,
    description: 'GitHub Pull Requests data',
  }

i want to retrieve documents if i mentioned user id present in the userids using collection.query metadata filters

for reference i looked this documentation
https://cookbook.chromadb.dev/core/filters/#metadata-filters

kindly help me to figure out a method to retreive the data if any one id matches within the userids

Playing audio with web audio api

I followed some tutorials to make the audio play automatically when certain conditions are met. However, the audio does not play automatically. Here is my code.

Parts_Request_Display_Servlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User usr = session.getAttribute("currentSessionUser") != null ? (User) session.getAttribute("currentSessionUser") : new User();
        if (!(UserBean.is_supervisor(usr) || UserBean.is_schedule(usr))) {
            response.sendRedirect("/hdi.jsp?err=AccessDenied");
            return;
        }

        ArrayList<Parts_Request_Display_Data> slist = new ArrayList<Parts_Request_Display_Data>();
        NumberFormat nfi = NumberFormat.getInstance();

        try {
            slist = new Parts_Request_Display_Beans().GetRequestFormDisplayList();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String tbl = "<div class="screen" style="padding:50px;">" +
                "<table class="table">" +
                "<tr><td colspan=2 class="text-left gray2 em3">Request Status</td><td colspan=4 class="text-right"><div id="clockbox"></div></td></tr>" +
                "<tr><td class="text-center white em3 bold">Req#</td>" +
                "<td class="text-left pink em4 bold">Req Loc</td>" +
                "<td class="text-left pink em4 bold">Requester</td>" +
                "<td class="text-center yellow em3 bold">Status</td>" +
                "<td class="text-center white em3 bold">Req Elap</td>" +
                "<td class="text-center white em3 bold">Ready Elap</td></tr>";

        DateFormat dbDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
        long REQ_elapsed = 0;
        String REQ_elapsedTime = "";
        long READY_elapsed = 0;
        String READY_elapsedTime = "";
        int beep = 0;
        String alamPath = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "assets" + File.separator + "PartRoom_alam" + File.separator;

        JSONObject json = new JSONObject(); // Create JSONObject instance

        for (int i = 0; i < slist.size(); i++) {
            Parts_Request_Display_Data dto = slist.get(i);
            String REQ_ID = dto.get_REQ_ID();
            String REQ_LOC = dto.get_REQ_LOC();
            String REQER = dto.get_REQUESTER();
            String STATUS = dto.get_STATUS().trim();
            String REQ_DATE = dto.get_REQ_DATE();
            String READY_DATE = dto.get_READY_DATE();
            int octa_include = dto.get_octa_include(); // Get the octa_include field value
            String audioPath = ""; // Path to the audio file

            String StatusBG = "";
            String ReqLocColor = ""; // Initialize ReqLocColor
            String ReqerColor = "";  // Initialize ReqerColor

            // Check if octa_include is 1
            if (octa_include == 1) {
                ReqLocColor = "style="color:yellow;"";  // Apply yellow color to REQ_LOC
                ReqerColor = "style="color:yellow;"";   // Apply yellow color to REQER
            }

            if (STATUS.equalsIgnoreCase("request")) {
                beep++;
                STATUS = "-----";
                READY_elapsedTime = "-----";
                try {
                    REQ_elapsed = DateCalc.getDateDiffMinutes(dbDateformat.parse(REQ_DATE), new Date());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                REQ_elapsedTime = String.format("%5dm", REQ_elapsed);

                // Check if octa_include is 1
                if (octa_include == 1) {
                    audioPath = alamPath + "octa+Request.mp3";
                } else {
                    audioPath = alamPath + "part+Request.mp3";
                }

                // Include the audio path in the JSON response
                json.put("audioPath", audioPath);
            } else if (STATUS.equalsIgnoreCase("ready")) {
                StatusBG = "bg-danger";
                STATUS = "Ready";
                try {
                    REQ_elapsed = DateCalc.getDateDiffMinutes(dbDateformat.parse(REQ_DATE), new Date());
                    READY_elapsed = DateCalc.getDateDiffMinutes(dbDateformat.parse(READY_DATE), new Date());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                REQ_elapsedTime = String.format("%5dm", REQ_elapsed);
                READY_elapsedTime = String.format("%5dm", READY_elapsed);
            }

            tbl += "<tr>";
            tbl += "<td class="text-center white em3 bold">" + REQ_ID + "</td>";
            tbl += "<td class="text-left pink em3 bold" " + ReqLocColor + ">" + REQ_LOC + "</td>";  // Apply yellow color to REQ_LOC if needed
            tbl += "<td class="text-left pink em4 bold" " + ReqerColor + ">" + REQER + "</td>";    // Apply yellow color to REQER if needed
            tbl += "<td class="text-center wheat em4 bold " + StatusBG + " ">" + STATUS + "</td>";
            tbl += "<td class="text-center white em4 bold ">" + REQ_elapsedTime + "</td>";
            tbl += "<td class="text-center white em4 bold ">" + READY_elapsedTime + "</td>";
            tbl += "</tr>";
        }

        tbl += "</table></div>";

        Date curdate = new Date();
        String curtime = "<span class='em2 font-italic purple-100'>" + new SimpleDateFormat("E").format(curdate) + ",</span>"
                + " <span class='em2 font-italic light-green-200'>" + new SimpleDateFormat("MM/dd/yyyy").format(curdate) + ",</span>"
                + " <span class='em2 font-italic cyan-100'>" + new SimpleDateFormat("HH:mm:ss a").format(curdate) + "</span>";

        response.setContentType("application/json;charset=utf-8");

        json.put("textMsg", tbl);
        json.put("timespan", 22000);
        json.put("beep", beep);
        json.put("curtime", curtime);

        try (PrintWriter pw = response.getWriter()) {
            pw.print(json.toString());
        }

Parts_Request_Display_Servlet.jsp

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@page import="java.text.*" %>
<%@page import="java.time.*" %>
<%@page import="java.util.*" %>
<%@page import="javax.servlet.*" %>
<%@page import="hdi.common.*" %>
<jsp:useBean id = "ub" class = "hdi.common.UserBean" scope="page"/>
<jsp:useBean id = "pu" class = "hdi.common.PageUtils" scope="page"/>

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0);
//prevents caching at the proxy server
request.setAttribute("hdiUrl", "/");

String pageHREF = request.getRequestURI();
Set<String> roleSet = ub.GetPageRoleSet(pageHREF);

User usr = session.getAttribute("currentSessionUser")!=null ? (User)session.getAttribute("currentSessionUser"): new User() ;

if ( UserBean.hasAccessPage(usr, roleSet)){
    UserBean.accessLogged(usr, pageHREF);
}else{
    response.sendRedirect("/hdi.jsp?err=AccessDenied");
    return;
}
%>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Parts Request Display</title>
<% out.println(pu.Header()); %>
<style>
.screen,
#slideshow,
#slideshow:after { 
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: 1; 
    color:#ffffff;
    background-color:#0000ff;
    text-align:center;
}
</style>
</head>
<body>
<input type='hidden' name='Serial' id='Serial' value='1'>
<div id="slideshow"></div>
<audio id="audioPlayer" preload="auto"></audio> <!-- Audio element for playing sound -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- jQuery CDN -->
<script>

var timespan = 15000;
var beep = 0;
var audioPlayer = document.getElementById('audioPlayer');

(function worker() {
    $.ajax({
        url: '/part/Part_Room/Parts_Request_Display/Parts_Request_Display_Servlet', 
        success: function(data) {
            $('#slideshow').html(data.textMsg);
            timespan = parseInt(data.timespan);
            beep = parseInt(data.beep);
            $('#clockbox').html(data.curtime);

            // Check if audioPath is available and play the audio
            if (data.audioPath) {
                audioPlayer.src = data.audioPath;
                audioPlayer.play();
            }
        },
        complete: function() {
            setTimeout(worker, timespan);
        }
    });
})();
</script>
</body>
</html>

The audio is supposed to play automatically when a request is received, but the audio is not playing.

How to Update a Kanban List Dynamically After Creating a New Task with MongoDB?

‘m working on a Kanban application where I need the list of tasks to update immediately after creating a new task. I’m using MongoDB with Express and Axios, but I’m having trouble getting the list to refresh dynamically without a full page reload.

Here are the main components of my application:

1.List Component: This component fetches and displays tasks grouped by stages. It uses the useState and useEffect hooks to manage state and fetch data from the server.

type Task = {
  id: string;
  title: string;
  description: string;
  dueDate?: Date;
  completed: boolean;
  stageId?: string | null;
  users: { id: string; name: string; avatarUrl: string }[];
  createdAt: string;
  updatedAt: string;
};

type TaskStage = {
  id: string;
  title: string;
  tasks: Task[];
  createdAt: string;
  updatedAt: string;
};

const List = ({ children }: React.PropsWithChildren) => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [stages, setStages] = useState<TaskStage[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const {replace} = useNavigation();

  // Fetch tasks and stages from MongoDB
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:3000/');
        setTasks(response.data.tasks);
        setStages(response.data.taskStages);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);
  // console.log(tasks);
  // console.log(stages);
 
  // Group tasks by stages
  const tasksStages = React.useMemo(() => {
    if (!tasks.length || !stages.length) {
      return {
        unassignedStage: [],
        columns: []
      };
    }

    const unassignedStage = tasks.filter((task: Task) => !task.stageId) ?? [];
    const groupedStages = stages.map((stage: TaskStage) => ({
      ...stage,
      tasks: tasks.filter((task: Task) => task.stageId === stage.id) ?? [],
    })) ?? [];

    return {
      unassignedStage,
      columns: groupedStages
    };
  }, [stages, tasks]);
  
  const handleTaskCreate = (newTask: Task) => {
    setTasks((prevTasks) => [...prevTasks, newTask]);
};
  // Handle adding new card by pressing the pluss icon : 
  const handleAddCard = (args: { stageId: string }) => {
    const path = args.stageId === 'unassigned' ? '/tasks/new' : `/tasks/new?stageId=${args.stageId}`;
    replace(path); // Use navigate instead of replace
  };
...
 return (
    <>
      <KanbanBoardContainer>
        <KanbanBoard onDragEnd={handleOnDragEnd}>
          <KanbanColumn
            id="unassigned"
            title="Unassigned"
            count={tasksStages.unassignedStage.length || 0}
            onAddClick={() => handleAddCard({ stageId: 'unassigned' })} description={undefined}>
            {tasksStages.unassignedStage.map((task: Task) => (
              <KanbanItem key={task.id} id={task.id} data={{ ...task, stageId: 'unassigned' }}>
                <ProjectCardMemo {...task} dueDate={String(task.dueDate) || undefined} />
              </KanbanItem>
            ))}
            {!tasksStages.unassignedStage.length && <KanbanAddCardButton onClick={() => handleAddCard({ stageId: 'unassigned' })} />}
          </KanbanColumn>

          {tasksStages.columns?.map((column: TaskStage) => (
            <KanbanColumn
              key={column.id}
              id={column.id}
              title={column.title}
              count={column.tasks.length}
              onAddClick={() => handleAddCard({ stageId: column.id })} description={undefined}>
              {column.tasks.map((task: Task) => (
                <KanbanItem key={task.id} id={task.id} data={task}>
                  <ProjectCardMemo {...task} dueDate={String(task.dueDate) || undefined} />
                </KanbanItem>
              ))}
              {!column.tasks.length && <KanbanAddCardButton onClick={() => handleAddCard({ stageId: column.id })} />}
            </KanbanColumn>
          ))}
        </KanbanBoard>
      </KanbanBoardContainer>
      {children}
    </>
  );
};

export default List;

2.TasksCreatePage Component: This component is used to create new tasks. It opens a modal form where users can input task details. Upon submission, the task is created, but I need to find a way to ensure the new task appears in the list immediately.

import { useSearchParams } from "react-router-dom";
import { useModalForm } from "@refinedev/antd";
import { useNavigation } from "@refinedev/core";
import { Form, Input, Modal } from "antd";
import axios from "axios";

const CreateTask = () => {
  const [searchParams] = useSearchParams();
  const { list } = useNavigation();

  const { formProps, modalProps, close } = useModalForm({
    action: "create",
    defaultVisible: true,
  });

  const onSubmit = async (values: any) => {
    const stageId = searchParams.get("stageId") || null;

    try {
      const response = await axios.post('http://localhost:3000/tasks', {
        title: values.title,
        stageId,
        completed: false,
        users: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      });

      if (response.status === 201) {
        // Optionally show a success message here
        list("tasks", "replace");
      }
    } catch (error) {
      console.error('Error creating task:', error);
    }

    close();
  };

  return (
    <Modal
      {...modalProps}
      onCancel={() => {
        close();
        list("tasks", "replace");
      }}
      title="Add new card"
      width={512}
    >
      <Form {...formProps} layout="vertical" onFinish={onSubmit}>
        <Form.Item label="Title" name="title" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateTask;

3.App Component: This component manages routing in the application and includes a route to TasksCreatePage.

 <Route path="/tasks" element={<List>
                          <Outlet/>
                        </List>}>
                          <Route path="new" element={<CreateTask/>}/>
                          <Route path="edit/:id" element={<EditTask/>}/>
                        </Route>

How can I update the List component dynamically when a new task is created using MongoDB?
I would appreciate any guidance or examples on how to achieve this functionality in a React application.

How to wait for navigation after clicking a button in a Chrome Extension?

I’m trying to click a button in a website and extract data from the next page after the content is loaded.

I tried using onDOMContentLoaded as well as trying to put a listener in the tab but it doesn’t work. The code is able to click the button in the page but anything after won’t run.

I’ve tried multiple things with no success, this is my current code:

export const nextAvailableDate: (tab: chrome.tabs.Tab) => void = async (tab) => {

  await new Promise((resolve: any) => { 
    chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
      if (tabId === tab.id && info.status === 'complete') {
        chrome.tabs.onUpdated.removeListener(listener);
        resolve();
      };
    })
  });

  const auctionDates = document.querySelectorAll('div.CALSELF, div.CALSELT') as NodeListOf<HTMLElement>;

  const nextAuctionDates: HTMLElement[] = [];
  
  auctionDates.forEach(auctionDate => {
    const availableAuctions = auctionDate?.querySelector('span.CALACT') as HTMLElement;

    if (parseInt(availableAuctions.innerText) > 0) {
      nextAuctionDates.push(
        auctionDate as HTMLElement
      );
    };

  });

  if (nextAuctionDates[0]) nextAuctionDates[0].click();

  return !!nextAuctionDates[0];
};
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

import { nextAvailableDate } from './utils';

function App() {
  const onClick = async () => {
    var tab = await chrome.tabs.create({
      url: "https://hillsborough.realforeclose.com/index.cfm?zaction=USER&zmethod=CALENDAR"
    });

    // chrome.webNavigation.onDOMContentLoaded.addListener(async (details) => {
    //   await chrome.scripting.executeScript({
    //     target: {
    //       tabId: details.tabId!
    //     },
    //     func: () => {
    //       alert('Puta');
    //     }
    //   })
    // }, {
    //   url: [
    //     {
    //       hostContains: 'https://hillsborough.realforeclose.com/index.cfm?zaction=AUCTION&Zmethod=PREVIEW&AUCTIONDATE='
    //     }
    //   ]
    // });

    let [ { result } ] = await chrome.scripting.executeScript<any[], void>({
      target: {
        tabId: tab.id!
      },
      args: [
        tab
      ],
      func: nextAvailableDate
    });

    alert(result);


  };

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => onClick()}>
          count is {0}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App

Dynamic extension of file for Tilelayer in Leaflet

I am wondering how to do it. I want to have different file extension depending on path to taht file. In my script below for example: white_orchard have .png files in z=2 and x=2.

// Funkcja do ustawiania odpowiedniej mapy na podstawie ścieżki
function setupMap() {
    let mapPath;
    let minZoom;
    let maxZoom;
    
    // Pobranie bieżącej ścieżki URL
    const currentPath = window.location.pathname;

    // Sprawdzenie ścieżki i ustawienie odpowiednich wartości
    if (currentPath.includes('/white_orchard/index.html')) {
        mapPath = '/resources/maps/white_orchard/{z}/{x}/{y}.jpg';
        minZoom = 2;
        maxZoom = 5;
    } else if (currentPath.includes('/velen_novigrad/index.html')) {
        mapPath = '/resources/maps/hos_velen/{z}/{x}/{y}.jpg';
        minZoom = 1;
        maxZoom = 6;
    } else {
        console.error('Nieznana ścieżka mapy');
        return;
    }

    // Obliczanie średniego zoomu
    const avgZoom = Math.round((minZoom + maxZoom) / 2);

    // Inicjalizacja mapy
    var map = L.map('mapid', {
        zoomControl: false,
        fullscreenControl: true,
        zoomSnap: 0.5,
        zoomDelta: 0.5
    }).setView([51.505, -0.09],avgZoom);

    // Dodanie kontrolek zoomu
    L.control.zoom({
        position: 'bottomright',
        zoomInTitle: 'Przybliż',
        zoomOutTitle: 'Oddal'
    }).addTo(map);

    // Okienko z koordynatami
    map.on('click', function (e) {
        var coords = e.latlng;
        var lat = coords.lat.toFixed(5);
        var lng = coords.lng.toFixed(5);
        console.log('Map clicked at:', lat, lng);
        L.popup()
            .setLatLng(coords)
            .setContent("Koordynaty: " + lat + ", " + lng)
            .openOn(map);
    });


    // Dodanie warstwy kafelków z opcją TMS
    L.tileLayer(mapPath, {
        minZoom: minZoom,
        maxZoom: maxZoom,
        tms: true // Ustawienie odwrotnej numeracji kafelków
    }).addTo(map);
}

// Wywołanie funkcji po załadowaniu DOM
document.addEventListener('DOMContentLoaded', function() {
    setupMap();
});

I tried to search for answers or use AI but it was in vain. I could use some advice on this particular problem.

How can I preprocess an image to improve text recognition accuracy with Tesseract OCR?

I’m trying to improve text recognition accuracy using Tesseract OCR by preprocessing images with Sharp, but I’m still struggling to get accurate results. The text in the images often contains noise or distortion, and despite various preprocessing attempts, Tesseract is not able to recognize the text correctly.

import sharp from 'sharp';
import Tesseract from 'tesseract.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

// Function to process the image with Sharp
async function processImage(imagePath, processedImagePath) {
    try {
        await sharp(imagePath)
            .resize(800) 
            .grayscale() 
            .normalize() 
            .threshold(228) 
            .sharpen() 
            .toFile(processedImagePath);
    } catch (error) {
        console.error("Error", error);
    }
}

// Function to recognize text with Tesseract
async function recognizeText(imagePath) {
    try {
        const { data: { text } } = await Tesseract.recognize(
            imagePath,
            "eng", 
            { 
                logger: info => console.log(info)
            }
        );
        console.log("Text:", text);
    } catch (error) {
        console.error("Error:", error);
    }
}

// Paths for the image files
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const tempImagePath = path.join(__dirname, "downloaded-image.jpg");
const processedImagePath = path.join(__dirname, "processed-captcha.png");

// Process and recognize the image
await processImage(tempImagePath, processedImagePath);
await recognizeText(processedImagePath);

This is the original image:

Original image

What I’ve Tried:

  • Grayscale Conversion: I converted the image to grayscale to simplify the color channels.

  • Normalization: I normalized the image to enhance contrast.

  • Binarization: I applied a threshold to binarize the image.

  • Sharpening: I sharpened the image to make the text more distinct.

Despite these efforts, the text recognition is still inaccurate. Could anyone suggest additional preprocessing techniques or improvements to this approach? Are there specific settings or methods I should consider to enhance OCR results with Tesseract?

This is the result:

Result

Why PATCH Method Fails While POST Method Works in Laravel?

I am encountering an issue when sending a PATCH request in my Laravel application. When sending a PATCH request to update a resource, I am not getting the expected result. However, when I send the same request using the POST method, I get the desired result. What could be the issue with the PATCH request?

// web
Route::patch('{id}/update', [UrunlerController::class, 'update'])->name('magaza.urun.guncelle.submit');
// Controller
    public function update(Request $request, string $id)
    {
        $sayi = $request->input('sayi');

        return response()->json([
            'success' => true,
            'sayi' => $sayi
        ]);
    }
// vanilla js
document.getElementById('patates').addEventListener('click', function() {
    var formData = new FormData();
    formData.append('sayi', 123); // Basit veri ekliyoruz

    var url = `{{ route('magaza.urun.guncelle.submit', ['id' => 8]) }}`; 

    fetch(url, {
        method: 'PATCH',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: formData 
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('Hata:', error);
    });
});

The result I expected

{
    "success": true,
    "sayi": "123"
}

The result I encountered

{
    "success": true,
    "sayi": null
}

Laravel v:11.20.0

“12”+ {“x”:”1″,toString(){return 10;},valueOf(){return 90}}; evaluate the above expression in Javascript

In the above expression why toString() method is not called? As per the algorithm if either the left or right side there is string then we call ToString() with hint as “String” for another side and if hint is “String” then the toString() method will be called first and then the valueOf() method. But the above expression is given answer as “1290” mean valueOf() is called.

Algorithm for additive expression: –

12.8.3The Addition Operator ( + )
NOTE
The addition operator either performs string concatenation or numeric addition.
12.8.3.1Runtime Semantics: Evaluation
AdditiveExpression:AdditiveExpression+MultiplicativeExpression
Let lref be the result of evaluating AdditiveExpression.
Let lval be ? GetValue(lref).
Let rref be the result of evaluating MultiplicativeExpression.
Let rval be ? GetValue(rref).
Let lprim be ? ToPrimitive(lval).
Let rprim be ? ToPrimitive(rval).
If Type(lprim) is String or Type(rprim) is String, then
Let lstr be ? ToString(lprim).
Let rstr be ? ToString(rprim).
Return the string-concatenation of lstr and rstr.
Let lnum be ? ToNumber(lprim).
Let rnum be ? ToNumber(rprim).
Return the result of applying the addition operation to lnum and rnum. See the Note below 12.8.5.

ToString rules: –

7.1.12ToString ( argument )
The abstract operation ToString converts argument to a value of type String according to Table 11:

Table 11: ToString Conversions

[ToString conversion table](https://i.sstatic.net/2P3V03M6.png)

According to the ToString Conversion table if there is object then hint “String” will be used.

Please help me out in this problem why valueOf() method is preferred.

Displaying state name to the AmCharts 5 Map

Using AmCharts 5 in react application to display the US geographic. I can able to view the states in US Geography, but unable to add the state name to the map. But on hovering of the state, i can able to display the state name in the tooltip. Is there a way to add the state name to any Geographic in amCharts5

import React, { useEffect } from 'react';
import * as am5 from '@amcharts/amcharts5';
import * as am5maps from '@amcharts/amcharts5/map';
import usaHigh from "@amcharts/amcharts5-geodata/usaHigh";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";

const MapChart = () => {
  useEffect(() => {
    // Create root element
    let root = am5.Root.new("mapDiv");

    // Set themes
    root.setThemes([am5themes_Animated.new(root)]);

    let chart = root.container.children.push(
        am5maps.MapChart.new(root, {
          projection: am5maps.geoAlbersUsa(),
          maxZoomLevel: 16,
          minZoomLevel: 1,
          zoomStep: 1.2,
        })
      );
    const polygonSeries = chart.series.push(
      am5maps.MapPolygonSeries.new(root, {
        geoJSON: usaHigh
      })
    );

    polygonSeries.mapPolygons.template.setAll({
      tooltipText: "{name}",
      templateField: "polygonSettings",
    });
     }, []);

return <div  id="mapDiv" style={{ width: "100%", height: "500px" }}></div>;
};

How can I scope and automatically buy low float items for CS2 on Steam community market?

I am trying to build a script that automatically looks for low float items on steam community market and if it was found for the specified amount make that purchase. I have seen some NPM packages for using steam but it wasn’t exactly what I was trying to do. If you have any ideas where to start and what can be done to achieve this please let me know.

I tried searching for some packages that would do similar things, but I couldn’t find any.