Why it doesn’t change colours? It’s JavaScript

Why doesn’t it change colours? Why do I have error: ts(1003)?

<html>
   <head>
       <script>
           var peso = prompt("Dime tu peso en kg")
           var altura = prompt("Dime tu altura en metros")
           var IMC = parseFloat(peso) / parseFloat(altura)**2
           if (IMC < 19) {
               document.write("Estás por debajo de tu peso ideal")
           } else {
               document.write("Obesidad")
           }
       </script>
   </head>
</html>

how to log [ 1, 2 ,3] not [1.0,2.0,3.0] as my array? [closed]

I’m am very new to programming and trying to salve a programing puzzle/game.
It’s a Spiral Matrix and the result is correct but
my array is outputting .0 at the end of my arrays.

example

input is [ 1, 2, 3],
         [ 4, 5, 6],
         [ 7, 8, 9]

output is [1.0,2.0,3.0,6.0,9.0,8.0,7.0,4.0,5.0]

looking for [ 1, 2, 3, 6, 9, 8, 7, 4, 5]

the code I am using is from this youtube video.
LeetCode 54 Spiral Matrix in javascript

how do I Logger.log(result) without the .0?


    function myFunction() {
    matrix = [
    [ 1, 2, 3], 
    [ 4, 5, 6], 
    [ 7, 8, 9]
             ];
    // result array
    const result = [];
    // boundry varibals
    let left = 0;
    let top = 0;
    let right = matrix[0].length - 1;
    let bottom = matrix.length - 1;
    // starting direction clock wise
    let direction = 'right';
    // start loop
    while (left <= right && top <= bottom) {

    if (direction === 'right') {
      for (let i = left; i <= right; i += 1) {
        result.push(matrix[top][i]);
      }
      top += 1;
      direction = 'down';
    }

    else if (direction === 'down') {
      for (let i = top; i <= bottom; i += 1) {
        result.push(matrix[i][right]);
      }
      right -= 1;
      direction = 'left';
    }

    else if (direction === 'left') {
      for (let i = right; i >= left; i -= 1) {
        result.push(matrix[bottom][i]);
      }
      bottom -= 1;
      direction = 'up';
    }

    else if (direction === 'up') {
      for (let i = bottom; i >= top; i -= 1) {
        result.push(matrix[i][left]);

      }

      left += 1;
      direction = 'right';
    }
    }
    Logger.log(result);
    return result;
    }

I hope this question is simple I don’t know what else I should add the puzzle is from an indie game BitRunner it got me more into programming than I use to be in adding this info at the end because the post won’t submit if it has more code then words

Flutter web with wcf service

I’m trying to call wcf service from flutter
Using https

It’s working from android emulator
But when I’m trying to call it from flutter web I get XMLhttprequest error

Any solution?????

JS Project to Teach kids alphabet

the prof. ask us to make aproject to tech alphabet and i doesnot know how to do it
can some one help with it
this is the description of the project :

In this project, you are required to implement a simple web application that allows kids in
schools to learn the basic English Alphabet. The basic idea is that, the user will choose
the number of letters he wants to learn, and when clicking on each letter, another page is
opened showing an image of something that begins with that letter. In addition, some user
interaction events are collected and stored in the localStorage object of the browser to be
used in subsequent versions of the project.
The application should look something like the following:

• It has an index.html page contains a number input and a button. The user chose
how many letters (from 1 up to 26) he wants to learn, then he presses OK.
A randomly chosen letters should be selected. For example, if the user wants to
learn 3 letters, he uses the number input field and chose 3, then presses OK and
after that he will get 3 randomly chosen letters from the English alphabet.

• The next step is for the user to click on one of the letters and then an Image is
displayed showing something that begins with that letter. Images are stored in a
folder for created for each letter (You should download some images from the
internet to use them in the project).


please guys i need your help the project has 25% of the Dgree of the course.

How to create a simple word fragmenter for English words?

I am working on a conlang (a fantasy language basically), and I would like to automatically translate various English words into the fantasy language. I already have a huge list of word bases which I have manually collected (words like “create”, “dig”, “house”, “cat”, “sophisticated”, etc.). Now I would like to take advantage of the fact that I have these word “bases” and use them to automatically translate/transcribe English words that are “derivatives” of the base words. So I am wondering basically how to construct a simple system in JavaScript to do that.

