Pushing items into array not working inside of jquery POST [duplicate]

my post was just deleted and they linked AJAX asynchronosity which didn’t help at all and is completely unrelated to my problem.

My problem is that I cannot push ITEMS, into my array using .push when it’s inside of a POST and not ajax…

CODE:

var rolearray = [];
$.post(
  "https://URL/getRoleData", 
  JSON.stringify({ businessid: $(this).data('businessid') }), 
  function(roles){
    $(roles).each(function(e) {
      rolearray.push({label: roles[e].role, value: roles[e].role})
    })
  }
)

This time please don’t just dismiss it. Cause the thread linked didn’t help.

Also yes the post is returning data.. For each is working as intended but it won’t push my values after it’s returned the result.

Timestamp field from firestore showing an invalid date if the field does not exist

These are my codes. selectedDate is a timestamp field:

<ListItemText
                          primary={
                            new Date(
                              user.items?.selectedDate?.seconds * 1000
                            ).toDateString() +
                            " at " +
                            new Date(
                              user.items?.selectedDate?.seconds * 1000
                            ).toLocaleTimeString()
                          }
                    />

It does show the data correctly. However, if the selectedDate does exist, it will show:

Invalid date at Invalid date

How can I fix this?

Is there a way to find only unused JSDoc type definitions?

For example:

/**
 * A number, or a string containing a number.
 * @typedef {(number|string)} NumberLike
 *
 * Dummy type
 * @typedef {(string|null)} StringLike
 */

/**
 * Set the magic number.
 * @param {NumberLike} x - The magic number.
 */
function setMagicNumber(x) {
}

As you can see NumberLike is used, but the StringLike type is not used and I’d like to find all such unused type definitions on our project. It’s a Nodejs project with typescript installed.

Here’s our tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": ".",
    "jsx": "react",
    "allowJs": true,
    "checkJs": true,
    "target": "ESNext",
    "noEmit": true,
    "moduleResolution": "node",
    "isolatedModules": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "strictNullChecks": true,
  },
}

How can I filter these JSON data where it check if category 1 and 2 is true and that the selectedDate exist?

I have this sample JSON data:

[
  {
    category: {
      selectedDate: { seconds: 1639903368, nanoseconds: 392000000 },
      category1: true,
      category2: true
    },
    name: "Sample 1"
  }
];

There are some cases where category1 and category2 are true, but the selectedDate is not present there. So how can I filter these where category 1 and category 2 are true and that the selectedDate exist?

These are my codes, however, this would not filter correctly.

 const filter = users.filter(
    (f) =>
      f.choices.category1 == true &&
      f.choices?.category2 == true &&
      f.choices?.selectedDate !== null
  );

  console.log(booster);

In Adobe Illustrator, How to change white color of Edittext to transparent with javascript when it is active

enter image description here

I want to change white color to transparent when the edittext is active.
Please help me.

w.alignChildren = ["fill","fill"];
w.preferredSize = [150, 250];
w.inputBox = w.add('panel', undefined, "Input Box");

w.inputBox.add('statictext{text: "Height: "}');

var heightInput = w.inputBox.add('edittext {characters: 12, active: true}');

w.inputBox.add('statictext{text: "Width: "}');

var widthInput = w.inputBox.add('edittext {characters: 12, active: false}');

w.inputBox.add('statictext{text: "Spine: "}');

var spineInput = w.inputBox.add('edittext {characters: 12, active: false}');

w.inputBox.add('statictext{text: "Joint: "}');

var jointInput = w.inputBox.add('edittext {characters: 12, active: false}');

var okBtn = w.add("button", undefined, "Draw");

How to add more objects to an array of objects continuing the numbering but not start over?

I have this minor issue but I’m so close.

I have a Array of Objects with 100 OBJECTS in it. [0-99]

I want to add another 100 or more objects to the end of the current object 99.

What I’m getting is [0-99], 100: [0-99]

