Microsoft Visual Studio 2022 Keep Adding Space After Backtick On JavaScript Code

Microsoft Visual Studio 2022 keep adding space after backtick (`) on JavaScript code. The code as below.

return `
    <div class="text-nowrap">
        <i class="bi bi-pencil-square"></i>
        <i class="bi bi-trash"></i>
    </div>
`;

When I format the document (Ctrl+K, Ctrl+D), automatic the code will have extra space as below.

return `
        <div class="text-nowrap">
            <i class="bi bi-pencil-square"></i>
            <i class="bi bi-trash"></i>
        </div>
    `;

The extra space will keep adding as long as I press (Ctrl+K, Ctrl+D).

return `
            <div class="text-nowrap">
                <i class="bi bi-pencil-square"></i>
                <i class="bi bi-trash"></i>
            </div>
        `;

Ordered Dithering to 4 colors with JavaScript

fellow devs!

I am trying to dither a 8-bit grayscale image to a 2-bit / 4 color image with an ordered dithering based on a Bayer 8×8 matrix. My result is somewhat there, but not quite. I kept banging my head at the problem but can’t figure out where I went wrong so any help would be greatly appreciated.

Here’s my code:

    // image_array_2d is a 2d array of grayscale values from 0-255
    // matrix is a 2d array with values normalized to be between 0.0 and 1.0
    // LUT is an array of 8-bit values, in this case [0, 85, 170, 255]

    const MAX = 255
    const image_height = image_array_2d.length
    const image_width  = image_array_2d[0].length
    for (let y = 0; y < image_height; y++)
    {
        for (let x = 0; x < image_width; x++)
        {
            const threshold = (matrix[y % 8][x % 8]) * MAX
            let pixel_value = image_array_2d[y][x];
            //pixel_value = gamma_correct(pixel_value)

            // find closest value to pixel in LUT
            let value_current, value_prev
            let closest = lut[0]
            for (let i = 0; i < lut.length; i++)
            {
                const closestDifference = Math.abs(closest - pixel_value);
                const currentDifference = Math.abs(lut[i]  - pixel_value);

                console.log(currentDifference + " / " + closestDifference)
                if (currentDifference < closestDifference)
                {
                    value_prev     = lut[i-1]
                    value_current  = lut[i]
                    closest        = value_current
                    console.log(closest)
                }
            }

            let new_value = 0
            new_value = pixel_value > threshold ? value_current : value_prev
            new_value = pixel_value >= MAX      ?           MAX : new_value
            
            image_array_2d[y][x] = new_value
        }
    }

Just for safety, that’s my Bayer matrix before its values get normalized to 0.0 – 1.0

        [ 0, 32,  8, 40,  2, 34, 10, 42],
        [48, 16, 56, 24, 50, 18, 58, 26],
        [12, 44,  4, 36, 14, 46,  6, 38],
        [60, 28, 52, 20, 62, 30, 54, 22],
        [ 3, 35, 11, 43,  1, 33,  9, 41],
        [51, 19, 59, 27, 49, 17, 57, 25],
        [15, 47,  7, 39, 13, 45,  5, 37],
        [63, 31, 55, 23, 61, 29, 53, 21]

(The following images have been scaled up by 400% for convenience)

This is the image I test my algorithm with:
Source at 400%

And this is the intended target:
Target at 400%

However, this is the result of the above code with the LUT array being [0, 85, 170, 255]
Result at 400%

Not able to access post-gres database through various functions other than main() in Javascript program

I’m trying to query a database in my JavaScript program. From what I can tell, I have successfully connected to the database. When I query it from within the main() function, I’m able to print out a table with the correct values. If, however, I try to query the database from another function and call that function from main, nothing is outputted. I’m hoping someone can tell me why that is occurring.

The code that prints out the information:

const {Client} = require('pg');

const client = new Client({
    user: "postgres",
    host: "localhost",
    port: 5432,
    database:"A4"
});

main();

async function main() {

    try{ 
        await client.connect()
        console.log("Connected successfully");

        const results = await client.query("SELECT * FROM Students");
        console.table(results.rows);
    } catch (ex) {
        console.log(`Something wrong happened ${ex}`);
    } finally {
        await client.end();
        console.log("Client disconnected successfully");
    }
}

And the code that doesn’t is basically the same except the results query and the console.table are called from a different function, and that function is called within main:

const {Client} = require('pg');
const prompt = require('prompt-sync')();

const client = new Client({
    user: "postgres",
    host: "localhost",
    port: 5432,
    database:"A4"
});

main();

async function main() {

    try{ 
        await client.connect()
        console.log("Connected successfully");

        getAllStudents(client);

    } catch (ex) {
        console.log(`Something wrong happened ${ex}`);
    } finally {
        await client.end();
        console.log("Client disconnected successfully");
    }
}

async function getAllStudents(client) {

    try {
        const results = await client.query("SELECT * FROM Students");
        console.log(results.rows);
    } catch (error) {
        console.error("Error executing query: ". error);
    }

}

I have looked into the client variable to make sure it does exist and is connected when I’m querying it. Ive checked it prior to connecting, after connecting, and from within the getAllStudents function and it seems to be the same in the last 2 scenarios, and just disconnected prior to connection.

Any and all help is greatly appreciated

Why isnt the script doing anything? [duplicate]

Im making some buttons that are meant to stay focused even if something else on the screen is clicked that is not a button. for some reason the script simply does not execute, or is badly written i dont know.
The other thing is that i cant tell if its the script thats bad or the src, becaouse there is 0 console errors.

<! DOCTYPE html>
<html>
    <head>
        <title> sample text</title>
        <style>
            .btn { 
            cursor: pointer; 
            border: none; 
            background-color: transparent; 
            height: 50px; 
            width: auto; 
            color: #000000; 
            font-size: 1.5em; }
            .btn:focus{
            border-left-style: solid;
            border-left-color:red;
            border:none solid none none;}
        </style>
        
    </head>
    <body>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            $(".btn").toggle(function(){
            $(".btn").removeClass("focus");
            $(this).addClass("focus");
            })
        </script>
        <button class="btn">stuff1</button><br>
        <button class="btn">stuff2</button>
        
    </body>
</html>

FastAPI – Websockets, Multiple connections for one client

Trying to implement websockets in my fastapi application, however, when I connect to the websocket from the javascript side, it opens 4 connections, I have implemented a workaround in the backend side that check if the certain customer is connected, however this would mean that a client couldn’t connect to the websocket on mobile while it’s open on the computer for example.

class ConnectionManager:
    def __init__(self):
        self.connections: dict[int, WebSocket] = {}

    async def connect(self, websocket, customer_id):
        existing_connection = self.connections.get(customer_id)
        if existing_connection:
            await websocket.close()
            raise ExistingConnectionError("Existing connection for customer_id")

        await websocket.accept()
        websocket.customer_id = customer_id
        self.connections[customer_id] = websocket
        print(list(self.connections.values()))

    async def disconnect(self, websocket):
        customer_id = getattr(websocket, 'customer_id', None)
        if customer_id in self.connections:
            del self.connections[customer_id]

    async def broadcast(self, message):
        for websocket in self.connections.values():
            await websocket.send_json(message)

    async def broadcast_to_customer(self, customer_id, message):
        matching_connection = self.connections.get(customer_id)
        if matching_connection:
            await matching_connection.send_json(message)


connection_manager = ConnectionManager()
@router.websocket("/sock")
async def websocket_endpoint(websocket: WebSocket, customer_id: int):
    try:
        await connection_manager.connect(websocket, customer_id)
        while True:
            data = await websocket.receive_json()
    except WebSocketDisconnect:
        await connection_manager.disconnect(websocket)
    except ExistingConnectionError:
        print("Existing connection detected, rejecting the new connection")

Javascript:

let socket;

    if (!socket || socket.readyState !== WebSocket.OPEN) {
        socket = new WebSocket(`ws://localhost:3002/sock?customer_id=${customer_id}`);

        socket.onopen = () => {
            console.log('Connected to WebSocket server');
        };

        let i = 0;

        socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log('Incoming data:', data);
            console.log('i:', i);
            i = i + 1;
        };
    }

