Unable to get the target message in the interactionCreate event

I’m encountering a frustrating issue with my interactionCreate event – it’s failing to retrieve the target message, which is the message I aim to decrypt after the modal form is submitted. Oddly, despite the message’s existence, it stubbornly returns an ‘undefined’ error, as if the message simply isn’t there. This event is activated through a context command, which opens a modal form for key entry. After submission, the subsequent interaction should yield a decrypted message.

Here is my sanbox code:

if (interaction.customId === 'key_modal') {
        try {
            // Extract the code provided in the modal form
            const submittedCode = interaction.fields.getTextInputValue('code-input');
            // Compare the submitted code with the expected code (e.g., '123')
            if (submittedCode !== '123') {
                await interaction.reply({ content: 'Incorrect code. Please try again.', ephemeral: true });
                return;
            }
    
            // Fetch the original message 
            const message = await interaction.channel.messages.fetch(interaction.targetMessage).id;
    
            if (!message || message.embeds.length === 0) {
                await interaction.reply({ content: 'No message or embed found.', ephemeral: true });
                return;
            }
    
            const embed = message.embeds[0];
            if (!embed.fields || embed.fields.length === 0) {
                await interaction.reply({ content: 'No fields found in the embed.', ephemeral: true });
                return;
            }
    
            // Use the same secret key and variable key that were used to encrypt the message
            const secretKey = generateSecretKey(); // Replace with your actual secret key generation
            const variableKey = submittedCode; // Use the submitted code for decryption
    
            const regex = /||```([^]+?)```(?:|||$)|||([^]+?)||/g;
    
            const encryptedContent1 = embed.fields[0].value.replace(regex, '$1');
            let decryptedMessage = decryptMessage(encryptedContent1, secretKey, variableKey);
    
            if (embed.fields[1]) {
                const encryptedContent2 = embed.fields[1].value.replace(regex, '$1');
                decryptedMessage += ` ${decryptMessage(encryptedContent2, secretKey, variableKey)}`;
            }
    
            if (decryptedMessage.length > 2000) {
                decryptedMessage = decryptedMessage.slice(0, 2000);
            }
    
            await interaction.reply({ content: `${decryptedMessage}`, ephemeral: true });
    
            const embed2 = new Discord.EmbedBuilder();
            embed2
                .setTitle(":unlock: Log Entry Decrypted")
                .setDescription(`${interaction.user.displayName} decrypted log entry: ${message.url}`)
                .setColor("Green")
                .setTimestamp();
            await interaction.channel.send({ embeds: [embed2] });
        } catch (error) {
            console.error(error);
            await interaction.reply({ content: 'An error occurred while decrypting the message.', ephemeral: true });
        }
    }

I have tried different approaches such as

interaction.targetMessage
interaction.targetMessage.id
const message = await interaction.channel.messages.fetch(interaction.messageId);
const message = await interaction.channel.messages.fetch(interaction.targetMessage).id;

Sticky Menu using Scroll View in Expo React Native Web

I am trying to keep my top menu from scrolling with the rest of the page in my Expo React Native Web project, but after hours of troubleshooting, I can’t get the menu to be sticky. Please have a look at my current JSX setup and help me solve this issue:

<View style={{flex:1}}>
  <ScrollView stickyHeaderIndices={[0]} scrollEnabled={false} style={{flex:1, flexDirection: 'column'}}>
    <View style={{flexDirection: 'row', height:50, backgroundColor: 'lightgrey', alignItems: 'center', gap: 40, justifyContent: 'center'}}>
      <Text style={{marginLeft: 30}}>Logo</Text>
      <View style={{flex: 1}}></View>
      <Text>Test</Text>
      <Text>Test</Text>
      <Text>Test</Text>
      <Text>Test</Text>
      <Text>Test</Text>
      <View style={{flex: .1}}></View>
    </View>

    <View style={{flex:1}}>
      <ScrollView nestedScrollEnabled={true} showsVerticalScrollIndicator={true} style={{backgroundColor:'red', flex: 1}}>
        <View style={{backgroundColor:'green', height: 2000}}></View>
        <View style={{backgroundColor:'yellow', height: 2000}}></View>
      </ScrollView>
    </View>
  </ScrollView>
