cut string after certain number of words javascript

I want to cut this paragraph after certain number of words, not characters

const Text = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you"

For instance: if i do

Text.substring(0,50)

the output will be

'But I must explain to you how all this mistaken id'

the word “idea” is cut and is not what I want, i want the whole word and then maybe add ” . . . “

example
‘But I must explain to you how all this mistaken idea . . .’

Module parse failed: Unexpected token (5:7) (Additional Loader?)

I’m having some issues with this error that’s a pain in the, well. you know.

Module parse failed: Unexpected token (5:7)
File was processed with these loaders:
 * ./node_modules/react-hot-loader/webpack.js
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| };
|
> export about from './about';
| export authenticator from './authenticator';
| export classroom from './classroom';
 @ ./js/store/configure-store.development.js 20:0-42 36:60-68
 @ ./js/store/configure-store.js 8:12-69
 @ ./js/index.js 20:0-53 54:12-26

is my stack trace, I can’t figure out exactly what is wrong but it’s becoming tiresome I’m not sure at all where or what is going wrong here, below is my webpack config.

Maybe something stands out to you that doesn’t stand out to me.

I’m trying to port an webapp to the ~latest everything, or as closely as possible.

Why would I get the above error, I also have another post here with other errors that are somewhat releated, however I seem to have at least caused the error to stop popping up by removing the “require(“path/to/thing”)”…. which I’m sure is going to cause issues down the road.

// Load dependencies
const webpack = require('webpack');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const mainPackageJson = require('./../package.json');

// File locations
const PATHS = {
    js: path.resolve(__dirname, '../js'),
    dist: path.resolve(__dirname, '../dist'),
    modules: [
        path.resolve(__dirname, '../node_modules/cleave.js')
    ]
};

exports = module.exports = {
    mode: 'development',
    entry: [
        'babel-polyfill',
        'webpack-dev-server/client?http://localhost:3457',
        'webpack/hot/only-dev-server',
        './js/index'
    ],

    output: {
        path: PATHS.dist,
        filename: '[name].js',
        publicPath: '/dist'
    },

    resolve: {
        extensions: ['.js', '.jsx']
    },

    devtool: 'eval-source-map',

    optimization: {
        runtimeChunk: "single",
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\/]node_modules[\/]/,
                    name: "vendor",
                    filename: "vendor.js",
                    chunks: "all"
                }
            }
        }
    },
    plugins: [

        // new config.optimization.splitChunks({name: 'vendor', filename: 'vendor.js'}),
        // new webpack.HotModuleReplacementPlugin(),
        // new webpack.NoEmitOnErrorsPlugin(),
        new webpack.DefinePlugin({
            __CONTENT__: JSON.stringify('#content'),
            __DEV__: true,
            __NOOP__: function () {
            },
            __VERSION__: JSON.stringify(mainPackageJson.version)
        }),
        new CopyPlugin({
                patterns: [{
                    from: path.resolve(__dirname, '..', 'conf.js'),
                    to: 'conf.js'
                }]
            }
        ),
        new MiniCssExtractPlugin({
            filename: '[name].css'
        })
    ],

    module: {
        noParse: /node_modules/quill/dist/quill.js/,
        rules: [
            {
                test: /.gif$/,
                loader: 'url-loader',
                options: {
                    mimetype: 'image/png'
                }
            },
            {
                test: /.woff(2)?(?v=[0-9].[0-9].[0-9])?$/,
                loader: 'url-loader',
                options: {
                    mimetype: 'application/font-woff'
                }
            },
            {
                test: /.(ttf|eot|svg)(?v=[0-9].[0-9].[0-9])?$/,
                loader: 'file-loader',
                options: {
                    name: '[name].[ext]'
                }
            },
            {
                test: /.s?css$/,
                use: [MiniCssExtractPlugin.loader, "style-loader", "postcss-loader", "css-loader", "sass-loader",
                    // fallback: 'style-loader',
                    // use: ['css-loader', {
                    //     loader: 'autoprefixer-loader',
                    //     options: {
                    //         browsers: 'last 3 version'
                    //     }
                    // },
                    {

                        options: {
                            sassOptions: {
                                outputStyle: 'expanded',
                                includePaths: [
                                    `${__dirname}/../node_modules`,
                                    `${__dirname}/../scss`
                                ]
                            }
                        }

                    }]
            },
            {
                test: /.jsx?$/,
                rules: [
                    {use: 'react-hot-loader/webpack'},
                    {
                        use: {
                            loader: 'babel-loader',
                            options: {
                                presets: [
                                    ['@babel/preset-env', {targets: "defaults"}]
                                ]
                            }
                        }
                    }],
                include: [
                    PATHS.js,
                    ...PATHS.modules
                ]
            }
        ]
    },

    devServer: {
        static: path.resolve(__dirname, '..'),
        historyApiFallback: true,
        // hot: true,
        host: 'localhost',
        port: 3457
    }
};