Let me show you the code:

addEntry = (newEntry) => {

    let newSortedData = [];

    // Parse any JSON previously stored in allEntries
    let existingEntries = JSON.parse(sessionStorage.getItem("magic1")).data;
    if (existingEntries === null) {
        existingEntries;
    }
    sessionStorage.setItem("magic1", JSON.stringify(newEntry));
    // Save allEntries back to local storage
    existingEntries.push(newEntry[0].data);

    console.log("existing entries with push for new ones: ", existingEntries);

    table.clear().draw();
    newSortedData.push(existingEntries);
    table.rows.add(_.sortBy(newSortedData, "title")); // Add new data
    table.columns.adjust().draw(); // Redraw the DataTable

    console.log("Existing and new ones sorted: ", newSortedData[0].data);

    sessionStorage.setItem("magic1", JSON.stringify(newSortedData[0].data));

};

What I’m getting is this:

magic1 starts out with 100 OBJECTS in the array. Where I’m getting the data from, there are 7000 items/products. I’m using a PHP to pull the data from the source. They only come in pages 1 – 70 with 100 objects in each page. hence, 7000 objects. It’s a BIZARRE way of me having to do this but I have to PING the server going past 100, 201, 301, 401, 501, 601, and so on, through all 70 hits to the server, 100 items at a time. They just can’t give me a getRowcount() as rowcount from the SQL. I have to continually ping or hit the server until I get a number of items LESS than 100 meaning, I’ve hit the last page of less than 100.

Here’s what the end of one array looks like and the beginning of the new one.

All I want to do is to KEEP appending the additional pages to continue the count with 100, 101, 102, all the way to 199. Then 200, 201, 201 – 299 and so on. Apparently obj.push(newObj) does what you see in the pic.

enter image description here

How to call external function in chain function?

This is a case about React and Dapp.

I call web3j to sendTransaction and wait callback by chian fucntion.
While error occur , I can’t call the function inside App.

I descibe the situations below codes around error block.

Is it possible to call function handleError?

//My code
class App extends Component {
    constructor(props) {
        super(props);
            this.state = {
            status: ''
            };
    };
    
    startTrade(){
        web3.eth.sendTransaction({
            from: "0x123....",
            to: "0x456....", 
            value: web3.utils.toWei("2", "ether"),
        }).on('error', (error)=>{
            
            //If write this line,the browser shows directly:
            //Failed to compile
            //srcApp.js
            //Line 62:7:  'handleFail' is not defined  no-undef     
            
            //handleError(); 
            
            //If add this. when error occurs,the console shows:
            //App.js:62 Uncaught TypeError: Cannot read properties of undefined (reading 'handleFail')
            
            //this.handleFail();

            //If I call otherHandle,It's work.
            //However I don't have the instance of App to change something...
            //otherHandle();
        }); 
    }
    handleError(){
       console.log("Do something..");
    }
    render(){ return();
    }
}
function otherHandle(){
    console.log("Do something..");
}

JavaScriptt React Issues with passing prop from a function in a child array to a function in the parent

I’m dealing with a problem passing a prop to a parent component from it’s child.

The idea of the code that I’m trying to make work is a set of buttons in a header component that when clicked, load new component pages for other parts of the website. I’m dealing with a couple of smaller bugs that I can fix at another time but the primary issue is when I try to pass the results of the function for handling the switch and the values showing as ‘undefined’ once they get to the App component. I doubt I’m explaining it well so allow me to show the code.

Parent Component (App)

import React from "react";
import Header from "./Components/Header/Header";
import Footer from "./Components/Footer/Footer";
import Pane from "./Components/Pane/Pane";
import MainPane from "./Components/Pane/MainPane";
import BookViewPane from "./Components/Pane/BookViewPane";
import AddBookPane from "./Components/Pane/AddBookPane";
import SignInPane from  "./Components/Pane/SignInPane";
import "./App.css";

