Hygraph & Next JS issue pulling data

So I am trying to pull in some data from Hygraph in a new Next JS application, I recieve the error of Error: Cannot read properties of undefined (reading ‘map’).

I am new to both these technologies and cannot find a solutions, for reference I create a new Next JS application and imported graphql and graphql-request and the following code is inside the page.js file inside the app folder.

import styles from './page.module.css'
import { GraphQLClient, gql } from 'graphql-request'

const graphcms = new GraphQLClient(
  "https://api-eu-west-2.hygraph.com/v2/cli0kziqx3ow801ta0mvy1tdg/master"
);

const QUERY = gql`
{
  articles {
    createdAt
    id
    publishedAt
    released
    slug
    title
    updatedAt
    coverPhoto {
      url
    }
    content {
      html
    }
  }
}
`;

export async function getStaticProps(){
  const {articles} = await graphcms.request(QUERY);
  return {
    props: {
      articles,
    },
    revalidate: 10,
  }
}

export default function Home({articles}) {
  return (
    <main className={styles.main}>
      {articles.map((article) => (
        <h1>{article.title}</h1>
      ))}
    </main>
  )
}

Any help on this issue would be much appreciated.

Generating a Java file using Typescript

I was trying to see if I can generate a .java file using Typescript. I stumbled this code in TS:

class MyClass {
  public name: string;
  public age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

In which, when you execute it with this command:

tsc -out myJavaFile.java myTypeScriptFile.ts

Should generate a myJavaFile.java file that looks like this:

public class MyClass {
  private name: string;
  private age: number;

  public MyClass(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public getName(): string {
    return this.name;
  }

  public setAge(age: number) {
    this.age = age;
  }

  public getAge(): number {
    return this.age;
  }
}

However, when I tried doing it on my end, this is what is generating:

var MyClass = /** @class */ (function () {
    function MyClass(name, age) {
        this.name = name;
        this.age = age;
    }
    return MyClass;
}());

Why is my event handler firing twice even after using stopPropagation and preventDefault in Javascript and HTML?

My event handler is firing twice and I can’t figure out why.

As you can see in my code below, I’ve tried stopPropagation (even though from what I’ve read that would has to do with other event listeners that I don’t have in my code), preventDefault, and double checking that the event isn’t listening to the other handlers (‘if e.target.id !==’) but the console.log still gives me two outputs each click.

let activePlayer;
const pname = document.getElementById("pname");
const p1 = document.getElementById("playerOne");
const p2 = document.getElementById("playerTwo");
const submit = document.getElementById("psubmit");
const p1name = document.getElementById("playerOne");
const p2name = document.getElementById("playerTwo");

const addPlayer = () => {
  if (players.length === 2) {
    submit.textContent = "Game's Full";
    return;
  } else if (players.length === 0) {
    submit.classList.remove("alert");
    players.push(makePlayer(pname.value, "X"));
  } else {
    players.push(makePlayer(pname.value, "O"));
    activePlayer = players[Math.floor(Math.random() * 2)];
    if (activePlayer === players[0]) {
      p1.classList.add("alert");
    } else {
      p2.classList.add("alert");
    }
  }
};

submit.addEventListener("click", (e) => {
  e.stopPropagation();
  e.preventDefault();
  // addPlayer();
  if (e.target.id !== "psubmit") return;
  /*
  if (players.length === 1) {
    p1name.textContent = `${players[0].name}`;
  } else if (players.length === 2) {
    p2name.textContent = `${players[1].name}`;
  }
  */
  console.log(activePlayer);
});
<div class="header">
  <form action="" method="get">
    <input type="text" name="pname" id="pname" placeholder="Name" />
    <button type="submit" id="psubmit" class="thisguy">Join the Game</button>
    <button type="button" id="newGame">New Game</button>
    </div>
  </form>
</div>
<div class="main">
  <div class="player1">
    <div id="playerOne">XXX</div>
    <div id="p1name"></div>
    <div id="p1winner">
      <p id="p1announcement"></p>
      <p id="Xwins">X wins: 0</p>
    </div>
  </div>
  <div id="game">
    <div id="gameboard"></div>
  </div>
  <div class="player2">
    <div id="playerTwo">OOO</div>
    <div id="p2name"></div>
    <div id="p2winner">
      <p id="p2announcement"></p>
      <p id="Owins">0 wins: 0</p>
    </div>
  </div>
</div>

Why does error message created by JS dorm validation function disappear after a short time in my html site

Why does error message created by JS dorm validation function disappear after a short time in my html site

i have a website with a registration page in which when you click the “submit” button a JS function validates all of the needed fields if a certein field is invalid it an error massage is spoused to appear and stay until the client change it , but in reality it appears for like half a second and then dissapears .

the html file is also connected to a C# page which uploads the indormation to the server , for the JS and C# not to clash i use a “onsubmit” function.

JS code :

function RegisterVerification() {
    let uName = document.getElementById("uName").value;
    let fName = document.getElementById("fName").value;
    let lName = document.getElementById("lName").value;
    let passwd = document.getElementById("passwd").value;
    let email = document.getElementById("email").value;
    let phone = document.getElementById("phone").value;


    var isValid = true;

    if (containsNumbers(fName) == true || fName.length < 2 || containsSpecialChars(fName) == true) {
        document.getElementById("fNameErorr").innerHTML = "first name invalid"
        isValid = false;
    }

    if (containsNumbers(lName) == true || lName.length < 3 || containsSpecialChars(lName) == true) {
        document.getElementById("lNameErorr").innerHTML = "last name invalid"
        isValid = false;
    }

    if (uName.length < 5 || containsNumbers(uName) == false) {
        document.getElementById("uNameErorr").innerHTML = "username invalid"
        isValid = false;
    }

    if (containsNumbers(passwd) == false || passwd.length < 8 || containsSpecialChars(passwd) == false) {
        document.getElementById("passwdErorr").innerHTML = "password invalid "
        isValid = false;
    }

    if (ValidateEmail(email) == false) {
        document.getElementById("emailErorr").innerHTML = "email invalid"
        isValid = false;
    }

    if (phoneRegex(phone) == false) {
        document.getElementById("phoneErorr").innerHTML = "email invalid"
        isValid = false;
    }


    return (isValid)

}

relevant html code :

<form id="mainform" runat="server"  onsubmit="return RegisterVerification()">

