i want to count the number of sentiments that are in excel which i have called with jspreadsheet, but it comes out #ERROR

`
var name = document.getElementById("name").value;
var url = window.location.origin + '/storage/excel-data/' + name

jspreadsheet(document.getElementById('spreadsheet'), {
    worksheets: [{
        csv: url,
        search: true,
        csvHeaders: true,
        tableOverflow:true,
        tableHeight:'450px',
        columns: [
            { width:300 },
            { width:80 },
            { width:100 },
        ],
        footers:[
            [
                'Total Positif',
                '=COUNTIF(H:H,"positive")',
            ],
            [
                'Total Negatif',
                '=COUNTIF(H:H,"negative")',
            ]
        ],
    }]
});
`

How to make current element become previous element in a loop?

I am trying to make a 1v1 card game where the player and computer take turns putting down 1 poker card per turn. In the first turn, the first card that is played will be the first current card. In the second turn, the current card in the previous turn becomes the new previous card and there is a new current card played. How do I do this?

My code below does not do this.

while (playerDeck.length > 0 && computerDeck.length > 0) {
  currentCard = playerDeck.pop();
  nextCard = computerDeck.pop();
  previousCard = currentCard;
  currentCard = nextCard;
}

How to make linaria work with turbo repo and next js?

To set up linaria with next js we can use next-linaria package as shown in with-linaria example. Setting up next js for linaria, we can do npx create-next-app -e with-linaria. However, I get trouble in adding linaria to the ui package in a turbo repo monorepo.

Following is directory structure of scaffold by npx create-turbo

- apps
  - admin
  - web
- packages
  - ui

I want to use linaria for ui component as well.

how can i change & save by class name

I have a a page like control panel for the index.html page and I want to change the contains from this page to that.

        <div>
            <span id= "item-name" class="item-name">phone 1</span>
            <span id= "item-name" class="item-name">phone 2</span>
        </div>

like here how can I access to phone 1 and change it permanent from that page.

Thank you

CSS not working properly on Custom HTML Elements

I’ve been trying to make a custom HTML Element by extending the HTMLElement class. I try adding some style to it by linking a CSS file that is in the same directory as my other two files – index.html and custom.css.

Main folder

  • index.html
  • custom.css
  • custom.js

index.html:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="nofollow" type="text/css" href=''>
</head>
 
    <body>
        <script src="./custom.js"></script>
        <smooth-button text="Smooth button" no-1 = 1 no-2 = 2></smooth-button>
    </body>
 
</html>

custom.css:

smooth-button{
    display: block;
    color: blue;
    background-color: orange;
}

custom.js:

class SmoothButton extends HTMLElement{
 
    constructor(){
        super();
        this.shadow = this.attachShadow({mode: "open"})
    }
 
    connectedCallback(){
        this.render();
    }
 
    render(){
        this.SumOfNo1AndNo2 = null;
        if(this.getAttribute("no-1")!=null && this.getAttribute("no-2")!=null){
            this.SumOfNo1AndNo2 = parseInt(this.getAttribute("no-1")) + 
            parseInt(this.getAttribute("no-2"));
        }
        else{
            console.log("Invalid attribute.")
        }
        this.shadow.innerHTML = `<button>` + this.getAttribute("text") + " " + this.SumOfNo1AndNo2   
        + "</button>"
    }
 
}
 
customElements.define("smooth-button", SmoothButton);  

With this, I get a button as expected, with the text, but the style is applied to the element as a whole and not to the elements it’s made of. How can I apply the styles separately to each of its elements (just a <button> for now) with an external CSS file? I’m using external CSS because it’s somehow better as I read it here.

Please help me with this i am provided all the information needed below [closed]

I am a computer science student in my first semester of the college. I know basic of C, learning c++ on my own and started data structures and Algorithms a month ago. Before that I studied HTML,CSS and basics of javascript till dom manipulation then i started c++ again.
I am planning to complete DS algo by the upcoming month and then start web dev again.
Is my speed ok? If yes can I monetize my skills that I have untill this point.
If no! What do I need to learn at what speed please help.