The goal for this question is just to do the first step in the transformation. That is, to split a word into its parts. Then given the word parts, I can easily convert it to my fantasy language with all its quirks no problem. I won’t distract you with those details. Instead, all I need to know how to do is effectively split an English word into its parts. It seems easy at first but then getting into the weeds a little I am not sure if I need to build a full-fledge character-by-character parser, or if I can do something a little more clunky and simple. It doesn’t really need to be the most efficient, just needs to get the job done.

I am just beginning, stuck at what to do for the first step. I have basically just captured the prefixes and suffixes I am considering for this small project.

const prefixes = [
  //  'con', // words starting with con aren't really prefixes they are part of the base word.
  'de', // "defrost"
  'un', // "unsatisfactory"
  'dis', // "discontinuation"
  'il', // not "illustrate" but "illegal"
  'in', // not "interesting" but "incomplete"
  'im', // "immortal"
]

// don't have every possible suffix, but here are the key ones I am considering.
const suffixes = [
  'ion', // "attribute" vs. "attribution" (drops the "e") or "compression" vs. "compress"
  'ify', // "dehumidify"
  'some', // "awesome"
  'ship', // "friendship"
  'hood', // "neighborhood"
  'ist', // "artist"
  'or', // "creator" but not "doctor"
  'er', // "interpreter" but not "mother"
  'ed', // "created"
  's', // "creates"
  'ing', // "creating"
  'ism', // "creationism"
  'ive', // "creative",
  'ity', // "creativity"
  'ible', // "responsible" but not "feasible"
  'able', // "knowledgeable"
  'ry', // "pleasantry"
  'ly', // "excitedly"
  'ily', // "fuzzily"
  'dom', // "kingdom"
  'ish', // "reddish" (doubles the "d")
  'ful', // "careful"
  'less', // "fearless"
  'est', // "tallest"
  'ness', // "cleverness"
  'ence', // "correspondence"
  'ance', // "resemblance"
]

/**
* Rules/facts:
*
* - if base word ends in '-e', then drop the 'e' to look for suffixes.
* - don't always drop the '-e', like "knowledgeable".
* - some words have multiple prefixes and suffixes, like "creationism" or "carefully".
* - some words are based off derived words, like "creativity" from "creative" from "create".
* - can try adding an extra letter to get to the prefix (adding "d" to "red" for "reddish")
*/

function convert(baseWord, testWord) {
  
}

The convert function should take a base word, and a “test” word (input), and first figure out if it matches, then if it does match, split it into its appropriate parts. Here is some desired input and output.

convert('knowledge', 'knowledgeable') // => { base: 'knowledge', suffixes: ['able'] }
convert('fearlessly', 'fear') // => { base: 'fear', suffixes: ['less', 'ly'] }
convert('glaring', 'glare') // => { base: 'glare', suffixes: ['ing'] }
convert('unsure', 'sure') // => { base: 'sure', prefixes: ['sure'] }
// this next one might be too hard, if so, can be skipped
convert('undeniable', 'deny') // => { base: 'deny', prefixes: ['un'], suffixes: ['able'] }
convert('random', 'knowledgeable') // => undefined
convert('knowledge', 'other') // => undefined

So then, I will simply iterate through my word list and desired words to split, and then split them into their parts. I will then take that metadata and use it to construct the final fantasy word. I am just not sure really where to begin on how to check for all these prefixes and suffixes in a word. Let’s walk through “undeniable” to see.

First, iterate through each prefix and check if it is there. I think we can assume for this project that there is only one prefix possibly attached. However (edge case), the word might begin with a prefix, but that prefix is part of the word! As in “illustrate”, so we can’t consume the prefix until we subsequently check if the full word follows. Which is why it starts to get confusing/convoluted. Then we check the main word, but if it ends in a vowel can try dropping the vowel and check that too. Or try changing a trailing y into i. Then if that matches, try matching the suffixes. If our suffix starts with a vowel, maybe try adding back the last letter from the main word to see if we can get a match (i.e. glare + glared). That seems like about it. But again I am not sure how to approach this from a parsing perspective, it seems quite hard.

download csv file in js display timestamp is not same with database