const App = ()=>{

    function LoadPaneHandler(props){
        var NewPaneName=props.paneName;

        // const NewPaneName={
        //  name: props.paneName
        // };
        
        // const NewPaneName=String(props);

        console.log(NewPaneName);
        switch(NewPaneName){
            case 'MainPane':
                return <MainPane />
            case 'AddBookPane':
                return <AddBookPane />
            case 'BookViewPane':
                return <BookViewPane />
            case 'SignInPane':
                return <SignInPane />
            default:
                return <Pane />
        }
    }

    return(
        <React.Fragment>
            <Header switchPane={LoadPaneHandler} />
            <main>
                <LoadPaneHandler paneName="MainPane" />
            </main>
            <Footer />
        </React.Fragment>
    );
}

export default App;

Child Component (Header)

import React from "react";
import "./Header.css";

const Header=(props)=>{
    var paneName="";

    const switchPaneHandler=event=>{
        event.preventDefault();
        console.log(paneName);
        props.switchPane(paneName);
    }

    return(
        <header id="header">
            <div id="header-title">
                <h1>Library</h1>
            </div>
            <div id="header-buttons">
                <button onClick={paneName="BookViewPane",switchPaneHandler}> View Books</button>
                <button onClick={paneName="AddBookPane",switchPaneHandler}> Add Books </button>
                <button onClick={paneName="SignInPane",switchPaneHandler}> Login</button>
            </div>
        </header>
    );
}

export default Header;

I’ve included the commented out code of other approaches I’ve used to get the data I need for the function to work properly so that you can have an Idea of what I’ve already tried.

The code works fine so long as I only pass values to the function from within the App component. Whenever I click on one of the buttons in the header though, it shows the ‘paneName’ correctly in the ‘switchPaneHandler’ function but then in ‘LoadPaneHandler’ it prints as ‘undefined’.

I’m still quite new to React so it’s likely a very obvious mistake that I’ve made but any help is appreciated all the same. Thanks!

Cannot Connect to MySQL with NodeJS, but can via Windows Powershell

I’ve seen many variations of this question, but I couldn’t find an answer – and in fact am not sure where to look for logs that could help me. Here’s the situation.

I was following this tutorial

I have the following in a file called “server.js”:

const mysql = require("mysql");
const express = require("express");
const bodyParser = require("body-parser");

var app = express();

app.use(bodyParser.json());

var mysqlConnection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "confidential666!",
    database: "blunt",
    multipleStatements: true
});

mysqlConnection.connect((err)=>{
    if(!err){
    console.log("Connected");
        }
    else{
        console.log("connect failed");
        console.log("big woof");

    }
});

app.listen(3000);
console.log("did run");

I run this code with “nodemon server.js”

However, my console shows me “connect failed” and “big woof”.

I then tried to connect to my database with mysql.exe with the same credentials, and could connect to “blunt” just fine.

Port is missing from my connection, but documentation suggests 3306 is the default and that’s what my server is using. Adding it made no difference. Any idea on how I can figure out why I can’t get my nodemon to connect to my database?

Compressing repeating code so file becomes tolerable to work on?

Hello folks.

I wanna try to make a simple grid based game, and currently with my 3×3 grid finding myself copying alooot of code. I’m simply wondering if there are huge solutions to compress repeating code I’m missing out on? see jsfiddle at bottom