Why do I have to use both .toString() and JSON.stringify()?

const SHA256 = require("crypto-js/sha256");

// the possible colors that the hash could represent
const COLORS = ['red', 'green', 'blue', 'yellow', 'pink', 'orange'];

// given a hash, return the color that created the hash
function findColor(hash) {
    let hashedColor;

    COLORS.forEach(color => {
        let hashedColor = SHA256(JSON.stringify(color)).toString();
        console.log(hashedColor);
        if (hashedColor === hash) {
            return color;
        };
    });
};


module.exports = findColor;

I’m experimenting with some hashing and manually using a rainbow table. When I import the SHA256 method, I find that I can create a hash for each of the colors but that this returns an object, which I then need to .stringify() to be able to console.log() the actual hash.

My question is, why do I have to both JSON.stringify() and .toString()?

I think I don’t quite understand what data type the SHA256 function gives me, and I can’t find it anywhere.

Printing Time without leading zero in Javascript

I’m pretty sure this is simple but I am trying to print out the current time in 12-hour format without including the leading zero in the time string. So, for example.

09:30 AM should print as 9:30 AM.

The current code I have so far (which prints the version with the leading zero) is this:

var d = new Date();
var timeString = d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

How can I change the above code to remove the leading zeros when they appear?

Why is prisim.js not formatin my new code?

I am trying to build an app where I can store my code as a cheat sheet. I am using prisim.js to format the HTML.

The app works like this, the user writes the code in a text area and when they press submit, a new element gets added to the DOM with its respective classes that prisim.js use but for some reason, it’s not formating the code correctly.

<div class="cont">
    <div class="sub-cont">
      <h1 class="title">Code Snippet!</h1>
      <h3 class="title" for='tite-input'>Title</h3>
      <input id='tite-input'class='tite-input' type="text">
      <textarea name="codeText" id="code" cols="30" rows="10"></textarea>
      <button class="btn">Submit</button>
    </div>

<div class="code-cont">

      <div class="code-inner">
        <h3 class="code-title">Center a div</h3>
        <pre>
          <code class='language-css'>
                  Img {
                    background: url("link");
                    background-size: cover;
                    background-position-x: center;
                    background-position-y: center;
                    background-repeat: no-repeat;
                  }   
          </code>
        </pre>
        <button class="edit-btn">Edit</button>
        <button class="delete-btn">Delete</button>
      </div>
// DOM variables
let titleInput = document.querySelector('.tite-input').addEventListener('input', getTitleInputValue);

let textArea = document.querySelector('textarea').addEventListener('input', getTextAreaValue);

let submitBtn = document.querySelector('.btn').addEventListener('click', submitButton);

// values
let titleInputValue,
    textAreaValaue;


function getTitleInputValue(){
  titleInputValue = this.value
  console.log(titleInputValue)
}

function getTextAreaValue(){
  textAreaValaue = this.value;
  console.log(textAreaValaue)
}


function submitButton(){

  let codeCont = document.querySelector('.code-cont')
  let html = `
      <div class="code-inner">
        <h3 class="code-title">${titleInputValue}</h3>
        <div class="code-toolbar">
          <pre class='language-javascript' tabindex="0">
            <code class='language-css'>
                ${textAreaValaue}
            </code>
          </pre>
        </div>
        <button class="edit-btn">Edit</button>
        <button class="delete-btn">Delete</button>
      </div>`;

      // codeCont.appendChild(html[0])
    console.log(  codeCont)

    codeCont.insertAdjacentHTML("beforeend", html);




}

My stylesheet does not load when using express route optional parameter (/:id?)

I’m trying to create a simple express project that shows a food menu and the details of each option. My problem is that if I try to set an optional parameter for a route (/:id?) my stylesheet does not load.