</View>

Print Or cancel it gives the same message and delettes the generated image

In the below code which is working fine but only single issue i am facing is that the file which is generated by html2canvas is deleting on canceling the print which is correct but when i successfully saved the PDF file using Microsoft Print To PDF printer it successfully saves the file but it executes the deletes the file also why and how i do not know. Please help.

Either way the response is:

Response from server: 
success

Deleted generated image: 
success

and below is the rest of the code:

$("#myButtonS").click(function () {
    var staffno = "<?php echo $staffno; ?>";
    var container = $("#canvasSaveder");
    var charA = $("#charA");
    var horizontalPadding = (container.width() - charA.width()) / 2;
    var verticalMargin = (container.height() - charA.height()) / 2;

    charA.css({
        "color": "black !important",
        "font-weight": "bold",
        "right": "0",
        "left": "0"
    });

    var userCancelledPrint = false; // Define the flag here

    html2canvas(container, {
        scale: 2,
        onrendered: function (canvas) {
            var imgsrc = canvas.toDataURL("image/jpeg", 1);
            $("#newimg").attr('src', imgsrc);
            var dataURL = canvas.toDataURL();

            $.ajax({
                type: "POST",
                url: "save_printed_id.php",
                data: {
                    imgBase64: dataURL,
                    staffid: staffno
                }
            }).done(function (o) {
                console.log('saved');
                printImage(imgsrc);
            });
        }
    });

    function printImage(imgSrc) {
        var staffno = "<?php echo $staffno; ?>";

        var printWindow = window.open('', '', 'width=600,height=600');
        printWindow.document.open();
        printWindow.document.write('<html><body>');
        printWindow.document.write('<div class="pagerA">');
        printWindow.document.write('<img style="margin-top: -8px; margin-left: -8px;" src="' + imgSrc + '" width="105%" />');
        printWindow.document.write('</div>');
        printWindow.document.write('<div class="pagerA">');
        printWindow.document.write('<img src="../../../images/idBacks.jpg" width="100%" />');
        printWindow.document.write('</div>');
        printWindow.document.write('</body></html>');
        printWindow.document.close();

        // Attach an event handler to the print window's beforeunload event
        printWindow.onbeforeunload = function () {
            // Set the userCancelledPrint flag to true when the print window is closed
            userCancelledPrint = true;
        };

        printWindow.print();

        // Close the print window automatically after a delay (e.g., 5 seconds)
        setTimeout(function () {
            printWindow.close();

            // Check if the user canceled the print job and delete the image if needed
            if (userCancelledPrint) {
                deleteGeneratedImage();
            }
        }, 1000); // Adjust the delay as needed

        function deleteGeneratedImage() {
            // Implement code to delete the generated image here
            // For example, you can make an AJAX request to a PHP script that handles the deletion.
            // Ensure you have the necessary logic in place to identify and delete the correct image.
            // Replace the following with your actual delete logic:

            $.ajax({
                type: "POST",
                url: "save_printed_id_cancelled.php",
                data: {
                    staffid: staffno
                }
            }).done(function (response) {
                console.log('Response from server: ' + response);
                if (response.trim() === "success") {
                    console.log('Deleted generated image: ' + response);
                } else {
                    console.log('Failed to delete generated image: ' + response);
                }
            });

        }
    }
});

save_printed_id_cancelled.php

<?php
include ('inc/db.php');

$staffno = mysqli_real_escape_string($dba_si, $_POST['staffid']);
    $sqlIM13    = "select id, filename from id_photos
    where staffno = '$staffno'
    order by id desc
    ";
    $sqlIM14    = $dba_si->query($sqlIM13);
    $sqlIM15    = $sqlIM14->fetch_assoc();
    
    $fileItem5 = 'images/employees/empcards/'.$staffno.'/'.$sqlIM15['filename'];
    //echo $fileItem6 = 'images/employees/empcards/'.$staffno.'/'.$sqlIM15['filename']; // Echo before any deletions