        <label class="tabletext" for="uName">User name</label>
        <input type="text" id="uName" name="uName" />
        <h4 class="erorr" id="uNameErorr"></h4>

        <label class="tabletext" for="passwd">Password</label>
        <input type="text" id="passwd" name="passwd" />
        <h4 class="erorr" id="passwdErorr"></h4>

        <label class="tabletext" for="lName">Last name</label>
        <input type="text" id="lName" name="lName" />
        <h4 class="erorr" id="lNameErorr"></h4>

        <label class="tabletext" for="fName">First name</label>
        <input type="text" id="fName" name="fName" />
        <h4 class="erorr" id="fNameErorr"></h4>


        <label class="tabletext" for="phone">Phone Number</label>
        <input type="text" id="phone" name="phone" />
        <h4 class="erorr" id="phoneErorr"></h4>

        <label class="tabletext" for="email">Email</label>
        <input type="text" id="email"  name="email" />
        <h4 class="erorr" id="emailErorr"></h4>


        <input id="registerbutton" type="submit" name="send"  />


    </form>

Canvas resolution and export resolution

I have canvas which is width=”600px” and height=”500px”.

then I show the image(1200px and 1000px) on this canvas

ctx.drawImage(img,600,500);

finally export with this script.

var a = document.createElement('a');
a.href = mycanvas.current.toDataURL('image/jpeg', 0.85);

In this case jpg’s final resolution is 600px x 500px.

However I want to keep final resolution 1200 x 1000 jpg.

What is the best practice for this purpose.

problem when show data in in Table and update it

I have a website that displays data in a dashboard format. The data is obtained from a server using a GET request. The server returns data in the following format:


 {
            "id": 3,
            "image_center": "uploaded_files/images/SYLTK/syltk-right.jpg",
            "image_left": "uploaded_files/images/SYLTK/syltk-left.jpg",
            "image_right": "uploaded_files/images/SYLTK/syltk-middle.jpg",
            "long": "35º 32’ 00” شمالا",
            "lat": "35º 45’ 00” شرقا",
            "mobile_number": "+961 41 476 452",
            "email": "[email protected]",
            "website": "http://lattakiaport.gov.sy/",
            "vessel_max_length": "240 m - 350 m",
            "vessel_max_deadweight": "50000 t.",
            "container_vessel_max_load": "4000 teus",
            "vessels_on_the_wave_breaker": "12 - 15",
            "vessels_received_simultaneously": "15",
            "container_vessels_pier": "{"min":"12.5 m","max":"12.0 m"}",
            "bulk_vessels_pier": "{"min":"11.5 m","max":"11.0 m"}",
            "harbor_basin": "{"min":"13.5 m","max":"12.0 m"}",
            "container_vessel": "{"Pier 12 + 12A":"360 m","Pier 14 - 15":"450 m"}",
            "bulk_vessel": "{"Silo Pier":"180 m","Kahaleh 1-4":"600 m","Passenger":"240 m","Pier 7 - 8 - 9":"525 m","Pier 10 - 11":"350 m"}",
            "lang": "ar",
            "created_at": "2023-05-27T07:37:10.000000Z",
            "updated_at": "2023-05-27T07:37:10.000000Z"
        }

I Need to show data in Table in dashbord and edit it , the data show in this website http://ocean.menumizeme.com/backup/syltk.php
my problem in table I can’t show it and edit

const React = require("react");
const { useContext, useEffect, useState } = require("react");
import { Button, Card, CardImage, Modal, ModalBody, ModalHeader, ModalFooter, Input } from "@themesberg/react-bootstrap";
import ReactDOM from 'react-dom';
import { CartProvider } from 'snappet';


const Syltk = () => {
  const [loading, setLoading] = React.useState(true);
  const [postData, setPostData] = React.useState([]);
  const [currentLang, setCurrentLang] = React.useState("it");
  const [selectedImage, setSelectedImage] = React.useState("");
  const [isImageSelected, setIsImageSelected] = React.useState(false);
  const [editingField, setEditingField] = React.useState("");
  const [editModalOpen, setEditModalOpen] = React.useState(false);
  const [editValue, setEditValue] = React.useState("");
  const authCtx = React.useContext(AuthContext);
  ////const token = authCtx.token;

  ////function fetch data
  const fetchData = async () => {
    try {
      const { data } = await axios.get(`${BASE_URL}/api/syltk`);
      setPostData(data);
      setLoading(false);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // useEffect(() => {
  //   const initialEditValues = data.map(() => "");
  //   setEditValues(initialEditValues);
  // }, [data]);

  const items = postData?.data;

  const handleLangChange = (lang) => {
    setCurrentLang(lang);
  };

  const filteredItems = items?.filter((item) => item.lang === currentLang);

  const handleModalOpen = (field, value) => {
    setEditingField(field);
    setEditValue(value);
    setEditModalOpen(true);
    if (
      field === "image_left" ||
      field === "image_center" ||
      field === "image_right"
    ) {
      setIsImageSelected(true);
    } else {
      setIsImageSelected(false);
    }
    // setIsOutsideClickDisabled(true);
  };

  const handleFileSelectUpdate = (e) => {
    setSelectedImage(e.target.files[0]);
    setIsImageSelected(true);
  };

  const handleUpdate = async () => {
    try {
      const updatedItem = {
        ...filteredItems[0],
        ...editValue,
      };

      const formData = new FormData();

      if (
        editingField === "image_left" ||
        editingField === "image_center" ||
        editingField === "image_right"
      ) {
        formData.append(editingField, selectedImage);
      } else {
        formData.append(editingField, editValue);
      }
      console.log(updatedItem);

      // await axios.post(`${BASE_URL}/api/syltk/${updatedItem.id}`, formData, {
      //   headers: {
      //     Authorization: `Bearer ${token}`,
      //     "Content-Type": "multipart/form-data",
      //     "X-localization": currentLang,
      //   },
      // });

      await fetchData();

      setEditModalOpen(false);
    } catch (error) {
      console.error("Error updating data:", error);
    }
  };

  const additionalDataFields = [
    {
      label: "Longitude",
      field: "long",
      buttonText: "Edit Longitude",
    },
    {
      label: "Latitude",
      field: "lat",
      buttonText: "Edit Latitude",
    },
    {
      label: "Mobile Number",
      field: "mobile_number",
      buttonText: "Edit Mobile Number",
    },
    {
      label: "Email",
      field: "email",
      buttonText: "Edit Email",
    },
    {
      label: "Website",
      field: "website",
      buttonText: "Edit Website",
    },
  ];

  const dataColumns1 = [
    "vessel_max_length",
    "vessel_max_deadweight",
    "container_vessel_max_load",
    "vessels_on_the_wave_breaker",
    "vessels_received_simultaneously",
  ];

  const dataColumns2 = [
    "container_vessels_pier",
    "bulk_vessels_pier",
    "harbor_basin",
  ];
  const dataColumns3 = ["container_vessel", "bulk_vessel"];

  const data = (filteredItems ?? []).map((item) => {
    const rowData = {};
    dataColumns1.forEach((column) => {
      rowData[column] = item[column];
    });
    return rowData;
  });

  const data2 = (filteredItems ?? []).map((item) => {
    const rowData = {};
    dataColumns2.forEach((column) => {
      rowData[column] = JSON.parse(item[column].replace(/'/g, '"'));
    });
    return rowData;
  });

  // Example usage of the EditableTable component with the dummy data
  return (
    <>
      <div
        className={`card-items-container ${
          currentLang === "ar" ? "text-end" : "text-start"
        } col text-center`}
      >
        <div className=" m-3">
          <MDBBtn className="  m-3" onClick={() => handleLangChange("en")}>
            English
          </MDBBtn>
          <MDBBtn className=" m-3" onClick={() => handleLangChange("it")}>
            Italy
          </MDBBtn>
          <MDBBtn className=" m-3" onClick={() => handleLangChange("ar")}>
            Arabic
          </MDBBtn>
        </div>
        {loading ? (
          <div>Loading...</div>
        ) : (
          filteredItems &&
          filteredItems.map((item, index) => (
            <React.Fragment key={index}>
              <MDBCard className="p-4">
                <div className="row">
                  <div className="col">
                    <div className="image-container">
                      {selectedImage && editingField === "image_left" ? (
                        <img
                          className="img-fluid shadow-4"
                          src={URL.createObjectURL(selectedImage)}
                          alt="Selected Image"
                        />
                      ) : (
                        <MDBCardImage
                          className="img-fluid shadow-4"
                          src={`${BASE_URL}/storage/${item.image_left}`}
                          position="top"
                          alt="..."
                        />
                      )}
                      <div className="m-3">
                        <MDBBtn
                          onClick={() =>
                            handleModalOpen("image_left", item.image_left)
                          }
                        >
                          Edit Image Left
                        </MDBBtn>
                      </div>
                    </div>
                  </div>
                  <div className="col">
                    <div className="image-container">
                      {selectedImage && editingField === "image_center" ? (
                        <img
                          className="img-fluid shadow-4"
                          src={URL.createObjectURL(selectedImage)}
                          alt="Selected Image"
                        />
                      ) : (
                        <MDBCardImage
                          className="img-fluid shadow-4"
                          src={`${BASE_URL}/storage/${item.image_center}`}
                          position="top"
                          alt="..."
                        />
                      )}
                      <div className="m-3">
                        <MDBBtn
                          onClick={() =>
                            handleModalOpen("image_center", item.image_center)
                          }
                        >
                          Edit Image Center
                        </MDBBtn>
                      </div>
                    </div>
                  </div>
                  <div className="col">
                    <div className="image-container">
                      {selectedImage && editingField === "image_right" ? (
                        <img
                          className="img-fluid shadow-4"
                          src={URL.createObjectURL(selectedImage)}
                          alt="Selected Image"
                        />
                      ) : (
                        <MDBCardImage
                          className="img-fluid shadow-4"
                          src={`${BASE_URL}/storage/${item.image_right}`}
                          position="top"
                          alt="..."
                        />
                      )}
                      <div className="m-3">
                        <MDBBtn
                          onClick={() =>
                            handleModalOpen("image_right", item.image_right)
                          }
                        >
                          Edit Image Right
                        </MDBBtn>
                      </div>
                    </div>
                  </div>
                </div>
              </MDBCard>
              {/* Additional data */}
              <div className="row m-2">
                {additionalDataFields.map((dataField) => (
                  <div className="col-md-4 mb-4" key={dataField.field}>
                    <MDBCard className="mt-3">
                      <div className="m-3">
                        <p>
                          {dataField.label}: {item[dataField.field]}
                        </p>
                        <div className="m-3">
                          <MDBBtn
                            onClick={() =>
                              handleModalOpen(
                                dataField.field,
                                item[dataField.field]
                              )
                            }
                            color="success"
                          >
                            {dataField.buttonText}
                          </MDBBtn>
                        </div>
                      </div>
                    </MDBCard>
                  </div>
                ))}
              </div>

              {/* start Table sections */}
              {/* Data table 1 */}
              <div className="card">
                <h3 className="card-header text-center font-weight-bold text-uppercase py-4">
                  Editable table
                </h3>
                <div className="card-body">
                  <div className="table-editable">
                    <table className="table table-bordered table-responsive-md table-striped text-center">
                      <thead>
                        <tr>
                          {dataColumns1.map((column) => (
                            <th key={column}>{column}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {data.map((item) => (
                          <tr key={item.id}>
                            {dataColumns1.map((column) => (
                              <td key={column}>
                                {item[column]}
                                <input
                                  type="text"
                                  className="form-control"
                                  onChange={(e) => {
                                    setEditingField(column); // Replace 'field' with 'column'
                                    setEditValue(e.target.value);
                                  }}
                                />
                              </td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                    <MDBBtn color="primary" onClick={handleUpdate}>
                      Save
                    </MDBBtn>
                  </div>
                </div>
              </div>
              {/* Data table  */}
              
              {/* end Table sections   */}
            </React.Fragment>
          ))
        )}

        {/* //Modal Show to update the data */}
        <MDBModal show={editModalOpen} tabIndex="-1">
          <div
            className="custom-modal-container"
            style={{
              backgroundColor: "white",
              marginLeft: "8rem",
              marginRight: "8rem",
              marginTop: "3rem",
              borderRadius: "10px",
            }}
          >
            <MDBModalHeader>Edit</MDBModalHeader>
            <MDBModalBody>
              {!isImageSelected && (
                <MDBInput
                  label="New Value"
                  value={editValue}
                  onChange={(e) => setEditValue(e.target.value)}
                />
              )}
              {isImageSelected && (
                <div className="mt-3">
                  <input type="file" onChange={handleFileSelectUpdate} />
                </div>
              )}
            </MDBModalBody>
            <MDBModalFooter>
              <MDBBtn color="secondary" onClick={() => setEditModalOpen(false)}>
                Cancel
              </MDBBtn>
              <MDBBtn color="primary" onClick={handleUpdate}>
                Save
              </MDBBtn>
            </MDBModalFooter>
          </div>
        </MDBModal>
      </div>
    </>
  );
};


function App() {
  return (
    <CartProvider>
      <main className="p-4">
        <Sytts />
      </main>
    </CartProvider>
  );
}

ReactDOM
  .createRoot(document.getElementById("root"))
.render(<App />)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

I need help all way using not work can any one help me

Unexpected end of input next js while fetching data

I’m trying to fetch data from an API while using next.js. This is how I am fetching it:

export default function getWeatherData() {
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid=${process.env.NEXT_PUBLIC_API_KEY}`;
  fetch(url, {
    method: "GET",
    mode: "no-cors",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      Origin: "http://localhost:3000",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": typeof true,
    },
  })
    .then((response) => response.json())
    .then((data) => console.log(data));
}

When I run this function, I get this error:

Uncaught (in promise) SyntaxError: Unexpected end of input 

I know there are lots of questions on google and stack overflow like this one, and I’ve tried several of them but they don’t seem to work. Any help will be appreciated 🙂

JS fractions for big numbers with no precision lose

Big numbers with fraction support:

I want to perform math operation with no precision loss.
How can I do it using JavaScript?
First I tried decimal.js, but it does not preserve precision as you see in next example:

import {Decimal} from 'decimal.js';
const a1 = new Decimal(1);
const a2 = new Decimal(3);
console.log(a1.div(a2).toFraction()); // should be `1/3` but I get `33333333333333333333/100000000000000000000`

Next I tried fraction.js but it does not work with large numbers, for example:

import Fraction from 'fraction.js';
const n1 = new Fraction("99999999999999999999999999999999999999999999999");
const n2 = new Fraction("99999999999999999999999999999999999999999999990");
console.log(+(n1.sub(n2))) // should be 9, but I get 0

Are there any solutions to work with relative large numbers(lets say same as decimal.js supports) but with high precision(same as fraction.js supports).

I checked out that mathjs uses fraction.js under the hood, so no any advantages for large numbers:

import * as math from "mathjs";
const a1 = math.fraction(math.number("99999999999999999999999999999999999999999999999"))
const a2 = math.fraction(math.number("99999999999999999999999999999999999999999999990"))
console.log(+(math.subtract(a1, a2))) // should be 9 but I get 0

Creating user sign up with Firebase Auth

Imported firebase script code into main.js file and referenced it with “” in the index.html.

    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-app.js";
    import {
    getAuth,
    createUserWithEmailAndPassword,
    } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-auth.js";
    const firebaseConfig = {
    apiKey: "AIzaSyBxTyIjvXXCDWNJTI8-sFjJfVP2UJOXdIA",
    authDomain: "mbconline-c8ae4.firebaseapp.com",
    projectId: "mbconline-c8ae4",
    storageBucket: "mbconline-c8ae4.appspot.com",
    messagingSenderId: "408267091210",
    appId: "1:408267091210:web:c8a1f1eacfd7087b775ef3",
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const submitData = document.querySelector(".submitData");
    submitData.addEventListener("click", (e) => {
    let email = document.getElementById(".email").value;
    let password = document.getElementById(".password").value;

    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      // Signed in
      const user = userCredential.user;
      // ...
      alert("User created successfully!");
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
      // ..
      alert("Registration error!");
    });
    });

There is no alert message when I try submitting the form.I also get this error on the console “main.js:25 Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at main.js:25:12(anonymous) @ main.js:25iframe.js:300 Info: The current domain i”

I’ve followed firebase implementations. But it seems no connection is established at all. Can’t figure what the heck am doing wrong. Can experts out here do me some good..

How can I fix the ‘Cannot read properties of undefined’ error in my vertical function for Project Euler Problem 11?

I am working on Project Euler Problem 11.
Here is the Link

In the problem, I am trying to loop over each number in the grid. For each entry, I am trying to calculate the product of consecutive 4 integers at different direction. My codes are as follows:

function largestGridProduct(arr) {

function horizontal(x,y){
    if(arr[x][y+1]&&arr[x][y+2]&&arr[x][y+3]){
        const product = arr[x][y]*arr[x][y+1]*arr[x][y+2]*arr[x][y+3];
        if(product>greatest){
          greatest = product;
          }
    }
  }

function vertical(x,y){
  if(arr[x+1][y]&&arr[x+2][y]&&arr[x+3][y]){
        const product = arr[x][y]*arr[x+1][y]*arr[x+2][y]*arr[x+3][y];
    if(product>greatest){
          greatest = product;
    }
  } 
}

  let greatest = -1;
  for(let i=0;i<arr.length;i++){
    for(let j=0;j<arr.length;j++){
        horizontal(i,j);
        vertical(i,j);
      }
    }

  return greatest
    
  }

However, I get an error from my vertical function. It is TypeError: Cannot read properties of undefined (reading '0') . I know that the error means an undefined value is accessed at index 0 but I have no idea why it happens.

Is it possible to call MathJax library directly from a folder in my HTML page without internet or third-party installations?

I want to use MathJax on my app’s html ui component which does not support accessing third-party JavaScript libraries by way of a CDN.

I want download the entire code of MathJax, which is available here as .zip file (https://github.com/mathjax/MathJax-src/releases/tag/3.2.2), and then extract it inside my app directory.

I don’t want to use npm to install MathJAx because the app will be distributed to my community so the users are not forced to install MathJax on their machines.

That is, I want my app to render LaTeX equations without internet and independent of any third-party installations. If there is a way to call MathJax library directly from the folder available above in the zip file it will be great.

I tried to insert the following basic HTML page as a hope to show user-defined equations supplied by my app, but I failed 🙁

<!DOCTYPE html>
<html>
<head>
  <title>MathJax Example</title>
  <script src="MathJax-src-3.2.2componentssrctex-chtml/tex-chtml.js" id="MathJax-script" async></script>
</head>
<body>
  <h1>Equation:</h1>
  <div id="equation">
    $$ y = frac{{sin(x^2)}}{{cos(2x)}} $$
  </div>
  <script>
    MathJax.Hub.Queue(["Typeset",MathJax.Hub,"equation"]);
  </script>
</body>
</html>

Any answer or comment will be very helpful to me .. Thank you

I’m trying to make MathJax library functioning in my html page without internet or third-part installation

Finding the nearest point with coordinates in leaflet

I am working on a school project where I have to create a Web Page where I should be able to use leaflet to create a route. I also have a JSON file with some Bike Docks. I need to find the nearest dock from the starting point of my trip and the nearest from the ending point of the route.

This is my code so far:

    <script>
        var map_var = L.map('map_id').setView([40.72730240765651, -73.9939667324035], 16);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map_var);

        var startPosition = L.latLng();
        var endPosition = L.latLng();

        L.Routing.control({
            waypoints: [
                startPosition,
                endPosition,
            ],
            routeWhileDragging: true,
            collapsible: true,
            geocoder: L.Control.Geocoder.nominatim()
        }).addTo(map_var);

        $.getJSON("citybike.json", function (json1) {
            for (var i = 0; i < json1.stationBeanList.length; i++) {
                var place = json1.stationBeanList[i];
                coordinate = [place.latitude, place.longitude];

                /*var marker = L.marker(coordinate);
                marker.addTo(map_var).bindPopup(`<b>${place.stAddress1}</b><br>Status: ${place.statusValue}<br>Bici disponibili: ${place.availableBikes}<br>Docks disponibili: ${place.availableDocks}`);*/
            }

        });
    </script>

My JSON file is like this:

{
    "stationBeanList": [
        {
            "id": 72,
            "stationName": "W 52 St & 11 Ave",
            "availableDocks": 32,
            "totalDocks": 39,
            "latitude": 40.76727216,
            "longitude": -73.99392888,
            "statusValue": "In Service",
            "statusKey": 1,
            "availableBikes": 6,
            "stAddress1": "W 52 St & 11 Ave",
            "stAddress2": "",
            "city": "",
            "postalCode": "",
            "location": "",
            "altitude": "",
            "testStation": false,
            "lastCommunicationTime": null,
            "landMark": ""
        }
}

Thank you for your help!

JavaScript filter function not working on JSON data with population filter criteria

`Dear guys, i am desperately wondering why my filter function does not work while sort function works well.

code is as below,

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

let cities = [];

fetch (endpoint)
.then (jsonout => jsonout.json())
.then(pushdata => cities.push(...pushdata));

let sortgo = cities.sort((a,b) => {
let firstone = a.population;
let nextone = b.population;

firstone > nextone ? -1 : 1;
});

let gofilter = cities.filter(n => n.population > 100000);

with the code above, when i do console.table(sortgo) in browser(f12), it shows cities in the order of population very well.

but when i console.table(gofilter) , it just returns undefined.. seeking for your help on this, thank you.

*attached is how json data looks like.enter image description here

I was trying to filter json data whose population is over 100000.`