Why are all of the rects drawing and not only the ones with the current key

We’re making a Five Pillars Simulator (game).

For debugging purposes, we draw a rectangle at the position of each door for the current stage (street, mosque, etc).

But when I go in the mosque, the doors from the street are also drawn, but only the doors in the mosque should be.

The doors are like this:

const doors = {
  'street': {
    139: 'your house',
    399: 'big building',
    730: 'supercor',
    1090: 'mosque'
  },
  'mosque': {
    1090: 'street'
  }
};

And the current stage can be street or mosque, depending on what door you go in.

And all of the code is this:

const start_screen = document.querySelector('div#start-screen');
const play_btn = start_screen.querySelector('button#play-btn');

const preload_images = document.querySelector('div#preload-images');
const player_img = preload_images.querySelector('img#player-img');
const floor_img = preload_images.querySelector('img#floor-img');
const houses_img = preload_images.querySelector('img#houses-img');
const mosque_inside_img = preload_images.querySelector('img#mosque-inside-img');

const canvas_cont = document.querySelector('div#canvas-cont');
const top_info = document.querySelector('div#top-info');
const times_prayed_span = top_info.querySelector('span#times-prayed');
const first_pillar_overlay = document.querySelector('div#first-pillar-overlay');
const yes_believe_btn = first_pillar_overlay.querySelector('button#yes-believe');
const no_believe_btn = first_pillar_overlay.querySelector('button#no-believe');
const congrats_muslim = document.querySelector('h2#congrats-muslim');
const canvas = canvas_cont.querySelector('canvas');
const ctx = canvas.getContext('2d');


play_btn.addEventListener('click', e => {
  start_screen.style.display = 'none';
});

yes_believe_btn.addEventListener('click', e => {
  first_pillar_overlay.style.display = 'none';

  congrats_muslim.style.display = 'unset';

  setTimeout(() => {
    congrats_muslim.style.display = 'none';
  }, 4000);

  startGame();
});

window.addEventListener('keydown', e => {
  switch (e.code)
  {
    case 'ArrowRight':
    case 'KeyD':
      move = 1;
      break;
    
    case 'ArrowLeft':
    case 'KeyA':
      move = -1;
  }
});

window.addEventListener('keyup', e => {
  switch (e.code)
  {
    case 'ArrowRight':
    case 'ArrowLeft':
    case 'KeyD':
    case 'KeyA':
      move = 0;
  }
});

window.addEventListener('keypress', e => {
  if (
    e.code == 'KeyW' ||
    e.code == 'Space'
  )
  goInDoor();
});


let floor_y = 300;
let player_x = 400;
let move = 0;
let times_prayed = 0;
const doors = {
  'street': {
    139: 'your house',
    399: 'big building',
    730: 'supercor',
    1090: 'mosque'
  },
  'mosque': {
    1090: 'street'
  }
};
let current_place = 'street';


