FirebaseError: Missing or insufficient permissions. with getDocs()

I tried reading the first couple of answers but none seem to have the same rule with the one I currently have my hands on.

When I try to call the getDocs() function (using react)

let userInfo = await getDoc(doc(db, chargerInfo.userRef));

I seem to be getting the error FirebaseError: Missing or insufficient permissions.
what can I do to not get this error? Below is the rule that I have

match /devices/{id} {
        allow read: if request.auth != null;
        allow update: if request.auth != null;
    }
    ```

Error: The top-level-await experiment is not enabled, but loader is already installed

This is the full error:

ERROR in ./src/index.js
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

but topLevelAwait is already enabled in webpack.config.js.

webpack.config.js:

const path = require('path');

module.exports = {
  // The entry point file described above
  entry: './src/index.js',
  // The location of the build folder described above
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },

  module: {
    rules: [{ 
        test: '/.js|.jsx$/', 
        use: 'raw-loader' }],
  },
  // Optional and for development only. This provides the ability to
  // map the built code back to the original source format when debugging.
  devtool: 'eval-source-map',

  experiments: {
    topLevelAwait: true,
  },
};

js:

import { initializeApp } from "firebase/app";
// import { getAnalytics } from "firebase/analytics";
import { getFirestore, collection, getDocs } from "firebase/firestore";

const firebaseApp = initializeApp({
  apiKey: "AIzaSyDLl4mlsDgKXzYqu7BtWj60Gne3ybwxEXU",
  authDomain: "tutorbuddy-a5411.firebaseapp.com",
  projectId: "tutorbuddy-a5411",
  storageBucket: "tutorbuddy-a5411.appspot.com",
  messagingSenderId: "402150617426",
  appId: "1:402150617426:web:eaab24a4375b5c543cca8b",
  measurementId: "G-B2KF86YVXC"
});

const db = getFirestore(firebaseApp);

const todosCol = collection(db, 'todos');
const snapshot = await getDocs(todosCol);
// const analytics = getAnalytics(app);

Probably a really simple answer, but I’ve been at this for a while haha any help is really appreciated!!

Unable to update the key value of json objects in an array with another list of array values in angular

While i’m trying to update the key values of an array of json objects using the values from another array:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  arr = [
    { name: 'Rakesh', age: 24 },
    { name: 'Ram', age: 26 },
  ];
  ar = [45, 50];
  array = [];


  ngOnInit() {
    this.myfunc();
  }

  myfunc(): void {
    this.arr.forEach((e) => {
      this.ar.forEach((el) => {
        e['age'] = el;
        this.array.push(e);
      });
    });
    console.log(this.array);
  }
}

While looping, age is getting updated with each value as in array, but on pushing into the array, the value of key(age) of json objects are getting updated with the last element of the array. How can I make this work?

Below is the output I’m getting:

    Output of my code:
    [{ name: 'Rakesh', age: 50 },
    { name: 'Rakesh', age: 50 },
    { name: 'Ram', age: 50},
    { name: 'Ram', age: 50 },]
    
    Expected output:
    [
    { name: 'Rakesh', age: 45 },
    { name: 'Rakesh', age: 50 },
    { name: 'Ram', age: 45 },
    { name: 'Ram', age: 50 }
    ]

Message from client side is received in server side but don’t know how to use it globally in socket.io

I am beginner so please help me. I currently build a simple chat with socket.io and express in node.js.

Problem:

I send the message from the client side.

client.js

user_send.addEventListener("click",()=>{
    const msg = user_msg.value;
    
    //emit message to server
    socket.emit('chatMessage',msg);
});

and I receive it in server side

server.js

   socket.on('chatMessage', msg =>{
    io.emit('message',msg);

   console.log(msg);
   
 
   });

but don’t khow how to use msg parameter which has to show in html
I currently use ejs.js

I just want that the msg paramater is stored in variable which can be used inside of ejs call function.

the ejs code is:

app.get("/", (req,res) =>{

 
  res.render("index",{messagedata: msg});
});

full code of client.js

const socket = io();


const user_send =document.querySelector(".send-btn");
const user_msg=document.querySelector(".input-msg");


//message from server
socket.on('message',message=>{
  console.log(message);
})

//getting socketid from server
socket.on('socketid',socketid=>{
  console.log(socketid);
  
});


//ading eventlistner in message send button
user_send.addEventListener("click",()=>{

    //get mesage from text filed
    const msg = user_msg.value;

    //emit message to server
    socket.emit('chatMessage',msg);
});

full code of server.js:

const express = require('express');
const path = require('path');
const app = express();
const mysql =require("mysql")
const server = require('http').createServer(app);
const socketio = require('socket.io');
const io = socketio(server);
const port = process.env.PORT || 3000




//for ejs view Engine
app.set('view engine','ejs');


app.get("/", (req,res) =>{

 
  res.render("index",{messagedata: **I just want that the reveived msg can use here**});
});





//set a static folder
//import path among other dependencies.
app.use(express.static(path.join(__dirname + '/public')));



//run when client connect
io.on('connection', socket => {

   console.log('someone is just connect..');
   // welcome current user
   socket.emit('message','welcome to chat-app');
   
   //Broadcast when the user connect.
   socket.broadcast.emit('message','user '+socket.id+' connect to the chat');
   
   //sending socketId to the coient side
   socket.broadcast.emit('socketid',socket.id);

   
   //run when user disconnect
   socket.on('disconnect',()=>{
    io.emit('message','user has disconnect the chat');
   });

   //listen chatMessage
   socket.on('chatMessage', msg =>{
    io.emit('message',msg);

   console.log(msg);
   
 
   });

  
});




//run when the server is runing
server.listen(port, () => {
  console.log(`Server running on port: ${port}`);
});

heroku[router]: at=error code=H10 desc=”App crashed” method=HEAD

I got this error from heroku:

enter image description here

This is what I got when write “heroku logs –tail” on command prompt

2022-07-10T14:28:53.606628+00:00 heroku[web.1]: Process exited with
> status 1 2022-07-10T14:28:53.703267+00:00 heroku[web.1]: State changed
> from starting to crashed 2022-07-10T14:40:41.758300+00:00
> heroku[router]: at=error code=H10 desc=”App crashed” method=HEAD
> path=”/api/v3/rate_limit” host=pomoworki.herokuapp.com
> request_id=c0d582d4-7781-4db6-af9b-706f2050de41 fwd=”181.56.0.86″
> dyno= connect= service= status=503 bytes= protocol=https
> 2022-07-10T14:40:47.486286+00:00 heroku[router]: at=error code=H10
> desc=”App crashed” method=GET path=”/” host=pomoworki.herokuapp.com
> request_id=2a00d7e4-316f-40ba-8218-a6d40df6cf29 fwd=”181.56.0.86″
> dyno= connect= service= status=503 bytes= protocol=https
> 2022-07-10T14:40:47.883806+00:00 heroku[router]: at=error code=H10
> desc=”App crashed” method=GET path=”/favicon.ico”
> host=pomoworki.herokuapp.com
> request_id=840f774a-19da-4ee4-85d0-f2f6e0a24c44 fwd=”181.56.0.86″
> dyno= connect= service= status=503 bytes= protocol=https

This is a screenshot from error:

enter image description here

This is my back end:

server.js

const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const connectDB = require('./config/db')
const passport = require('passport')
const bodyParser = require('body-parser')
const routes = require('./routes/index')

connectDB()

const app = express()

if(process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'))
}

app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(routes)
app.use(passport.initialize())
require('./config/passport')(passport)

const PORT = process.env.PORT || 3000

app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));

Procfile

web: node server

.gitignore

node_modules/

index.js

const express = require('express')
const actions = require('../methods/actions')
const router = express.Router()

router.get('/', (req, res) => {
    res.send('Hello World')
})

router.get('/dashboard', (req, res) => {
    res.send('Dashboard')
})

//@desc Adding new user
//@route POST /adduser
router.post('/adduser', actions.addNew)
//@desc Authenticate a user
//@route POST /authenticate
router.post('/authenticate', actions.authenticate)
//@desc Get info on a user
//@route GET /getinfo
router.get('/getinfo', actions.getinfo)

module.exports = router

user.js

var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var userSchema = new Schema({
    name: {
        type: String,
        require: true
    },
    password: {
        type: String,
        require: true
    }
})

userSchema.pre('save', function (next) {
    var user = this;
    if(this.isModified('password') || this.isNow) {
        bcrypt.genSalt(10, function (err, salt){
            if(err) {
                return next(err)
            }
            bcrypt.hash(user.password, salt, function(err, hash){
                if (err) {
                    return next(err)
                }
                user.password = hash;
                next()
            })
        })
    }
    else {
        return next()
    }
})

userSchema.methods.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if(err) {
            return cb(err)
        }
        cb(null, isMatch)
    })
}

module.exports = mongoose.model('User', userSchema)

actions.js

var User = require('../models/user')
var jwt = require('jwt-simple')
var config = require('../config/dbconfig')

var functions = {
    addNew: function(req, res) {
        if((!req.body.name) || (!req.body.name)) {
            res.json({success: false, msg: 'Enter all fields'})
        }
        else{
            var newUser = User({
                name: req.body.name,
                password: req.body.password
            });
            newUser.save(function (err, newUser) {
                if (err) {
                    res.json({success: false, msg: 'Failed to save'})
                }
                else{
                    res.json({success: true, msg: "Successfully saved"})
                }
            })
        }
    },
    authenticate: function (req, res) {
        User.findOne({
            name: req.body.name
        }, function (err, user) {
            if (err) throw err
            if (!user) {
                res.status(403).send({success: false, msg: 'Authentication failed. User not found'})
            }
            else {
                user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                        var token = jwt.encode(user, config.secret)
                        res.json({success: true, token: token})
                    }
                    else{
                        return res.status(403).send({success: false, msg: 'Authentication failed, wrong password'})
                    }
                })
            }
        }
        )
    },
    getinfo: function (req, res) {
        if(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            var token = req.headers.authorization.split(' ')[1]
            var decodedtoken = jwt.decode(token, config.secret)
            return res.json({success: true, msg: 'Hello ' + decodedtoken.name})
        }
        else{
            return res.json({success: false, msg: 'No Headers'})
        }
    }
}


module.exports = functions

passport.js

var JwtStrategy = require('passport-jwt').Strategy
var ExtractJwt = require('passport-jwt').ExtractJwt

var User = require('../models/user')
var config = require('./dbconfig')

module.exports = function (passport) {
    var opts = {}

    opts.secretOrKey = config.secret
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt')

    passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
        User.find({
            id: jwt_payload.id
        }, function (err, user) {
            if(err) {
                return done(err, false)
            }
            if (user) {
                return done(null, user)
            }
            else{
                return done(null, false )
            }
        }
        )
    }))
}

db.js

const mongoose = require('mongoose')
const dbConfig = require('./dbconfig')

const connectDB = async() => {
    try {
        const conn = await mongoose.connect(dbConfig.database, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        })
        console.log(`MongoDB Connected: ${conn.connection.host}`)
    }
    catch (err) {
        console.log(err)
        process.exit(1)
    }
}

module.exports = connectDB 

How to solve this issue

Thank you in advance

Dynamically Retrieving Data Entered from Static Forms with Javascript

I’m going to write a service with PHP and thanks to this service, I need to take what the content of the data in any form on any website is and show it to the user of the service.

I am planning to fetch the data in the form with javascript. The working principle will be as follows.

  1. The user will become a member of the system.
  2. He will be given a management panel.
  3. In this panel, he will enter the website address where the form is located.
  4. After entering the domain, it will enter the id of the form from which the data will be retrieved and the id/classes of the fields from which the information will be obtained.
  5. A link with a javascript code will be generated.
  6. This will add the link to the head area of ​​the site.
  7. Whenever data is sent over the form, he will see the form data he wants on his own panel (in the 2nd).

As I mentioned, I want to upload a javascript file to the relevant website to get the data from the form. But I’m not sure how healthy this procedure will be.

Also, don’t think about a single form, there can be a different form on almost every page and I cannot create a separate javascript file for each form. That’s why I need to handle operations with a single javascript file.

How to better write using jquery to click on the periphery to close the pop-up window

I want to realize that a window can appear when the button is clicked, and when the click is outside the window, the window can be closed, but at present I judge it by e.target.className, but I think this way of writing is not ideal because if it is inside the window If there are a lot of objects, I seem to have to write more e.target.className to complete the requirements, so I want to find a better and more professional way of writing!

In addition, I hope that I can click the tool button repeatedly to close and open the window, but I don’t know how to write it. I tried to use the toggle method but still can’t achieve the effect. I hope I can get your help, thank you.

$(".tool").on("click", function (e) {
  $(document).on("click", function (e) {
    if (
      e.target.className == "delet_wrap" ||
      e.target.className == "consider" ||
      e.target.className == "confirm" ||
      e.target.className == "btn_group" ||
      e.target.className == "tool" ||
      e.target.className == "txt"
    ) {
      $(".delet_wrap").css("display", "inline-block");
    } else {
      $(".delet_wrap").css("display", "none");
    }
  });
});
body {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tool {
  position: relative;
  text-decoration: none;
  background-color: yellow;
  border: 1px solid #222;
  border-radius: 6px;
  padding: 10px;
  color: #222;
}
.tool .delet_wrap {
  padding: 20px;
  position: absolute;
  bottom: -90px;
  left: 10px;
  background-color: #ccc;
  border: 1px solid #222;
  display: none;
}
.tool .delet_wrap p {
  text-align: center;
}
.tool .delet_wrap .btn_group {
  display: flex;
  white-space: nowrap;
  margin-top: 10px;
}
.tool .delet_wrap .btn_group .consider {
  background-color: #fff;
  border: 1px solid #222;
  margin-right: 10px;
}
.tool .delet_wrap .btn_group .confirm {
  text-decoration: none;
  border: 1px solid #222;
  margin-left: 10px;
  background-color: #222;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="javascript:;" class="tool">tool
  <div class="delet_wrap">
    <p class="txt">Are you sure you want to remove?</p>
    <div class="btn_group">
      <button class="consider">consider</button>
      <button class="confirm">confirm</button> 
    </div>
  </div>
</a>

React Native Pan Gesture Handler dragging not working properly

So I’m trying to implement a draggable circle which can be moved up an down randomly inside a svg-element.
I am using the Svg-element from react-native-svg and inside I have multiple of the following custom component:

const panGestureHandler = useAnimatedGestureHandler({
    onStart: (event, context) => {
        context.translateY = translateY.value;
        console.log("start");
    },
    onActive: (event, context) => {
        console.log(event.translationY);
        let tmp = event.translationY + context.translateY;
        if (posY + tmp >= svgHeight) {
            translateY.value = svgHeight - posY;
        } else if (posY + tmp <= 0) {
            translateY.value = -posY;
        } else {
            translateY.value = tmp;
        }
    },
    onEnd: (event, context) => {
        console.log("end");
    },
});

const translateStyle = useAnimatedStyle(() => {
    return {
        transform: [
            {
                translateY: translateY.value,
            },
        ],
    };
});

return (
    <PanGestureHandler onGestureEvent={panGestureHandler} style={translateStyle}>
        <AnimatedCircle
            cx={posX}
            cy={posY}
            r={radius}
            fill={color}
            stroke={color}
            style={translateStyle}
            animatedProps={strokeAnimation}
        />
    </PanGestureHandler>
);

The onActive inside panGestureHandler should prevent the dragging outside of the svg.
AnimatedCircle is an animated component from react-native-reanimated and implemented like this:

import { Circle } from "react-native-svg";
const AnimatedCircle = Animated.createAnimatedComponent(Circle);

However, most of the time the dragging only works on the element created last (created while iterating over an array) and once moved up or down, it cannot be moved anymore.

But if I drag the circle somewhere and then place it at its start-point, I can drag it again.

Trying it without the style on the PanGestureHandler yields the same result btw.

Any help is appreciated πŸ™‚

Array of object and forEach method element access

I have an array of objects defined as such:

const people = [
   {
     name: "John",
     dateOfBirth: 1990,
     dateOfDeath: 2020
   },
   {
     name: "Jane",
     dateOfBirth: 1970,
     dateOfDeath: 2019,
   },
   {
    name: "Micheal",
    dateOfBirth: 2002,
   }
 ]

I want to loop through the whole array and set the dateOfDeath for every person still alive to today.

I used

people.forEach ( element => {
   if(!("dateOfDeath" in element)) 
        element.dateOfDeath = (new date()).getFullYear();
});

My question is, why does this work? how can the callback arrow function access the array element and modify it? shouldn’t it modify only the local element variable (which is the function parameter), hence leaving the array item intact?

Load text from a .txt file and display in jsPsychHtmlButtonResponse

I want to use jsPsychHtmlButtonResponse to display a .txt-file from a local folder on my computer.
The reproducible code below does not work, while a very similar adaptation works for the display of images with jsPsychImageButtonResponse.

Does not work:

var text_display = {
  type: jsPsychHtmlButtonResponse,
  stimulus: text_files/test.txt,
  choices: ["Ready"],
};

Works:

var image_display = {
  type: jsPsychImageButtonResponse,
  stimulus: images_files/test.png,
  choices: ["Ready"],
};

Do you have any suggestions how to handle this problem?

Highlight New added content Html, CSS & JS

I have a web page that dynamically update it self (adds new text from a json file). The new added content gets a red color and the previous gets a white color.
How can I make the new added content when the user clicks anywhere on the web page change its color to white?

Split URL that contains more than one comma javascript

so basically i try to split a string of URL that contains morethan one Comma, but the result turns out to be like this:

{
            "photoUrl": [
                "https://m.media-amazon.com/images/M/MV5BMTU4MTgxOTQ0Nl5BMl5BanBnXkFtZTgwNDI0Mjk1NDM@._V1_UY100_CR19",
                "0",
                "100",
                "100_AL_.jpg",
                "https://m.media-amazon.com/images/M/MV5BMTczMTk5MjkwOF5BMl5BanBnXkFtZTgwMDI0Mjk1NDM@._V1_UY100_CR12",
                "0",
                "100",
                "100_AL_.jpg",
                "https://m.media-amazon.com/images/M/MV5BZTFiODA5NWEtM2FhNC00MWEzLTlkYjgtMWMwNzBhYzlkY2U3XkEyXkFqcGdeQXVyMDM2NDM2MQ@@._V1_UX100_CR0",
                "0",
                "100",
                "100_AL_.jpg"
            ]
        },

Here is my code, is there a way to fix it….

for (let i = 0; i < data.length; i++) {
                console.log(data[i].genre[i].genre.split(","));
                New_data.push({ photoUrl: data[i].photo[i].photoUrl.split(",") });
                New_data.push({ genre: data[i].genre[i].genre.split(",") });
            }