if (unlink($fileItem5)){
    $dba_si->query("delete from id_photos where id = '".$sqlIM15['id']."' ");
    echo "success";
    // Log a message to a file
    error_log("Image deleted successfully for staffno: " . $staffno);
}else{
    echo "Failed to delete generated image: Error - " . error_get_last()['message'];
    // Log an error message to a file
    error_log("Failed to delete image for staffno: " . $staffno);
}

?>

django passing variable to javascript in html template

I was trying to pass a variable to my html template in my django project and I can’t seem to find a solution to why it doesn’t work.

The input of username_list: [‘name1’, ‘name2’]

back end:

    username_list = [user.username for user in User.objects.all()]

    return render(response, "main/main-page.html", {"list": username_list})

template:

<script>
    let availableKeywords = {{ list }};
    console.log(availableKeywords);
</script>

The javascript won’t run and I don’t understand if there is another correct way of doing it that I am not aware of.
Can’t figure it out.
Thanks for the help!

Unable to synchronise store dispatch from loop

Dispatching action from for loop is not getting synchronised. Here are the code snippets:

Component:

function mapStateToProps(state) {
  return {
    downloads: state.downloads
  }
}

function mapDispatchToProps(dispatch, props) {

}

export class ProgressBarIndicator extends Component {
  componentDidUpdate = () => {
    console.log(this.props.downloads.requestCount);
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ProgressBarIndicator);

Action Dispatch:

export function processFetchPlan(plans) {
  return function (dispatch, getState) {
    Object.keys(fetchPlans).forEach((fetchObjectName) => {
      dispatch(_getPrefetchPending(fetchObjectName));
      ...........
    };
  }
}

function _getPrefetchPending(objectName) {
  return {
    type: types.DOWNLOAD_DATA_PENDING,
    meta: {
      objectName,
    },
  };
}

Action Handler:

import Immutable from 'seamless-immutable';

const ACTION_HANDLERS = {
  [types.DOWNLOAD_DATA_PENDING]: (state, action) => {
    return Immutable.update(state, 'downloads', (downloads) => downloads.merge({
      requestCount: (downloads.requestCount || 0) + 1,
    }, { deep: true }));
  };
}

With this code, console log is printing the last count for requests. Support fetch plan has 10 objects, so it’s printing 10, 10 times, instead it should print 1,2,3…..10.

useEffect in React Not Triggering as Expected

I am new in React Native when i start my code i have an error Cannot convert null value to object becouse i can not update my store with useEffect

i can not find a resone why the code show the but and i hope that you can help me

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Text, View } from "react-native";
import { currencyExchangeListSelectors } from "../../store/selectors";
import { setCurrencyExchangeList } from "../../store/thunk";
import { formatterСurrency } from "../../utils/helpers";
import style from "./style";

const CurrencyExchange = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    console.log("useeffect");
    dispatch(setCurrencyExchangeList());
  }, []);

  const currencyExchangeList = useSelector(currencyExchangeListSelectors);
  const { buy, sale, ccy } = currencyExchangeList[1] || {};
  const saleUSD = formatterСurrency(sale);
  const buyUSD = formatterСurrency(buy);
  return (
    <View style={style.container}>
      <Text>
        {" "}
        {ccy} {saleUSD} / {buyUSD}{" "}
      </Text>
    </View>
  );
};

export default CurrencyExchange;

ERROR TypeError: Cannot convert null value to object

This error is located at:
in CurrencyExchange (created by Main)
in RCTView (created by View)
in View (created by Main)
in Main (created by App)
in Provider (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent), js engine: hermes

What is the best way to update state with useState?

Assuming I have a stateful variable as so const [numbers, setNumbers] = useState([1,2,3]); what is the preferred/best way to update state and why? From a technical level. I have encountered rendering cycle mismatch before and I got the solution shown to me but I want to understand why.

Option 1:

setNumbers(numbers.slice(1))

Option 2:

setNumbers(state => numbers.slice(1))

Option 3:

setNumbers(state => state.slice(1))

Which one of these is the “correct” way to go about it, especially to avoid unwanted render cycle mismatch between state being updated and UI showing updated state?

Navigation from login to another page is not happening in Redux

