Accordion with 2 row Grid content being pushed down

when i open an accordion it adds the extra space to both the rows, how do i make it only add space to the side the accordion is being opened on. Below is the code and an image of how it looks when i open the accordion

import Grid from '@mui/material/Grid'
import Accordion from '@mui/material/Accordion'
import AccordionSummary from '@mui/material/AccordionSummary'
import AccordionDetails from '@mui/material/AccordionDetails'
import Typography from '@mui/material/Typography'
import ExpandMoreIcon from '@mui/icons-material/ExpandMore'

const accordionData = [
  { title: 'Accordion 1', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' },
  { title: 'Accordion 2', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' },
  { title: 'Accordion 3', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' },
  { title: 'Accordion 4', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' },
  { title: 'Accordion 5', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' },
  { title: 'Accordion 6', content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis eget.' }
];

export default function SimpleAccordion() {
  return (
    <div>
      <Grid container spacing={2}>
        {accordionData.map((item, index) => (
          <Grid item xs={12} sm={6} key={index}>
            <Accordion style={{ width: '100%' }}>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Typography>{item.title}</Typography>
              </AccordionSummary>
              <AccordionDetails>
                <Typography>{item.content}</Typography>
              </AccordionDetails>
            </Accordion>
          </Grid>
        ))}
      </Grid>
    </div>
  )
}

Picture of Accordion

Is it possible to trigger the click event of a “Save” button using jQuery or JavaScript when the user presses Ctrl + S (or Command + S)? [duplicate]

Is it possible to trigger the click event of a “Save” button using jQuery or JavaScript when the user presses Ctrl + S (or Command + S)?

I was exploring how to use jQuery or JavaScript to simulate a “Save” button click when a user presses Ctrl + S (or Command + S). My goal was to trigger the button’s click event through keyboard shortcuts.

React component re-rendering when object is a prop

If I have a component say- <Component />
which acceps props as data={a:1, b:2} which is created after some custom operation lets say that operation is performed by a function getData() which returns this data object.

Now this component re-renders and again getData returns us data={a:1, b:2} as props.

Now will my <Component /> update on UI? as the memory location of both the props is different but their properties are same?

Accessing Properties that are decided at runtime

The employee type can be either PartTime | FullTime and is decided at run time. Now since this is decided at runtime, every line where I use employeeType, I am unable to navigate to the desired method using [CMD + Click] on VS Code. Each time I access methods that are not available in all the other Classes (like Bonus method in FullTime Class), I get the following warning

//Property 'Bonus' does not exist on type 'PartTime | FullTime'. Property 'Bonus' does not exist on type 'PartTime'.

In my actual code there are 30+ variables which can be of different types, and based on the runtime value the values are assigned in the respective index files.

I am able to handle this using (employeeObj.employeeType as FullTime).Bonus, but this needs to be done for each access and I would have 50+ lines that needs to do this.

Is there a way I can specify the type of this variable during import at the top level something like
import {employee. employeeType as FullTime} or import {employee. employeeType as PartTime}

class Employee
{
    employeeType: PartTime | FullTime;
}

class PartTime
{
   get Salary() { return 1000; }
}

class FullTime
{
   get Salary() { return 2000; }

   get Bonus() { return 500; }
}

class Main
{
let employeeObj = new Employee();

let fulltimeEmp = new FullTime()
employeeObj.employeeType = fulltimeEmp;

console.log(employeeObj.employeeType.Bonus)
}

How can I use webhooks to automate button clicks using Express and Puppeteer?

I need some assistance with this project.
This project is to automate trading signals from webhooks and onto Tradovate using emulated button clicks. Here’s what it’s supposed to do:

•run js app
•chrome opens, logs in to Tradovate acct
•prints “Awaiting…”, “Node.js server started on port 5000.”
•listens for webhook (using insomnia to emulate)
•POST send JSON to forwarding URL from insomnia, 200 OK
if “order_action” = “buy”, click buy
if “order_action” = “sell”, click sell

Ngrok is running at HTTP 5000 in the background.

Here’s where I’m stuck: The buys and sells are not hitting. No other error messages are made.
I feel the problem may be the following line
app.post( '/', async function( req, res )

I have very little practice with Puppeteer so I’d appreciate any help I can get. Let me know if you have any questions. Thanks!

Here is the code:

import puppeteer from 'puppeteer';
import express from 'express';

const app = express();
app.use( express.json() );

(async () => {
    // Launch the browser and open a new blank page
    const browser = await puppeteer.launch(
      {headless: false}
    );
    const page = await browser.newPage();
  
    // Navigate the page to a URL
    await page.goto('https://trader.tradovate.com/welcome');
  
    // Set screen size
    await page.setViewport({width: 1080, height: 1024});
  
    // Type into search box
    await page.type('#name-input', 'XXXXX');
    await page.type('#password-input', 'XXXXX');
  
  
    const login = '.MuiButtonBase-root.MuiButton-root';
    //const login = '#onboarding-view-div > div.MuiContainer-root.onboarding-content.main-container.MuiContainer-maxWidthLg > div > div.mb-60 > div > div:nth-child(1) > div > form > button';
    await page.waitForSelector(login);
    await page.click(login);
    //await page.keyboard.press('Enter');
    await page.waitForNavigation({
      waitUntil: "networkidle0",
    })
  
    await page.click("#tm_options > div:nth-child(2) > div > div:nth-child(2) > button");
  

    console.log( 'Awaiting...' )
    app.post( '/', async function( req, res )  {
      if (req.body.strategy.order_action == 'buy')
      {
          await page.click("#content > div > div.app-modules > div > div.gm-scroll-view > div > div > div > div:nth-child(1) > div:nth-child(1) > div.lm_items > div > div > div > div.module.chart.chart-wrapper > div.header > div > div > div.gm-scroll-view > div:nth-child(6) > div:nth-child(2) > div:nth-child(1) > div")
          await page.click("#none > div.popover-content > div.btn-group-justified.btn-group > div:nth-child(1) > div")
          console.log('Buy initiated!')
      }
      else if (req.body.strategy.order_action == 'sell')
      {
          await page.click("#content > div > div.app-modules > div > div.gm-scroll-view > div > div > div > div:nth-child(1) > div:nth-child(1) > div.lm_items > div > div > div > div.module.chart.chart-wrapper > div.header > div > div > div.gm-scroll-view > div:nth-child(6) > div:nth-child(2) > div:nth-child(2) > div")
          await page.click( "#none > div.popover-content > div.btn-group-justified.btn-group > div:nth-child(1) > div" )
          console.log('Sell initiated!')
      }
    
    
        res.sendStatus( 200 );
    } );
    
    app.listen( 5000, () => console.log( 'Node.js server started on port 5000.' ) );

  })();

Google Tag Manager – Trigger off Custom JS Variable

I have a trigger that does work which is a custom event > some custom events. {{dlv – email}} contains @

{{dlv – email}} pulls information from the following code

`<script>
(function () {
  var element = document.querySelector('input[name="contact_details_email"]') 

  element.addEventListener("change", function(e) {
  dataLayer.push({
                    'event': 'email', 
                    'email': e.target.value                   
              });
  }, true);
})();  
</script>`

I have another variable {{JS contact form country}} which is custom JavaScript as it’s pulling data from a drop down selection.

`function () {
    var country = document.getElementById('country_id').selectedOptions[0].text;
    if (country)
        return country;
    else 
        return "Country not selected";  
}
`

I’m trying to use the above in a trigger which is a custom event > some custom events. {{JS contact form country}} contains Australia
However it’s not working as the first example.

Can anyone explain what the difference is and offer any guidance?

I got an error when trying to run: Failed to upload image. Please try again. Error: Unexpected token ‘<', "<!DOCTYPE "… is not valid JSON

This is the js code that I am using to package the json, I use the response.json() packaging method, responseClone variable is required to hold a clone of the response object because the body of a response can only be read once . When response.json() is called the body of the original response is read, which means it cannot be read again when handling the JSON parse error. Cloning the response to responseClone provides two copies of the response body to work with; one in the original response to use with response.json() and another to use with responseClone.text() if response.json() fails

let responseClone;
    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });

        responseClone = response.clone(); // Tạo một bản sao của phản hồi
        const result = await response.json();

        if (result.success) {
            const linkContainer = document.getElementById('linkContainer');
            const link = `http://send.thanhkien.id.vn/reply.html?mess-id=${result.messId}`;
            linkContainer.innerHTML = `<p>Link to your message: <a href="${link}" target="_blank">${link}</a></p>`;
            document.getElementById('copyLinkButton').style.display = 'block';
            document.getElementById('copyLinkButton').dataset.url = link;
        } else {
            alert('Failed to upload image. Server responded with error: ' + (result.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error during upload:', error);
        alert('Failed to upload image. Please try again. Error: ' + error.message);

        // Xử lý lỗi phân tích cú pháp JSON và ghi lại nội dung phản hồi
        responseClone.text().then(function (bodyText) {
            console.error('Received the following instead of valid JSON:', bodyText);
        });
    }
});

I tried using packing methods for json but it didn’t seem to work. I don’t know why the server handler file recognizes html instead of json. Please help me fix the above error:

// Xử lý việc tải lên tin nhắn
app.post('/upload', upload.single('image'), (req, res) => {
    const username = req.body['mess-id'];
    if (!username) {
        return res.status(400).json({ success: false, message: "Username is required" });
    }

    if (req.file) {
        const imageUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`;
        const message = req.body.message;

        const messageData = {
            username: username,
            imageUrl: imageUrl,
            message: message,
            replies: [] // Initialize replies array
        };

        const userDir = path.join(__dirname, 'messages', username);
        if (!fs.existsSync(userDir)) {
            fs.mkdirSync(userDir, { recursive: true });
        }

        const messageFile = path.join(userDir, 'message.json');
        fs.writeFileSync(messageFile, JSON.stringify(messageData));

        const messageUrl = `${req.protocol}://${req.get('host')}/reply.html?mess-id=${username}`;
        res.json({ success: true, url: messageUrl });
    } else {
        res.status(500).json({ success: false, message: "File upload failed" });
    }
});

Drag and Drop API Causing Flickering Issues During Image Uploads Due to Re-render

I’m, facing flickering issues with drag and drop API.

Two things which are causing flickering:

  1. When a image is uploaded or dropped it causes re-render due to state update.
  2. When dragLeave & dragEnter fires which also causes re-render due to dragActive state update.

https://codesandbox.io/p/sandbox/dawn-star-73dt8g

Is there a way to avoid flickering when an item is added or removed from the state?
And also how can I avoid flickering on dragActive state change as the files stay the same.

I want to wait all async task complete -> TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

let status = []
const promises = files.forEach(async (file) => {
let path = ${localPath}/${file}
let info = await imagepredictions(path)
let flag = await fileUpload(info, req, path)console.log("flag", flag);
if (flag) { status.push(info ? info : null) }
console.log("INSIDE ",status);return info, flag;})
await Promise.all(promises);
console.log("outside ",status);

console.log("outside ",status); ** –> I want to wait all async task complete**

** output:- **

outside  []
[]
{ class: 'healthy', confidence: 100 }
flag 1
INSIDE  [ { class: 'healthy', confidence: 100 } ]

How can I fix the decoding error in my gRPC Node.js application?

I’m new to gRPC with Node.js, and I’m trying to create a simple request to understand how it works.

I asked ChatGPT for a simple application where the client sends data to the server, and the server returns the same data using the Proto protocol.

I understand that Proto is typically used for server-to-server communication, but I want to use it for client-to-server communication for learning purposes.

I have this code, but it’s not working. The error I get from the client is:

Success: Invalid data

And the internal error from the server is:

Error decoding data: TypeError: Data.decode is not a function
    at file:///Users/user/node-proto/server.mjs:32:23

The problem seems to be that the decode function does not exist on the Data object. I’m not sure what I should use instead.

Here is the full code for the server:

import express from "express";
import bodyParser from "body-parser";
import grpc from "@grpc/grpc-js";
import protoLoader from "@grpc/proto-loader";
import fs from "fs";
import path from "path";
import cors from "cors";

const app = express();
const port = 3000;

app.use(cors());

const PROTO_PATH = path.join("./message.proto");

const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
});
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const Data = protoDescriptor.Data;

app.use(bodyParser.raw({ type: "application/x-protobuf" }));

app.post("/data", (req, res) => {
  try {
    const data = Data.decode(req.body);
    console.log(`Received data: ${JSON.stringify(data)}`);
    res.status(200).send("Data received");
  } catch (err) {
    console.error("Error decoding data:", err);
    res.status(400).send("Invalid data");
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

message.proto:

syntax = "proto3";

message Data {
  string id = 1;
  string name = 2;
}

And here is the client code:

<!DOCTYPE html>
<html>
  <head>
    <title>Protobuf Client</title>
  </head>
  <body>
    <h1>Send Data</h1>
    <button id="sendData">Send Data</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/protobufjs/6.11.2/protobuf.min.js"></script>
    <script>
      document
        .getElementById("sendData")
        .addEventListener("click", async () => {
          const protoRoot = await protobuf.load("message.proto");
          const Data = protoRoot.lookupType("Data");
          const payload = { id: "123", name: "John Doe" };
          const errMsg = Data.verify(payload);

          if (errMsg) {
            throw Error(errMsg);
          }

          const message = Data.create(payload);
          const buffer = Data.encode(message).finish();

          fetch("http://localhost:3000/data", {
            method: "POST",
            headers: {
              "Content-Type": "application/x-protobuf",
            },
            body: buffer,
          })
            .then((response) => response.text())
            .then((data) => {
              console.log("Success:", data);
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        });
    </script>
  </body>
</html>

What am I doing wrong? How can I fix the decoding error on the server?

How can I fill the gaps on the Shopify collection page when I hide or exclude products?

the first page is not filled entirely, but it already created other pages after excluding/hidding particular taged products.


{% for product in collection.products %}
  {% if product.tags contains 'hideProd' %}{% continue %}{% endif %}
  <!-- your product grid item -->
{% endfor %}

Gaps should fill.

For example, if there are 100 products in a collection and the pagination is set to 5 pages (with 20 products per page), but 20 products are excluded or hidden, the pagination should adjust to display only 4 pages.

My Flashcard Buttons wont work properly nor does my score card fuctionality

I have project for school that requires me to code a flashcard app, it came with a tutorial, aka a programming video to show me some of the steps along the way but no matter how many times i watch the videos, there error and other things coming up (the buttons not working properly, not displaying the proper score, or the score screen popping up before the end of the ‘game’), anyone minding to help or take a look to see what I’ve done wrong?

I’ve tried my videos several times and went back in to look and see if i could catch any missspellings, but i cant seem to find my error.

What’s wrong with my code? Firebase create account

Trying to create a button so that the user can input their email and password and pass recaptcha to create an account with firebase. Would like to add the option of signing up with microsoft or google. idk whats wrong new at coding….

<div id="signupModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('signupModal')">&times;</span>
        <h2>Sign Up</h2>
        <form id="signupForm">
            <input type="email" id="signupEmail" placeholder="Email" required>
            <input type="password" id="signupPassword" placeholder="Password" required>

            <!-- CAPTCHA container -->
            <div class="captcha-container">
                <div class="g-recaptcha" data-sitekey="example"></div>
            </div>

            <!-- Sign Up button -->
            <button type="button" onclick="handleSignup()">Sign Up</button>

            <!-- Or text -->
            <p style="text-align: center; margin-top: 10px;">or</p>

            <!-- Google Sign-In button -->
            <div id="googleSignInButton" class="google-button" onclick="handleGoogleSignIn()">
                Sign Up with Google
            </div>
        </form>
    </div>
</div>

<script>
    // Function to open a modal
    function openModal(modalId) {
        var modal = document.getElementById(modalId);
        modal.style.display = "block";
    }

    // Function to close a modal
    function closeModal(modalId) {
        var modal = document.getElementById(modalId);
        modal.style.display = "none";
    }


    // Function to handle signup
    function handleSignup() {
        var email = document.getElementById('signupEmail').value;
        var password = document.getElementById('signupPassword').value;
        var recaptchaResponse = grecaptcha.getResponse();

        if (!recaptchaResponse) {
            alert("Please complete the reCAPTCHA to proceed.");
            return;
        }

        firebase.auth().createUserWithEmailAndPassword(email, password)
            .then((userCredential) => {
                var user = userCredential.user;
                alert('Signup successful!');
                closeModal('signupModal');
            })
            .catch((error) => {
                var errorMessage = error.message;
                alert(errorMessage);
            });
    }

    // Function to handle forgot username or password
    function handleForgot() {
        var email = document.getElementById('forgotEmail').value;
        alert('Forgot username or password functionality not implemented.');
    }
</script>
<script src="https://www.gstatic.com/firebasejs/10.12.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.12.4/firebase-auth.js"></script>
<script>
    // Firebase configuration
    const firebaseConfig = {
        apiKey: "example",
authDomain: "example",
databaseURL: "example",
projectId: "example",
storageBucket: "example",
messagingSenderId: "example",
appId: "example"
};
// Initialize Firebase
    firebase.initializeApp(firebaseConfig);
 </script>
</body>
</html>

the sign up button is not work/store, I put the word example, but I actually put the real firebase info.

Typescript: how to get the property of a extracted union type by the value of function parameter

I am wondering if there’s a way could let ts compiler determine the type of callback in useListenAPI as

  • (data: number[]) => void if eventType === APIType.API1
  • (data: {isAdmin: boolean, data: number[]}) => void if eventType === APIType.API2
const enum APIType {
    API1 = 1,
    API2 = 2
}

interface API1{
    type: APIType.API1,
    Data: number[]
}

interface API2{
    type: APIType.API2,
    Data: {
        isAdmin: boolean,
        data: number[]
    }
}

type UnionAPI = API1 | API2;

//ts error
//'eventType' refers to a value, but is being used as a type here. Did you mean 'typeof eventType'?
const useListenAPI = (eventType: APIType, callback: (data:Extract<UnionAPI,{type: eventType}>["Data"]) => void)) => {
    // do whatever
}

//'type: typeof eventType' will just make callback is (any) => void
const useListenAPI = (eventType: APIType, callback: (data:Extract<UnionAPI,{type: typeof eventType}>["Data"]) => void)) => {
    // do whatever
}

I know it is solvable using generic like following but I am just wondering if there’s a simpler version, or it is out of reach from ts compiler since it a runtime thing

const useListenAPI = <T,>(eventType: APIType, callback: (data:Extract<UnionAPI,{type: T}>["Data"]) => void)) => {
    // do whatever
}

useListenAPI<APIType.API1>(APIType.API1, (data) => {
    // data: number[]
})