javascript – How to have density js file work with my code?

I was able to show the text inputted; I was able to count the words on the said text. But right now, I want to show all the word’s density. I tried following what this website says: https://www.cssscript.com/word-density-counter/ I was able to download the density.js. But I don’t know how to connect my code to this downloaded file (the STEP 2 on the website). Here’s my code:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Word Counter</title>
  </head>
  <body>
    <div id="input-page">
      <h1>Word Counter</h1>
      <form action="">
        <textarea id="text" type="text" rows="22" cols="60"></textarea>
        <br />
      </form>
      <button onclick="displayText()">COUNT</button>
    </div>

    <div id="count-page" style="display: none;">
      <h1>Your Text:</h1>
      <p id="display-text"></p>

      <div id="word-count"></div>
      </div>
    </div>
  </body>
  <script src="https://stackoverflow.com/app.js"></script>
  <script src="density.js"></script>
</html>

app.js:

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const text = document.getElementById("text");
  const textValue = text.value;

  if (text.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-text").innerText = textValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("Please enter some text first.")
  }

  const countWords = (str) => {
    return str.split(" ").length;
  };
  const wordCount = (countWords(textValue));

  const renderWordCount = () => {
    const wordCountDiv = document.getElementById("word-count");
    wordCountDiv.innerHTML = "<h1> Words Counted: " + wordCount + "</h1>";
  };

  renderWordCount();
};

This is the downloaded density.js:

class density {
  static defaults() {
    return {
      words: 1,
      characters: 0,
      stopwords: (),
      filter: ("toText", "toAlpha", "toLowercase", "stripWhitespace"),
      selected: ()
    };
  }
  static set(content) {
    this.add(content);

    this.o.filter.forEach(filter => {
      switch (filter) {
        case "toText":
          this.toText();
          break;
        case "toAlpha":
          this.toAlpha();
          break;
        case "toLowercase":
          this.toLowercase();
          break;
        case "stripWhitespace":
          this.stripWhitespace();
          break;
      }
    });

    if (this.o.selected.length > 0) {
      this.processSelected();
    } else {
      this.process();
    }
  }
  static setOptions(options) {
    this.o = Object.assign({}, this.defaults(), options);
  }
  static getUnsorted(content, options) {
    this.setOptions(options);
    this.set(content);
    return this.unsorted;
  }
  static getSorted(content, options = {}) {
    this.setOptions(options);
    this.set(content);
    this.sort();
    return this.sorted;
  }
  static sort() {
    // Put it back as array to get it sortable by occurrences
    let i = 0;
    let array_results = ();
    for (let collection in this.unsorted) {
      array_results(i) = {
        count: this.unsorted(collection),
        word: collection
      };
      i++;
    }

    this.sorted = array_results.sort((a, b) => b.count - a.count);
  }
  static processSelected() {
    let object_unsorted = {};

    this.o.selected.forEach(phrase => {
      object_unsorted(phrase) = vitimusOccurrences(
        " " + this.content + " ",
        " " + phrase + " ",
        true
      );
    });

    this.unsorted = object_unsorted;
  }
  static process() {
    let array = this.content.split(" ");
    let object_unsorted = {};
    let array_words = ();

    // Set x number of words to array
    for (let i = 0; i < array.length; i++) {
      let collection = "";
      // Loop limit to set x number of words
      for (let j = 0; j < this.o.words; j++) {
        if (typeof array(i + j) === "undefined") continue;
        if (j > 0) collection += " ";
        collection += array(i + j);
      }
      if (this.o.stopwords.includes(collection)) continue;
      if (collection.length <= this.o.characters) continue;
      array_words(i) = collection;
    }

    // Put the words as key and count the words occurrences
    array_words.forEach(item => {
      object_unsorted(item) =
        typeof object_unsorted(item) === "undefined"
          ? 1
          : object_unsorted(item) + 1;
    });

    this.unsorted = object_unsorted;
  }
  static add(content) {
    this.content = content;
  }
  static toText() {
    let div = document.createElement("div");
    div.innerHTML = this.content;

    let text = div.textContent || div.innerText || "";
    this.content = text.replace(/(rn|n|r)/gm, " ");
  }
  static toLowercase() {
    this.content = this.content.toLowerCase();
  }
  static toAlpha() {
    this.content = this.content.replace(/(^a-zA-Z0-9À-žs)/g, "");
  }
  static stripWhitespace() {
    this.content = this.content.replace(/s+/g, " ").trim();
  }
}

