How to call a method from a distinct component using Vue 3 & Pinia

I want to call an inner function of a component if I click a button. There are many suggestions using shared data, but it should work separately for different components. Here’s an example:

// Page.vue
<template>
    <MyComponent my-prop="abc"/>
    <button @click="???">ButtonX</button>

    <MyComponent my-prop="123"/>
    <button @click="???">ButtonY</button>
</template>
// ...
// MyComponent.vue:
<script>
    function foo() {
        //Do something inside this component
    }
</script>
// ...

My goal is that if I press ButtonX then foo() function called for <MyComponent my-prop="abc"/> but if I press ButtonY the same inner foo() function runs for <MyComponent my-prop="123"/>.
How could I achieve that? (The components could be far from each other in the component tree.)

I prefer solution using only Vue 3 and Pinia.

Mongoose: define a schema property with one name in Document object and another in the actual database

I have in my app multiple models defined for one collection: Trainee, Employee, Contractor, Manager, and Removed.

Each model schema has a date property that represents the time the person “entered” into the status represented by the model:

const TraineeSchema = new Schema({
  ...
  accetedOn: Date,
  ...
});

const EmployeeSchema = new Schema({
  ...
  hiredOn: Date,
  ...
});

const ContractorSchema = new Schema({
  ...
  contractedOn: Date,
  ...
});

const ManagerSchema = new Schema({
  ...
  promotedOn: Date,
  ...
});

const RemovedSchema = new Schema({
  ...
  terminatedOn: Date,
  ...
});

In one case I perform an aggregation that filters data based on these properties. It would be a simpler code if all of these properties had the same name in the database. So, if for example, the data property is named enteredIntoStatusOn for all these schemas, I could just have:

{ $match: { enteredIntoStatusOn: { $gt: ... } }

Is it possible to define in a schema a property that has one name when used in a mongoose Document object, but actually saved under a different name in the database?

I know I could do something similar using aliases. For example, I could define the manager schema with the enteredIntoStatusOn defined, and then also define a virtual field named promotedOn that simply gets and sets the enteredIntoStatusOn field. But then, both promotedOn and enteredIntoStatusOn are exposed in a document for the Manager model. Is there a way in Mongoose to just have the alias without the original property?

How to intercept backend (api) requests at browser level in multi monitor setup

Problem:
Assume an application launched in multimonitor. i.e. Application launched in 2 monitors with separate browser instances.
Now each browser instance makes a API call to backend to load the data i.e. http:///loadData

As we see here, there are two requests to backend from separate browser instances but actually both are trying to load same data. This will create unnecessary overhead on backend.

Is there any way we can intercept backend API at browser level and make sure only one request goes to backend. And other browser request will be served from the response.

enter image description here

Looked into Service worker to handle this scenario. But it is main intent to use for offline mode. And not sure if it handles all the scenarios like intercepting GET/POST requests.

How to general 4D, 3D and 2D number from 4 input numbers

I got stuck how to generate array like this from 4 input values.

enter image description here

As = first position = 12

Kop = second position = 34

Kepala = third position = 56

ekor = fourth position = 78

User will be able to any number into those position (input) or sometime some field can be blank.

I would like the those 4 input values combine together and form as 4D, 3D and 2D number. But make sure the position cannot be change and the generate number cannot duplicate.

Example:

  • number 1 and 2 are on first position ever.
  • number 3 and 4 are on second position ever.
  • number 5 and 6 are on third position ever.
  • number 7 and 8 are on fourth position ever.

Source code (PHP or JS) or Idea both are appreciated.

problem with setting a value of a global variable inside a function [duplicate]

i have a problem with setting the value of a global variable inside a function so that it can be later used inside another function.

My code:

var user_id;

router.post('/add_note', function(request, response, next){
var note_title = request.body.note_title;
var note_content = request.body.note_content;

database.query(sql,function(err, result) {
  if (err) throw err;
  var results=JSON.parse(JSON.stringify(result))
  user_id=results[0].user_id;
  console.log("from inside: "+user_id);
});

var sql = `INSERT INTO notes (user_id, note_title, note_content) VALUES (${user_id}, "${note_title}", "${note_content}", NOW())`;
console.log("from outside: "+user_id);
console.log(sql);

when i submit the form it returns:

from outside: undefined
INSERT INTO notes (user_id, note_title, note_content) VALUES (undefined, "ads", "ads", NOW())
from inside: 2

why is it undefined, the variable should be global, i am going insane

Categorization Projects with HTML, CSS & JS

I have a webpage with lists of DIV that shows my projects. Each project has a tag that describes its type, such as Graphic Design, Animation, or Photography. I want to add buttons as well for viewers to filter through tags. If a viewer clicks on the Photography button, all other projects should be hidden.

Is it possible to make a function like this in JS? How do I target projects (divs) with their tag?

Eel Python : VS code isn’t printing anything when button is triggered

I have been trying to print hello world on the VS code terminal when my button is pressed. The javascript code takes the input from an HTML button and passes to python through Eel

my HTML code –

<button
type="button"
id="setuplogger"
style="background-color: #dd9000"
class="btn btn-dark"
onclick="setuplogger_fnc()"
>

My JS code —

function setuplogger_fnc() {
     
  eel.logger()(return_msg);

};

function return_msg() {
  console.log('returned hello')
}

My python Eel code –

@eel.expose
def logger():
    print("hello world")

    return "hello"

The code is returning “hello” back to the JS but isn’t printing anything on VS code. Can anyone explain why?

Adding Javascript to check dimensions in Qualtrics

Does anyone know if it’s possible to alter the meta info question in Qualtrics to check phone dimensions?

By default, it provides the screen resolution of the respondent’s browser in pixels. However, I’m trying to create a screening survey that checks respondents’ phone dimensions so I can determine whether are eligible for a study without asking them to measure their phones as it seems lots of people don’t know their phone dimensions.

Does anyone know how to do this using Javascript?

I’m familiar with Javascript but not sure where to start with this particular issue.

Thank you!

Angular project backend on Netlify/Render or Public IP [closed]

I’m working on an Angular Project and I’m hosting it on Netlify currently. I’m able to access the website but if I want to login, I need to have the app.js file running on my local machine, which is understandable as I’m connecting to my mongoDB database through that, but I can’t always have it running on my local machine so I’m looking for a way to somehow have it running on some server(not sure if that’s the right thing to do or even the right term).

Is there a way I can run it along with the rest of my code on Netlify or even somewhere else. I’m open to all suggestions and solutions.

I’m very new to this so please let me know if you need more info regarding anything.

This is the app.js file:

const express=require('express');
const app=express();
const port=process.env.port || 8080 //this is used for server port z
const authRoute=require('./routes/auth-route');
const mongoose=require('mongoose');
const bodyParser = require('body-parser');
const cors=require('cors');

mongoose.connect('some_random_text_to_replace_the_mongodb_connection_string',(err)=>{
    if(err){
        console.log("Database is not connected");
    }else{
        console.log("Database is connected...")
    }
}); 

mongoose.set('strictQuery', true);

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use(cors())
app.use('/auth',authRoute);

app.get('/',(req,res) => {
    res.send('welcome to hSVPGis .... ')
})
app.listen(port,()=>{
console.log("Node server is connected..",port)
})

Como inserir um índice apos outro em um array ate o final do mesmo [closed]

Olá gostaria de inserir um elemento após cada índice de um array ate o final do mesmo.
O array exemplo esta assim:
[1,2,3,4]
quero que ele fique assim:
[separa,1,separa,2,separa,3,separa,4,separa]

Importante:

  • o array em questão já ira vir definido com seus índices, portanto não e possível inserir a cada criação do array.
    o que eu tentei:
arr = [1,2,3,4]
let element = 'separa';
let insertInArray = arr.indexOf(element);
while (insertInArray!= -1) {
arr.push('separa');
insertInArray= arr.indexOf(element, insertInArray+ 1);
console.log (arr);
}

eu pensei que ele iria fazer ate o final, mas assim que cria o primeiro elemento ele para.

Acho que expliquei tudo ali em cima.
se estou fazendo de maneira errada ou se tem outra função que não seja o indexof, estou para ouvir.

Appending Child Fails without Exception

I have a JSON file that stores an array of objects. In the object, I have a property named url that stores the URL to a YouTube video. Once I fetch the JSON file and loop over the objects I am creating an <iframe> that sets the src to the url property. Here is the method I am using:

const update = (information, selector) => {
    const parent = document.querySelector(selector);
    if (!information) {
        const rootParent = parent.parentNode;
        rootParent.remove();
        return
    }

    parent.querySelector('h4').innerText = information.title;
    parent.querySelector('h6').innerText = information.dateFormatted;

    const iframe = document.createElement('iframe');
    iframe.setAttribute('height', '315');
    iframe.setAttribute('width', '560');
    iframe.setAttribute('frameborder', '0');
    iframe.setAttribute('src', information.url);
    parent.appendChild(iframe);
}

The issue is that the first call to the method works fine, but after the second iteration when it makes the call again it fails on the parent.appendChild line.

If I setup a try/catch and setup a breakpoint in the catch, the catch never gets fired. It isn’t even being hit if I add a debugger statement to it.

What could be causing this and more importantly, why isn’t the debugger being triggered?

Proxy error: Could not proxy request /auth/register from localhost:3000 to http://localhost:8800/api/

register.jsx

import React from 'react'
import { useState } from "react";
import {Link } from 'react-router-dom'
import axios from "axios";

const Register = () => {
const [inputs,setInputs] = useState({
  username:"",
  email:"",
  password:"",
})
const [err, setError] = useState(null)
const handleChange = e =>{
  setInputs(prev=>({...prev, [e.target.name]: e.target.value}))
}

const handleSubmit = async e =>{
  e.preventDefault()
//  try{
   const res = await axios.post("/auth/register", inputs)
console.log ("test",res)
// }catch(err){
  // console.log("test",err.response.data)
  // }
}

  return (

    <div className='auth'>
        <h1>Register</h1>
        <form>
            <input required type="text" placeholder='username' name='username' onChange={handleChange}/> 
            <input required type="email" placeholder='email' name='email' onChange={handleChange}/>
            <input required type="password" placeholder='password' name='password' onChange={handleChange}/>
            <button onClick={handleSubmit} >Register</button>
            {err &&<p>{err}</p>}
            <span>Do you have an account? <Link to="/login">Login</Link>
            </span>
        </form>
    </div>
  );
}

export default Register

auth.js

import { db } from "../db.js";
import bcrypt from "bcryptjs";

export const register = (req, res) => {
    //CHECK EXISTING USER
    const q = "SELECT * FROM users WHERE email = ? OR username = ?";
  
    db.query(q, [req.body.email, req.body.username], (err, data) => {
      if (err) return res.status(500).json(err);
      if (data.length) return res.status(409).json("User already exists!");
  
      //Hash the password and create a user
      const salt = bcrypt.genSaltSync(10);
      const hash = bcrypt.hashSync(req.body.password, salt);
  
      const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
      const values = [req.body.username, req.body.email, hash];
  
      db.query(q, [values], (err, data) => {
        if (err) return res.status(500).json(err);
        return res.status(200).json("User has been created.");
      });
    });
  };

export const login = (req, res) ={};
export const logout = (req, res) ={};

package.json

{
  "name": "booking",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "dompurify": "^2.4.0",
    "moment": "^2.29.4",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-quill": "^2.0.0",
    "react-router-dom": "^6.4.1",
    "react-scripts": "5.0.1",
    "sass": "^1.55.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8800/api/"
}

I’m following tutorial https://www.youtube.com/watch?v=0aPLk2e2Z3g&t=3250s

i’m stuck at this error: Proxy error: Could not proxy request /auth/register from localhost:3000 to http://localhost:8800/api/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

please help

i tried everything online nothing work

for loop netsuite saved search

i have created saved search for loop netsuite

    do {
    var searchResult = reportSeach.run().getRange({
        start: startrow,
        end: startrow + 1000
    })
    var cartonMin = 0;
    var pcsMin = 0;
    for (var i = 0; i < searchResult.length; i++) {
        var carton = searchResult[i].getValue(searchResult[i].columns[0]);
        var cartonReceipt = searchResult[i].getValue(searchResult[i].columns[1]);
        var pcs = searchResult[i].getValue(searchResult[i].columns[2]);
        var pcsReceipt = searchResult[i].getValue(searchResult[i].columns[3]);
        var date = searchResult[i].getValue(searchResult[i].columns[4]);
        var location = searchResult[i].getValue(searchResult[i].columns[5]);
        
        //calculate problem
        cartonMin = parseInt(carton - cartonReceipt);
        pcsMin = parseInt(pcs - pcsMin);

    }
} while (suratResult.length == 1000);

and the result in excel
only last row is true

can help me solve that problem, thanks