My router:

router.get('/detalle/:id?', controller.details)

My controller:

const controller = {
    home: function(req,res){
        return res.render('index.ejs', {platos: platos})
    },
    details: function(req,res){
        return res.render('detalleMenu.ejs', {platos: platos})
    }
}

If I load http://localhost:3000/detalle just like that I get the css stylesheet linked to detalleMenu.ejs without a problem.
The thing is that if I try to load for example http://localhost:3000/detalle/3 I get the detalleMenu.ejs but without the stylesheet!

Any ideas why this is happening?

Is there any way to block ads on iframe us javascript? [closed]

Suppose I embed

https://gogoplay1.com/streaming.php?id=OTc2MzI=&title=Boruto%3A+Naruto+Next+Generations+Episode+1

This Video in my website and I know that they are use Adsterra(Ads Provider) Service to show their ads So is there any way to block ads using javascript that is coming from Adsterra…

I already used sandbox and and its sandbox protected
Here’s a shot: enter image description here

Even if you can give me php script that would help me. I just want to remove ads from this player….

Classes based on React.Component

New, new, new to React. Downloaded the following sample of setState method in classes that extend React.Component. It works fine, but I’m not understanding why no object needs to be instantiated for App, since each user could be in a different location…

I somehow thought index.js would need:

const app = new App()

Is there a reason for this?

index.js

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

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';


class App extends React.Component {
    constructor ( props ) {
        super ( props );
        this.state={ latitude: null};

        window.navigator.geolocation.getCurrentPosition (
            ( postion ) => {
                this.setState( {latitude: postion.coords.latitude })
            },
            ( error ) => console.log ( error )
        );
    }

    render () {


        return (
            <div className="App">
                <header className="App-header">
                    <p>
                        LATITUDE: {this.state.latitude}
                    </p>
                </header>
            </div>
        );
    }
}

export default App;

How to get and save images from cache – chrome extension

I would like to be able to download an image that has be cached by chrome to a specified folder using a chrome extension. Currently I am getting the url of the image and passing it to the background.js which then downloads the image. Yet on this specific website (the website this chrome extension is being built around), does not allow you to get the url of the image.

What changes to my code will I need to be able to do this?

(the extension flips to another page, and attempts to download around 50 images per subsection of the site. this site also does not have 1 class for each image, and regularly makes the class name or Id the token of the individual)

popup.js

 const scriptCodeCollect =
  `(function() {
        // collect all images 
    let images = document.querySelectorAll('img');
        let srcArray = Array.from(images).map(function(image) {
            return image.currentSrc;
        });
        chrome.storage.local.get('savedImages', function(result) {
                // remove empty images
                imagestodownload = [];
                for (img of srcArray) {
                    if (img) {
                        img.substring("data:image/".length, img.indexOf(";base64"));
                        console.log(img);   
                    }imagestodownload.push(img);
                };
                result.savedImages = imagestodownload;
                chrome.storage.local.set(result);
                console.log("local collection setting success:"+result.savedImages.length); 
            });
    })();`;

    const scriptCodeDownload =
    `(function() {
      chrome.storage.local.get('savedImages', function(result) {
        let message = {
          "savedImages" : result.savedImages
        };
        chrome.runtime.sendMessage(message, function(){
          console.log("sending success");
        });
        
      });
      })();`;

      function injectTheScript() {
        // Gets all tabs that have the specified properties, or all tabs if no properties are specified (in our case we choose current active tab)
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            // Injects JavaScript code into a page
            chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
        });
    }
    // adding listener to your button in popup window
    document.getElementById('flipbtn').addEventListener('click', injectTheScript);
    