Backend logs:

INFO:     connection open
INFO:     ('127.0.0.1', 33366) - "WebSocket /sock?customer_id=185" 403
Existing connection detected, rejecting the new connection
INFO:     connection rejected (403 Forbidden)
INFO:     connection closed
INFO:     ('127.0.0.1', 33368) - "WebSocket /sock?customer_id=185" 403
Existing connection detected, rejecting the new connection
INFO:     connection rejected (403 Forbidden)
INFO:     connection closed
INFO:     ('127.0.0.1', 33384) - "WebSocket /sock?customer_id=185" 403
Existing connection detected, rejecting the new connection
INFO:     connection rejected (403 Forbidden)
INFO:     connection closed

Frontend logs:

Connected to WebSocket server
Firefox can’t establish a connection to the server at ws://localhost:3002/sock?customer_id=185.
Firefox can’t establish a connection to the server at ws://localhost:3002/sock?customer_id=185.
Firefox can’t establish a connection to the server at ws://localhost:3002/sock?customer_id=185.

Tried to implement websocket in FastAPI, opens multiple connections instead of one, for each client.

What happens when you load TinyMCE v6 on an unsupported browser?

I see here that TinyMCE version 6 does not support Internet Explorer 11. So how can I tell when somebody tries to load it on IE11?