For example:
if(cell1.innerHTML == <img src="/images/character.png"> || cell2.innerHTML == <img src="/images/character.png"> || cell3.innerHTML == <img src="/images/character.png">){

Could I maybe write this as something like:
if (cell[1,2,3].innerHTML == <img src="/images/character.png">){

The biggest issue is I wanna expand to 9×9 or larger–, which is 81+ cells. So I can have more room to work with and actually make a small game. But unless there is a smart way to compress the repeating code its simply going to be overwhelming to work with i think..

What I’ve tried to create so far is a 3×3 grid with a character in the middle and (shadow) on the adjacent tiles. To remove the shadow the character.png in the middle has to move to said cell to reveal whats underneath (havent added anything underneath any cell yet).

I’ve not found a smart way to move character from one cell to another either.
So currently I’ve landed on this repetetive cellNumber.innerHTML = “”; thing to clear out all cells.

https://jsfiddle.net/ykj9e2cs/

Any answers are welcome. Thx 🙂

How do I create a bubble chat based on sale price in D3?

I’m trying to create an interactive bubble chart in D3. The size of the cirlces and the shade of color (green) is supposed to be based on how much a hotel sold for. When the user hovers over the cirlce with their mouse a tooltip should display additional information from the other columns.

A list of columns and data are below. I keep getting the following error:
Error: <circle> attribute cx: Expected length, "NaN"

I’m reading the data in from a csv file with the following columns:

PropertyName,
PropertyAddress,
City,
SalePrice,
Square_Footage,
Units,
Price_SF,
Price_Unit,
SaleDate,
Buyer,
Seller,
Link

And my code is below:

(function () {

    // Margin convention
    const margin = { top: 30, right: 50, bottom: 50, left: 50 }
    const width = 600 - margin.left - margin.right
    const height = 425 - margin.top - margin.bottom
  
    const svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  
    // Define colour scale
    const colorScale = d3.scaleOrdinal()
      .domain(['SalePrice'])
      .range(["#228C22"])
  
    // Set radius scale
    const radiusScale = d3.scaleSqrt()
      .domain([0, 300001])
      .range([0, 40])
  
    // Define years
    const years = [2021]
  
    // Define x axis position
    const xPositionScale = d3.scalePoint()
      .domain(years)
      .range([140, width - 110])
  
    // Create currency formatted
    var formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0
    });
  
    // Create tooltip
    const tooltip = d3
      .select("body")
      .append("div")
      .attr("class", "svg-tooltip")
      .style("position", "absolute")
      .style("visibility", "hidden");
    
    // Force simulation and prevent overlap
    const forceX = d3.forceX(d => xPositionScale(d.year)).strength(1)
    const forceY = d3.forceY(200).strength(1)
    const forceCollide = d3.forceCollide((d => radiusScale(d.amount) + 4))
    const simulation = d3.forceSimulation()
      .force("overlap", forceCollide)
      .force("y", forceY)
      .force("x", forceX)
      .force('charge', d3.forceManyBody().strength(-50))
  
    // Read in csv
    d3.csv("2021_hotel_sales_for_graphic.csv")
      .then(ready)
    function ready (datapoints) {
      datapoints.forEach(d => {
        d.x = 0;
        d.y = 0;
      })
  
      // Show text labels
      svg.selectAll('text')
        .data(years)
        .join('text')
        .attr('text-anchor', 'end')
        .attr('x', d => xPositionScale(d))
        .attr('dx', 20)
        .attr('dy', 0)
        .text(d => d)
  
      // Set position of circles
      svg.selectAll('circle')
        .data(datapoints)
        .join('circle')
        .attr("id", "circleBasicTooltip")
        .attr('r', d => radiusScale(d.SalePrice))
        .attr('cx', 200)
        .attr('fill', d => colorScale(d.colorScale))
        .attr('cy', 200)
        .attr('stroke', 3)
  
      // Trigger tooltip
      d3.selectAll("circle")
        .on("mouseover", function(e, d) {
          d3.select(this)
            .attr('stroke-width', '2')
            .attr("stroke", "black");
          tooltip
            .style("visibility", "visible")
            .attr('class','tooltipdiv')
            .html(`<h4>${d.PropertyName}</h4>` + 
                  `<p><strong>Address</strong>: ${d.PropertyAddress}<br />` +
                  `<p><strong>City</strong>: ${d.City}<br />` +
                  `<p><strong>Sale Price</strong>: ${d.SalePrice}<br />` +
                  `<p><strong>Square Footage</strong>: ${d.Square_Footage}<br />` +
                  `<p><strong>Units</strong>: ${d.Units}<br />` +
                  `<p><strong>Price per Sq Ft</strong>: ${d.Price_SF}<br />` +
                  `<p><strong>Price per Unit</strong>: ${d.Price_Unit}<br />` +
                  `<p><strong>Sale Date</strong>: ${d.SaleDate}<br />` +
                  `<p><strong>Buyer</strong>: ${d.Buyer}<br />` +
                  `<p><strong>Seller</strong>: ${d.Seller}<br />`);
        })
        .on("mousemove", function(e) {
          tooltip
            .style("top", e.pageY - 10 + "px")
            .style("left", e.pageX + 10 + "px");
        })
        .on("mouseout", function() {
          d3.select(this).attr('stroke-width', '0');
            tooltip.style("visibility", "hidden");
      });
  
      simulation.nodes(datapoints)
        .on('tick', ticked)
      function ticked() {
        svg.selectAll('circle')
          .attr("cx", d => d.x)
          .attr("cy", d => d.y)
        
      }
    }
  })();