function startGame()
{
  player_x = 400;

  const frame = () => {
    player_x += 3 * move;

    if (player_x < 0)
    player_x = 0;

    else if (player_x > 2000)
    player_x = 2000;

    canvas_cont.scrollLeft = player_x - 400;

    times_prayed_span.innerText = times_prayed;
    
    ctx.clearRect(0, 0, 2000, 500);

    if (current_place == 'street')
    {
      floor_y = 300;

      ctx.drawImage(
        floor_img,
        0,
        floor_y,
        2000,
        200
      );

      ctx.drawImage(
        houses_img,
        0,
        00,
        2000,
        300
      );
    }
    else if (current_place == 'mosque')
    {
      floor_y = 400;

      ctx.drawImage(
        mosque_inside_img,
        0,
        0,
        2000,
        500
      );
    }

    for (let door of Object.keys(doors[current_place]))
    {
      door = parseInt(door);

      ctx.rect(
        door - 20,
        floor_y - 20,
        40,
        20
      );

      ctx.fill();
    }

    ctx.drawImage(
      player_img,
      player_x,
      floor_y - 20,
      40,
      40
    );

    requestAnimationFrame(frame);
  };

  requestAnimationFrame(frame);
}

function goInDoor()
{
  for (let door_x of Object.keys(doors[current_place]))
  {
    door_x = parseInt(door_x);

    if (
      player_x + 20 >= door_x - 20 &&
      player_x + 20 <= door_x + 20
    )
    {
      const door_id = doors[current_place][door_x];

      current_place = door_id;

      break;
    }
  }
}

But when drawing the doors, it should only loop through doors[current_place] and not all of the doors.

Any ideas?

NextJS: Is it possible to use Kute.js for SVG animations inside a component?

I want to animate SVGs using Kute.js, which was installed using npm, in NextJS.

I have created an animations.js file inside a js folder in the public directory ‘public/js/animations.js’. Then I tried adding it to my component which holds the svgs but it kept returning the following error ‘KUTE is not defined’.

My public/js/animations.js code

const animate = KUTE.fromTo('firstSVG', {path: '#firstSVG' }, { path: '#secondSVG' });
animate.start();

Using Script from ‘next/script’ to import the js file

<Script src="/js/animations.js"/>

How to sort table by two columns instead of one

I have a table that I sort ASC by building name. The next column is the corresponding building number for the building. I have a function that will sort the table in ASC order based on the building name. I want to be able to sort by the building name and the building number at the same time. This is a snippet of the table when the page loads. The first <td> which is the building name goes in order. However, the next <td> which is the building number does not go in order.

<tbody class="meterList">
   <tr>
      <td>ACB</td>
      <td>A2095</td>
   </tr>
   <tr>
      <td>ACB</td>
      <td>E1559</td>      
   </tr>
   <tr>
      <td>ACB</td>
      <td>E1540</td>      
   </tr>
   <tr>
      <td>ADH</td>
      <td>A0001</td>      
   </tr>
   <tr>
      <td>ADH</td>
      <td>E1076</td>     
   </tr>
   <tr>
      <td>ADH</td>
      <td>S0001</td>      
   </tr>
   <tr>
      <td>ADH</td>
      <td>E1075</td>      
   </tr>
</tbody>

This is the function I use the sort the table in ASC order by building name.

$('.meterList').find('tr').sort(function(a, b) {
    return $('td:first', a).text().localeCompare($('td:first', b).text());
 }).appendTo($('.meterList'))

I tried doing something like this to sort by both the first and second <td> but this didnt work.

$('.meterList').find('tr').sort(function(a, b) {
    return $('td:first, td:second', a).text().localeCompare($('td:first, td:second', b).text());
 }).appendTo($('.meterList'))

If anyone has any idea how I can sort by two columns any advice would be greatly appreciated!

javascript (nodejs) const variable overridden in callback function

