How to replace all blank space with &nbsp while ignoring html tags

I was replacing all of the spaces in a div element with   so I could easily read all the spaces with a JavaScript file. When I was coding this I realized the elements inside the div would get messed up because properties like ids requires spaces between the tag name and the property would get replaced breaking the tag. How could I ignore the space in between the tag and the name and only replace the text spaces.

Code:

let el = document.getElementById('parent');

function replaceText() {
  let text = el.innerHTML.split(' ').join(' ');
  el.innerHTML = text;
  console.log(text);
}
//I dont want the span tag or em tag to get messed up by this
<!DOCTYPE html>
<html>
  <body>
    <div id='parent'>
      Lorem ipsum 
      <span id='element'>
        <em id='child'>dolor sit amet</em>
      </span>
    </div>
    <button onclick='replaceText()'>Change with nbsp</button>
   </body>
</html>

JS, filter datatables in header

Currently I have filter in footer of table(tfoot), I want it moved to header and I can’t resolve this issues.

$('.input-col').each( function () {
            var title = $(this).text();
            if (!$(this).hasClass('skip')) {
                $(this).html( '<input class="form-control form-control-sm" type="text" placeholder="'+ title + '" />' );
            }
        } );
        $('#dt').DataTable( {
            /* Started column */
            "order": [[ 9, "desc" ]],
            "pageLength": 10,
            "lengthMenu": [10, 15, 20, 25, 30, 35, 50],
            "lengthChange": true,
            "searching": true,
            "paging":   true,

            stateSave: true,
            initComplete: function () {
                // Apply the search
                this.api().columns().every( function () {
                    var that = this;
                    $( 'input' ).val(that.search()).on( 'keyup change clear', function () {
                        if ( that.search() !== this.value ) {
                            that
                                .search( this.value )
                                .draw();
                        }
                    } );
                } );
            }

On line: $( ‘input’ ).val(that.search()).on( ‘keyup change clear’, function ()
before it was $( ‘input’ , this.footer())…., I tried with this.header() but it doesn’t work as expected. Datatable is in form of:

<div class="table-responsive">
            <table id="dt" class="table table-striped table-sm">
                <thead class="thead-light">
                    <tr>
                        <th class="input-col skip" scope="col" style="width:3%"></th>
                        <th class="input-col skip" scope="col" style="width:3%"></th>
                        <th class="input-col skip" scope="col" style="width:3%"></th>
                    </tr>
                </thead>
...

DateTime difference in google charts data visualization

I have an dataTable in google charts and I need to compare the last two columns which are Date and create another column for time duration. Wondering if there is anyway to do this using google charts. I tried sending Math.abs('Date(2022,04,13,15,54,41) - Date(2022,04,13,16,15,35)'] as data . Should i just use pure javascript to do that?

['15:45 10202', 'Waiting', 'color:#0560bd', 'Date(2022,04,13,15,54,41)', 'Date(2022,04,13,16,15,35)']
['15:45 10202', 'Imaging', 'color:#ec9332', 'Date(2022,04,13,16,20,43)', 'Date(2022,04,13,16,25,47)']
['15:45 10202', 'Treatment', 'color:#c44129', 'Date(2022,04,13,16,25,47)', 'Date(2022,04,13,16,28,30)']
['15:45 10202', 'UnusedImaging', 'color:#ecc432', 'Date(2022,04,13,16,15,35)', 'Date(2022,04,13,16,16,12)']

where the labels are:

[{type: 'string', label: 'Task Name'}, {type: 'string', label:'Resource'} , { type:'string', role: 'style', label: 'Color' }, {type: 'datetime', label: 'Start Time'}, {type: 'datetime', label: 'End Time'}]

JS is printing a day before from date instead of correct day [duplicate]

I’m using Javascript lang and I have a date brought from database which value returns 2022-02-20T00:00:00.000Z. Then I made a function that parse these informations to a readable string value.

export const convertDateToReadable = (date) => {
  if (!date) return null
  let nd = new Date(date)
  let day = nd.getDate().toString().padStart(2, "0")
  let month = (nd.getMonth()+1).toString().padStart(2, "0")
  let year = nd.getFullYear().toString()
  let stringfyd = `${day}/${month}/${year}`
  return stringfyd
}

The expected value to be returned should be "20/02/2022" but instead it’s returning "19/02/2022". The same thing is happening to other dates which passes through this function.

It could be possible to solve the problem by adding 1 on .getDate() but I feel that it would not solve for long.

How do I proceed to get the correct “stringfied” date?

Why useEffect is working twice even if I change the data?

I try to call a method in service class from MainPanel with useEffect hook:

Here is my MainPannel:

function MainPanel() {

  const [customers, setCustomers] = useState([]);
  

  useEffect(() => {
    const getCustomers = async () => {
      const customers = await getCustomerList();
      setCustomers({ customers });
      console.log(customers)
    };
    getCustomers()
  }, []);

  return (
    <div className="App">
      {/* do something */}

    </div>
  );
}

export default MainPanel;

And here is the service method that I called from useEffect:

export async function getCustomerList() {

    axios.get("http://localhost:8080/customer", { params: { id: 1 } })
    .then(response => console.log(response.data))
}

In this scenario useEffect is working but working twice and console.log is printing twice (2 times log correct value and 2 times undefined).

If I just get the data with return statement instead of printing to console like

export async function getCustomerList() {

    axios.get("http://localhost:8080/customer", { params: { id: 1 } })
    .then(response => {return response.data})
}

Same thing happening but this time response is coming as undefined. I know they are separate problems but I just need to understand a proper way of fetching data and use it in useEffect only once.

How can I achieve it ?

Using Remark and Rehype plugins with MDX in Next.js (with @next/mdx)

I was trying to use Github Flavored Markdown using @next/mdx but I can’t seem to figure out how to use plugins with the code. Here is what I did:

(I am following along from Next.js Documentation: https://nextjs.org/docs/advanced-features/using-mdx)


Initializing the Application

1. I created the Next.js App using the command

yarn create next-app next-gfm

2. I then added the required modules to the

yarn add @next/mdx @mdx-js/loader

3. In the pages/ directory, I deleted the index.js file that was auto generated and replaced it using a index.mdx file.

From here, I used the following configuration for my next.config.js file.

const withMDX = require('@next/mdx')({
  extension: /.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
  },
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})

If we run the code using yarn dev everything works fine so far.

Adding GFM

Here is where the main issue is. I now installed the following packages to use Github Flavored Markdown using the command:

yarn add remark-gfm rehype-stringify

Import Syntax Error?

I tried to import the modules in the next.config.js using the syntax

import remarkGfm from 'remark-gfm'

But this gives me the following error:

import remarkGfm from 'remark-gfm'
^^^^^^

SyntaxError: Cannot use import statement outside a module

Making the project a module

I have also tried adding the following line at the top of my package.json

"type" : "module",

But this seems to conflict with the require syntax that is being used to import @next/mdx:

const withMDX = require('@next/mdx')({
...

This gave me the error:

Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Using older import() syntax

I did a bit of searching online, and found the import() syntax. I attempted to do this and my next.config.js now looked like:

const remarkGfm  = import('remark-gfm');
const remarkParse  = import('remark-parse')
const remarkRehype  = import('remark-rehype')
const rehypeStringify  = import('rehype-stringify')

const withMDX = require('@next/mdx')({
  extension: /.mdx?$/,
  options: {
    remarkPlugins: [remarkGfm, remarkParse, remarkRehype],
    rehypePlugins: [rehypeStringify],
  },
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})

I tried running this, using the yarn dev and everything works, except that none of the markdown plugins are functioning at all. (The base markdown is working but if I try using footnotes, or tables it is rendered as plain text).

Could anyone explain how one might proceed using external plugins (e.g Github Flavored Markdown) with MDX and Next.js (using the @next/mdx package)?

Reference

This is my complete project structure and (relevant) files:

next-gfm
  |_ pages
       |_ index.md
  |_ package.json
  |_ next.config.js

Files

index.md

# GFM

## Autolink literals

www.example.com, https://example.com, and [email protected].

## Footnote

A note[^1]

[^1]: Big note.

## Strikethrough

~one~ or ~~two~~ tildes.

## Table

| a | b  |  c |  d  |
| - | :- | -: | :-: |

## Tasklist

* [ ] to do
* [x] done

package.json

{
  "name": "next-mdx-template",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@mdx-js/loader": "^2.1.1",
    "@next/mdx": "^12.1.5",
    "next": "12.1.5",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "rehype-katex": "^6.0.2",
    "rehype-stringify": "^9.0.3",
    "remark-gfm": "^3.0.1",
    "remark-math": "^5.1.1",
    "remark-mdx": "^2.1.1"
  },
  "devDependencies": {
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5"
  }
}

next.config.js

const remarkGfm  = import('remark-gfm');
const remarkParse  = import('remark-parse')
const remarkRehype  = import('remark-rehype')
const rehypeStringify  = import('rehype-stringify')

const withMDX = require('@next/mdx')({
  extension: /.mdx?$/,
  options: {
    remarkPlugins: [remarkGfm, remarkParse, remarkRehype],
    rehypePlugins: [rehypeStringify],
  },
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
})

making one circle from many lat long on google maps react js

I have data like this. I want to draw one circle on google map with those data.

[
    {
        "id": 1,
        "name": "Park Slope",
        "latitude": "40.6710729",
        "longitude": "-73.9988001"
    },
    {
        "id": 2,
        "name": "Bushwick",
        "latitude": "40.6942861",
        "longitude": "-73.9389312"
    },
    {
        "id": 3,
        "name": "East New York",
        "latitude": "40.6577799",
        "longitude": "-73.9147716"
    }
]

]

Why is the onclick event running 2 different functions

I am trying to run a function by clicking Modify2 or Edit2 in the code.
It runs all the time the function defined with onClick and then showCard again

  1. List section loads
  2. Select an entry of the list, it will run showCard and loads the item.
  3. Clicking on Edit2 or Modify2 triggers showConn and right away showCard again

It should just trigger showConn !

And why is it running showCard right after showConn?

Thanks for any suggestions.

The Code:

import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';

function App() {
  const [list, setList] = useState(true);
  const [card, setCard] = useState(false);
  const [netconn, setNetconn] = useState(false);
  const [networks, setNetworks] = useState([]);
  const [network, setNetwork] = useState({});

  useEffect(() => {
    fetch(window.location.protocol+"//"+window.location.hostname+":3001/networks/list")
      .then((response) => response.json())
      .then((responseJson) => {
        setNetworks(responseJson.data);
      });
  }, []);

  let showCard = (id) => {
    console.log( "Show Card");
    fetch(window.location.protocol+`//`+window.location.hostname+`:3001/networks/${id}`)
      .then((response) => response.json())
      .then((responseJson) => {
        setNetwork(responseJson.data);
        setList(false);
        setNetconn(false);
        setCard(true);
      });
  };
  
  let showConn = (id) => {
    console.log( "Show Connection");
    setList(false);
    setCard(false);
    setNetconn(true);
  };
  let showList = () => {
    setCard(false);
    setNetconn(false);
    setList(true);
  };
  const handleSubmit = (event) => {
    event.preventDefault();
  }
  const handleGetconn = (event,id) => {
    event.preventDefault();
    alert(id);
    showConn(id)
  }
  return (
    <div className="container">
      {netconn ? (
        <div className="row">
          <div className="col-auto">
            <div
              onClick={showCard(network._id)} 
              className="btn btn-primary">Submit</div> 
            <div 
              onClick={showList()}
              className="btn btn-default">Cancel</div>
          </div>
        </div>
      ) : null}
      {list ? (
        <div className="list-group">
          {networks.map((network) => (
            <li
              key={network._id}
              onClick={() => showCard(network._id)}
              className="list-group-item list-group-item-action">
              {network.name}
            </li>
          ))}
        </div>
      ) : null}
      {card ? (
        <div className="row">
          <div className="col-auto">
            <div 
              onClick={(e) => handleGetconn(e,network._id)} 
              className="btn btn-success">
              Modify2
            </div>
            <div onClick={() => showConn(network._id)} className="btn btn-primary">
              Edit2
            </div>
            <div onClick={() => showList()} className="btn btn-default">
              Back
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

export default App;

How do I have a sprite in a group have the same position as another sprite not in a group upon collision?

In p5.js, I am having trouble with having sprites in a group locking onto the same position as the player sprite upon collision.

function draw () {
   traySprite.collide(toppingsGroup, toppingsTouch)
}
function toppingsTouch(player, topping) {
   topping.position.x = traySprite.position.x;
   topping.position.y = traySprite.position.y;
   topping.velocity.x = 0;
}

toppingsGroup includes five different sprites, and I want to have it so that when one of the sprites collides with traySprite, that singular sprite from the group locks onto the same position as traySprite, without affecting any of the other sprites in that group. This should apply to all of them, but the issue I am having is that once one of the sprites collides with traySprite, it quickly but visibly phases out of the canvas.

Javascript event listeners/variable passing in separate files

I am completely new to javascript and am struggling with this. I am trying to get a token out of this front end and into my python script. Any help is super appreciated.

I have index.html and index.js. Users click a button to use a SSO and login. The token is then stored in a global variable in index.js. I also have server.js which is listening.

I have successfully been able to write a JSON file from server.js, but I can not figure out how to wait until the login is successfully completed and then pass the token string from index.js to server.js. Can anyone help me figure out what to do? Thanks in advance.

//index.js
document.getElementById('login-btn').addEventListener('click', () => {
      /***
        Returns a promise which resolves with a usertoken when a user successfully authenticates and authorizes
      ***/
      token.authorize().then(UserToken => {
        console.log(`Authorized, user-token: ${UserToken}`); ## This line is not printing in console.
      });
    });

    // expose our instance globally for testing
    window.token = token; ##this is the string I want to pass to server.js

I know that the authorization works as I’m able to use other functionality in the front-end, I just can’t figure out how to wait for the token to be generated and then pass it from index.js to server.js

SQL/MariaDB timestamp to Javascript returns empty object `{}`

I have a MariaDB table contact that has a field added_at of type timestamp.

The client device makes a request to a cloud function to return some rows in the table. The cloud function is written in TypeScript with TypeORM.

return connection.createQueryBuilder()
    .select('id, uid, contact, name, added_at')
    .from(ContactEntity, 'contact')
    .where('uid = :uid', { uid })
    .orderBy('name', 'ASC')
    .execute();

The appropriate rows are sent back to the client with the correct data. However, added_at is returned as {} (when console.loged on the client device.

Is there any solution to return the timestamp as a physical date object or something parsable back into a date? It only returns {}.

Additional information:
The added_at field in the ContactEntity for TypeORM is as follows:

@Column({type: 'timestamp'})
last_interaction: Date;

How to check if a twilio token is expired

I have a nextjs project and I need to verify if a twilio token is expired or not.

I thought about using the library jwt-decode to decode the token and take the exp attribute from it, then compare it to the actual date. The problem is that the exp date seems to be broken because it is always in 1970.

For example I have just created this token:

{
  "jti": "SKbec4a565d0598f1e4130f65db51a8345-xxxxxxxxxx",
  "grants": {
    "identity": "618f7ef057c2923be10dfd1d",
    "chat": {
      "service_sid": "ISbffc1a6c2f8647ac8a6774xxxxxxxxxx"
    }
  },
  "iat": 1649879042,
  "exp": 1649882642,
  "iss": "SKbec4a565d0598f1e4130f6xxxxxxxxxx",
  "sub": "AC1d09a2edee3f481fbd1dafxxxxxxxxxx"
}

If I do new Date(1649882642) it comes out to be 1970-01-20T02:18:02.642Z. Always.

Maybe should I specify the token expiration when I create it? I created it following the official doc. So what should I do in order to determinate if a token is valid or not?

Export a boolean value with react hook

I have this hook and I need export a const with an boolean value, this way is sending a string.

export const useType = () => {
  
    const isFoo = 'string';
    const isBar = 'other_string';
  
    return { isFoo, isBar };
  };

How can I transform this in an boolean value?

I’m new, Thanks if anyone can help me