How to play sounds in github?

I was making a github repository with a HTLM5 file and a mp3 file.

On the html file i writed:

<script>
var audio = new Audio('sound.mp3');
audio.play();
</script>

And then i uploaded in the repository a mp3 file, imagine if the file name was sound.mp3.

Here’s what the files look like:

index.html

sound.mp3

The problem is that the HTML script i made is not playing the sound on the github page.

I’m 100% sure that i have the volume up but it dosn’t play.

What can i do to make it play the sound in the repository files?

Also i tried using images and looks like the html can get the img file in the repository but not sounds.

Locking down a TypeScript class so that it is final and all invariants are guaranteed, even at runtime?

What is the best way of making a TypeScript class final, and ensure that all its invariants are guaranteed, even during runtime (when it might be accessed by arbitrary JavaScript code)?

A simple example of what I want to do is the following MutableInt class:

export class MutableInt {

    static {
        Object.setPrototypeOf(MutableInt.prototype, null);
        Object.freeze(MutableInt.prototype);
        Object.freeze(MutableInt);
    }

    #value : int

    constructor (value : int = 0) {
        if (new.target !== MutableInt) throw new Error("MutableInt is final");
        if (!Number.isInteger(value)) throw new Error(`Integer expected, found: ${value}`);
        this.#value = value;
        Object.freeze(this);
    }

    get value(): number {
        return this.#value;
    }

    set value(v) {
        if (!Number.isInteger(v)) throw new Error(`Integer expected, found: ${v}`);
        this.#value = v;
    }

}

Is MutableInt properly locked down? Or is there something wrong or missing with this approach?

How to build/What’s the build command for vue2 typescript project for production?

I have vue2 and vuetify project written in typescript. Following is configuration files.

package.json

"scripts": {
    "build": "tsc --build",
  },
"devDependencies": {
    "typescript": "~4.1.5",
  },

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "dist",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Now, When I try to build using command npm run build, it successfully builds the dist folder but it doesn’t adds .vue files inside dist folder. So, what’s wrong here?

Why can I log an object value before declaration?

I just notice that the code below works even before I declare anything using var, let or const. I read an explanation that I’m creating anything on the global/window object (in non-strict mode), but I’m not doing any variable declaration/creation here (instead just throwing anything out of nowhere).

So, anything = {} is enough for JS to understand that I’m declaring (and initializing) anything? How does this really work?

anything = { 1: "anything" }
console.log(anything) // {1: "anything"}

How to get x number of random document in firestore with web v9

I’m working on a project where an explore page requires random posts. I want to get 10 random posts from the posts collection. I am using firebase web SDK v9.6.3.

This is code I have written to get x number of posts:

export async function getRandomPosts(postCount) {
   const q = query(
      collection(db, "posts"),
      limit(postCount)
      // orderBy("timestamp", "desc")
   );
   const querySnapshot = await getDocs(q);
   let posts = [];
   querySnapshot.forEach((doc) => {
      posts.push({
         id: doc.id,
         ...doc.data(),
         timestamp: doc.data().timestamp?.toDate().toString(),
      });
   });
   return posts;
}

I can’t find anything to get the random documents. Is there anything like rand in mySQL ?

CommonJS JavaScript modules – passing data to parent functions

Using CommonJS JavaScript Modules.
I have a module that I cannot edit or control. I call this the parent module.

I want to build on the parent’s functionality with additional features. Some of these child features need to use the functions in the parent. So I need to pass data to the parent and have it run like it was part of the parent module. The whole of the parent is exported.

Parent

function ParentModule () {
  DefaultElement.setStatus = function (status, block) {
    var statusBlock = block.querySelector('.' + this.statusBlock)
    var statusText = status ? 'Available' : 'Out of Stock';
  
    statusBlock.innerHTML = statusText;
  }
}

Child


function ChildModule () {
  UpdatedElement.update = function (el) {
    var selected = document.getElementById(el)
    var block = this.getBlock(selected)

    window.ParentModule.DefaultElement.setStatus(true, block);
  }
}

(Expected) Error

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

What is the syntax or pattern for this?

Calling the relevant function within the child module, simply causes an error. As I understand this is expected – as the child module imports the parent function it runs within the child so doesn’t have access to the same data.