Here I have created a login form, and in the reducer I already store the registered user’s email and password. If any one gives proper login credentials, they will go to the logout component; otherwise, they will throw an alert saying “try again.” , I have created that using Redux, so in the app components, I have written logic that if some one gives proper email and password, they will navigate to the logout components; otherwise, they stay in the form components. But the problem is that if I give proper credentials, it will not navigate to the logout components. Still,still blank page is showing, but there is no error we are getting. So what is the problem and How to navigate and show the data of users IDs and provide proper credentials, app components code is given below

import "./App.css";
import Form from "./Components/Form";
import { useSelector } from "react-redux";
import Logout from "./Components/Logout";

function App() {
  const users = useSelector((state) => state.users);
  if (users.email && users.password) {
    return (
      <>
        <Logout />
      </>
    );
  } else
    return (
      <>
        <Form />
      </>
    );
}

export default App;

//Form or Login components code is given below




 import { useState } from "react";
    import "./Form.module.scss";
    import { useDispatch, useSelector } from "react-redux";
    export default function Form() {
      const [name, setName] = useState("");
      const [email, setEmail] = useState("");
      const [password, setPassword] = useState("");
      const dispatch = useDispatch();
      const users = useSelector((state) => state.users);
      const register = () => {
        const payload = users.find(
          (user) => user.email === email && user.password === password
        );
        if (payload) {
          dispatch({
            type: "REGISTER",
            payload: {
              id: new Date().getTime(),
              email,
              password,
            },
          });
        } else {
          alert("try again");
        }
      };
      const handleSubmit =(e) =>{
        e.preventDefault()
      }
      return (
        <>
          <form className="border login__form" onSubmit={(e)=>handleSubmit(e)}>
            <h3>Login Form</h3>
            <hr />
            <div className="mb-3">
              <label htmlFor="exampleInputName1" className="form-label">
                Name
              </label>
              <input
                type="text"
                className="form-control"
                id="exampleInputName1"
                aria-describedby="emailHelp"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
             
            </div>
            <div className="mb-3">
              <label htmlFor="exampleInputEmail1" className="form-label">
                Email address
              </label>
              <input
                type="email"
                className="form-control"
                id="exampleInputEmail1"
                aria-describedby="emailHelp"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <div id="emailHelp" className="form-text">
                we will never share your email with anyone else.
              </div>
            </div>
            <div className="mb-3">
              <label htmlFor="exampleInputPassword1" className="form-label">
                Password
              </label>
              <input
                type="password"
                className="form-control"
                id="exampleInputPassword1"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
            <div className="mb-3 form-check">
              <input
                type="checkbox"
                className="form-check-input"
                id="exampleCheck1"
              />
              <label className="form-check-label" htmlFor="exampleCheck1">
                Check me out
              </label>
            </div>
    
            <div className="d-grid gap-2">
               
                <button
                  className="btn btn-outline-danger"
                  type="submit"
                  onClick={register}
                >
                  Submit
                </button>
              
            </div>
          </form>
        </>
      );
    }

logout components code

import { useDispatch, useSelector } from "react-redux";

export default function Logout() {
  const products = useSelector((state) => state.products);
  const users = useSelector((state) => state.users);

  const dispatch = useDispatch();

  return (
    <>
      Welcome<span className="user_name">User</span>
      {products.map((products) => (
        <div key={products.id}>
          {products.name}-{products.price}
        </div>
      ))}
      {users.map((users) => (
        <div key={users.id}>
          {users.email}-{users.password}
        </div>
      ))}
      <button
        className="btn btn-outline-danger"
        type="submit"
        onClick={() => {
          dispatch({
            type: "LOGOUT",
          });
        }}
      >
        Logout
      </button>
    </>
  );
}

store which reducer components code

import {createStore} from 'redux';
const initialState={
    users: [{
        email:"[email protected]",
        password:"123"
    }],
    loggedInUser:null,
    products:[{
        id:1,
        name:'pen',
        price:10
    },{
        id:2,
        name:'pencil',
        price:5
    },{
        id:3,
        name:'Eraser',
        price:15
    }],
    cart:[]
}

const reducer = (state=initialState,action) =>{
    switch(action.type){
        case "REGISTER":
            return{
                ...state,
                users:action.payload
            }
        case "LOGOUT":
        return{
            ...state,
            users:null
        }
        default:
            return state;
    }
}
export default createStore(reducer)