If I load tinymce.min.js in IE11 then look for the resulting global tinymce object, will it exist? Will it have some error attribute?

(I do not have a copy of IE11 to test with, so forgive me for asking this sort of dumb question!)

Loop through dynamically created forms using PHP

I’m trying to insert data from multiple forms with PHP. The problem is, when I insert it using the subimit button on the first form, it only inserts the data from the first form, when I use the button on the second form onwards it does not register any and presents the error “Undefined array key “cod-1 “”. I’ve tried several ways with the help of GPT chat and it’s not working.

<form action="patCadastro.php" id="form-1" class="formCadastro" method="POST">
  <input type="hidden" name="formCount" value="1">
  <div class="rowForm">
   <div class="colForm">
    <label for="cod">CÓDIGO</label><br>
     <input id="cod-1" type="text" name="cod-1" required>
   </div>
   <div class="colForm">
    <label for="item">ITEM</label><br>
    <input type="text" name="item-1" id="item-1" required>
   </div>
   <div class="colForm">
    <label for="marca">MARCA</label><br>
    <input type="text" name="marca-1" id="marca-1">
   </div>
   <div class="colForm">
    <label for="modelo">MODELO</label><br>
    <input type="text" name="modelo-1" id="modelo-1">
   </div>
   <div class="colForm">
    <label for="condicao">CONDIÇÃO</label><br>
     <select id="condicao-1" name="condicao-1">
      <option value="" title="" selected="selected"></option>
      <option value="ÓTIMO" title="ÓTIMO">ÓTIMO</option>
      <option value="BOM" title="BOM">BOM</option>
      <option value="REGULAR" title="REGULAR">REGULAR</option>
      <option value="RUIM" title="RUIM">RUIM</option>
      <option value="INSERVÍVEL" title="INSERVÍVEL">INSERVÍVEL</option>
     </select>
    </div>
  </div>
  <div class="btnForm">
   <span class="spanBtn"><i class="fas fa-paper-plane"></i><input class="button cadastro" name="submitForm" type="submit" value="CADASTRAR"></span>
   <span class="spanBtn"><i class="fas fa-plus"></i><input class="button moreItem" type="button" value="+ITEM" onclick="moreForm()"></span>
  </div>
 </form>
 <div id="newForm"></div>
