MathJax – Supporting $ $ delimeters within HTML – Canvas

I am able to add DOM elements to HTML canvas via the code.

<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!----------------------------- Start Game ------------------->

<style>
#gameCanvas {
  background-color: lightyellow;
}
</style>
<div class="canvasHolder1">
  <div id="eqn1"> $3+3=$<input type="text" id="q1j" />
    </div>
  <div id="eqn2"> 3+2=<input type="text" id="q2j" />
    </div>
  <div id="eqn3"> 5+2=<input type="text" id="q3j" />
    </div>
  <canvas id="gameCanvas" width="600" height="600">Not supported</canvas>
<script type="text/javascript">
var m=1;
var quest=[];
quest[m]= document.getElementById(`q${m}j`);

  var values = [];
  var stage = new createjs.Stage("gameCanvas");
  var obj=[];
  can = document.getElementById("gameCanvas");
function response(){
    alert("New Question");
    document.getElementById(`eqn${m}`).remove();
    m=m+1;
    
    quest[m] = document.getElementById(`q${m}j`);
    quest[m].addEventListener("keyup", enterFunction);
    values[m] = document.getElementById(`q${m}j`);
    obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
    obj[m].x = Math.random()*can.width;
    obj[m].y = 0.5;
    stage.addChild(obj[m]);
}
function startGame() {  
    quest[m].addEventListener("keyup", enterFunction);
    values[m] = document.getElementById(`q${m}j`);
    obj[m] = new createjs.DOMElement(document.getElementById(`eqn${m}`));
    obj[m].x = Math.random()*can.width;
    obj[m].y = 0.5;
    stage.addChild(obj[m]);
    createjs.Ticker.addEventListener("tick", handleTick);
    createjs.Ticker.setFPS(2);
    function handleTick(event){
    drop(m);
    stage.update();
    }
}
 function drop(i){
      obj[i].x += 1;
      obj[i].y +=3;
 }
 function enterFunction(){
  if (event.keyCode === 13 ) {
   document.getElementById("myBtn").click();
   }
 }
</script>
<body onload="startGame();">
    <div >
  <canvas>This browser or document mode doesn't support canvas object.</canvas>
    </div>
</body>
<button id="myBtn" onclick="response()">New Question</button>
</html>

When I teach math, I typically make a worksheet where the delimeters are set to $ $ (i.e. single dollar signs around math equations (see question of the post here). I also attached the code to change the delimeters accordingly below.

<script>
MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\(', '\)']]
  }
};
</script>
<script id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>

Placing the delimeters inside, e.g. the $3+3$ part, messes up the code to the point where it does not work. I do not know if it is jquery or something that isn’t allowing it, but I would really any help to get the $ $ delimeters to respond within div elements in canvas by adding the tiny bit of code above to canvas. I can get them to work if the delimeters are like this (3+3) but I do not want that.

Allowing only one person to create blog entries on the site [closed]

I have created a website for a photographer that has a blog page on the site. I want only that photographer to have permission to create blog entries to the site. Do I need to make a user login that checks if that user (the photographer) has logged into the site and then allow posts to the blog using JavaScript? Do I need backend languages to make this happen (I only am familiar with frontend technology)? Just looking to be pointed in the correct direction.

How retrieve element from 1-dimensional array?

There is an array 8×8:

var tiles: [
    1, 3, 3, 3, 1, 1, 3, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 2, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 2, 1, 1, 1, 1,
    1, 1, 1, 1, 2, 1, 1, 1,
    1, 1, 1, 1, 2, 1, 1, 1,
    1, 1, 1, 0, 0, 1, 1, 1
  ];

How to get element by column, row index, I tried this function from network:

getElement(row, column) {
    var index = row * 8 + column; 
}

But I did not get how does this function work, why we multiply on 8 and plus column?

iFrame embedding: Scrollbar handling

I am running a platform that provides simple forms and simple outputs for a bunch of clients who embed this features in there webpages by iframe. As these forms and outputs tend to grow over common screen heights, the idea is to let the main scrollbar of the embedding webpage also control the scrollbar of the embedded iframe, i.e. if the scrollbar reaches the iframe, the embedding page stops to scroll, but the iframe is scrolled till it reaches its bottom. Afterwards, the embedding page will be continued to be scrolled. Embedding pages and my platform are on different domains.

It is possible for me to include some (perferently vanilla) javascript besides the HTML code for iFrame.

My questions:
1.) Is there a framework to handle control of the scrollable elements? (I have seen such things on a newspaper website, but it isn’t online anymore.)
2.) Am I running into some Cross-Domain same origin policy issues anyway?

Split an array with Start and End times into separate arrays with no overlapping times

Say I have an array such as below, what would the best method be to separate these into individual arrays if the times overlap? I’m using moment but am a bit unsure of how to tackle this.