Creating a Discord-Style Mouse Parallax Effect in HTML, CSS, and JavaScript

I am trying to achieve a mouse parallax effect similar to what can be seen on the Discord login page (for reference: Discord Login Page). I have created a particle animation in my HTML, CSS, and JavaScript code, but I am having difficulty implementing the desired mouse parallax effect.

Here is my current code:

HTML:

<div class="container">
 <div class="particles" id="particles-container"></div>
</div>

CSS:

body, html {
    height: 100%;
    margin: 0;
    overflow: hidden;
}

.container {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #111;
    overflow: hidden;
}

.particles {
    position: absolute;
    width: 100%;
    height: 100%;
}

/* Style the particles */
.particle {
    position: absolute;
    background-color: #fff; /* Color of particles */
    border-radius: 50%; /* Make them circular */
    pointer-events: none; /* Prevent particles from blocking mouse events */
    transform: translate(-50%, -50%); /* Center particles on their positions */
}

/* Add z-index for particles */
.particle {
    z-index: 1;
}

JS:

const particlesContainer = document.getElementById('particles-container');
let particleCount = 300; // Adjust the initial particle count
const particles = [];

// Create particles
for (let i = 0; i < particleCount; i++) {
    createParticle();
}

function createParticle() {
    const particle = document.createElement('div');
    particle.className = 'particle';

    const size = Math.random() * 2 + 2; // Random size between 2px and 4px
    const x = Math.random() * window.innerWidth;
    const y = Math.random() * window.innerHeight;
    const color = getRandomColor();

    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;
    particle.style.left = `${x}px`;
    particle.style.top = `${y}px`;
    particle.style.background = color;

    particlesContainer.appendChild(particle);

    // Store particles in the array
    particles.push({
        element: particle,
        x,
        y,
        speedY: Math.random() * 0.5 + 0.1, // Slower vertical speed
        speedX: Math.random() * 0.5 + 0.1, // Slower horizontal speed
    });
}

// Animation loop
function animateParticles() {
    for (const particle of particles) {
        // Update particle positions for a parallax effect
        particle.x -= particle.speedX; // Added horizontal motion
        particle.y -= particle.speedY; // Added vertical motion

        // Reset particle position if it goes above the viewport
        if (particle.y < 0) {
            particle.y = window.innerHeight + Math.random() * 100;
            particle.x = Math.random() * window.innerWidth;
        }

        // Apply the new position
        particle.element.style.transform = `translate(${particle.x}px, ${particle.y}px)`;
    }

    requestAnimationFrame(animateParticles);
}

// Helper function to generate random colors
function getRandomColor() {
    const colors = ['#ffffff', '#dddddd', '#666666']; // White, light gray, and dark gray
    return colors[Math.floor(Math.random() * colors.length)];
}

// Start the animation loop
animateParticles();

In my current code, I have a particle animation that moves particles independently within the viewport. However, I want to add a mouse parallax effect similar to the one on the Discord login page, where particles move in response to the mouse cursor’s movement but do not follow the cursor directly.

I am looking for guidance on how to modify my existing code to achieve this effect. Specifically, I want to know how to update the particle positions based on the mouse movement while maintaining the particles’ independent animations.

Any help or code examples would be greatly appreciated. Thank you!

“I have already attempted to create a particle animation in my HTML, CSS, and JavaScript code. I followed a tutorial and successfully generated a particle animation that moves independently within the viewport. However, my goal is to add a mouse parallax effect similar to the one seen on the Discord login page.

What I tried:

Created a particle animation with random movement.
Added event listeners to detect mouse movement.
Experimented with adjusting particle positions based on mouse coordinates.
What I expected:
I expected the particles to respond to the mouse cursor’s movement in a parallax-like fashion, similar to the Discord login page.

What actually resulted:
The particles in my animation either followed the cursor too closely or did not respond to the mouse movement as desired. My current code does not achieve the desired mouse parallax effect.”

how to update only one data in json database in reactjs?

i am getting quantity from input. But i set quantity=0 for all object in json database. i need to update quantity for every object in order to filter only selected object.

import './App.css';
import FormInput from './Components/FormInput';
import axios from 'axios'
import { useEffect, useState } from 'react'