function vitimusOccurrences(string, subString, allowOverlapping) {
  string += "";
  subString += "";
  if (subString.length <= 0) return string.length + 1;

  var n = 0,
    pos = 0,
    step = allowOverlapping ? 1 : subString.length;

  while (true) {
    pos = string.indexOf(subString, pos);
    if (pos >= 0) {
      ++n;
      pos += step;
    } else break;
  }
  return n;
}

javascript – Track visitors across different domains using Google Analytics even when they don’t click between the sites

Apparently there are ways to track visitors across different domain using google analytics as described in documentation here and here.

It follows the principle where a visitor click on a link on website1.com and get redirects to website2.com with some additional path params which helps GA track if the visitor is same and GA maintain it’s session.

I have been looking around a lot and couldn’t find a solution on how can I track a visitor which comes on website1.com through ads and then leaves (And/Or open new tab) and immediately/later goes on to website2.com and make some purchase. I am not targeting to maintain session per user but at least I need to know if it’s the same visitor which goes there and converts.

I definately have access to both sites and can put GA tags and javaScripts on both websites.

javascript – MMMRjs a product of BYTES Genesis

Hello there, I am Syed Mohammad Sannan a team member of BYTES Genesis

We have published a product today called MMMR.js this product is licensed under the MIT license and is
built by

Syed Mohammad Sannan

The uniqueness of this product is that it is built with and for Javascript though there are many libraries out there such as NumPY, SciPY, and much much more but they are built for Python or another language and there isn’t one for Javascript that is where MMMR.js comes.

View more details for this product over here: https://mmmrjs.000webhostapp.com/

This is the source code of MMMR.js

// Mean - The average value.
// Median - The mid point value.
// Mode - The most common value.
// Range The smallest and the biggest value.

// This is Mean.
// Mean returns the average value from an array of numbers.
// To call/run this function we can type mean(Your array of numbers separated with commas ',');
const mean = (numbers) => {
  let total = 0,
    i;
  for (i = 0; i < numbers.length; i += 1) {
    total += numbers(i);
  }
  return total / numbers.length;
};



// This is Median.
// Median returns the middle point value from an array of numbers.
// To call/run this function we can type median(Your array of numbers separated with commas ',');
const median = (numbers) => {
  const sorted = numbers.slice().sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);

  if (sorted.length % 2 === 0) {
    return (sorted(middle - 1) + sorted(middle)) / 2;
  }

  return sorted(middle);
};



// This is Mode.
// Mode returns the most common/used value from an array of string, numbers, etc.
// To call/run this function we can type mode(your array of numbers);
const mode = (a) => {
  a.sort((x, y) => x - y);

  let bestStreak = 1;
  let bestElem = a(0);
  let currentStreak = 1;
  let currentElem = a(0);

  for (let i = 1; i < a.length; i++) {
    if (a(i - 1) !== a(i)) {
      if (currentStreak > bestStreak) {
        bestStreak = currentStreak;
        bestElem = currentElem;
      }

      currentStreak = 0;
      currentElem = a(i);
    }

    currentStreak++;
  }

  return currentStreak > bestStreak ? currentElem : bestElem;
};



// This is Range.
// Range is basically a function used to return the smallest and the biggest values from an array of numbers.
// To call/run this function we can type range(your array of numbers);
const range = (value) => {
  value.sort();
  return (value(0), value(value.length - 1));
}

We just wanted you to review this code and tell us is this library user-friendly, maintainable and what improvements can we add to this.

8 – Trigger a Drupal behavior from another module in Javascript?

The block_ajax module defines a behavior in its module:

https://git.drupalcode.org/project/block_ajax/-/blob/8.x-1.x/js/refresh_ajax_block_command.js

