how i can insert javascript variables into database

I have this function in javascirpt

enter code here

function addRow( i , name , first , second , final , partic , abc , Grade){

names[i] = name ;
fiM[i] = first ;
secM[i] = second ;
finalM[i] = final ;
parti[i] = partic ;
Y_N[i] = abc ;
grades[i] = Grade ;

}

enter code here

the parameters of this function I want to insert it into database
I tried so much but never work
please help

Global variable doesn’t change js [duplicate]

function get_info()
{
  var temp;
  con.connect(function (err) {
    if (err) throw err;
    con.query("SELECT * FROM customers", function (err, result, fields) {
      if (err) throw err;
      temp = result;
      console.log(temp);
    });
  });
  console.log(temp);
}

when I run the function, the console.log(temp) at the end of the function shows “undefined” even though it shows the data when I do console.log(temp) in the inside function. I think the problem is that the global variable doesn’t change but I don’t know how to fix it. Any ideas?

node cron job on existing express server?

I want to run a cronjob to aggregate data from my users for every hour. Currently there’s quite a lot of data to aggregate and i’d ideally want to use python, and am currently running an express server.

I’m wondering – how would I run these scripts from express?

import psycopg2 as pg
import pandas as pd
from datetime import datetime, timedelta

import db_conn

def handler(thing, context):
    
    """
    this connects, calculates the last hour, then writes a new line to a table in postgress.
    """
    conn = db_conn.main()

    #step one
    current_hour_epoch, previous_hour_epoch = calculate_last_utc_hour()
    #step two
    df = query_sentiment_statistics(conn, previous_hour_epoch, current_hour_epoch)
    #step three
    write_db(conn, df, previous_hour_epoch, 1)

    pass

def calculate_last_utc_hour():

    """
    this is used for the cronjob processing.
    """
    
    current_time = datetime.now()
    current_hour_start = current_time.replace(minute=0, second=0, microsecond=0)
    previous_hour_start = current_hour_start - timedelta(hours = 1)

    current_hour_epoch = datetime.timestamp(current_hour_start)
    previous_hour_epoch = datetime.timestamp(previous_hour_start)
    print("query from ", previous_hour_epoch, "to", current_hour_epoch)
    return current_hour_epoch, previous_hour_epoch

def query_sentiment_statistics(conn, lower, upper):

    """
    Gathers sentiment data statistical information.
    """

    sql = """
        SELECT 
            user_id,
            AVG(sentiment) as sentiment,
            AVG(magnitude) as magnitude,
            SUM(sentiment) as total_sentiment,
            SUM(magnitude) as total_magnitude,
            MAX(sentiment) as max_sentiment,
            MIN(sentiment) as min_sentiment,
            COUNT(user_id) as count
        FROM
            sentiments
        WHERE
            created
            BETWEEN %s and %s
        GROUP BY
            user_id;
    """
    try:
        cur = conn.cursor()
        df = pd.read_sql(sql, con=conn, params=(lower, upper))
        cur.close()
        return df
    except (Exception, pg.DatabaseError) as error:
        print(error)
    pass

def write_db(conn, dataframe, lower, detail = 1):

    # set the additional columns required to be written into the table
    dataframe['detail'] = detail
    dataframe['created'] = lower
    
    try:
        #writes to new table that aggregates sentiments
        dataframe.to_sql('sentiments_aggregate', con = conn, if_exists = 'append', index = False)
    except (Exception, pg.DatabaseError) as error:
        print(error)
    pass

if __name__ == '__main__':
   
    pass

Would it just be easier to do the same code in javascript? something liek this,

const { db } = require("./db");


const sql = "SELECT user_id, AVG(sentiment) as sentiment, AVG(magnitude) as magnitude, SUM(sentiment) as total_sentiment,  SUM(magnitude) as total_magnitude,MAX(sentiment) as max_sentiment, MIN(sentiment) as min_sentiment,COUNT(user_id) as count FROM sentiments WHERE created BETWEEN %s and %s GROUP BY user_id;"

db.query(sql, [id], (err, rows) => {
   
});
}

and using node-cron to replicate the time intervals?

thanks!

How do I toggle a css class to elements of the same class, on click of another single element, in pure JavaScript?

I want to toggle a css class on all elements with the same class, on click of another element. I had it working with jQuery but need to switch to pure JavaScript. The lovely jQuery that works:

$(function () {
            $("#logo").click(function () {
                $(".grey").toggleClass("white",1000);
                $(".red").toggleClass("orange",1000);
        });
        });

