alternate depending on whether their id is odd or even React

I am using React for a web page. In a component, I have a div on the left and an image on the right.

I would like them to alternate depending on whether their id is odd or even.

function Item({ title, text, link, img,id }) {
  return (
    <div >
      <div>
        <h3>
          {title}
        </h3>
        <p>{text}</p>
        <a href={link}>
          text
        </a>
      </div>
      <img src={img} alt={title} />
    </div>
  );
}

How to close popup.html for my google extension?

How can I visibly hide my popup.html whenever I click a button on that popup. I want to keep my scripts running but minimize the popup off the page. The reason i’m doing this is because i’m making an eye dropper extension that can get the color under your cursor and perhaps that color is being blocked by the popup hence why I want to get hide it when I’m looking for a color. Once I’ve picked my color the popup reappears.

how to query from firebase realtime database with security rules applied

I have setup a basic security rules of firebase realtime database for this question. Before I jump to the problem, I have created a Flutter mobile app with GetX and also I have installed http: ^0.13.4 plugin for querying.

Here is how I set the security rules

{
  "rules":{
    ".read" : "auth.uid !== null && auth.token.email_verified == true",
    ".write" : "auth.uid !== null"    
  }
}

So basically, I want users to be able to read the data if they are authenticated and email verified.

And for write rule, only if the user is authenticated and the custom claims of isAdmin is set to true. For isAdmin, I don’t know to set it in the security rules.

Is it something like this?

"auth.uid !== null && root.child('isAdmin').val() == true" 

Anyways, my problem is how to query using http plugin on client side?
Here is a sample of GET query

Uri url = Uri.parse('URL HERE with /.json file');

getIPTIdAndName() async {
  iptList.value = [];
  await http.get(url, headers: {"Authorization": FirebaseAuth.instance.currentUser!.uid}).then(
    (value) {
      var response = json.decode(value.body) as List<dynamic>;
      for (var i = 0; i < response.length; i++) {
        iptList.add({
          "iptIndex": i,
          "iptId": response[i]['id'],
          "iptName": response[i]['name']
        });
      }
      iptList.refresh();
    },
  );
}

How to query if the security rules is set?

POST returns undefined with Cloud Function

I’m implementing Stripe for React Native and I’m trying to send the customerId to my Cloud Function using POST, but when I execute the code it returns in the console.log undefined

Cloud Function (Firebase)

exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {

   let id = await request.body.customer_id
  
   response.send({
     result: id
   })
});

Client side

