javascript – Condicionais em Dart retornando uma função por determinadas vezes

tenho uma função que gera um número
e quero saber como faço para executar essa função por 3 vezes e somar o resultado do número gerado.

var numero = 1;

funcão(gera um numero){}

como fazer para executar a função acima por três vezes e somar o resultado.

javascript – Starting with asynchronous JS and promises

I’ve learn to code almost alone, so I really need some ideas/advice, as it started to get really difficult to advance.

Because this is mostly server side, I can’t provide a running snippet, but yet it’s a short snippet.


When I press a UI button, it fetches a resource, and this should create a set of list items. Simple enough:

const btn = document.getElementById("btn")
const ul = document.getElementById("ul")
const putItems = (items)=>{items.forEach(item=>ul.innerHTML=`

btn.addEventListener("click", ()=>{

On the server side, the main function and imports are:

const { MongoClient } = require("mongodb")
const cors = require('cors')

async function callDB(){   //get data from mongoDB
    const call = await MongoClient.connect( uri, {useNewUrlParser:true, useUnifiedTopology:true})
    let result
        result = await call
    } catch(e){

    return result;

app.get("/todos", cors(), (req, res)=>{
    const items = callDB().then(d=>res.json(d)).catch(e=>console.log(e))

This code imports dotenv to hide my sensible parts, and uses express I removed those imports just to be concise.

Mainly, I’d like to know if my asynchronous practice makes sense, or not. And I’m also getting a CORS error, that couldn’t fix after an hour. That would help too.

javascript – Como montar gráfico de barras do google charts com quantidade de colunas dinâmicas

Estou tentando montar um gráfico utilizando essa api do google charts com colunas DINÂMICAS mas sem sucesso, minha dificuldade é como pegar o retorno do JSON e inserir dentro do objeto data.
No exemplo abaixo a quantidade de HORAS NÃO irá variar, sempre será das 08h até as 20h, porém a quantidade de NOMES pode variar:

function montarGrafico(url) {

    var model = {
        "DT_INICIO": $("#dtInicio").val(),
        "DT_FIM": $("#dtFim").val()

        url: url,
        type: "POST",
        data: JSON.stringify(model),
        contentType: "application/json; charset=utf-8",
        success: function (response) {

            //$(response).each(function (i) {          
            //    console.log(response(i).HORA + " - " + parseInt(response(i).NU_TOTAL) + " - " + response(i).ST_NOME);                
            google.charts.load('current', { 'packages': ('bar') });

            function drawChart() {
                var data = google.visualization.arrayToDataTable((
                    ('Hora', 'JAQUELINE', 'CARLOS', 'DANIELE'),
                    ('08:00', 2, 1, 2),
                    ('09:00', 3, 4, 4),
                    ('10:00', 35, 45, 43),
                    ('11:00', 57, 53, 56),
                    ('12:00', 98, 97, 90),
                    ('13:00', 134, 132, 137),
                    ('14:00', 134, 139, 139),
                    ('15:00', 170, 167, 165),
                    ('16:00', 150, 155, 145),
                    ('17:00', 142, 102, 122),
                    ('18:00', 2, 6, 5),
                    ('19:00', 1, 5, 7),
                    ('20:00', 1, 0, 0)

                var options = {
                    chart: { }

                var chart = new google.charts.Bar(document.getElementById('ChartBarSaleSale'));
                chart.draw(data, google.charts.Bar.convertOptions(options));

Tem como acessar e modificar um valor de uma campo no form do Django dentro do javascript?

Estou tentando fazer um form em que o usuário faz o upload de um ou mais arquivos. Mas não gostaria de salvar o arquivo em si no banco, e sim o seu conteúdo (texto, os arquivos são .txt).

Isso é possível de ser feito?

javascript – Bitcoin Script – Beautify

I know about miniscript and what it intends to do:

    …writing (a subset of) Bitcoin Scripts in a structured way, enabling analysis, composition, generic signing and more

 My question is if something exists to do the job in the opposite direction.

 For example, given the below Bitcoin Script:


  It would create something of this form (in JavaScript):

function canUnlock(preImageOrSig) {
    let pubKey1 = null;
    if (preImageOrSig.size() === 32) {
        if (hash(preImageOrSig) !== 'dea3...') {
            return false;
        pubKey1 = '301...';
    } else {
        if (!checkLockTime('19323434...')) {
            return false;
        pubKey1 = '303...';
    if (!checkSignature(pubKey1, preImageOrSig)) {
        return false;
    return true;

  The resulting JS code is NOT to be executed or compiled back to Bitcoin Script, but only to help a developer reason about the logic of the original Bitcoin Script.

javascript – Web-Based Music Royalty Measurement Tool

Working on a passion project so I am willing to invest the time & research, just need some starting advice/tips.

Currently just started and have only…

  • AWS Light Sail Sever
  • WordPress + bitnami

Looking to create a web-based music recording royalty model & graphing tool that breaks down different royalty earning measurements for artists based on their data and generates graphs. The data will be retrieved from the artist’s TuneCore & DistroKid account. Averages, Change in Earnings based on catalog size, etc. (Not worried about the math part so much right now since I have these calculations done already).

The big hurdle that is keeping me in the way is figuring out a way to grab this information from the outside websites & accounts. This is needed so that my web app can then generate graphs and models off of their data. I am not looking to store their account information and data, other than the streaming data needed to generate the graphs and charts. Streaming reports can be downloaded from TuneCore (.CSV file) & DistroKid (.TSV file)

The streaming reports are typically stored in the “bank”.

My belief is that DistroKid & TuneCore are pulling their numbers & stats from the .CSV & .TSV files stored on their end.

A website called Royalty Exchange offers something quite similar, however, they’re collecting from different royalty agencies and don’t deliver the data I am looking for. They’re collecting data from artists’ publishing agencies.

Royalty Exchange has a blog post that shows their early model of the “Royalty Calculator” and how they used the user’s inputted username and password for their BMI (publisher) account to access their data and reports. Blog post link with video demonstration.

My thoughts/questions were

  1. Is Royalty Exchange is using JavaScript & AJAX in order to collect the inputted Publishing Account Username and Password. Maybe that, once RoyaltyExchange’s app got access to the account it downloaded and store the .CSV / .TSV information to the registered artist’s account on the Royalty Exchange. Bringing the data from BMI (Publisher) to the Royalty Exchange’s server.
  2. While not storing the artist’s username and password, RoyaltyExchange stores the catalog & streaming information in their servers in order to draw the graphs and measurements for the artist. Wouldn’t this be the case if they’re able to show that information in the artists’ dashboard without them needing to sign into their Publishing account again?
  3. Maybe instead of downloading & storing the.TSV and .CSV files – Royalty Exchange’s app is just scanning for the specific artist’s stats on the site and transferring it some other way?
  4. Like mentioned in the beginning, I am aware of how intense or complex this may sound especially for my obvious lack of experience, but it’s a passion project of mine that I’d really like to work on. I feel like this community though will help point me in the right direction with what I need to brush up on & learn.

Image Links For Reference:

Appreciate it, anything will help!

javascript – Resize divs when maximum divs are created

See the diagram below – Main Container

On click i create a div of width 680px and height 295px in the top left corner of the screen and go on until the bottom left corner of the screen with javascript. like image below…
enter image description here

Now when the 4th div is created, On the 5th click, i want my application to be able to calculate the space available and if there is no space available it creates a second div next to the first div created and so on in all other divs as seen in image…
enter image description here

Does anyone know how to calculate the space available dynamically everytime a div is created and then accordingly create smaller divs to fit into the spaces in the main container?

javascript – Como fazer uma requisição para a API do BackEnd usando HTML5

Sou novo com APT, quero fazer uma requisição para a API do BackEnd e pegar a resposta um JSON e o meu Javascript do FrontEnd manipular essas informações.
Estou usando HTML5 é possivel ?

<!doctype html>


Sua Pesquisa:


javascript – mask.js:5 Uncaught TypeError: v_fun is not a function

Estou utilizando um script JS para personalizar máscaras em inputs dentro de formulários. Um arquivo mask.js está sendo carregado nas páginas, contendo as seguintes funções:

function mascara(o,f){
    setTimeout(() => {
function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(d{5})(d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v


Um input:

<div class="col-sm-2">
    <div class="form-group">
        <label for="cep">CEP do Endereço</label>
        <input type="text" class="form-control cep" id="cep" name="cep" 
         placeholder="00.000-000" required>

E um script no final da página para relacionar o input à função:

$('.cep').attr("onkeypress", "mascara(this, cep)")
$('.cep').attr("maxlength", "9")

Porém eu recebo o erro:

“Uncaught TypeError: v_fun is not a function
at mask.js:5”,

sendo a linha 5:


Não consigo encontrar o erro. O mais interessante é que o mesmo script funciona em outra página perfeitamente. Ao usar o console.log(v_fun) dentro da função mascara, na página que funciona corretamente o retorno é:

ƒ cpf(v){
    v=v.replace(/D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(d{3})(d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos

Porém na página que não funciona o retorno é igual ao componente html que o chamou:

<input type="text" class="form-control cep" id="cep" name="cep" placeholder="00.000-000" required="" onkeypress="mascara(this, cep)" maxlength="9">