for a few days I have the problem and could not find a solution to it.
I use nodejs and the packages ethers and want to execute code on “pending” transactions.
The problem i face is that, when i declare a const transaction = await provider.getTransaction(tx) at the beginning of my code and do some stuff at some point the data in transaction changes to a new transaction while i am still in the same callback function. How can this happen?

Sample Code:

 provider.on("pending", async (tx) => {
      const transaction = await provider.getTransaction(tx);
      if(!transaction['data'])
          return;
      ... do some stuff with await and setTimeout etc.
      
      let dataArray= formateTransactionDataToArray (transaction['data']); <= error Cannot read property 'data' of null
 });

How do I learn how to develop a website with simple interactive word games? [closed]

I have little experience in programming. In the past couple of years I coded some simple Chrome extensions to enhance my experience and automate stuff on certain websites, did some basic generative art in Python, things like that.

Now I’d like to build a website with simple interactive word games (stuff like crossword puzzles, Wordle, NYT’s Spelling Bee). I’m interested in the learning experience of building it at least as much as I am in the end product, so I’m not looking for libraries that already implement crossword puzzles and other shortcuts like that.

My question is: how do I find out what I need to learn? Where do I start? Are there any tutorials that walk you through similar projects almost from scratch?

I’d really appreciate any tips, thanks!

Flask Send Data to server

I am new to flask and I start to learn post and get requests. I do them with a form.
FLASK

from flask import Flask,render_template,request
app = Flask(__name__)
@app.route("/a",methods=['POST','GET'])
def home():
    if request.method == 'POST':
        a = request.form['name']
        print(a)
    return render_template('index.html',b=a)
if __name__ == '__main__':
    app.run(debug=True)     

HTML

<!DOCTYPE html>
<html>
    <body>
        <form action="" method='post'>
            <input type='text' name='name'>
            <button>OK</button>
        </form>
        <p>{{b}}</p>
    </body>
</html>

How can I send data like this but without a form?

When I run it I get "POST /a HTTP/1.1" 200 -

Thanks.

my tic-tac-toe game if condition doesn’t work

let cells = document.querySelectorAll(".cell");

let turn = "x";

cells.forEach( box => {
    box.addEventListener("click",
     () => box.classList.add("fill-" + turn));   

     if ( turn === "x" ) turn = "o";
     else turn = "x";
  
},
 { once: true}
);
#board{
  border: 2px solid red;
  width: 210px;
  height: 210px;
  margin: auto;
  
  
}

.cell{
  border: 1px solid red;
  display: block;
  background-color: rgb(241, 239, 239);
  text-decoration: none;
  width: 68px;
  height: 68px;
  float: left;
  cursor: pointer;
  font-size: 60px;
  text-align: center;
  line-height: 60px;
}

.cell:hover{
  background-color: rgb(207, 207, 207);

}

.cell.fill-x::after{
  content: "x";
  color: blue;
}

.cell.fill-o::after{
  content: "0";
  color: red;
}
<!Doctype html>
<html>
 <head>
  <title>Dooz</title>
  <meta charset="UFT-8">
  <link rel="stylesheet" href="dooz.css">
 
 </head>
 <body>
  
   <div id="board">
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
    <a  class="cell"></a>
   </div>

   <script src="dooz.js"></script>
 </body>
</html>

I’m learning javascript and trying to build a tic-tac-toe game.
I want to create an if condition to whether choose “x” or “o” after another, but my code doesn’t work probably.
inside first if statement line:
when it’s ( turn = “o” ), it only shows “o”
when it’s (turn === or == “o”), it only shows “x”
What’s the problem and how can I fix this?

Not able to access elements in React array

I can’t read the values that I am pushing into my array in React. I am using a useCallback() hook to populate an array with values from an asynchronous call (web3 events). I am doing this because I don’t want to use setState() method multiple times over to re-render my component. Instead I want to populate one array and pass that into my setState(). I am new to React and programming in general, let me know if I made a silly mistake.

