How do I render different pages with variables on post request of login with passport.js local authentication?(Express)

I am trying to login the user with passport.js authentication and on success I redirect the user to the last page that comes from a variable inside the login page, and on failure I re-render the login page with a message, I tried to do it but I fail, here what I did:

router.post('/login', 
  body('backurl').trim().escape(),

  (req,res,next) =>{
    passport.authenticate('local', (err,user)=>{
      if(err){return next(err)}
      if(!user){
        return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
      }
      if(req.body.backurl == null){
        return res.redirect('/yourcourses')
      }
      return res.redirect(req.body.backurl)
    });
  }
); 

it just keeps endlessly loading and nothing comes out, what is wrong with my code?

Thanks!

NoSuchElementError: no such element: Unable to locate element: {“method”:”css selector”,”selector”:”*[id=”table”]”}

I’m trying to write browser tests for create-react-app with selenium.

Test Code:

 var browser = new webdriver.Builder()
  .usingServer()
  .withCapabilities({ browserName: "chrome" })
  .build();

it("upload file and check table is loaded", async function () {
    browser
      .findElement({ id: "fileUpload" })
      .sendKeys("/home/user/test.csv");

    webdriver.until.elementIsVisible(
      browser.findElement(webdriver.By.id("table"))
    );
    return new Promise((resolve, reject) => {
      browser
        .findElement(webdriver.By.id("table"))
        .then((elem) => resolve())
        .catch((err) => reject(err));
    });
  });

Component:

class Home extends Component {
  state = {
    data: "",
  };
  getData = (e) => {
    var formData = new FormData();
    formData.append("file", e.target.files[0]);
    return fetch("http://localhost:8080/api/csv/upload", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((response) => {
        this.setState({ data: response });
      })
      .catch((error) => {
        console.log("Unable to fetch data");
      });
  };
  render() {
    const { classes } = this.props;
    return (
      <div data-testid="home">
        <br />
        {this.state.data !== "" ? (
          <>
            <Graphs data={this.state.data} />
            <DataTable data={this.state.data} />{" "}
          </>
        ) : (
          <input
            accept="image/*"
            id="fileUpload"
            multiple
            type="file"
            onChange={this.getData}
            data-testid="inputFile"
          />
        )}
      </div>
    );
  }
}

DataTable component:

export default function DataTable(props) {
  const classes = useStyles();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event.target.value);
    setPage(0);
  };
  const headers = Object.keys(props.data[0]);
  return (
    <Paper className={classes.root} data-testid="table" id="table">
      <TableContainer className={classes.container}>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>
              {headers.map((header, index) => {
                return <TableCell key={index}>{header}</TableCell>;
              })}
            </TableRow>
          </TableHead>
          <TableBody>
            {props.data
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map((dataValue, index) => {
                return (
                  <TableRow hover role="checkbox" tabIndex={-1} key={index}>
                    {headers.map((header, key) => (
                      <TableCell key={key}>{dataValue[header]}</TableCell>
                    ))}
                  </TableRow>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
      <TablePagination
        rowsPerPageOptions={[5, 10, 15]}
        component="div"
        count={props.data.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
    </Paper>
  );
}

Basically, application populates data from csv file into table and charts.I want to write browser test for app. Even though I added wait it’s still unable to find element.For more reference ,source code link: https://github.com/renukatamboli/data-visualization. Any help will be appreciated.

Menu that fades out non-related divs depending on category with jquery

I’m making this project that needs to have a menu of categories in which when I click a category i want, it will fade out the other projects that don’t have that category, the problem is i can’t come up with the logic to make the parent div disappear, in the beginning i was able to make all the tags that weren’t the one clicked disappear but when I tried to do the same with the parent div i failed, all i did was make all the projects disappear including the ones that do have that category.

It must be done with jQuery, and I don’t want to have to add another class to make it disappear.

I found a similar problem that was solved here and tried to follow the code:

$("#link-that-will-be-clicked").click(function() {
$(".common-class:not(.class1)").fadeOut();});

but I could only make it work for the div that contained the categories, not the whole parent. So I tried going for the parent and then checking if it contains the category but it didn’t work.

This is what I’ve done so far:
https://jsfiddle.net/devgnox/68xpy7av/36/

Removing pairs from DOM

I am working on a Shopify page where I need to remove pairs from various input groups using jQuery and am not sure what is the best approach since there are many ways to do this.

example

<fieldset>
  <legend>
  <input type="radio" id="1">
  <label for="1"> one</label>

  <input type="radio" id="2">
  <label for="2"> two</label>

  <input type="radio" id="3">
  <label for="3">Three</label>
</fieldset>

Here I want to re-display the fieldset using an include list containing [1,3] so removing 2 and its label

  • Should I clone the fieldset, .empty the original and then loop
    through the clone adding each matching field pair back in?
  • Is there
    a shortcut to add the label since it uses ‘label for’ ?
  • Or should I perhaps generate a map and use that
  • Or, just directly remove the ‘2’ input and its label from DOM?
  • Something else?

Is this easier in Javascript?

Button’s clickable area is above the button

I’m relitavely new to HTML and have ran into this error after using display: flex.
My buttons clickable area is about 10px above the actual button, and when I use inspect element, the button highlight says its above where the visible button is.

<body>
    <h1 id="HomepageTitle" style="display: flex; justify-content: center; font-family: sans-serif; color: black;">CoderTom</h1>
    <h2 id="HomepageHeader" style="display: flex; justify-content: center; font-family: sans-serif; color: blue;">Home</h3>

    <div class="button-group" style="display: flex; justify-content: center;">
        <a href="contactpage.html"><button style="position : relative; top: 50px; background-color: rgb(0, 255, 55); font-family: sans-serif; font-weight: 700; color: black; width: 100%; height: 100%;">Contact</button></a>
    </div>
    <script src="application.js"></script>
</body>

using async await for node.js function [duplicate]

I have this:

var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {
            
            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }
          

        }
        mysqlconn.end();

    })
})