<script>
let formCount = 1;
function moreForm() {
    formCount++;
    const newForm = document.getElementById('newForm');
    const morePats = document.createElement('FORM');
    morePats.method='POST';
    morePats.action="patCadastro.php";
    morePats.classList.add('formCadastro');
    morePats.id = `form-${formCount}`;

    morePats.innerHTML = 
    
    <input type="hidden" name="formCount" value="${formCount}">
    <div class="rowForm">
        <div class="colForm">
            <label for="cod">CÓDIGO</label><br>
            <input id="cod-${formCount}" type="text" name="cod-${formCount}" required>
        </div>
        <div class="colForm">
            <label for="item">ITEM</label><br>
            <input type="text" name="item-${formCount}" id="item-${formCount}" required>
        </div>
        <div class="colForm">
            <label for="marca">MARCA</label><br>
            <input type="text" name="marca-${formCount}" id="marca-${formCount}">
        </div>
        <div class="colForm">
            <label for="modelo">MODELO</label><br>
            <input type="text" name="modelo-${formCount}" id="modelo-${formCount}">
        </div>
        <div class="colForm">
            <label for="condicao">CONDIÇÃO</label><br>
            <select id="condicao-${formCount}" name="condicao-${formCount}">
                <option value="" title="" selected="selected"></option>
                <option value="ÓTIMO" title="ÓTIMO">ÓTIMO</option>
                <option value="BOM" title="BOM">BOM</option>
                <option value="REGULAR" title="REGULAR">REGULAR</option>
                <option value="RUIM" title="RUIM">RUIM</option>
                <option value="INSERVÍVEL" title="INSERVÍVEL">INSERVÍVEL</option>
            </select>
        </div>
    </div> ;
    newForm.appendChild(morePats);
</script>
<?php
if (isset($_POST['submitForm'])) {

        for ($i = 1; $i <= $_POST['formCount']; $i++) {

            $cod = $_POST['cod-' . $i];
            $item = $_POST['item-' . $i];
            $marca = $_POST['marca-' . $i];
            $modelo = $_POST['modelo-' . $i];
            $condicao = $_POST['condicao-' . $i];
            $timeStamp = time();

            $stmt = $mysqli->prepare("INSERT INTO patrimonio (id, item, marca, modelo, condicao, lastCheck) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssss", $cod, $item, $marca, $modelo, $condicao, $timeStamp);
            $stmt->execute();
            $stmt->close();
        }
        header("Location: patCadastro.php");
        exit();
    }

    $mysqli->close();
?>

Using JavaScript to toggle visibility of content based on URL parameter

I have this test HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {
            font: 300 20px "Open Sans", sans-serif;
            color: #666;
            background-color: #bdc3c7;
            line-height: 1.8rem;
        }

        .mask-img {
            -webkit-mask-image: linear-gradient(to top, transparent 25%, black 75%);
            mask-image: linear-gradient(to top, transparent 25%, black 75%);
        }

        .mask-img img {
            display: block;
            margin-left: auto;
            margin-right: auto;
            max-width: 100%;
            border: 1px solid;
            box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.4);
            -moz-box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.4);
            -webkit-box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.4);
        }

        article {
            max-width: 60%;
            background-color: white;
            margin: 0 auto;
            padding: 5px 30px;
            border-radius: 15px;
            box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
        }

        article h1 {
            color: #3498db;
            padding-bottom: 15px;
            border-bottom: 1px dashed #bdc3c7;
        }
    </style>
    <title>Title</title>
</head>

<body>

    <article>
        <h1>Title</h1>
        <p>Para English</p>
        <p>Para Italian</p>
    </article>

    <script>
        // Get the URL parameter value
        const urlParams = new URLSearchParams(window.location.search);
        const paragraphNumber = urlParams.get('paragraph');

        // Hide all paragraphs except the one specified in the URL parameter
        const paragraphs = document.querySelectorAll('p');
        paragraphs.forEach((paragraph, index) => {
            if (index + 1 !== parseInt(paragraphNumber)) {
                paragraph.style.display = 'none';
            }
        });
    </script>
</body>

</html>

So I can call it like this:

  • test.html?paragraph=1
  • test.html?paragraph=2

But:

  1. I will have 50+ languages
  2. I need to also do the title and h1 elements.

Is there a more elegant JavaScript solution?

Why is my JSdelivr hosted javascript not working in Webflow?