const fetchPaymentSheetParams = async () => {
    const response = await fetch(`${API_URL}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ customer_id: customerId })
    });
    const { result } = await response.json();

    console.log(result)

  };

Equal sides of an array in JS

Question: Take an array with integers and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. Let’s say you are given the array {1,2,3,4,3,2,1}:
Your function equalsides() will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.

I have written the following

  1. Declare two variables mid and i where
    mid the index we are looking for
    i= this is starting index
  2. Then while (mid<= arr.length-1) we will go through the array and add up each side of the array one side from i=0 to i=mid and then from i=mid to i=array.length-1, while adding up each side to leftSum and rightSum respectively
  3. And if leftSum==rightSum in any of these instances we will return mid if it didnt it will increase mid by one and reiterate ,
  4. If mid is not returned we will return -1 at the end.

In code it is the following

function findEvenIndex(arr)
{
  //Code goes here!
  let mid =1;
  let leftSum=0;
  let rightSum=0;
  while(mid<(arr.length-1)){
   
      
    for(i=0;i<mid;i++){
      
        leftSum=leftSum+arr[i]
      
    }
    
    rightSum = rightSum + arr[mid]
 
 
    if(rightSum==leftSum){
        console.log("mid: "+ mid);
        return mid;
    }
    else{
        
        mid++;
        
    }

  }
 return -1;
}

however I am not sure why this is not working, any help would be appreciated

H88 Error: Invalid account: #0 for network: mumbai – Expected string, received undefined

This is my hardhat.config.js file code


module.exports = {
  solidity: "0.8.4",
  networks: {
    hardhat: {
      chainId: 1337
    },
    mumbai: {
      url: "https://rpc-mumbai.matic.today",
      accounts: [process.env.pk]
    },
    // polygon: {
    //   url: "https://polygon-rpc.com/",
    //   accounts: [process.env.pk]
    // }
  }
};

When running npx hardhat test the following error appears:

**Error HH8: There’s one or more errors in your config file:

  • Invalid account: #0 for network: mumbai – Expected string, received undefined**

Seems I have a couple of errors with my hardhat.config.js file but can’t locate. I am using Nader Dabit’s full-stack-web3 tutorial for full stack web3 development.

Load and access data sequentially within functions in a JavaScript class

I need to load data from json into a function within a class. The data loads but the sequence is off as shown below. How can I get the data 1st before the process continues?

”’

"use strict";

customElements.define('myexample', class extends HTMLElement {
    constructor() { 
        super();
        …
    }

    connectedCallback() {
         ….
         this.paths = [];
         let go=this;
         go.loaditems ();
    }


    loaditems(){
        …
        this.getimage();
    }

    //problem area: data is 
     getimage(){
        …
        this.pic=[]
        let retpic= this.processpic();
        alert(“returned in place: “ + retpic”);
        this.pic=retpic;
         … (other processes that require reference with “.this”)
    }
    alert(“after returned pic”);
    
    processpic(){
            $.get("pics.json", function(data){
                let ds = data.pics[0].pic1 + “.jpg”;
                return ds;
            })
    }

});

”’

Problem: the alert(“after returned pic”) fires before the image is loaded. Putting a callback with processpic() and wrapping getimage() within the callback makes it impossible to properly reference “this.”

How can I get all the different values for the same key in an array (JS)?

I’ve an array Like:

var array = [
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'}, 
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'},
            {charId: 'OTXDAY', text: 'Older Than x Days', selectOpt: 'EQ'},
            {charId: 'REFPER', text: 'Reference Period', selectOpt: 'EQ'},
            {charId: 'OTXDAY', text: 'Older Than x Days', selectOpt: 'BT'}
            ];
            
How I can achieve:

var newArray = [{
                param: 'REFPER',
                value: [{text: 'Reference Period',
                        selectOpt: 'EQ'
                        },
                        {text: 'Reference Period',
                        selectOpt: 'EQ'
                        },
                        {text: 'Reference Period',
                        selectOpt: 'EQ'
                        }]
                },
                {
                param: 'OTXDAY',
                value: [{text: 'Older Than x Days',
                        selectOpt: 'EQ'
                        },
                        {text: 'Older Than x Days',
                        selectOpt: 'BT'
                        }]
                }];

I need to save it in database.
I viewed: How to add an object to an array
JavaScript: Push into an Array inside an Object?
Thanks in advance.

Firestore realtime updates missed while disconnected

I have a simple web app that uses Firestore to receive realtime updates. For simplicity, I can demonstrate the issue with the example from the documentation:

const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
  console.log("Current data: ", doc.data());
});

I am NOT using offline persistence and am using v 9.6.8.

Under normal conditions, everything works as expected. When I lose connectivity, however, I am not notified of changes that happen while disconnected even after connectivity is restored (I simulate this by going on ‘airplane mode’).

One option I’ve considered, but not yet tried, is to subscribe to connectivity events from the device (online and offline windows events). Before pursuing this option, I was wondering if there is a simpler or better solution.

How to permanent change html text after a submitted has been triggered

Im currently trying to find out if its possible to change a text in extension when a submit has happend. I currently have a text saying “ENTER DISCORD USER ID AND SUBMIT” and when an user has entered its USER ID and submitted, the text should be changed to “USER ID SUBMITTED” and the text should always say that afterwards, meaning that if someone closes and opens the extensions – the text should still say “USER ID SUBMITTED”.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="../css/style.css">
    <script src="../js/popup.js"></script>
</head>

<body>
    <div class="text-center">
        <form id="form" class="form-control mt10">
            <label> <input type="number" id="discord-id-input" name="discord-id-input"></label>
            <button id="discord-id-button" type="submit" class="submit"></button>
            <output id="help-text" class="help-text" value="">ENTER DISCORD USER ID AND SUBMIT</output>
        </form>
    </div>
</body>
function get_discord_id(callback) {
    chrome.storage.sync.get(["discord_id"], (result) => {
        callback(result.discord_id);
    });
}

function set_discord_id(discord_id) {
    chrome.storage.sync.set({ discord_id: discord_id }, () => {});
}

window.addEventListener("DOMContentLoaded", (e) => {
    // check if discord ID is already stored
    get_discord_id((discord_id) => {
        if (discord_id == null) {
            form.addEventListener('submit', () => {
                let value = document.getElementById("discord-id-input").value;

                chrome.runtime.sendMessage({ discord_id: value }, function(response) {});

                set_discord_id(value);
                document.getElementById('help-text').innerHTML = 'USER ID SUBMITTED';
            });
            e.preventDefault();
        };
    });
});

I wonder how I am able to permanent change a text after a submitted trigger has happend?

How to add Google Ads conversion purchase event to my WooCommerce Thank you Page

I saw this
Adding Google Ads Event Snippet To Conversion Page (thank you.php)

But I have a different situation. I am using ” Auto Complete Processing WooCommerce orders on Thank you Page” and “Redirect WooCommerce checkout page” all these are inside my functions.php file.

This is what my functions.php file looks like. I hid my site with ” ********* “

//Auto Complete Processing WooCommerce orders on Thankyou Page

add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( $order->has_status('processing') ) {
        $order->update_status( 'completed' );
    }
   
}

// Redirect WooCommerce checkout page to ******************** after the payament
add_action( 'woocommerce_thankyou', 'pfwp_redirect_woo_checkout');
function pfwp_redirect_woo_checkout( $order_id ){
    $order = wc_get_order( $order_id );
    $url = 'https://*********/*********/*********/';
    if ( ! $order->has_status( 'failed' ) ) {
        wp_safe_redirect( $url );
        exit;
    }
}

And I want to add the Event snippet inside the Thank You for google ads.

<!-- Event snippet for Purchase conversion page -->
<script>
  gtag('event', 'conversion', {
      'send_to': 'AW-***********/********kDENy8vL4o',
      'value': 1.0,
      'currency': 'SAR',
      'transaction_id': ''
  });
</script>
<!-- End Event snippet for Purchase conversion page -->


Because I am redirecting the thank you page to another page, the script will trigger? Or not?

And how and where do I add the Event snippet at the functions.php because I have a lot of code that control WooCommerce?

Python __repr__ method: writing a JS equivalent?

I am working through a short beginner’s course on Algorithms and Data Structures. The instructor’s language is Python; I am converting the code examples to JavasScript. So far, so good.

I am dealing with Linked Lists. The instructor tests the code using Python’s repr() method; after days of trial and error, I have a working JS solution, but it is not exactly the same as the Python code. I would like to know if there is a better way of implementing the JS code, which I provide, along with the Python code.

Py

# class LinkedList and its methods are presumed to exist

def __repr__(self):
  
  nodes = []
  current = self.head

  while current:
    if current is self.head:
      nodes.append("[Head: %s]" % current.data)
    elif current.next_node is None:
      nodes.append("[Tail: %s]" % current.data)
    else
      nodes.append("[%s]" % current.data)

    current = current.next_node
  return '-> '.join(nodes)

# running script
>>> l = LinkedList()
>>> l.add(1)
>>> l.add(2)
>>> l.add(3)
>>> l
[Head: 3]-> [2]-> [Tail: 1]  # output
>>>

JS

// class LinkedList and its methods are presumed to exist

repr () {
  
  nodes = [];
  current = this.head;

  while (current) {
    if (current === this.head) {
      nodes = `Head: ${current.data}-> `;
    } else if (current.nextNode === null) {
      nodes += `Tail: ${current.data)`;
    } else {
      nodes += `${current.data}-> `;
    }
    current = current.nextNode;
  }
  return nodes;

// running the script
let l = LinkedList();
l.add(1);
l.add(2);
l.add(3);

let result = l.repr();
console.log(result);  // Head: 3-> 2-> Tail: 1

Again, the two fragments will only run in a full implementation of the Linked List algorithm, but they do work.

Attempts I have made: I tried to use JS toString(), append() and appendChild(), but they were too difficult for me to understand how best to use them, particularly as the last two modify the DOM. I’m sure there is a better way of implementing a JS equivalent of the Python repr(); I would like to know how it might be done.

Thank you.

How do you make a function in JavaScript that displays 10 elements at a time with a button?

I am displaying data from a JSON file to a website using HTML. I want it to display the first 10 actors in the list and the movie they are in. Then I want the user to be able to press a button and be able to display the next 10, and another button to go back 10. I have been able to display the first 10 onload, I have an index on line 17 that counts how many rows I have added to “newContent” and once it reaches 10 it breaks the loop on line 36. But when I press the button on the page the index no longer works. It just goes past 10 without breaking till the loop goes through the entire JSON file.

var actors = [];


const xhr = new XMLHttpRequest(); //Gets the http request

xhr.onload = function () {
    if (xhr.status == 200) {
        var responseObject = JSON.parse(xhr.responseText);
        var newContent = '';

        var parameter = 0;
        var counter = 0;
    
    function table(parameter) {
        
        var index = 0;

        for (var i = parameter; i < responseObject.movies.length; i++) {
            for(var j=0; j < responseObject.movies[i].cast.length; j++){
                //Checking for duplicates
                if((actors.indexOf(responseObject.movies[i].cast[j]) == -1)) {
                    var letter = responseObject.movies[i].cast[j].charAt(0);
                        if((/[a-zA-Z]/).test(letter)) {
                            newContent += '<tr class="event">';
                            newContent += '<td>' + responseObject.movies[i].cast[j] + '</td>';
                            newContent += '<td>' + responseObject.movies[i].title + '</td>';
                            newContent += '<td>' + index + '</td>';
                            newContent += '</tr>';
                            index++;
                        }
                    }
                }
                counter++;

                if (index == 10) {   
                    break;
                }
            }
            return newContent;
        }
        document.getElementById('castNames').innerHTML = table(0);

        var showMoreBtn = document.getElementById('showMoreBtn');
        showMoreBtn.addEventListener('click', showMore, false);

        
        function showMore() {
            parameter = counter;
            return document.getElementById('castNames').innerHTML = table(parameter);
        }
        
    }
    

}


xhr.open('GET', "static/data/movies.json", true);
xhr.send();
table {
    width: 100%;
}

tr {
    border-bottom: 1px solid black;
}

th {
    color: black;
}

td {
    padding-top: 5px;
    color: black;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  
    <link rel="stylesheet" href="static/css/style.css">

  </head>
  <body>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="container">
        <img src = "static/images/movieLogo.png" alt = "reel of film" width = "50px" height = auto style = "margin-right: 25px;">
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
          <li><a href="{{ url_for('index') }}" class="nav-link px-2 link-secondary">Home</a></li>
          <li><a href="{{ url_for('movies') }}" class="nav-link px-2 link-dark">Movies</a></li>
          <li><a href="{{ url_for('actors') }}" class="nav-link px-2 link-dark">Actors</a></li>
          </ul>
        </div>
      </div>
    </nav>
    
<div id = "buttonClass">
    <button id="showMoreBtn" class = "button" type="button">More</button>
    <!--<button id="viewLessBtn" class = "button" type="button">More</button>-->
</div>
    <table>
        <thead>
            <tr>
                <th class = "tableHeader">Name</td>
                <th class = "tableHeader">Movie</td>
            </tr>
        </thead>

        <tbody id="castNames">

        </tbody>
    </table> 
    
    <!--<p id="castNames"></p>-->

    <script src="{{ url_for('static', filename='actorDisplay.js') }}"></script>
    
        <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->
  </body>
</html>

TLDR index in my JavaScript in the function table() is working when I load the page but not when I call the function with the button to see the next 10.

How does a re-render affect useRef values

At the top of my component I define a variable with useRef like below.

const data = {
    item1 : useRef (null),
}
console.log (data['item1'].current?.srcObject)

Now as the logic proceeds through the component the value for item1 is set up. The ref is attached to a video element. And at certain points the component re-renders.
The console.log prints the value of the srcObject upon the first re-render and the second. But on the third that value is lost. The srcObject is not explicitly changed in between the re-renders.

I don’t fully understand refs but I’d like to know how these values are retained or destroyed. Of course I get that they maybe case specific but I’d still like to get the general idea.

Parent SPFx React hooks web part open and close children’s windows. the child close hangs the parent

I have 2 applications that need to work together.
the parent has a list of jobs and the user may open them in the second (child) application as many jobs as he wants.
The code to open a child is:

 window.open(finalUrl, 'W' + event.data.ProjJob, "alwaysRaised=yes,titlebar=no,left=0,top=0,width=800,height=800");
    if (!inboxPopUpJobs.some(j => j.job === event.data.ProjJob)) {
      setInboxPopUpJobs(PopUpJobs => [...PopUpJobs, event.data.ProjJob]);
    }

When the child windows needs to refresh the parent and close, it sends a message using the ‘broadcast-channel’ library

The message is received OK by the parent with the job number so the window is intercepted by using:

 const w = window.open("", 'W' + job);

then to close it I use:

await w.close();

but now the parent window hangs, there is nothing showing in the console as error and there is no way to even refresh the browser (EDGE and Chrome)
I tried: w.opener.focus(); and window.focus(); but it is still hanging.

Does any one have a suggestion how to prevent the parent from hanging?
Thank you