function App() {
  const [list, setList] = useState([])
  const [qty, setQty] = useState({})
  const crackers = async () => {
    const res = await axios.get("http://localhost:8000/items")
    const initialQty = {}; 
    res.data.forEach((item) => {
      initialQty[item.name] = 0;
    });
    setQty(initialQty);
    setList(res.data)
  }

  useEffect(() => {
    crackers()
  }, [])

  const handleChange = (e) => {
    e.preventDefault()
    const { name, value } = e.target;
    setQty({
      ...qty,
      [name]: parseInt(value) || 0, 
    });

  }
  let sum = 0

  list.forEach((item) => {
    sum += item.price * qty[item.name]
  })

  const submitHandler = (e) => {
    e.preventDefault()
    updatelist()
  }

  return (
    <div >
      <form onSubmit={submitHandler}>
        <table>
          <thead>
            <tr>
              <th>S.no</th>
              <th>Name</th>
              <th>Unit</th>
              <th>price</th>
              <th>Quantity</th>
              <th>total</th>
            </tr>
          </thead>
          <tbody>
            {list.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.unit}</td>
                <td>{item.price}</td>
                <td>
                  <FormInput
                    type="number"
                    name={item.name}
                    handleChange={handleChange}
                    value={qty[item.name]} />
                </td>
                <td>{item.price * qty[item.name]}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <button type='submit'>Submit</button>
      </form>
      <h1>total:{sum}</h1>
    </div>
  );
}

export default App;

db.json

{
  "items": [
    {
      "id": 1,
      "name": "Bijili",
      "unit": "Pocket",
      "price": 100,
      "quantity": 0,
      "total": 0
    },
    {
      "id": 2,
      "name": "Chakker",
      "unit": "Box",
      "price": 200,
      "quantity": 0,
      "total": 0
    },
    {
      "id": 3,
      "name": "Flower",
      "unit": "Box",
      "price": 300,
      "quantity": 0,
      "total": 0
    },
    {
      "id": 4,
      "name": "Lakshmi",
      "unit": "Pocket",
      "price": 20,
      "quantity": 0,
      "total": 0
    },
    {
      "id": 5,
      "name": "Sparklers",
      "unit": "Box",
      "price": 50,
      "quantity": 0,
      "total": 0
    }
  ]
}

i tried to implement for each method with axios to modify quantity of every object in db.json and called it on submit form. But this is not working.

const updatelist=()=>{
  list.forEach(item=>{
    axios.patch(`http://localhost:8000/items?name=${item.name}`,{quantity:qty[item.name]})
  })
}

Angular: How to set values for select dropdown separetely using formcontrol

I have a list of food categories. Then I have a table for a list of food items and there is a field for foodcategory which classifies which category this item falls. The food category is being mapped based on Guid but is being displayed in readable format for the user. For every dropdown a new form instance is being used. How can I set the value separately. Using the exisiting code, all of them will have the same as it using same form control name.

Here is my code snippet.

    <tr *ngFor="let food of foodItems" id="{{food.Guid}}" class="alternate-row">
      <td><label>{{food.foodName}}</label></td>
      <td><label>{{food.foodDescription}}</label></td>
      <td>
        <form class="table_form" [formGroup]="tableForm" (ngSubmit)="onTableFormSubmit(tableForm.value)">
          <select class="form-control" formControlName="foodCategorySelect" (change)="onTableFormSubmit(tableForm.value, food.Guid)">
            <option *ngFor="let foodCategory of foodCategoryList" [value]="foodCategory.Guid" [selected]="foodCategory.Guid == food.category">
              {{ foodCategory.categoryName }}
            </option>
          </select>    
        </form> 
      </td>
    </tr>

Here is my logged value data:

    foodCategoryList
    0: 
    Guid: "b6b64fba-1879-44fb-8a8d-1b26c2229367"
    categoryName: "Starter"
    [[Prototype]]: Object
    1: 
    Guid: "ba9e3828-ddf0-4db4-bff2-2ec668d973d0"
    categoryName: "Dessert"
    [[Prototype]]: Object

    foodList
    0: 
    foodName: "Chicken Wings"
    Guid: "ec34ce1f-5274-4d32-a17f-4a518fef9a1f"
    foodDescription: "Delicious spicy chicken wings served with sauce"
    category: "b6b64fba-1879-44fb-8a8d-1b26c2229367" --starter
    [[Prototype]]: Object