—when you click on the element with id=”logo”, everything with class=”grey” toggles “white” class and everything with class=”red” toggles “orange”. Perfect.

I’ve googled like mad for a solution to this, but I can’t get anything to work even though it seems like a simple thing — I’ve taken over a day to try to learn what I need to know but a solution is escaping me. (Scripting is not my first language by any stretch.) Thank you in advance.

How to use _sortBy in an array of objects that contains nested array of objects

I have a list of array of objects that contains a nested array of objects like so:

const mainList = [
{
    id:'001',
    category: 'A',
    content: [ 
        {
            title: 'Apples',
            language: 'en'
        },
        {
            title: '苹果',
            language: 'zh-cn'
        },
        {
            title: '苹果HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'002',
    category: 'B',
    content: [
        {
            title: 'Grapes',
            language: 'en'
        },
        {
            title: '葡萄',
            language: 'zh-cn'
        },
        {
            title: '葡萄HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'003',
    category: 'C',
    content: [
        {
            title: 'Bananas',
            language: 'en'
        },
        {
            title: '香蕉',
            language: 'zh-cn'
        },
        {
            title: '香蕉HK',
            language: 'zh-hk'
        },
    ]
}
]

I want to display this list using lodash _sortBy, by its title in alphabetical order like this:

Apples, Bananas, Grapes

My approach:

console.log(_sortBy(mainList.content.title))

But the result comes back with undefined at index 0

Thanks in advance!

Make the List to be responsive design

Goal:
Make the list (ul and its li) to be responsive design in relation to the screen’s width.

Problem:
I don’t know how to solve it.

Info:
*You need to take account to amount of li in each ul list. Different responsive design depends on the width of the ul.
*Each ul can be random from 1 to 10 li or more.

JSBin:
https://jsbin.com/xibalahave/edit?html,css,output

Thank you!


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
      <li>1Test 3</li>
    </ul>
  </div>
  <br />
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
      <li>1Test 3</li>
      <li>1Test 4</li>      
    </ul>
  </div>  
  <br />
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
    </ul>
  </div> 
  
</body>
</html>

.aaa ul.listlist{
    margin: 10px 0 16px;
    padding: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
}

.aaa ul.listlist li {
  font-size: 1.125rem;
  display: block;  
  margin-right: 24px;
  line-height: 22px;
  border-radius: 12px 12px 12px 12px;  
  padding: 8px 24px;
  background-color: #00FFFF;
  white-space: nowrap;
}

How do I perform the mouse slider in react using react-router-dom?

This is my app.js

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css";
import Home from "./Home";
import Navbar from "./Navbar";
import Works from "./Works";

function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/works" element={<Works />} />
        </Routes>
      </Router>
    </>
  );
}

export default App;

This is my Home.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./mainpage.css";
import cloud1 from "./images/cloud1.svg";
import cloud02 from "./images/cloud02.svg";
import cloud2 from "./images/cloud2.svg";
import moon from "./images/moon.svg";
import cloud3 from "./images/cloud3.svg";
import cloud01 from "./images/cloud01.svg";
import { useNavigate } from "react-router-dom";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";

function Home() {
  let navigate = useNavigate();
  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      {loading ? (
        <ClimbingBoxLoader size={20} color={"#F37A24"} loading={loading} />
      ) : (
        <MouseParallaxContainer
          className="main-page"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <Navbar />
          <h1 className="heading">SASWATA</h1>
          <h1 className="heading2">GHOSH</h1>
          <span className="bar1"></span>
          <span className="bar2"></span>
          <p className="para">web developer</p>
          <p className="scrolldown">SCROLL DOWN</p>
          <span className="verticaline"></span>
          <MouseParallaxContainer
            className="moon"
            containerStyles={{
              width: "100%",
              overflow: "none",
            }}
          >
            <MouseParallaxChild
              className="moon_text"
              factorX={0.01}
              factorY={0.01}
            >
              <p>PORTFOLIO</p>
            </MouseParallaxChild>
            <MouseParallaxChild
              className="moon_img"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={moon} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud01"
              factorX={0.04}
              factorY={0.06}
            >
              <img src={cloud01} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud02"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={cloud02} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud_front1"
              factorX={0.04}
              factorY={0.07}
            >
              <img src={cloud1} alt="cloud1" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud3"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={cloud3} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud2"
              factorX={0.06}
              factorY={0.05}
            >
              <img src={cloud2} alt="cloud2" />
            </MouseParallaxChild>
          </MouseParallaxContainer>
          <div className="nav-left">
            <span className="span1"></span>
            <span className="span2"></span>
            <span className="span3"></span>
            <span className="span4"></span>
          </div>
        </MouseParallaxContainer>
      )}
    </MouseParallaxContainer>
  );
}

export default Home;

This is my Works.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./Works.css";
import cloud02 from "./images/cloud02.svg";
import works from "./images/LandingPage.png";
import { useNavigate } from "react-router-dom";
import cloud01 from "./images/cloud01.svg";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";

function Home() {
  let navigate = useNavigate();
  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      <MouseParallaxContainer
        className="main-page"
        containerStyles={{
          width: "100%",
          overflow: "none",
        }}
      >
        <Navbar />

        <h1 className="heading">
          Web Sec<span className="name-span">urity</span>
        </h1>
        <h1 className="heading2">Project</h1>
        <span className="bar1"></span>
        <span className="bar2"></span>
        <p className="para">website</p>

        <MouseParallaxContainer
          className="moon"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <MouseParallaxChild className="cloud01" factorX={0.04} factorY={0.06}>
            <img src={cloud01} alt="" />
          </MouseParallaxChild>
          <img className="works-img" src={works} alt="" />
        </MouseParallaxContainer>
        <div className="nav-left">
          <span className="span11"></span>
          <span className="span12"></span>
          <span className="span13"></span>
          <span className="span14"></span>
        </div>
        <div className="page-number">
          <p>01</p>
        </div>
      </MouseParallaxContainer>
    </MouseParallaxContainer>
  );
}