When I try to console.log() ‘arr’ in the useEffect() I get an array that look like the picture, but I can’t access arr[0], or arr1 its just undefined.
enter image description here

import React, { useState, useEffect, useMemo, useContext, useCallback } from "react";
import { useTable } from 'react-table';
import { DAOContext } from '../pages/index.jsx';
import Vote from './Vote.jsx';
import ExecuteProposal from "./ExecuteProposal";
import Countdown from "./Countdown.jsx"
import VoteState from "./VoteState.jsx"

function VotingTable(){
  const[proposals, setProposals] = useState([]);
  const[votes, setVotes] = useState([]);
  const[updated, setUpdated] = useState(1);

  const {web3} = useContext(DAOContext);
  const {accounts} = useContext(DAOContext);
  const {contract} = useContext(DAOContext);
  const {connectedAddress} = useContext(DAOContext);
  const {contractAddress} = useContext(DAOContext);
  const {socketContract} = useContext(DAOContext);



  const getProposals = useCallback(() => {
    if (socketContract != undefined && connectedAddress != undefined){
      var arr = new Array();
      socketContract.events.proposalEdit({fromBlock:0}, function(error,event){
        if (error){console.log(error)}
        const newProposal = {"id":event.returnValues.id,
                             "name":event.returnValues.name,
                             "amount":event.returnValues.amount,
                             "recipient":event.returnValues.recipient,
                             "votes": event.returnValues.votes,
                             "executed":event.returnValues.executed ,
                             "end":event.returnValues.end
                            };
        arr.push([newProposal]);
        }
      )
      console.log(arr[1]);
    return arr;
    }
  }, [socketContract,connectedAddress])


  useEffect(() => {
      const arr = [getProposals()];
      const reactElementsArray = arr.map(proposal => {
        console.log(proposal);
      })
      //console.log(reactElementsArray[0]);
    })

/*
  useEffect(() => {
    if (socketContract != undefined && connectedAddress != undefined){
      socketContract.events.emitVote({fromBlock:0}, function(error, event){
        if (error){console.log(error)}
        const newVote = {"ProposalId" :event.returnValues.proposalId,
                         "Sender": event.returnValues.sender
                        };
        console.log(newVote);
        if (votes.length == 0){
          setVotes(votes => ([...votes, newVote]));
        }
      })
    }
  },[socketContract,connectedAddress])

*/

  const votesData = useMemo(() => [...votes], [votes]);
  //Apparently useMemo() is the only option here, not totally sure why jsut yet, should do more research on this...
  //Setting up the Header & accessor for the columns information
  const proposalsData = useMemo(() => [...proposals],[proposals]);
  const proposalsColumns = useMemo(() => proposals[0] ? Object.keys(proposals[0]).filter((key) => key !== "rating").map((key) =>{
    return {Header: key, accessor: key};
  }) : [] , [proposals]);
  //console.log(votesData);

  const voteHooks = (hooks) => {
    hooks.visibleColumns.push((columns) => [
      ...columns,
      { id:"Vote State",
        Header: "Vote State",
        Cell: ({row}) =>(<VoteState index ={row.id} value={votesData}/>),
      },
      { id:"Countdown",
        Header: "Time Remaining",
        Cell: ({row}) =>(<Countdown futureTime={proposals[row.id]["end"]}/>),
      },
      { id:"Vote Button",
        Header: "Vote",
        Cell: ({row}) =>(<Vote index={row}/>),
      },
      { id:"Execute Button",
        Header: "Execute",
        Cell:({row}) =>(<ExecuteProposal index={row}/>),
      },
    ]);
  };

  //Create a table instance with 'useTable()' from react-table
  const tableInstance = useTable({columns: proposalsColumns, data:proposalsData}, voteHooks);
  const {getTableProps, getTableBodyProps, headerGroups, rows, prepareRow} = tableInstance;

  //console.log("proposals",proposals[0]);
  //render the table information and populate with desired data
  return(
    <div>
    <table {...getTableProps()}>
      <thead>
      {headerGroups.map((headerGroup) => (
        <tr {...headerGroup.getHeaderGroupProps()}>
          {headerGroup.headers.map((column) =>(
            <th {...column.getHeaderProps()}>{column.render("Header")}</th>
          ))}
        </tr>
      ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row) =>{
          prepareRow(row);
          return <tr {...row.getRowProps()}>
           {row.cells.map((cell,idx) => (
            <td  {...cell.getCellProps()}> {cell.render("Cell")} </td>
          ))}
          </tr>
        })}
      </tbody>
    </table>
    </div>
  )

}
export default VotingTable;