my Program is connection with firebase,in firebase the sensor timestamp is utc+8.but in my program to download csv file the time is display utc+0.how can i improve my program to let that csv file the time is UTC+8.

    default: {
        let csv = `uFEFF${['Timestamp'].concat(dataFields).join(',')}n`;
        for (const dataDocSnap of dataQrySnap.docs)
            if(dataDocSnap.get('object.data')) {
                csv += [dataDocSnap.get('timestamp').toDate().toISOString()]
                    .concat(dataFields.map((dataField) => dataDocSnap.get(`object.data.${dataField}`)))
                    .join(',') + 'n';
            }
        res.header('Context-Type', 'text/csv');
        res.attachment(`${sensorDocSnap.get('name') ?? sensorDocSnap.id}-${date.toFormat('yyyy-MM')}.csv`);
        res.send(csv);
        return;
    }

unable to use id of dynamically created cards using JS

i displayed some songs from firebase database to cards, i assigned the id of the cards dynamically, i want to use the id to play song on clicking it. But i am unable to use the playsong.addeventlistener. Error shows : playsong is undefined. what am i doing wrong?

onChildAdded(dbRef, (snapshot) => {

    var childKey = snapshot.key;
    console.log(childKey);
    var childData = snapshot.val();
    console.log(childData.SongName);
    
    let card = document.createElement("div");

    card.className = 'card';
    card.id = 'playsong';
   
   card.style.backgroundImage =  "url('https://firebasestorage.googleapis.com/v0/b/soundemic-4f707.appspot.com/o/"+childData.SongName+"%2FThumbnail?alt=media&token=c34ebabe-4bbd-4659-b4e4-ff22221376cb')";
 

  document.querySelector(".fresh-album-cards").appendChild(card);
  
  
   }), {
  onlyOnce: true     
};

i want show two div with same id by click button 3 but it show one div only

i want show div 3 and last div 3 at same time when i click button 3

//button for click to show div element

                <button  class="single" target="1">1</button>
                <button  class="single" target="2">2</button>
                <button  class="single" target="3">3</button>

    
              //element i want to show
              
                <section>
                <div id="div1" class="target">1</div>
                <div id="div3" class="target">3</div>
                <div id="div2" class="target">2</div>
                <div id="div3" class="target">3</div> 
                </section>

        
        //jquery code
        
          jQuery('.single').click(function(){ 
          jQuery('.target').hide();
          jQuery('#div'+$(this).attr('target')).show();

Can I use HTML sidebar to call a function in Google Appscript?

I need to use a sidebar to get some variables and print then in the last line of a sheet, using AppScript. So, I was trying to use this code:

Sidebar.HTML

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>
  <p>Name: <input type="text" name="txtName" /></p>
  <p>Date: <input type="text" name="txtDate" /></p>
  <p>Value: <input type="text" name="txtValue" /></p>
  <button onclick="doSomething()"> submit </button>
  <script>
    function doSomething() {
      google.script.run.withFailureHandler(myFunction(document.getElementById("txtName", "txtDate", "txtValue").value))
    }
  </script>

</body>

</html>

Code.js

function myFunction(name = "", date = "", value = "") {
  var ss = SpreadsheetApp.getActive()
  var sheet = ss.getSheetByName("1")

  var lr = sheet.getLastRow() + 1

  sheet.getRange(lr, 1).setValue(name)
  sheet.getRange(lr, 2).setValue(date)
  sheet.getRange(lr, 3).setValue(value)
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile("Sidebar");
  html.setTitle("Form");
  SpreadsheetApp.getUi().showSidebar(html);
}

But it don’t worked. When I click on the button nothing happen. I’m new in HTML, so, what can I do to fixit?

Based on click event, how to show accordion and display name by status in Vuejs

Component 1

<script>
import { data } from "../data";
export default {
  name: "HelloWorld",
  data() {
    return {
      items: data,
    };
  },
};
</script>
**data.js**

export const data = [
  {
    id: 1,
    val: "1",
    kk: "mm",
    status: "ok"
  },
  {
    id: 2,
    val: "2",
    kk: "aa",
    status: "ok"
  },
  {
    id: 3,
    val: "3",
    kk: "dd",
    status: "notok"
  },
  {
    id: 4,
    val: "4",
    kk: "gg",
    status: "medium"
  },
  {
    id: 5,
    val: "5",
    kk: "gg",
    status: "notok"
  },
  {
    id: 6,
    val: "6",
    kk: "gg",
    status: "ok"
  },
  {
    id: 7,
    val: "7",
    kk: "gg",
    status: "medium"
  },
  {
    id: 8,
    val: "7",
    kk: "gg",
    status: "notok"
  },
  {
    id: 9,
    val: "9",
    kk: "gg",
    status: "medium"
  }
];
<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <input type="checkbox" />
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id, item } }">
        {{ item.val }}
      </router-link>
    </div>
  </div>