export default Home;

I want to perform mouse slide such that it lands on new page on mouse scroll.
This is the website I am referring.(https://kuon.space/).
It is done using HTML and jquery but I am trying it with React.js and CSS. I hope you can help me. I have tried almost all libraries and couldn’t help myself.

SignalR instant notification doesn’t work at client page but after one refresh, it works fine

I have used signalR in my project to provide instant notification for the clients. When I send a message to a client, there is no update in the notification. But if I refresh the client page, the notification is updated and no further refresh is necessary. I checked the console in client page. There was an error:

Error: Cannot start a HubConnection that is not in the 'Disconnected' state.
    at L.j (signalr.js:1)
    at L.start (signalr.js:1)
    at pmPage:513

and after that, the following message has been written in the console:

[2022-01-08T07:37:35.208Z] Information: WebSocket connected to wss://localhost:7166/Home/Messages?id=hPCczwx4iIzIUdirBjH9ig.

Javascript code that I use is as follows (message.js):

    var connection = new signalR.HubConnectionBuilder().withUrl("/Home/Messages").withAutomaticReconnect().build();
connection.start();
if (document.getElementById("sendBtn") != null) {
    document.getElementById("sendBtn").addEventListener("click", function () {
        var costCenter = $("#cost-center").val();
        connection.invoke("SendMessage", costCenter).catch(function (err) {
            return console.error(err);
        });
    });
}

The code for Hub is:

public async Task SendMessage(string costCenter)
    {
        var HttpContext = _httpContext.HttpContext;
        string userId = _userRepository.GetUserIdByCostCenter(costCenter).ToString();
        string sender = HttpContext.Session.GetString("department");
        await Clients.User(userId).SendAsync("ReceiveMessage", sender);
    }

Javascript code for the client page:

<script>
connection.on("ReceiveMessage", function (param) {
    var currentMessageNum = parseInt($('#badge-count').text());
    var messageBadge = @Model.MessagesList.Where(x => x.receiverUserId == userId).Count();
    if($('#badge-count').length){
        $('#badge-count').text(currentMessageNum + 1);
        $('.main-msg-list').prepend('<li><a class="dropdown-item message-item" asp-controller="Messages" asp-action="Index" id="msg-'+ currentMessageNum + 1 +'">New message from '+ param +'</a></li>');
    }else{
        $('#badge-count').text('1');
    }
});
connection.start().catch(function (err) {
return console.log(err);
});

How can I fix this problem?

Multiple Values on Checkbox?

I am currently trying to make a “”””calculator”””” for an RP Server, anyways, I need to calculate a sentence and a fine using values on checkboxes.
I already did the sentence, and I would like to make the fine similar to it, but I know I can’t use more than 1 value on each input. What is the best way to get it done?

Sentence Code >

let checkedValue = 0;
let inputElements = document.getElementsByClassName('check');
for(let i=0; i < inputElements.length; ++i){
    const element = inputElements[i]

    if(element.checked){
      checkedValue = checkedValue + parseInt(element.value)
    }
}

How to create a session in axios

I am trying to log in to a website using forms data payload. It requires a _csrf token which is uniquely generated every time the login page opens up. I was trying to get to the login page to take the _csrf id then post the payload in the very same session.

My python code was able to do it with requests.session() but I am having trouble with axios.

My python code

login = {'_csrf': 0, 'email': '[email protected]', 'password': "password"}
with requests.Session() as s:
    url = "https://example.com/login.html"
    res = s.get(url, headers={'User-Agent': 'Mozilla/5.0'})
    soupy = soup(res.content, 'html.parser')
    _csrf = soupy.find('meta', attrs={'name': "csrf-token"})['content']
    login['_csrf'] = _csrf
    res = s.post(url, data=login, headers={'User-Agent': 'Mozilla/5.0'}

My Node.js Code

var url = "https://example.com/login.html";
let response = await axios.get(url,{
    headers:{
       'User-Agent': 'Mozilla/5.0'
    }
})
.then(function(response){
    let soup = cheerio.load(response.data, null, false);
    var _csrf = soup('meta[name="csrf-token"]').attr('content');
    var login = {'_csrf': _csrf, 'email': '[email protected]', 'password': "password"};
    response = axios.post(url,{
        headers:{
            'User-Agent': 'Mozilla/5.0'
        },
        data: login,
    }).catch((e)=> {console.log(e)});
    console.log(response.data);
});

but it doesn’t work as I get a _csrf mismatch error. What can I do to get axios work in a session?

I’m making a circle follow the cursor but want it to fadeout when the mouse stops

Im making a circle follow the cursor using jquery which works fine but i was wondering if there was a way so that the circle fades out whenever the mouse stops.

I have tried using mouseout funtion of jquery and making the opacity 0 but it would just stop the circle in between whenever the mouse stops which is obvious but is there some other method to achieve this ?

My jquery code –

 var mouseX = 0, mouseY = 0;
   var xp = 0, yp = 0;
        
  $(document).mousemove(function(e){
    
    $("#circlecc").css({opacity: 1})
     
    mouseX = e.pageX - 12;
    mouseY = e.pageY - 12;
    
  });

  setInterval(function(){

    xp += ((mouseX - xp)/6);
    yp += ((mouseY - yp)/6);
    $("#circlecc").css({left: xp +'px', top: yp +'px'});
    
  }, 20);

Also while moving the cursor below the site or beyond the site the circle goes beyond the site too and adds a scroll bar, is there a way to avoid that

The Website

How can I improve this paginated do while async await GET request in Javascript (NodeJS)?

I am learning JavaScript (Node.js – using the Pipedream platform). I have been writing scripts to help automate some little tasks in my day to day work.

I am creating one that generates a report on recent interactions with clients.

As part of this I am using axios to get “engagements” from the Hubspot API (basically a list of identifiers I will use in later requests).

The API returns paginated responses. I have encountered pagination previously and understand the principle behind it, but have never written a script to handle it. This is my first.

It works. But I feel it could be improved. Below I’ve commented how I’ve approached it.

The endpoint returns up to 100 values ‘per page’ along with a "hasMore":true flag and an "offset":987654321 value which can be passed as a query parameter in subsequent requests (if hasMore === true).

Example API response:

{"results":[1234,1235,1236],"hasMore":true,"offset":987654321}

My code:

import axios from 'axios';
//function to get each page of data
async function getAssoc(req){
      const options = {
        method: 'GET',
        url: `https://api.hubapi.com/${req}`,
        headers: {
          Authorization: `Bearer ${auths}`,
        },
      };
      return await axios(options);
}
//declare array in which to store all 'associations'
const assocs = [];
//store the ID that I get in an earlier step
const id = vid;
//declare variable in which to temporarily store each request response data
var resp;
//declare query parameter value, initially blank, but will be assigned a value upon subsequent iterations of do while
var offset = '';
do {
  //make request and store response in resp variable
  resp = await getAssoc(`crm-associations/v1/associations/${id}/HUBSPOT_DEFINED/9?offset=${offset}`);
  //push the results into my 'assocs' (associations) array
  resp.data.results.forEach(element => assocs.push(element));
  //store offset value for use in next iteration's request
  offset = resp.data.offset;
} while (resp.data.hasMore); //hasMore will be false when there's no more records to request

return assocs;

I feel it could be improved because:

  1. The DO WHILE loop, I believe, is making sequential requests. Is parallel a better/faster/more efficient option?
  2. I’m re-assigning new values to vars instead of using consts which seems simple and intuitive in my beginner’s mind, but I don’t understand a better way in this instance.
  3. I would welcome any feedback or suggestions on how I can improve this for my own learning.

Thank you in advance for your time and any assistance you can offer.