and then inside the function getNumOfSessionForTrainerClientList, I have this:

async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

    var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
    mysqlconn.connect(async function(err) {
        if (err) {
            console.error('Database connection failed: ' + err.stack);
            return;
        }
            mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
                if (err) {
                    console.log(err);
                } else {
                    numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                    console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

                }

            })

    })

   }

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

Setting an element position according to another element (seems JS/CSS bug)

I have a div that will be set according to the hovered element position in window. At first I thought this was a JQuery bug, but after more investigating and changing to vanilla, it’s still the same.

I have created a code snippet to demonstrate my problem. If you mouse enter white div from top, the position is correct and orange box cover entire white box, but if you enter it from other sides, it’s incorrect by few pixel:

var inspector_rect2= document.getElementById('inspector_rect');

$(window).mouseover(function(event) {     
  inspector_rect2.style.left= event.target.getBoundingClientRect().x+'px';
  inspector_rect2.style.top= event.target.getBoundingClientRect().y+'px';
  inspector_rect2.style.width= event.target.getBoundingClientRect().width+'px';
  inspector_rect2.style.height= event.target.getBoundingClientRect().height+'px'; 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="UTF-8">
</head>

<style>
  html, body  {
    height : 100%;
    margin : 0;
    width : 100%;
  }
  .MyCSS  {
    background-color : silver;
  }
  .Container  {
    height : 100%;
    margin : auto;
    width : 50%;
  }
  .Header {
    height : 5%;
    padding : 2% 0;
    width : 100%;
  }  
  .MainContent {
    background-color : white;
    height : 70%;
    width: 100%;
  }
  .inspector{
    position: absolute; 
    pointer-events: none; 
    z-index: 999; 
    background: rgba(255, 166, 0, 0.5);
  }
</style>

<body class="MyCSS">
  <div class="Container" >
    <div class="Header" ></div>
    <div class="MainContent"  ></div>
  </div>  
</body>
<div id=inspector_rect class=inspector></div>

Why does a Cloud Function for Firebase (deployed without errors), throw “Uncaught (in promise) FirebaseError: internal” when called?

I am making an onCall function to do crud operations with the admin-sdk, create, read, update and delete users, and customClaims, but when calling the deployed function it throws the following errors in the browser console (the client is web):

POST http://localhost:5001//southamerica-east1/usersCrud net::ERR_CONNECTION_REFUSED

Uncaught (in promise) FirebaseError: internal

This is the function code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.usersCrud = functions
  .region("southamerica-east1")
  .https.onCall((data, context) => {
    if (!context.auth || !context.auth.token.rol === "Supervisor") {
      throw new functions.https.HttpsError("Permission denied", "ERROR6", {
        error,
      });
    }

    switch (data.operation) {
      case "get":
        return listAllUsers()
          .then((listUsersResult) => {
            let users = [];
            listUsersResult.users.forEach((userRecord) => {
              users.push(userRecord.toJSON());
            });
            return users;
          })
          .catch((error) => {
            throw new functions.https.HttpsError(
              "Error getting users",
              "ERROR0",
              { error }
            );
          });
        break;

      case "del":
        return deleteUser(data.uid);
        break;

      case "cre":
        return createUser(data.user);
        break;

      case "upd":
        return updateUser(data.uid, data.user);
        break;

      default:
        throw new functions.https.HttpsError("Operation wrong", "ERROR5");
        break;
    }
  });

const listAllUsers = async () => {
  return await admin.auth().listUsers(20);
};

const deleteUser = async (uid) => {
  return await admin
    .auth()
    .deleteUser(uid)
    .then(() => {
      return { deletedUser: uid };
    })
    .catch((error) => {
      throw new functions.https.HttpsError("Error deleting user", "ERROR1", {
        error,
      });
    });
};

const createUser = async (newUserData) => {
  const { displayName, email, rol, sucursal } = newUserData;

  if (!displayName || !email || !rol || !sucursal) {
    return { message: "Missing fields" };
  }
  try {
    const { uid } = await admin.auth().createUser({ displayName, email });
    await admin.auth().setCustomUserClaims(uid, { rol, sucursal });
    return { createdUser: uid };
  } catch (error) {
    throw new functions.https.HttpsError("Error creating user", "ERROR3", {
      error,
    });
  }
};

const updateUser = async (uid, updatedUser) => {
  const { displayName, email } = updatedUser;
  return await admin
    .auth()
    .updateUser(uid, { displayName, email })
    .then((userRecord) => {
      return admin
        .auth()
        .setCustomUserClaims(uid, {
          rol: updatedUser.rol,
          sucursal: updatedUser.sucursal,
        })
        .then(() => {
          return { updatedUser: userRecord.toJSON() };
        });
    })
    .catch((error) => {
      throw new functions.https.HttpsError("Error updating user", "ERROR4", {
        error,
      });
    });
};

I don’t think it’s an error in the code itself, because with the Emulator Suite it works correctly,
I think it’s more an error with the admin sdk or credentials but I’m not sure. I obviously set the GOOGLE_APPLICATION_CREDENTIALS environment variable before deploying the function, but calling it on the client gives me the same error

I need help

React State variable keeps resetting and changing within one render

export default function Questionnaire(props) {
    const initialState = {
        questionCount: 0,
        is_host: false
    }
    const [ roomData, setRoomData ] = useState(initialState) 
    const { roomCode } = useParams()
    const [ displayedTable, setDisplayedTable ] = useState(1);

    useEffect(() => {
        fetch("/audio/get-room" + "?code=" + roomCode)
          .then(res => res.json())
          .then(data => {
            setRoomData({
              roomData,
              questionCount: data.questionCount,
              is_host: data.is_host,
            })
          })

          window.addEventListener('keydown', (e) => {
            console.log("questionCount 1:", roomData.questionCount);
            if (e.keyCode == '39') {
                setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
            } else if (e.keyCode == '37') {
                setDisplayedTable(showPreviousStage(displayedTable));
            }
        });

        // cleanup this component
        return () => {
          window.removeEventListener('keydown', (e) => {
            if (e.keyCode == '39') {
                setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
            } else if (e.keyCode == '37') {
                setDisplayedTable(showPreviousStage(displayedTable));
            }
        });
        };
    },[roomCode,setRoomData])

    console.log("questionCount 2:", roomData.questionCount);

    return (
        <div>
            {components[displayedTable]}
        </div>
    )
  }

Every time the State refreshes, the two console.logs() return “questionCount 1: 0” and “questionCount 2: 5” (the value fetch() retrieves). But since questionCount is only set to 0 in the initial UseState(), it shouldn’t be resetting to 0 and should remain at 5 after it gets set to that. But it doesn’t. Why is this? How is it even possible for the one State variable to have two different values in the one render(), when State changes are meant to rerender the page?

What am I doing wrong with these objects? [duplicate]

the problem says like this

You must create a function called warWords that receives two words as a parameter and returns the winner according to the sum of the value of its letters (given by its position in the alphabet).

example:

warWord(“hola”, “chau”) debe retornar  “hola” (36 > 33)
warWord(“love”, “friendship”) debe retornar “friendship”

utilitis:

var abc = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};

my code:

function warWords(palabra1,palabra2){
  var abc = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
  let p1 = [];
  let p2 = [];
  
  for(prop in abc){
    console.log(abc)
  }
  
}

meh, i’m really sad to be honest, i can’t understand this exercise nor the objects in javascript, it’s totally different than an array

Reduce method of array not reaching last element

So I’m really new to JavaScript, and I’m having a bit trouble with reduce method in JavaScript which doesn’t reach the last element of the array. My function removes duplicates from array by first sorting the array, and then using the reduce method to delete element if first and second element are same.

I’m thinking maybe it has something to do with the splice method I use in conjunction with it. But I’m not entirely sure what is going on, can someone help explain what’s happening here?

function removeduplicate3(arr) {
    arr.sort((first, second) => (first > second));
    console.log(arr);
    arr.reduce((first, second) => {
        console.log(`${first} ${second}`); // check pair of elements it reduces
        if (first === second) {
            arr.splice(arr.indexOf(second), 1)
            return first;
        }
        else
            return second;
    }, undefined);
}
let arr = ["Hello", "World", "Bye", "World", "I", "Am", "I", "World"];

my finally (incorrectly) filtered array has: [ "Am", "Bye", "Hello", "I", "World", "World" ]

I printed the pairs of elements of array with ${first} ${second}, and it’s missing the last pair: World World

Add thousand separator with javascript when add input dynamically

I have problem when adding input dynamically with thousand separator,
when I click add and the input form appears.
it should be when I type the number it will be arranged in thousand separator.
Please help me

$(document).ready(function(){
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" /></td>';
  html += '</tr>';
  $('#item_table').append(html);
 });

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(d*.)(.*).(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/.(d{2})d+/, '.$1')
      // Add thousands separators:
      .replace(/B(?=(d{3})+(?!d))/g, ",")
  });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <div class="table-repsonsive">
     <table class="table table-bordered" id="item_table">
      <tr>
       <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
      </tr>
     </table>
    </div>