document.getElementById("startbtn").addEventListener("click", function() {
if((url.includes('http://127.0.0.1:5500/example%20test/physics/'))) {
    document.getElementById("success").innerHTML = "<strong><u>In progress<br></u></strong> Currently downloading: <br>" +urlfilename

  
      setInterval(function(){ //Loops download
        
      
        chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
          let urlfilename = tabs[0].url.replace('http://127.0.0.1:5500/example%20test/', '').replace('.html', '').replace('?','');
              document.getElementById("success").innerHTML = "<strong><u>In progress<br></u></strong> Currently downloading: <br>" +urlfilename
          let bknb= tabs[0].url.replace('http://127.0.0.1:5500/example%20test/', '').replace('.html', '').replace('/',' ').replace('?', '').replace(/D/g, '');

        chrome.storage.local.set({'foo': urlfilename, 'bar': bknb}, function() {
          console.log('Settings saved');
          console.log(urlfilename);
        });
        function sleep (time) {
          return new Promise((resolve) => setTimeout(resolve, time));
        }
        

        sleep(5000).then(() => {  //Pauses so URL can write and display correctly
          chrome.tabs.executeScript({code : scriptCodeCollect}); //Collects Image (page is saved as image on the website)
          
          let textCollect = document.getElementById('textCollect');
          chrome.storage.local.get('savedImages', function(result) {
            textCollect.innerHTML = "collected "+ result.savedImages.length + " images"; 
          });
        });
          chrome.tabs.executeScript({code : scriptCodeDownload}); //Downloads Image

          document.getElementById("warning").innerHTML = "test"

          sleep(5000).then(() => { //Waits so image can download fully
              chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"}); //Injects Script to flip page
          });
        });
        });
    }, 10000); //Waits 10s and then loops
  

background.js

let downloadsArray= [];
let initialState = {
    'savedImages': downloadsArray
};
chrome.runtime.onInstalled.addListener(function() {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({
                    css: ['img'],
                    css: ['img[input[type="image"[aspect-ratio[attr(1000)/attr(1419)]]]]'],
                    css: ['id[image]']
                })],
            actions: [ new chrome.declarativeContent.ShowPageAction() ]
        }]);
    });
    chrome.storage.local.set(initialState);
    console.log("initialState set");
});


//chrome.downloads.onChanged.addListener(function() {
    chrome.storage.local.get(['foo', 'bar'], function(items) {
        var urlfilename = items.foo
        console.log(urlfilename)
        var bkpg= items.bar
//  });

    chrome.runtime.onMessage.addListener(
        function(message, callback) {
        console.log("message coming");
        console.log(message);
        let srcArray = message.savedImages;
        var counter = bkpg-1;
        for (let src of srcArray) {
            console.log(src);
            chrome.downloads.download({url:src, filename:urlfilename + ".png"});
        };
    });
    });

Why do we need extraData for re-render flatList?

I’m new to React native and I’m experimenting to understand some things. In the flatlist below, I am replacing the element at index 0 in the list variable with onPress. I learned that the extraData props are used to reflect the changes. However, in the example below, even if there is no extraData, the changes are reflected on the screen because the state has changed. So why do we need extraData then?

import React, { useState } from 'react'
import { FlatList, Text, TouchableOpacity, View } from 'react-native'

let data = [{ id: 1, word: "Strong" }, { id: 2, word: "Support" }, { id: 3, word: "Discovery" }]

export default function WordSelect() {

  const [list, setList] = useState(data)
  const [selectedId, setSelectedId] = useState(null)

  const onPress = () => {
    list[0] = { id: 4, word: "Together" }
  }

  return (
    <FlatList
      data={list}
      // extraData={selectedId}
      keyExtractor={(data) => data.id.toString()}
      renderItem={({ item }) => (
        <TouchableOpacity
          onPress={() => {
            onPress()
            setSelectedId(item.id)
          }}
        >
          <View style={{ paddingTop: 30, alignSelf: 'center' }}>
            <Text >{item.word}</Text>
          </View>
        </TouchableOpacity>
      )}
    />
  )
}