I recently created a javascript code to help me turn Webflow form into a multi step form, and it always work whenever I use the raw javascript code, but whenever I used the CDN link hosted on JSdelivr through Github, it doesn’t work. What is the problem and how can I solve it?

//the raw code

<script>
document.addEventListener('DOMContentLoaded', function () {
  var currentStep = 1;

  showStep(currentStep);

  document.addEventListener('click', function (event) {
    if (event.target.classList.contains('form-btn')) {
      handleButtonClick(event.target);
    }
  });

  function handleButtonClick(btn) {
    if (btn.getAttribute('data-next-step')) {
      var nextStep = parseInt(btn.getAttribute('data-next-step'));
      if (validateStep(currentStep)) {
        currentStep = nextStep;
        showStep(currentStep);
      }
    } else if (btn.getAttribute('data-prev-step')) {
      var prevStep = parseInt(btn.getAttribute('data-prev-step'));
      currentStep = prevStep;
      showStep(currentStep);
    } else if (btn.getAttribute('data-submit')) {
      // You can add your form submission logic here
      // In this case, we're submitting the Webflow form
      submitWebflowForm();
    }
  }

  function showStep(step) {
    var steps = document.querySelectorAll('.form-step');
    for (var i = 0; i < steps.length; i++) {
      steps[i].style.display = 'none';
    }

    steps[step - 1].style.display = 'block';
  }

  function validateStep(step) {
    // You can add your own validation logic here
    // Return true if the validation passes, false otherwise
    return true;
  }

  function submitWebflowForm() {
    // Assuming the Webflow form has the ID "myForm"
    var webflowForm = document.getElementById('myForm');
    
    // Submit the Webflow form
    if (webflowForm) {
      webflowForm.submit();
    }
  }
});
</script>

The JSdelivr link:

https://cdn.jsdelivr.net/gh/johnope/multistep@tree/3bd6b58c148434000022aa908f7e4640cc2e4409

Hi, I recently created a javascript code to help me turn Webflow form into a multi step form, and it always work whenever I use the raw javascript code, but whenever I used the CDN link hosted on JSdelivr through Github, it doesn’t work. What is the problem and how can I solve it?

access parent state in children slot

My component in react js:

import React, { useState } from 'react';

const ComponentA = ({ children }) => {
  const [state1, setState1] = useState('Hello');
  const [state2, setState2] = useState('World');

  // Your component logic here
  return <div>{children}</div>;
};

export default ComponentA;

i need to use this method but not work but when use this not show:

const YourComponent = () => {
  return (
    <div>
      <ComponentA>
        {(state1, state2) => (
          <div>
            State 1: {state1}
            <br />
            State 2: {state2}
          </div>
        )}
      </ComponentA>
    </div>
  );
};

export default YourComponent;

How to resolve that?

Globe GL – How To Combine Labels Layer With Earthquake Data?

I’m trying to combine Globe GL’s Labels Layer with USGS data but I’m facing some challenges. The issue arises when adding Label Layer code into the existing setup I have. It all works and a globe is displayed until ‘// Points’ comment is inserted.

  1. Is the Label Layer code wrong? I tried to follow the earthquake globe example for the naming.

  2. Did I insert the Layer code wrongly? It does not work even if I combined the function containing label properties with the above function with document.getElementbyId.

            const world = Globe({ animateIn: false })(
              document.getElementById("globeViz")
            )
              .globeImageUrl(
                "//unpkg.com/three-globe/example/img/earth-blue-marble.jpg"
              )
              .bumpImageUrl(
                "//unpkg.com/three-globe/example/img/earth-topology.png"
              );

            world.backgroundColor("hsl(245 10% 10%)");
            world.width(710);
            world.height(650);

            // Auto-rotate
            world.controls().autoRotate = true;
            world.controls().autoRotateSpeed = 0.63;

            // Points
            fetch(
              "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson"
            )
              .then((res) => res.json())
              .then((equakes) => {
                world.labelsData(equakes.features);
              });

            const world = Globe()
              .labelsData(equakes.features)
              .labelLabel((d) => d.properties.title)
              .labelLat((d) => d.geometry.coordinates[1])
              .labelLng((d) => d.geometry.coordinates[0])
              .labelText((d) => d.properties.title)
              .labelSize((d) => Math.sqrt(d.properties.mag) * 4e-4)
              .labelDotRadius((d) => Math.sqrt(d.properties.mag) * 4e-4)
              .labelColor(() => "rgba(255, 165, 0, 0.75)")
              .labelResolution(2)(document.getElementById("globeViz"));