I know I have to sort the array initially.

data:

const timetable = [
  { class: 'one', start: '2021-11-16T09:00:00', end: '2021-11-16T10:00:00' },
  { class: 'two', start: '2021-11-16T010:00:00', end: '2021-11-16T11:00:00' },
  { class: 'three', start: '2021-11-16T09:00:00', end: '2021-11-16T10:00:00' },
];

expected:

const timetable = [
  [
    { class: 'one', start: '2021-11-16T09:00:00', end: '2021-11-16T10:00:00' },
    { class: 'two', start: '2021-11-16T010:00:00', end: '2021-11-16T11:00:00' },
  ],
  [
    {
      class: 'three',
      start: '2021-11-16T09:00:00',
      end: '2021-11-16T10:00:00',
    },
  ],
];

Express.js Make request from client-side to server-side for a JSON file

I am trying to fetch certain data from the server.

The client-side runs a function from script.js to fetch a JSON file from the server and the server will return back with the config (JSON file) which is stored in the same folder as server.js, being called config.json. So the config can be used in a script.js.

For the server I am using express.
Any help regarding this will be extremely appreciated, thanks.

Jquert – Current element from array

Yo mates, I have a question. Is it possible to get extract working element from array without using a loop?

By working I mean, having some characteristic trait or whatever.

For example:

document.scroll(function(){
  if($('.super_duper_class').working){
    $('.super_duper_class').css('something...');
  }
});

pass JSON Dictionary into html onclick

I would like to write the following variable in the HTML code through JavaScript.

{
  "content": "Hallo Welt, das ist ein Testn",
  "filelength": 1,
  "filename": "a5c12c102bdaed8ee80168cb41606295eaf5512ba04045fac5dd0dc65c2f54f13566090025c05f14cdfdf9b1e39ce835c6f3262a4aedba31f8b6d07ed299b23b",
  "language": "plain",
  "path": "caadaf7ed1f27ea37cbb9157d9c6cff1683cae85244b772c856b660c3609ad32faa0d6997ecaf727c46650443f1a03f63c0f67219f46d10cf5295556579422b6/c6ee9e33cf5c6715a1d148fd73f7318884b41adcb916021e2bc0e800a5c5dd97f5142178f6ae88c8fdd98e1afb0ce4c8d2c54b5f37b30b7da1997bb33b0b8a31/a5c12c102bdaed8ee80168cb41606295eaf5512ba04045fac5dd0dc65c2f54f13566090025c05f14cdfdf9b1e39ce835c6f3262a4aedba31f8b6d07ed299b23b",
  "type": "text"
}

The problem is, when I look at the HTMl code in the browser, it doesn’t show the corresponding variable, it shows

[object Object]

here the code to extend the HTML code

// create the row
let row = "<tr>";

// set the actions
let actions_append = '';
// file
if (value['type'] === 'file') {
    // preview
    if (value['preview_available']) {
        console.log(value["preview"]);
        actions_append += `<td nowrap width="1%">
                                <span data-toggle="tooltip" title="Vorschau" onclick="setPreviewContent(${value['preview']})">
                                    <button onclick="setNames('${value['name']}')" type="button" class="btn btn-link btn-sm"
                                        data-toggle="modal" data-target="#previewModal"><i class="material-icons text-primary">desktop_windows</i>
                                    </button>
                                </span>
                            </td>`
    }
}
// append row to table
$('#fileTableBody').append(row + actions_append + '</tr>')

here the HTML code resulting output

<td width="1%" nowrap="">
<span data-toggle="tooltip" title="Vorschau" onclick="setPreviewContent('[object Object]')">
    <button onclick="setNames('test.txt')" type="button" class="btn btn-link btn-sm"
            data-toggle="modal" data-target="#previewModal"><i class="material-icons text-primary">desktop_windows</i>
    </button>
</span>
</td>

Can anybody help me? I don’t know JavaScript so well.

Is there any best practice for handling timezone in Js and Firebase?

my problem:
I have 1 computer that sends data (also timestamp) to some firebase collection, let׳s say – Las Vegas, Nevada.

When Im trying to fetch data on my firebase functions I get the Timestamp property in GMT.

and my firebase function׳s propose is to return to frontend all Timestamps occur on specific day of the week, eventually I should get 7 days of the week with timestamps on each day.

my problem is to get GMT time and return the time based on clients location/timezone
on each timestamp from the collection so I can show it on a graph on the client side.

the status now: is I get timestamps that occur on Sunday, but I know that nothing happend on Sunday for sure.

no matter what I have tried, nothing helps.. I will be glad for some help 🙂
code below.


/////util functions:
const exposeDayName = (date) => {
  return new Intl.DateTimeFormat('en-US', { weekday: 'long' }).format(date);
}