I want to initiate this call every 60 seconds so the contents of the block can refresh if there is new data from my own script file.

I tried two ways.

The first way I tried was setting up a route for a simple controller that returned an AjaxResponse:

  public function execute() {
    $response = new AjaxResponse();
    $response->addCommand(new RefreshBlockAjaxCommand('.my_block'));
    return $response;
  }

Hitting the route with Drupal.ajax results in ‘context.querySelectorAll is not a function’, but it appears that the block is replaced (but missing the block wrapper around it, oddly enough, which probably won’t work calling it over and over).

The second way is I tried to call it from the browser console with Javascript, but I can’t figure out between this answer and the linked Javascript file at the top of the question what to call.

javascript – Exercício For & If (dúvida sobre erro obtido)

Estava buscando uma resposta para um exercício que estou fazendo e, a plataforma onde estou estudando, devolveu com erro o que escrevi.

O exercício era:

As árvores utópicas crescem de uma forma particular, em dois ciclos:

  • Cada primavera dobram seu tamanho
  • Cada verão crescem um metro

Se Laura planta uma árvore utópica com um metro, no final do outono, qual seria sua altura depois de N ciclos?

Alguns exemplos:

  • si N = 0, sua altura será 1 metro (não cresceu nada)
  • si N = 1, sua altura será de 2 metros (dobrou a altura na primavera)
  • si N = 2, sua altura será de 3 metros (cresceu um metro mais no verão)
  • si N = 3, sua altura será de 6 metros (dobrou a altura na primavera seguinte)

Escreva a função alturaArvoreUtopica, que utilize uma quantidade de ciclos de crescimento, e retorne a altura resultante da árvore de Laura.

A minha primeira solução foi:

    function alturaArvoreUtopica(ciclos){
    var tamanhoDaArvore = 1;

    for(var i = 1; i <= ciclos; i++){
        if (i % 2 ===0) tamanhoDaArvore += 1;
    } else {
        tamanhoDaArvore *=2;
    }
    return tamanhoDaArvore
}
console.log(alturaArvoreUtopica);

Contudo, ao enviar o exercício pela plataforma, ele não passou (eu deveria ter printado o erro). Entrei aqui para buscar alguma coisa sobre e encontrei aqui. exatamente o mesmo exercício, com a solução abaixo (e que passou pela plataforma):

function alturaArvoreUtopica(ciclos){
    var tamanhoDaArvore = 1;

    for (var i = 1; i <= ciclos; i++) {
        if (i % 2 ===0) tamanhoDaArvore += 1;
        else tamanhoDaArvore *= 2;
    }
    return tamanhoDaArvore;
}

console.log(alturaArvoreUtopica(4));

A dúvida: eu não consigo entender por qual razão o que eu escrevi não passou e, a segunda solução encontrada aqui, passou. Se alguém puder me ajudar com esse entendimento, me ajudaria demais!

javascript – Web, no carga imagen.png en “Iphone 6”, q esta está dentro de un svg

yo tengo creada una web, donde dentro de svg, tengo una imagen de W:8000px y H:4500px.

La tengo dentro de un svg.

El tema es que cuando abren la web desde ese celular en particular, no carga la imagen, si el svg y todos los elementos(polygon) que se crean automáticamente con js…

<div id="diver" class="zoom-svg-container" style="margin-bottom: 20px;">
                <svg id="usersvg" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 280" height="100%" width="100%" version="1.1" preserveAspectRatio="xMinYMid slice" xmlns:cc="http://creativecommons.org/ns#"
                    xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/">
                    <polyline id="polyline" style="fill:white;stroke:black;stroke-width:1"/>
                    <image id="imglote" xlink:href="resources/imagen.png" x="0" y="0" width="100%"></image>
                </svg>
                <div class="zoom-svg-zoom zoom-svg-zoom-in"> + </div>
                <div class="zoom-svg-zoom zoom-svg-zoom-rst"> = </div>
                <div class="zoom-svg-zoom zoom-svg-zoom-out"> - </div>
            </div>

javascript – O que fazer para retornar os dados de forma correta no parametro do objeto?

Opa…