</template>

Component 2

<script>
import { data } from ".././datatwo";
export default {
  name: "HelloWorld",
  data() {
    return {
      selects: data,
    };
  },
};
</script>
**datatwo.js**

export const data = [
  {
    id: 1,
    val: "a",
    kk: "mm",
    status: "notok"
  },
  {
    id: 2,
    val: "b",
    kk: "aa",
    status: "ok"
  },
  {
    id: 3,
    val: "c",
    kk: "dd",
    status: "ok"
  },
  {
    id: 4,
    val: "d",
    kk: "gg",
    status: "medium"
  },
  {
    id: 5,
    val: "e",
    kk: "gg",
    status: "medium"
  },
  {
    id: 6,
    val: "f",
    kk: "gg",
    status: "ok"
  },
  {
    id: 7,
    val: "g",
    kk: "gg",
    status: "medium"
  },
  {
    id: 8,
    val: "h",
    kk: "gg",
    status: "notok"
  },
  {
    id: 9,
    val: "i",
    kk: "gg",
    status: "medium"
  }
];
<template>
  <div>
    <b>Vuejs dynamic routing2</b>
    <div v-for="select in selects" :key="select.id">
      <input type="checkbox" />
      <b>{{ select.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link
        :to="{ name: 'UserWithIDTwo', params: { id: select.id, select } }"
      >
        {{ select.val }}
      </router-link>
    </div>
    <br /><br /><br />
  </div>
</template>

I have two components called component1, component2. Where in both components data is coming from individual .js called(data.js, datatwo.js)

So when user click on checkbox from componet1, I need to show the names which is in component2(datatwo.js) based on the status present in datatwo.js(component2)

for example like. in my case status is categorized into 3 types called. “ok”, “notok” “medium”. So when user click on checkbox from component1, i need to display name present in component2(dtatwo.js) and drawing lines like below. and when user uncheck checkbox it need to hide again.

enter image description here

code:- https://codesandbox.io/s/data-change-dynaic-t48f9?file=/src/datatwo.js

testing user input with jsdom

i’m a complete beginner in when it comes to jsdom and i just want to know how to simulate the user typing the string and hitting solve button this is what i got so far

unitTest.js

suite("UnitTests", () => {
  beforeEach(function () {
    return JSDOM.fromFile(path.join(__dirname, "../views/index.html"), {
      resources: "usable",
      runScripts: "dangerously",
    }).then((resolve) => {
      window = resolve.window;
      document = resolve.window.document;
      textArea = document.getElementById("text-input");
      error = document.getElementById("error");
      solveButton = document.getElementById("solve-button");
    });
  });
  suite("solver solve method", function () {
    test("Valid puzzle strings pass the solver", function () {
      const invalidPuzzleString =
        "1.5..2.84..63.12.7.2..5.....9..1....8.2.367473.7.2..9.47...8..1..16....926614.478";
      textArea.textContent = invalidPuzzleString;
      solveButton.dispatchEvent(
        new window.MouseEvent("click", { bubbles: true })
      );
      console.log(textArea.textContent);
      console.log(error.innerHTML);
      assert.equal(
        error.innerHTML,
        '<code>{ "error": "Puzzle cannot be solved" }</code>'
      );
    });
```

Uncaught (in promise) TypeError: Cannot set properties of null (setting ‘onclick’) at users.js:18

I am trying to create a login form whereby the users data is fetched via a fetch request and is checked with the following javascript code:

fetch('./login.php', {
    method: 'GET'
})
.then((res) => res.json())
.then(res => {
    let user = []
        for (let data of res){
            user.push({
                email: "'"+data.email+"'",
                password : "'"+data.password+"'"
            })
        }

    let button = document.querySelector('.btn btn-danger submit');

    function login(){
        let email = document.getElementById('useremail').value;
        let password = document.getElementById('userpassword').value;
        for(i=0; i < user.length; i++){
            if(email == user[i].email && password == user[i].password){
                window.location = "home.html";
            }
        }
    }
    
    button.onclick =  login();
})

Whenever I check the console it shows the error in the title.
Is there something wrong with how I am trying to go about this?

Here is my HTML code for the form (using bootstrap):

<form action="" id="loginform">
            <div class="mb-3">
                <label for="useremail" class="form-label">Email:</label>
                <input type="email" class="form-control" id="useremail" aria-describedby="Email" name="useremail" required>
            </div>
            <div class="mb-3">
                <label for="userpassword" class="form-label">Password:</label>
                <input type="password" class="form-control" id="userpassword" aria-describedby="Password" name="userpassword" required>
            </div>
            <button class="btn btn-danger submit" type="submit">Login</button>
            <div class="row mt-3">
                <a href="register.html" class="text-decoration-none text-decoration-underline text-dark fst-italic">Don't have an account? Register Here.</a>
            </div>
        </form>

How to send data into monogodb using postman

I am trying to send data into mongodb database using postman. Everything seems fine but i am getting error.I sent data like this.

But i am getting error like this

and this

My code looks like this. i have tried to follow MVC pattern. It is bit messy. Hope i can get solution. I have used express generator

This is app.js file

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
const {
  createUserRoute,
  usersRouter,
  indexRouter
} = require('./routes');

// const createUserRoute = require('./routes/createuser-route');

require('./db_init');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');



// app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/adduser', createUserRoute);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

This is database initializer

const mongoose = require('mongoose');
const dbUrl = "mongodb://localhost:27017/payroll-system";

mongoose.connect(dbUrl, (err,success) => {
    if(err){
        console.log('Error connecting to database');
    }
    else{
        console.log('Connected to database');
    }
})

This is create user router

var express = require('express');
var router = express.Router();

// var UserModel = require('../models/user-model');

const {createUser} = require('../controller/createUser');

router.post('/', createUser);


// router.post('/', function (req, res, next) {
//     const user = new UserModel(req.body);
//     user.save((err, result) => {
//         if (err) {
//             res.json(err);
//         }
//         else {
//             res.json(result);
//         }
//     })
// });
module.exports= router;

It handles every routes and exports them to app.js

module.exports.createUserRoute = require('./createuser-route');
module.exports.indexRoute = require('./index');
module.exports.usersRoute = require('./users');

This is usercreate controller

var express = require('express');
var router = express.Router();

var UserModel = require('../models/user-model');

function createUser(req,res,next){
    const user = new UserModel(req.body);
    user.save((err,result) => {
        if(err){
            res.json(err);
        }
        else{
            res.json(result);
        }
    })
}

module.exports = {createUser};

Database Model looks like this

const mongoose = require('mongoose');

const employeeSchema = new mongoose.Schema({
   name:{
        type:String,
        required:true
   },
    email:{
        type:String,
        required:true,
        unique:true
    },
    // password:{
    //     type:String,
    //     required:true
    // },
    phone:{
        type:Number,
        required:true
    },
    address:{
        type: String,
        required: true
    },
    date_of_birth:{
        type:Date,
        // required:true
    },
    gross_salary:{
        type:Number,
        required:true
    },
    gender:{
        type:String,
        enum:['male','female','other']
    },
    position:{
        type: String,
        enum:['Board Member','Senior Developer', 'Junior Developer','Admin Officer','Project Manager','Intern','Staff']
    },
    bank:{
        type: String,
        required: true,
        enum:['Agriculture Bank','Bank of Kathmandu','Citizens Bank','Everest Bank','Nepal Investment Bank','Nepal SBI Bank','Nepal Union Bank','Standard Chartered Bank']
    },
    account_number:{
        type:Number,
        required:true
    },
    account_holder_name:{
        type:String,
        required:true
    },
    status:{
        type:String,
        enum:['active','inactive']
    },
    shift:{
        type:String,
        enum:['Full Time','Part Time', 'Hour Basis']
    },
    marital_status:{
        type:String,
        enum:['Married','Unmarried']
    }
});

const Employee = mongoose.model('Employee', employeeSchema);
module.exports = Employee;