const fillMissingDays = (countObject) => {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const today = days.indexOf(exposeDayName(new Date()));
  const fullWeekCount = {};

  for (let i = today + 1; i < (days.length + today + 1); i++) {
    const indexDay = i < 7 ? i : i - 7;
    fullWeekCount[days[indexDay]] = countObject[days[indexDay]] ? countObject[days[indexDay]] : 0;
  }
  return fullWeekCount;
}
/////

const getAllWeeklySessionsDividedByDays = async (req, res) => {
  try {
    //function i have tried to solve this problem with no success.
    function convertTZ(date, tzString) {
      return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", { timeZone: tzString }));

    }

    let timezone = req.body.timezone;
    let id = req.body.id;

    const currentDate = new Date();
    const previousWeekDate = new Date(currentDate.getTime() - 6 * 24 * 60 * 60 * 1000);

    const conversationRef = db.collection("conversation");
    const sessionsArr = [];

    const snapshot = await conversationRef
      .where('id', '==', Id)
      .where("timestamp", ">=", previousWeekDate)
      .where("timestamp", "<=", currentDate)
      .get();

    snapshot.forEach(doc => {
      const element = doc.data();
      sessionsArr.push({
        Id: element.id,
        sessionId: element.session_id,
        timestamp: exposeDayName(element.timestamp.toDate())
      });
    });

    const uniqueSessionsArr = [...new Map(sessionsArr.map(v => [JSON.stringify(v), v])).values()];

    const countSessionsPerDay = {};
    uniqueSessionsArr.forEach(session => {
      const day = session.timestamp;
      countSessionsPerDay[day] = countSessionsPerDay[day] ? countSessionsPerDay[day] + 1 : 1;
    });

    const fullWeekSessionsPerDay = fillMissingDays(countSessionsPerDay);

    const result = {
      labels: Object.keys(fullWeekSessionsPerDay),
      datasets: [
        {
          label: "Daily Sessions",
          data: Object.values(fullWeekSessionsPerDay)
        },
      ],
    }

    res.status(200).send(result);
  } catch (err) {
    res.status(400).send(err.message);
  }
}

My Wep Page Show Nothing When i Use Route

Hi Guys i want to create a web page that change pages with Navbars so i want to use bootstrap and react-route-dom to create this but before i use bootstrap its show nothing some kind of errors may occurred that i didn’t see i post my code here i just create one page and used it in App.jsx file but it’s show nothing but when i use home page as in App file’s return function it works pretty much good and its ok i can’t find any error it’s just say’s

No routes matched location “/”

here is my index.jsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/pages/App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App/>,
    rootElement
)
;
reportWebVitals();

and here is the App.jsx file:

import '../../App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import React from "react";
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Home from './home';
import HeaderBar from '../layout/HeaderBar';

function App() {
    return (
        <Router >
            <div>
                <HeaderBar/>
                <Routes>
                    <Route exact path='./pages/home' component ={Home}/>
                </Routes>
            </div>
        </Router>
    );
}

export default App;

And my Home file:

import React from 'react';

const Home = () => {
    return (
        <div className="container">
            <h1 className='display-5 text-uppercase py-5 text-center'>
               Welcome to JavaScript World
            </h1>
        </div>
    );
};

export default Home;

and finally this is my package.json:

{
  "name": "forex_trader",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.0",
    "react-dom": "^17.0.2",
    "react-router-bootstrap": "^0.26.0",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "styled-components": "^5.3.3",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Firebase auth user is null even tho the user is clearly signed in?

Whenever i sign in a user and get redirected to the right component and then reload the browser, i get an error saying “TypeError: Cannot read properties of null (reading ’email’)” because i’m trying to render the logged in user that i can see at first but not after i refresh the page.

Is there anyone who can point out what i’m doing wrong?

My Context


useEffect(() => {
    onAuthStateChanged(auth, (data) => {
      if (data) {
        // User is signed in
        setisSignedIn(true);
        setCurrentUser(data);
        console.log('state = definitely signed in');
        console.log(currentUser);
      } else {
        // User is signed out
        setisSignedIn(false);
        console.log('state = definitely signed out');
      }
    });
  }, [isSignedIn, currentUser]);

Signing in a user

const signInUser = (props: ISignIn) => {
    signInWithEmailAndPassword(auth, props.email, props.password)
      .then((user) => {
        setFirebaseError(false);
        navigate('/swipe');
      })
      .catch((error) => {
        setFirebaseError(true);
        setErrorMsg({ errorMessage: error.message, errorCode: error.code });
        navigate('/');
      });
  };

Using currentUser

import { useAuth } from '../Utils/Contexs/AuthContext';

export const SwipeView = () => {
  const { currentUser, signOutUser } = useAuth();
  return (
    <div>
      <h1>Swipe View</h1>
      <p>The current user logged in: {currentUser.email}</p>
      <button onClick={() => signOutUser()}>Log out</button>
    </div>
  );
};

Console.log’s

Loggin the currentUser img

Console error

error msg on page reload img

Does writing onPress={onPress()} have anything to do with iife?

If I write onPress below, when I click the button, the console will write test. But if I write onPress(), it writes a test on the console as the page renders. Does writing onPress() have anything to do with iife? Is that why it works without being called the moment the page is rendered?

import React from 'react';
import { Button } from 'react-native';

const Screen = () => {

    const onPress = () =>{
        console.log('test')
    }

    return (
        <Button title='button' onPress={onPress()}/>
    )
};

export default Screen;

How can I solve the following error when. when I try to make a connection to mongo I have the following error “TypeError: db.on is not a function”

En el siguiente código:

var mongoose = require('mongoose');

var mongoDB = 'mongodb://localhost/red_bicicletas';
mongoose.connect(mongoDB, {useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.Connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));

TypeError: db.on is not a function

Unable to append element on a list item

I am unable to add a delete button to a list item in my code, pls I need assistance. Below is my code

function addDeleteBtn() {
  const ul = document.querySelector("ul");
  let li = document.querySelectorAll("li");
  let btn = document.createElement("button");
  const text = document.createTextNode("delete");
  btn.appendChild(text);
  for (const item of li) {
    li.append(btn);
  }

  ul.appendChild(li);
}
addDeleteBtn();

Add Cron Job to Function (node.js, express, react, mongodb)

Can you help me with cron function in my app? I’m stuck with it(

Here’s my “track.controller.js” and “server.js” with “multiTrack” function. multiTrack() function starts re-crawling process by users URL’s, it’s starts manually via button in users dashboard, but i want to add cron job to this function (multiTrack).
Imported “multiTrack” function in server.js file return “req is not defined”…
Thank u!

/———–server.js————/

const cron = require('node-cron');
const multiTrackfunc = require('./controllers/track.controller.js');

cron.schedule("*/60 * * * * *", () => {
  try {
    multiTrackfunc.multiTrack(req, res, next);
    console.log(`Re-crawling starts via cron`);
  }
  catch (err) {
    console.log(`${err} - in cron`);
  }
});

/———–server.js————/

/———–track.controller.js————/

const cron = require('node-cron')

exports.multiTrack = async (req, res, next) => {
  try {
    const { userId, createdTracks } = req.body;
    const trackIds = createdTracks.map((createdTrack) => createdTrack._id);

    const user = await User.findById(userId);
    if (!user) {
      return res.status(401).json({
        success: false,
        error: "User does not exist",
      });
    }

    try {
      // loop through each track START
      await new Promise((resolve, reject) => {
        createdTracks.forEach(async (createdTrack) => {
          const existingTrack = await Track.findById(createdTrack._id);
          if (!existingTrack) {
            reject();
          }
          
          // crawl Amazon product
          console.log(`${createdTrack.name} re-crawling starts`);
          const browser = await puppeteer.launch();
          const page = await browser.newPage();

          await page.goto(createdTrack.productUrl, {
            waitUntil: "networkidle2",
          });

          const crawledProduct = await page.evaluate(() => {
            let actualPrice = 0;

            const prepOurPrice = document.querySelector("span.woocommerce-Price-amount.amount").innerText;

            const image = document.querySelector(".woocommerce-product-gallery__image a img").src;
            const ourPrice = parseFloat(prepOurPrice.replace(/[^0-9.-]+/g, ""));
            const salePrice = document.querySelector("#priceblock_saleprice");
            const dealPrice = document.querySelector("#priceblock_dealprice");

            ///parseFloat(actualPrice.replace(/[^0-9.-]+/g, ""))

            if (ourPrice) {
              actualPrice = ourPrice;
            } else if (salePrice) {
              actualPrice = salePrice.innerText;
            } else if (dealPrice) {
              actualPrice = dealPrice.innerText;
            }

            return {
              image,
              actualPrice,
            };
          });
          console.log(`${createdTrack.name} re-crawling ends`);
          await browser.close();

          const { image, actualPrice } = crawledProduct;

          if (existingTrack.image !== image) {
            existingTrack.image = image;
            await existingTrack.save();
          }

          if (existingTrack.actualPrice !== actualPrice) {
            existingTrack.actualPrice = actualPrice;
            await existingTrack.save();
          }

          resolve();
        });
      });
      // loop through each track END
    } catch {
      return res.status(401).json({
        success: false,
        error: "Found invalid track id",
      });
    }

    const tracks = await Track.find({ _id: { $in: trackIds } });

    return res.status(201).json({
      success: true,
      data: tracks,
    });
  } catch (err) {
    console.log("crawling failed");
    return res.status(500).json({ error: err.message });
  }
};

/———–track.controller.js————/