How to calculate control point for a quadratic curve for rounded corners on a pie segment

I’m trying to draw a pie chart where each segment (pie piece) of the chart has rounded corners. The cutout (mouth of the pacman) should also have rounded corners, but i’m strugling a bit with location the control point for the quadratic bezier curve I need to draw in the outside corners.

Illustration of problem

So i want to calculate the point the orange arrow points to. I know the two points inside the orange circle.

I tried one implementation where i would find the perpendicular angle to the line between the two orange points, and then, using that angle, and the center point between the two orange points i can move a desired amount away from that middle point on that angle. That approach sort of works, but depending on where on the circle I am i get some bad results where some places the control point is on the wrong side of the line between the orange points. Best illustrated by this example:

examples of where it goes wrong

What is the correct way to calculate this point a long the circle with the information i have available?

I’m doing this in JS and drawing using PDFKit’s tools, but any help regardless of language or tools that can draw bezier curves would be helpful.

Recursion in Depth

From the code below, I was trying to understand about recursion

function eleven(number) {
  if (number === 1) {
    return number;
    else {
      return number * eleven(number - 1);
    }
  }

  console.log(eleven(5));

I can’t understand how the last return statement works because its calls itself.

after if condition happens true it should return and stop the code.

but after that else statement returns 120 at last

I need to understand how does the pattern works underneath into the answer 120

is there any resources to get to know more about recursion pattern at core !!

As a beginner How do i master it..

look for a value in an array with map and find

I have a JSON object and I want to write a function to look for the chat_userID and return the corresponding nome.

I came up with:

utenti_chat = [{
    "nome": "John Doe",
    "id": 5,
    "email": "[email protected]",
    "chat_userID": "c1f2580cad95fa0f"
  },
  {
    "nome": "Jane Doe",
    "id": 6,
    "email": "[email protected]",
    "chat_userID": "ed86742608dde1fe"
  }
]


userConnected = utenti_chat.filter(a => a.chat_userID.find(w => w == user.userID)).map(a => a.nome);

but it returns that

a.chat_userID.find is not a function

how can I fix it?

Is it possible to host a Q&A coding site on GitHub Pages

What is CodeGitOverflow?

CodeGitOverflow is a Q&A coding site that is designed to address the issues of StackOverFlow, it will provide the user with features such as:

Security well working on client side:

  • All your data will be will be secure by using secure tampering and encryption libraries to ensure that no data can be directly accesed by the client side,
  • Only required information like username will be shown when asking questions.

Improved Features on StackOverFlow

It has various features to improve on StackOverFlow such as:

  • Instant reload when a question you are on is updated,

  • Notifications when your question recieves an update.

  • Multiple questions
    you can ask multiple questions even if your previous one was closed.

  • Closed questions won’t go against your account:
    No matter how many questions are closed it will never go against your account.

  • Recommended Answers:
    This site uses cookies to give each user a recommend answer to improve your user experience.

  • Completely free:
    This webiste is and always will be free so anyone can use this site

    But how is the data publicly stored well operating at the client-side?

    The website uses JSON to store information like comments, replies, up votes, down votes, usernames and much more to ensure that data can be publicly available while operating on the client-side to achieve this it fetches the question JSON file than renders it on the browser.
    Also, this website uses GitHub REST API to save questions, replies, upvotes and downvotes so everything can be public.
    Also, to ensure questions have their own page without having too many HTML files it uses Jekyll to render each question based off of parameters.
    And the best feature is if your question doesn’t get answered or perfer security it will be answered by AI.
    All designed to improve the cons of StackOverflow.

Also, the prototype doesn’t have the built in features.

Thanks for the help

Asking two computer science teachers.