Gostaria de criar um objeto que me retornasse os dados de uma determinada API. Porém dentro desse objeto tem um parametro que é igual uma função, que faz a uma requisição AXIOS em outro arquivo e retorna o valor referente ao ID de cada elemento.

Porém quando dou console.log no objeto infoMatch, o parametro eventStats me retorna indefinido.

O que tenho que fazer para retornar os dados de forma correta?

//ARQUIVO PRINCIPAL    
import axios from "axios";

    import {statsMatch} from './listEventStats.js';

    axios({
        "method":"GET",
        "url":"https://bet365-scoccer-odds.p.rapidapi.com/v1/events/inplay",
        "headers":{
            "content-type":"application/octet-stream",
            "x-rapidapi-host":"bet365-scoccer-odds.p.rapidapi.com",
            "x-rapidapi-key":"8d24a42559msha81fb1ceefbf743p107bdcjsn582ec4963",
            "useQueryString":true
        },
        "params":{
            "LNG_ID":"1",
            "sport_id":"1"
        }
        })
        .then((body) => {
            let inPlayMatchesList = body.data.results;
            async function getInfoMatch(matches){
                await matches.forEach( element => {
                    let infoMatch = {
                        id: element.id,
                        league: element.league.name,
                        homeName: element.home.name,
                        away: element.away.name,
                        eventStats: statsMatch(element.id)
                    }
                    console.log(infoMatch);
                });
            }
            getInfoMatch(inPlayMatchesList);

        })
        .catch((error) => {
          console.log(error)
        })

Resultado do console.log

{
  id: '2419587',
  league: 'Esoccer Battle - 8 mins play',
  homeName: 'West Ham (Flewless_phoenix) Esports',
  away: 'Everton (Chellovekk) Esports',
  eventStats: undefined //RETORNO INDEFINIDO
}

Arquivo de requisição de informação secundária:

import axios from "axios";


export function statsMatch (element){

   axios({
        "method":"GET",
        "url":"https://bet365-scoccer-odds.p.rapidapi.com/v1/event/stats_trend",
        "headers":{
        "content-type":"application/octet-stream",
        "x-rapidapi-host":"bet365-scoccer-odds.p.rapidapi.com",
        "x-rapidapi-key":"8d24a42559msha81fb1ceefbf743p107bdcjsn582ec4963",
        "useQueryString":true
        },
        "params":{
            "event_id":`${element}`
        }
    })
    .then((response) => {
        return response.data;

    })
    .catch((error) => {
        console.log(error)
    })
}

O que deveria retornar:

o que deveria retornar

rxjs – Unrecognised javascript syntax

I have come across a particular javascript code while looking into RxJs documentation.

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

map(x => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));

I understand what it does but I have not come across this syntax before as far as I remember. Which syntax is this?

javascript – Criando Crud em Nodejs Erro no post

const users ={
  nome: String,
  idade: Number,
  saldo: Number,
  aposta: ()=>{return dados}
};
const dados = {
  gama: String,
  investimento: Number,
  lucro: Number,
  totalRetorno: (investimento, lucro) =>{let total = investimento+lucro; return totalRetorno}
};

Estou tentando criar um usuario

server.post('/users', (require, response) => {
  const { name, idade, saldo, aposta, game, investimento, lucro} = require.body; 

  users.push(name, idade, saldo, aposta(game, investimento, lucro));

  console.log("Usuario criado")
  return response.json(users, dados);
});

Nao consigo criar o usuario nao sei pq.
ERRO: TypeError: users.push is not a function

javascript – ¿Como puedo hacer acción de dos elementos superpuestos y que cada uno haga una acción?

¡Gracias por contribuir en StackOverflow en español con una respuesta!

  • Por favor, asegúrate de responder a la pregunta. ¡Proporciona información y comparte tu investigación!

Pero evita

  • Pedir ayuda o aclaraciones, o responder a otras respuestas.
  • Hacer declaraciones basadas en opiniones; asegúrate de respaldarlas con referencias o con tu propia experiencia personal.

Para obtener más información, consulta nuestros consejos sobre cómo escribir grandes respuestas.