Chart.js Pie Chart Consistent Labels and Color

I’m using a pie/doughbut chart and lets say I have 3 pieces of data I want to show in my chart: ['value 1', 'value 2', 'value 3']. I want to make sure each value always has the same label and color for consistency. So, if all 3 values are greater than 0 I can just pass labels and colors like:

{
  type: 'doughnut',
  data: {
    labels: ['label 1', 'label 2', 'label 3'],
    datasets: [
      {
        data: ['value 1', 'value 2', 'value 3'],
        backgroundColor: ['color 1', 'color 2', 'color 3'],
        hoverOffset: 4,
      },
    ],
  },
  options: {
    radius: 80,
    plugins: {
      legend: false,
    },
  },
}

and everything works fine. However, if value 2 is 0 then value 3 will be given the label label 2 and color color 2. I’m looking for a way to pass my data to ensure my values always have the same label and color. I’ve tried the object examples from the docs and neither render a chart even when directly copy and pasted.

Streaming a file from URL in smaller chunks from a controller back to view for client to download

I am looking to stream a file in chunks from a URL to avoid memory issues. My main issue that I cannot get passed is returning it to the view for and it starting a download for the user.

js

async downloadAttach(ID: any) {
    
    window.open(await ApiFunc.post('Ticket', 'Download', CommID));// my own API call fucntion that works. 

    
}

This code calls to the API in the C# Controller when a button is clicked. This API works for functions that I currently have in place.

Controller

[Route("api/Ticket/Download")]
        [HttpPost]
        public async Task<//Streamed file> Download([FromBody]string uri)
        {
            //Load file into stream in chunks recursively, to pass back to view
        }

This is the controller that takes the URI supplied from the view section and loads in chunks back to the client.

What is the best practice around this?( I am looking to chunk it out already to avoid memory issues). I have also seen uses of HttpWebRequest but I’m not exactly sure how it works out returning to the view.

HttpWebRequest

Example from: Download/Stream file from URL – asp.net

This is the example I have been looking over that splits it up into small chunks but Im unsure how to get it to return through to the view and download. I have coded it up and made the proper modifications to fit with the packages Im using but onclick nothing happens.

How to delay el.classList.remove?

If you see an image when scrolling, it is set to be an animation.
If I can’t see the image, I’ll let them return to their original state, but I’d like to give them a “five-second” delay, not “immediately.”
I tried to put delay, but it failed. Is there anyone who can help?

window.onload = function () {
            const targets = document.querySelectorAll('[data-observer]')
            const images = document.querySelectorAll('[data-img]')
            const options = {
                rootMargin: '0px',
                threshold: 1.0
            }
            const addClass = (el) => {
                if (!el.classList.contains('is-visible')) {
                    el.classList.add('is-visible')
                }
            }
            const removeClass = (el) => {
                if (el.classList.contains('is-visible')) {
                    el.classList.remove('is-visible')
                }
            }




            const doThings = (entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        addClass(entry.target)
                    } else {
                        removeClass(entry.target)
                    }
                })
            }
            const observer = new IntersectionObserver(doThings, options)
            const observer2 = new IntersectionObserver(doThings, {
                ... options,
                threshold: 0.4
            })
            targets.forEach(target => {
                observer.observe(target)
            })
            images.forEach(target => {
                observer2.observe(target)
            })
        }