Rather than import into the child is there a way to have the child module simple behave like it was all one file? Or how can I pass data up to the parent and have it behave like it’s always been part of the parent?

JavaScript function calculate square

The HTML page contains an element with the id “number”. The page calls a function calcSquare(), which has to fetch the value of the element, calculate its square (power of two), and print it in the console like so: “The square of X is Y”. Write this function. The HTML page in question will load your code, so you can refer to the page with the document keyword.

<body>
<p id="number">0</p>
<button id="button1" 
onclick="calcSquare()">Click here! 
</button>
</body>

Example output:

The square of … is …

The output of the program must be exactly the same as the example output (the most strict comparison level)

MY CODE:

function calcSquare() {
var number = document.getElementById("number").value;
Math.pow(number, 2);
}
console.log ("The square of" number "is" calcSquare)

That ID is given in the web page

Don’t understand how to write here console.log or maybe problem in the function??

I made a new request for a specific API [closed]

I made a new request for a specific API and I made a Loop that sends several requests, but the problem is that I want to print each response individually in the textarea, but it prints all responses after the Loop ends
I mean, I want him to print every response for each cycle of the loop, but I don’t want him to complete all the cycles the screenshot will close the ideasceenshot

Wrap is not working after dynamic load, why?

The wrap(); works well on its own, but after it is called after the load();, it doesn’t.

What could be done to make it work? I tried to put the wrap(); code inside a separate .js file, but that didn’t work. I also tried to load the wrap(); inside: $( window ).on( "load", function() { ... }) and then place it inside the footer of the html, which didn’t solve the problem either.

Here is my code:

$('.page-id-202 #partner, .page-id-201 #partner').load('https://webhelytervezo.hu/ #gallery-1');
         $(".gallery-item").each(function() {
  $(this).wrap($("<a/>").attr("href", "http://" + $(".gallery-caption", this).text().trim()));
    $("#gallery-1 a").attr('target','_blank');
});
figcaption{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gallery-1" class="gallery galleryid-9 gallery-columns-3 gallery-size-full"><figure class="gallery-item">
            <div class="gallery-icon landscape">
                <img width="200" height="74" src="https://webhelytervezo.hu/wp-content/uploads/2022/01/cup_revolution_logo.jpg" class="attachment-full size-full" alt="" loading="lazy" aria-describedby="gallery-1-49">
            </div>
                <figcaption class="wp-caption-text gallery-caption" id="gallery-1-49">
                www.web.cuprevolution.eu
                </figcaption></figure><figure class="gallery-item">
            <div class="gallery-icon landscape">
                <img width="200" height="74" src="https://webhelytervezo.hu/wp-content/uploads/2022/01/areklam.jpg" class="attachment-full size-full" alt="" loading="lazy" aria-describedby="gallery-1-39">
            </div>
                <figcaption class="wp-caption-text gallery-caption" id="gallery-1-39">
                www.areklam.hu
                </figcaption></figure><figure class="gallery-item">
            <div class="gallery-icon landscape">
                <img width="200" height="74" src="https://webhelytervezo.hu/wp-content/uploads/2022/01/coca_cola.jpg" class="attachment-full size-full" alt="" loading="lazy" aria-describedby="gallery-1-48">
            </div>
                <figcaption class="wp-caption-text gallery-caption" id="gallery-1-48">
                www.coca-cola.hu
                </figcaption></figure><figure class="gallery-item">
            <div class="gallery-icon landscape">
                <img width="200" height="74" src="https://webhelytervezo.hu/wp-content/uploads/2022/01/arkad.jpg" class="attachment-full size-full" alt="" loading="lazy" aria-describedby="gallery-1-40">
            </div>
                <figcaption class="wp-caption-text gallery-caption" id="gallery-1-40">
                www.arkad.hu
                </figcaption></figure><figure class="gallery-item">
            <div class="gallery-icon landscape">
                <img width="200" height="74" src="https://webhelytervezo.hu/wp-content/uploads/2022/01/besttv.jpg" class="attachment-full size-full" alt="" loading="lazy" aria-describedby="gallery-1-41">
            </div>
                <figcaption class="wp-caption-text gallery-caption" id="gallery-1-41">
                www.besttv.hu
                </figcaption></figure> 
        </div>

Gmail: shortcut to filter messages like this

I would like to quickly access my Gmail emails sent by the same sender. That will save me some time and fluidify my workflow.

I’m dreaming of a shortcut to find those emails quickly and, unless I’m mistaken, there is unfortunately not such a default shortcut in Gmail.

Did anyone try to do the same, and if yes, how did you do it?

I’m trying to use Shortkeys Google Chrome extension by firing a JavaScript event, but for now I couldn’t make it work:

Firing a JavaScript event with Shortkeys

All help is welcome.

Not able to make a SignUP request on app deployed on Heroku & Netlify

I am facing an error while making the POST SignUp request.

I had deployed the frontend on Netlify here and the backend on Heroku here.

Error

I am getting 2 errors:

  1. I am getting

     `users.findOne()` buffering timed out after 10000ms
    
  2. I am getting this on console

      SyntaxError: Unexpected token i in JSON at position 0
    

enrror

Code

Attached is the code in the flow

index.js

const connectToMongo = require('./db');
const express = require('express');


connectToMongo();
var cors = require('cors')
const app = express()
// const port = 5000

//to use req body 
app.use(cors())
app.use(express.json())

//Available routes
app.use('/api/auth',require('./routes/auth'));
app.use('/api/notes',require('./routes/notes'));

app.listen(process.env.PORT  , () => {
  console.log(`my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:${process.env.PORT }`)
})

auth.js (see only route1)

const express = require("express");
const { body, validationResult } = require("express-validator");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const JWT_SECRET = "mohitisagood$boy";
const fecthUser = require("../middleware/fetchUser");

//ROUTE 1 :Creating a User :POST - "/api/auth/createuser"
router.post(
  "/createuser",
  [
    body("name", "Name must have at least 3 characters").isLength({ min: 3 }),
    body("email", "Enter a valid email").isEmail(),
  ],
  async (req, res) => {

    let success = false;
    //If there are errors, then return bad request + Errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({success, errors: errors.array() });
    }

    try {
      //Check whether email exists
      let user = await User.findOne({ email: req.body.email });
      //console.log("user.nemail = " + user);
      if (user) {
        //console.log(user.email);
        return res.status(400).json({success, error: "Email Already Taken" });
      }

      //hashing the password here
      const salt = await bcrypt.genSalt(10);
      const secPass = await bcrypt.hash(req.body.password, salt);
      //user is created
      user = await User.create({
        name: req.body.name,
        email: req.body.email,
        password: secPass,
      });

      //passing the id as data to make jwt token
      const data = {
        user: {
          id: user.id,
        },
      };

      const authToken = jwt.sign(data, JWT_SECRET);
      //console.log(authToken)

      
      success = true;
      //res.json(user);
      res.json({success, authToken });
    } catch (error) {
      console.log(error.message);
      res.status(500).send("internal server error");
    }
  }
);

//ROUTE 2 :Authenticating a User :POST - "/api/auth/login"
router.post(
  "/login",
   .......
    )
});

module.exports = router;


MODEL_SCHEMA – users

const mongoose = require("mongoose");
const { Schema } = mongoose;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    validate(value) {
      if(value.length < 5) {
        throw new Error( "Minimum length is 5 characters");
      }
      else if (!value.match(/d/) || !value.match(/[a-zA-Z]/) ) {
        throw new Error(
          "Password must contain at least one letter and one number"
        );
      }

    }
    
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

const User = mongoose.model("users", UserSchema);
module.exports = User;

SignUpPage.js (frontEnd)

import React,{useState} from 'react';
import { useHistory } from 'react-router-dom';
import imgpath from "../assets/notepic.jpg";
import { motion } from 'framer-motion';