Please help.. Cant seem to find a way

Communicate with a native Windows application

I have a windows hello.exe executable which turns out to be a native application which is called by the browser via sendNativeMessage so for example:

chrome.runtime.sendNativeMessage("en.lol.hello", arguments, function (res){
//nothing
}); 

where

arguments = { arg1: "hello1", arg2: "hello2",arg3: { arg4: "hello4" }.

Is there a way to communicate via hello.exe without going through javascript?

I have hello.exe and I tried via powershell to pass the arguments as –arg1 “hello”…. and as ‘{ arg1:”hello1 …}’ but it doesn’t work. Can you recommend a python script or is it simply not possible?

querySelector working in devtools console but not in Selenium ‘execute_script’ with CSS selector

When I load the page on Chrome without Selenium, and run the same querySelector function the console, the correct element is returned, however when using driver.execute_script with the same querySelector function None is returned.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

driver = webdriver.Chrome()

url = 'https://www.bestbuy.com/site/searchpage.jsp?st=4090&_dyncharset=UTF-8&_dynSessConf=&id=pcat17071&type=page&sc=Global&cp=1&nrp=&sp=&qp=&list=n&af=true&iht=y&usc=All+Categories&ks=960&keys=keys'

selector = 'div#pricing-price-60753325 > div > div > div > div > div > div > div > div > div > span'

driver.get(url)

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "html")))

sleep(5)

elem = driver.execute_script(f'document.querySelector("{selector}")')

print(elem)

driver.quit()

You can even try it on the devtools console and see that document.querySelector('div#pricing-price-60753325 > div > div > div > div > div > div > div > div > div > span') returns <span aria-hidden="true">$1,699.99</span> as it should. I have also tried using xpath with execute_script and query selector, and driver.findElement() by xpath and css selector to no avail.

Unable to get data when using ip address as host in nodejs

I am using VS code to create a react js application.
I was able to get the data using this setup. I can see the results on my console log.

const db = mysql.createPool({
  host     : 'xxx.xxx.xxx.xxx',
  user     : 'myusername',
  password : 'mypassword',
  database: 'mydatabase',
  connectTimeout : 10000,
  port: 3306
})

app.listen(3306,()=>{
    let sqlInsert = "SELECT el.examID, el.categoryID, el.SubCategoryID, el.Question,A.A, A.B, A.C, A.D, A.Answer ";
    sqlInsert += " FROM ExamList el ";
    sqlInsert += " inner join ExamAnswer A on A.ExamID = el.ExamID ";
    sqlInsert += " inner join ExamSubCategory es on es.ID = el.SubCategoryID ";
    sqlInsert += " where el.CategoryID = 1 and es.ID = 1";
    db.query(sqlInsert,(err, result)=>{
        console.log(result);
    })
})

But when trying to get the data using app.get. My browser just keep on loading.
I tried http://xxx.xxx.xxx.xxx:3306/api/get

app.get("/api/get",(req,res)=>{
    let sqlInsert = "SELECT el.examID, el.categoryID, el.SubCategoryID, el.Question,A.A, A.B, A.C, A.D, A.Answer ";
    sqlInsert += " FROM ExamList el ";
    sqlInsert += " inner join ExamAnswer A on A.ExamID = el.ExamID ";
    sqlInsert += " inner join ExamSubCategory es on es.ID = el.SubCategoryID ";
    sqlInsert += " where el.CategoryID = 1 and es.ID = 1";
    db.query(sqlInsert,(err, result)=>{
        res.send(result)
    })
    });

I also tried https://xxx.xxx.xxx.xxx/api/get and this is the error message
The connection for this site is not secure
xxx.xxx.xxx.xxx sent an invalid response.
ERR_SSL_PROTOCOL_ERROR

I am very new in react js and only relying on tutorials right now but I was able to build my application. And now I am facing this issue. I’ve been trying to solve this for 2 days now.
Hope someone can help me with this.