How to send a email with a PDF file attachment based on a condition using Google App Script

I solved the following problem.
Send PDF files to everyone using the Google Script service of Google Sheets.
I tried sending one file to everyone on the list. It went well.
However, I’ve run into a problem trying to make a similar Script, but for sending multiple files to different people on a Google Sheet list.Each person has different files.

For example:
John has three PDF files: John_ 999901.pdf, John_ 999902.pdf, and John_999903.pdf.
David has two PDF files: David_ 999901.pdf and David_99990.
Jun has two PDF files: Jun_999901.pdf and Jun_999902.pdf.
And finally, Michel has only one PDF file: Michel_999901.pdf.
All PDF files are saved on GOOGLE DRIVE.
This is where I save the PDF file
This is my spreadsheet
Is there a way to send an email based on the file name that corresponds to the person of the same name in the list?
Below is the code that I tried to send the file

function onOpen() 
{
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('メール送信')
     
      .addItem('送信', 'sendFormToAll')
      .addToUi();
}
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function sendFormToAll()
{
   var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  
   var last_row = sheet.getDataRange().getLastRow();
  
   for(var row=2; row <= last_row; row++)
   {
     sendEmailWithAttachment(row);
     sheet.getRange(row,8).setValue("send");
   }
}

function sendPDFForm()
{
  var row = SpreadsheetApp.getActiveSheet().getActiveCell().getRow();
  sendEmailWithAttachment(row);
}

function sendEmailWithAttachment(row)
{
  var filename= '?????.pdf';// I don't know what to do at this point
  
  var file = DriveApp.getFilesByName(filename);
  
  if (!file.hasNext()) 
  {
    console.error("Could not open file "+filename);
    return;
  }
  
  var client = getClientInfo(row);
  
  var template = HtmlService
      .createTemplateFromFile('index');
  template.client = client;
  var message = template.evaluate().getContent();
  
  
  MailApp.sendEmail({
    to: client.email,
    subject: "Send File",
    htmlBody: message ,
    attachments: [file.next().getAs(MimeType.PDF)]
  });

}

function getClientInfo(row)
{
   var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
   
   var values = sheet.getRange(row,1,row,8).getValues();
   var rec = values[0];
  
  var client = 
      {
        name:rec[0],
        email: rec[1]
      };
  client.name = client.name;
  return client;
}
<!DOCTYPE html>
<html>
   <head>
      <base target="_top">
      <!-- CSS only -->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
      <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
      
   </head>

  
   <body>
     <div  >
     
     
      <p>Hi, <?= client.name ?>Sir </p>
      <p>I send you file . Please check it</p>
   
     
      <p>*********************************************************</p>
     
     </div>
   </body>
</html>