const Signup = (props) => {

    let history = useHistory();

    const [credentials, setCredentials] = useState({name:"", email:"", password:"",confmpassword:""});

    const onChange = (e) => {
        setCredentials({ ...credentials, [e.target.name]: e.target.value });
        //input mei value typed ho sake,jaise jaise value change ho vese-vese note me set ho jaye
      };

      const goToLogin = () => {
        history.push("/login")
      }

      const handleSubmit = async(e) => {
        e.preventDefault();
        const response = await fetch('https://my-notebook-mohit.herokuapp.com:/api/auth/createuser', {
            method: 'POST', 
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({name:credentials.name, email:credentials.email, password: credentials.password})
          });
          const json = await response.json();
          if(json.success === true){
            //storing the authtoken
            localStorage.setItem('token',json.authToken);
            history.push("/");
            console.log(json);
            props.showAlert("User registered succesfully!","info");
          } 
          else {
            props.showAlert("Invalid Credentials","danger");
          }
    }

    return (
      <motion.div className="container" id="manku" animate={{scale:[0.5,1]}} transition={{times:[0.1,0.4], ease:'easeInOut'}}>
      <div id="picturebody">
        <img src={imgpath} alt="note-pic" width="100%" />
      </div>
        <div id="loginbody">
        <div className="mt-3">
            <h2 className="my-2">Create your account here </h2>
            <form onSubmit={handleSubmit} className="login-form">
                ..
                ..
                ..
            </form>
            <div className="text-center my-3" id="bottom-text">
            mynotebook
        </div>
        </div>
        </div>
        </motion.div>
    )
}

export default Signup

I am also sharing the HEROKU LOGS here also
Screenshot
hlogs

In written form:

2022-01-22T10:35:31.575900+00:00 app[web.1]: > [email protected] start
2022-01-22T10:35:31.575901+00:00 app[web.1]: > node index.js
2022-01-22T10:35:31.575901+00:00 app[web.1]: 
2022-01-22T10:35:32.186481+00:00 heroku[web.1]: State changed from starting to up
2022-01-22T10:35:32.002450+00:00 app[web.1]: my-notebook backend listening at https://my-notebook-mohit.herokuapp.com:23186
2022-01-22T10:36:01.901941+00:00 app[web.1]: Connected to Mongo Successfully!
2022-01-22T10:37:28.170226+00:00 heroku[router]: at=info method=OPTIONS path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ca6d3e38-ca85-4b8d-834c-2503743f261e fwd="157.34.191.86" dyno=web.1 connect=0ms service=5ms status=204 bytes=301 protocol=https
2022-01-22T10:37:29.785982+00:00 app[web.1]: Cannot read properties of undefined (reading 'findOne')
2022-01-22T10:37:29.788991+00:00 heroku[router]: at=info method=POST path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=3f713497-80fb-45e1-a73c-c25fa7f03c4e fwd="157.34.191.86" dyno=web.1 connect=0ms service=25ms status=500 bytes=272 protocol=https
2022-01-22T10:54:57.762199+00:00 heroku[router]: at=info method=GET path="/api/auth/createuser" host=my-notebook-mohit.herokuapp.com request_id=ae666363-1d9c-4d9e-9104-c542c7d10837 fwd="34.230.34.4" dyno=web.1 connect=0ms service=2ms status=404 bytes=434 protocol=https
2022-01-22T10:55:04.937835+00:00 heroku[router]: at=info method=HEAD path="/" host=my-notebook-mohit.herokuapp.com request_id=f132be41-83f5-4a16-9b9d-ed98dda893bf fwd="217.182.175.162" dyno=web.1 connect=0ms service=2ms status=404 bytes=276 protocol=https

Are there any differences in .Jsx and .js saving extensions?

I made an app with react library and saved all the files as .js and its working perfectly fine. Can anyone please help me in understanding what differences does it bring when we save the files with .jsx extensions in terms of performance or anything?

And if it doesn’t why do we use .jsx ?

PS: Although, I am new to react but I am aware of the basic differences between .jsx and .js extensions.

Google App Script: Open Google Sheet, wait for all formulas to process, close sheet

The Problem

Google Data Studio is not fetching new data from Google Sheet, because Google Sheet is not open, and formulas will not run to update data.

My Setup: Google Form > Google Sheet > Google Data Studio

  1. I am using a Google Form to add data to a Google Sheet.
  2. Google Sheet contains formulas to modify the data from the Google Form.
  3. Google Data Studio fetches Google Sheet data every 15 minutes.

Note

Normally when opening the Google Sheet, it takes around 5 minutes to finish running all the formulas. (it’s a very large file, with many formulas)

My Solution: Is this the best option?

Trigger set to run every 10 minutes.

function wakupSheet(){
   var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
   Utilities.sleep(100000);
}