Why can’t I get text with .text method when text exists?

I’m practicing web scraping using Selenium, and I hope to get the color of this dress. When I inspect the website, I can see the text content under the ‘screen-reader-text’ class but when I try to fetch it, I always get an empty value. What’s going on? Is it because the Zara website blocks me to scrape it? My code is the following,

driver_path = 'D:/Python/Selenium/chromedriver'
option1 =  webdriver.ChromeOptions()
option1.add_experimental_option('detach',True)

driver = webdriver.Chrome(chrome_options=option1,executable_path=driver_path)
driver.get(url)

color = driver.find_element_by_xpath('//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul/li[1]/button/span/span/span').text

Since I wish to get all the possible colors, I also tried the following code, which doesn’t work as well:(

colors = driver.find_elements_by_xpath('//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul')
col = []
for i,color in enumerate(colors):
    prefix = '//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul'
    try: 
        col.append(color.find_elements_by_xpath(prefix+f'/li[{i}]'+'/button/span/span/span').text)
    except:
        pass
col

enter image description here

Why Lazy load doesn’t Perfectly?

Hello there I working on lazy load images and it works perfectly, but I face a problem when I have to add, different attributes in images extension to enhance the quality.

when I scroll down to the bottom at class has been added lazy-img, src attribute src has been implemented into the image tag and lazy load works perfectly.

where is my code which will only at the class lazy-img

this is the older jsFiddle not working
Older jsFiddle code

$(function($) {
  /**
   * @return {?}
   */
  $.fn.lazyimg = function() {
    return this.each(function() {
      /**
       * @return {undefined}
       */
      function o() {
        var threshold = $(window).height();
        if ($(window).scrollTop() + threshold > t.offset().top) {
          /** @type {!Image} */
          var a = new Image;
          /**
           * @return {undefined}
           */
          a.onload = function() {
            t.addClass("lazy-img");
          };
          a.src = s;
        }
      }
      var t = $(this);
      var a = t.attr("src");
      /** @type {number} */
      var i = Math.round(t.height());
      /** @type {string} */
      var s = "";
      s = a.match("s72-c") ? a.replace("/s72-c", i) : a;
      $(window).on("load scroll", o);
      o();
    });
  };
});

on other hand, in same condition my friend also used is jQuery code, which works perfectly without any problem.
he told me just rewrite the code reshuffle and use it for your project, but due to insufficient knowledge about jQuery I am not able to do this anyone can help me to rewrite this code again.

New jsFiddle working file
jsFiddle New

Please check this jsFiddle file it’s perfectly working for lazy load I want to arrange this code and so that I can use in my project.

I know it’s doesn’t sound good but I have to do nothing more good options available to use lazy load.
The permission has been taken from my friend that I can use this code for my project

Any kind of help or advice is highly appreciated

Get hidden input value on form POST after redirect to another page?

I’m using Visual Studio with asp.net, vb.net, and javascript in order to implement an API. I am editing sample code from Authorize.Net.

I need to pass the values of dataValue and dataDescriptor

<input type="hidden" name="dataValue" id="dataValue" />
<input type="hidden" name="dataDescriptor" id="dataDescriptor" />

to the next page after the form POSTS

    'This returns as EMPTY!!! right now
    Dim infoValue = Request.Form("dataValue")
    Dim infoDescriptor = Request.Form("dataDescriptor")

How can I pass these two hidden field values over to the next page?

FULL CODE

PaymentInfo.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PaymentInfo.aspx.vb" Inherits="AuthorizeAccept.PaymentInfo" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<!--
    This file is a standalone HTML page demonstrating usage of the Authorize.net
    Accept JavaScript library when integrated with your own payment form.

    For complete documentation for the Accept JavaScript library, see
    https://developer.authorize.net/api/reference/features/acceptjs.html
-->
<head runat="server">
    <title>Sample form</title>
</head>

<body>

<script type="text/javascript"
    src="https://jstest.authorize.net/v1/Accept.js"
    charset="utf-8">
</script>

<form id="paymentForm" runat="server"
    method="POST"
    action="PaymentProcess.aspx" >
    <input type="text" name="cardNumber" id="cardNumber" placeholder="cardNumber" value="4111111111111111"/> <br><br>
    <input type="text" name="expMonth" id="expMonth" placeholder="expMonth" value="12"/> <br><br>
    <input type="text" name="expYear" id="expYear" placeholder="expYear" value="2028"/> <br><br>
    <input type="text" name="cardCode" id="cardCode" placeholder="cardCode" value="123"/> <br><br>
    <input type="text" name="amount" id="amount" placeholder="cardCode" value="6.00"/> <br><br>
    <input type="text" name="accountNumber" id="accountNumber" placeholder="accountNumber"/> <br><br>
    <input type="text" name="routingNumber" id="routingNumber" placeholder="routingNumber"/> <br><br>
    <input type="text" name="nameOnAccount" id="nameOnAccount" placeholder="nameOnAccount"/> <br><br>
    <input type="text" name="accountType" id="accountType" placeholder="accountType"/> <br><br>
    <input type="hidden" name="dataValue" id="dataValue" />
    <input type="hidden" name="dataDescriptor" id="dataDescriptor" />
    <button type="button" onclick="sendPaymentDataToAnet()">Pay</button>
</form>

<script type="text/javascript">

function sendPaymentDataToAnet() {
    var authData = {};
    authData.clientKey = "6bpMZ759ELh6K3dAWx7MVNqyYX88zsN5R3zj7FChrwnYjTQ3bQ93TS7h6YjcE64M";
    authData.apiLoginID = "93cWyMh9Kd6G";

    var cardData = {};
        cardData.cardNumber = document.getElementById("cardNumber").value;
        cardData.month = document.getElementById("expMonth").value;
        cardData.year = document.getElementById("expYear").value;
        cardData.cardCode = document.getElementById("cardCode").value;

    // If using banking information instead of card information,
    // build a bankData object instead of a cardData object.
    //
    // var bankData = {};
    //     bankData.accountNumber = document.getElementById('accountNumber').value;
    //     bankData.routingNumber = document.getElementById('routingNumber').value;
    //     bankData.nameOnAccount = document.getElementById('nameOnAccount').value;
    //     bankData.accountType = document.getElementById('accountType').value;

    var secureData = {};
        secureData.authData = authData;
        secureData.cardData = cardData;
        // If using banking information instead of card information,
        // send the bankData object instead of the cardData object.
        //
        // secureData.bankData = bankData;

    Accept.dispatchData(secureData, responseHandler);

    function responseHandler(response) {
        if (response.messages.resultCode === "Error") {
            var i = 0;
            while (i < response.messages.message.length) {
                console.log(
                    response.messages.message[i].code + ": " +
                    response.messages.message[i].text
                );
                i = i + 1;
            }
        } else {
            paymentFormUpdate(response.opaqueData);
        }
    }
}

function paymentFormUpdate(opaqueData) {
    document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
    document.getElementById("dataValue").value = opaqueData.dataValue;

    // If using your own form to collect the sensitive data from the customer,
    // blank out the fields before submitting them to your server.
    document.getElementById("cardNumber").value = "";
    document.getElementById("expMonth").value = "";
    document.getElementById("expYear").value = "";
    document.getElementById("cardCode").value = "";
    document.getElementById("accountNumber").value = "";
    document.getElementById("routingNumber").value = "";
    document.getElementById("nameOnAccount").value = "";
    document.getElementById("accountType").value = "";

    document.getElementById("paymentForm").submit();
}
</script>

</body>
</html>

PaymentProcess.aspx

Imports System
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports AuthorizeNet.Api.Controllers
Imports AuthorizeNet.Api.Contracts.V1
Imports AuthorizeNet.Api.Controllers.Bases

Public Class PaymentProcess
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'EMPTY!!!
        Dim infoValue = Request.Form("dataValue")
        Dim infoDescriptor = Request.Form("dataDescriptor")

        Run()
    End Sub

    Private Sub Run()
        ' Public Shared Function Run(ByVal ApiLoginID As String, ByVal ApiTransactionKey As String, ByVal amount As Decimal) As ANetApiResponse
        Console.WriteLine("Create an Accept Payment Transaction Sample")
        ApiOperationBase(Of ANetApiRequest, ANetApiResponse).RunEnvironment = AuthorizeNet.Environment.SANDBOX
        ApiOperationBase(Of ANetApiRequest, ANetApiResponse).MerchantAuthentication = New merchantAuthenticationType() With {
                .name = ConfigurationManager.AppSettings("AUTHORIZE_NET_API_LOGIN"),
                .ItemElementName = ItemChoiceType.transactionKey,
                .Item = ConfigurationManager.AppSettings("AUTHORIZE_NET_TRANSACTION_KEY")
            }
        Dim opaqueData = New opaqueDataType With {
                .dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT",
                .dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9"
            }
        Dim billingAddress = New customerAddressType With {
            .firstName = "John",
            .lastName = "Doe",
            .address = "123 My St",
            .city = "OurTown",
            .zip = "98004"
        }
        Dim paymentType = New paymentType With {
            .Item = opaqueData
        }
        Dim lineItems = New lineItemType(1) {}
        lineItems(0) = New lineItemType With {
            .itemId = "1",
            .name = "t-shirt",
            .quantity = 2,
            .unitPrice = New Decimal(15.0)
        }
        lineItems(1) = New lineItemType With {
            .itemId = "2",
            .name = "snowboard",
            .quantity = 1,
            .unitPrice = New Decimal(450.0)
        }
        Dim transactionRequest = New transactionRequestType With {
            .transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
            .amount = "5.00",
            .payment = paymentType,
            .billTo = billingAddress,
            .lineItems = lineItems
        }
        Dim request = New createTransactionRequest With {
            .transactionRequest = transactionRequest
        }
        Dim controller = New createTransactionController(request)
        controller.Execute()
        Dim response = controller.GetApiResponse()

        If response IsNot Nothing Then

            If response.messages.resultCode = messageTypeEnum.Ok Then

                If response.transactionResponse.messages IsNot Nothing Then
                    Console.WriteLine("Successfully created transaction with Transaction ID: " & response.transactionResponse.transId)
                    Console.WriteLine("Response Code: " & response.transactionResponse.responseCode)
                    Console.WriteLine("Message Code: " & response.transactionResponse.messages(0).code)
                    Console.WriteLine("Description: " & response.transactionResponse.messages(0).description)
                    Console.WriteLine("Success, Auth Code : " & response.transactionResponse.authCode)
                Else
                    Console.WriteLine("Failed Transaction.")

                    If response.transactionResponse.errors IsNot Nothing Then
                        Console.WriteLine("Error Code: " & response.transactionResponse.errors(0).errorCode)
                        Console.WriteLine("Error message: " & response.transactionResponse.errors(0).errorText)
                    End If
                End If
            Else
                Console.WriteLine("Failed Transaction.")

                If response.transactionResponse IsNot Nothing AndAlso response.transactionResponse.errors IsNot Nothing Then
                    Console.WriteLine("Error Code: " & response.transactionResponse.errors(0).errorCode)
                    Console.WriteLine("Error message: " & response.transactionResponse.errors(0).errorText)
                Else
                    Console.WriteLine("Error Code: " & response.messages.message(0).code)
                    Console.WriteLine("Error message: " & response.messages.message(0).text)
                End If
            End If
        Else
            Console.WriteLine("Null Response.")
        End If
    End Sub
    '   Return response
    'End Function
End Class

How do you have document.write result to drawing the same square size but with different calculated metrics?

I am creating a picture matting calculator which you can find the code on JSFiddle here.

The output I am trying to achieve is a large picture frame (a square) that’s always the same size, and that the results of:

Width: document.write((1/2)*(hf-hp+o));
Height: document.write((1/2)*(wf-wp+o));

…are placed in the appropriate location of the width & height of the square.

For example, if I enter the following information into my calculator on JSFiddle:

Example of calculator inputs

The output should be:

Width = 1.625 or 1 5/8
Height = 2.625 or 2 5/8

Therefore, the output should look like this:

Example image of output

Here is another JSFiddle of what I’ve attempted to do. I replaced my document.write((1/2)*(hf-hp+o)); with document.write(6 + 7); in order to show how I want it displayed. I need help with how to incorporate this JSFiddle code with this JSFiddle code. I’m not sure if this is even the correct approach.

Currently, my calculator’s output look like this with the above input example: 1.6252.625. This is correct, but both answers are bunched together: 1.625 and 2.625.

React useState passed as props is not changing in child components

I have this component, it has an array of objects called recogidas, but, i’m putting it within a useState, and, i’m passing it to other components as you can see.

interface ITableProps {
    showDrawer: boolean;
}

const SinAsignarTable: FC<ITableProps> = ({ showDrawer }) => {
    const animationStart = useSelector(getSinAsignarSlide);
    const containerRef = useRef(null);

    const [recogidas, setRecogidas] = useState<any[]>(recogidasSinAsignarArray);

    return (
        <MainContent open={showDrawer} ref={containerRef}>
            {/* Title */}

            <SinAsignarTitle animationStart={animationStart} />

            <TableContainer component={Paper} sx={{ maxHeight: 624, borderRadius: '5px' }}>
                <Table stickyHeader aria-label="customized table" sx={{ minWidth: 800 }}>
                    {/* Header */}
                    <SinAsignarHead recogidas={recogidas} setRecogidas={setRecogidas} />

                    {/* Hero content */}
                    <SinAsignarContent recogidas={recogidas} />
                </Table>
            </TableContainer>
       
        </MainContent>
    );
};

export default SinAsignarTable;

The problem, is that, in SinAsignarHead component, is where i’m updating the useState, but, it only shows the updates after re-rendering the component, let me show you.

SinAsignarHead component

const SinAsignarHead: FC<{ recogidas: any[]; setRecogidas: Dispatch<SetStateAction<any[]>> }> = ({
    recogidas,
    setRecogidas,
}) => {
    const [descendent, setDescendent] = useState<boolean>(true);

    const handleDataOrganization = (): void => {
        setDescendent(!descendent);
        setRecogidas(recogidas.sort((a: any, b: any) => a.recogida - b.recogida));
        // else setRecogidas(recogidas.sort((a: any, b: any) => b.recogida - a.recogida));
    };

    return (
        <>
            {/* Table's header */}
            <TableHead>
                <TableRow>
                    <TableCell padding="checkbox" sx={{ padding: '0px 0px 0px 4px' }}>
                        <Checkbox color="primary" indeterminate={false} checked={false} />
                    </TableCell>

                    <TableCell align="left" sx={{ padding: '7.5px 16px 7.5px 16px' }}>
                        <div
                            style={{
                                width: '100%',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'space-between',
                            }}
                        >
                            Recogida
                            <IconButton onClick={handleDataOrganization} sx={{ marginLeft: '5px', padding: '6px' }}>
                                {descendent ? (
                                    <ArrowDownward sx={{ width: 22, height: 22 }} />
                                ) : (
                                    <ArrowUpward sx={{ width: 22, height: 22 }} />
                                )}
                            </IconButton>
                        </div>
                    </TableCell>

                    <TableCell sx={{ minWidth: '255px', padding: '7.5px 16px 7.5px 6.5px' }} align="left">
                        Dirección
                    </TableCell>

                    <TableCell sx={{ minWidth: '115px', padding: '7.5px 16px 7.5px 16px' }} align="left">
                        Ciudad
                    </TableCell>

                    <TableCell sx={{ minWidth: '150px', padding: '7.5px 16px 7.5px 16px' }} align="left">
                        Tipo cuenta
                    </TableCell>

                    <TableCell sx={{ minWidth: '105px', padding: '7.5px 16px 7.5px 16px' }} align="left">
                        Producto
                    </TableCell>

                    <TableCell sx={{ minWidth: '165px', padding: '7.5px 16px 7.5px 16px' }} align="left">
                        Contacto
                    </TableCell>
                </TableRow>
            </TableHead>
        </>
    );
};

export default SinAsignarHead;

When handleDataOrganization function executes, it should update recogidas’s state, but it doesn’t.

This is SinAsignarContent

const SinAsignarContent: FC<{ recogidas: any[] }> = ({ recogidas }) => {
    return (
        <TableBody>
            {recogidas.map(({ recogida, direccion, ciudad, tipoDeCuenta, producto, contacto }, index) => {
                // const sinAsignarData = {
                //     recogida,
                //     direccion,
                //     ciudad,
                //     tipoDeCuenta,
                //     producto,
                //     contacto,
                // };
                return (
                    <TableRow key={index}>
                        <TableCell padding="checkbox" sx={{ padding: '0px 0px 0px 4px' }}>
                            <Checkbox color="primary" checked={true} />
                        </TableCell>

                        <TableCell
                            sx={{
                                color: '#086BB5',
                                fontWeight: 500,
                                cursor: 'pointer',
                                padding: '5px 20px 5px 0px',
                            }}
                            align="center"
                        >
                            {recogida}
                        </TableCell>

                        <TableCell
                            sx={{
                                color: '#00000099',
                                cursor: 'pointer',
                                padding: '5px 16px 5px 6.5px',
                            }}
                            align="left"
                        >
                            {direccion}
                        </TableCell>

                        <TableCell
                            sx={{ color: '#00000099', cursor: 'pointer', padding: '5px 16px 5px 16px' }}
                            align="left"
                        >
                            {ciudad}
                        </TableCell>

                        <TableCell
                            sx={{ color: '#00000099', cursor: 'pointer', padding: '5px 16px 5px 16px' }}
                            align="left"
                        >
                            {tipoDeCuenta}
                        </TableCell>

                        <TableCell
                            sx={{ color: '#00000099', cursor: 'pointer', padding: '5px 16px 5px 16px' }}
                            align="left"
                        >
                            {producto}
                        </TableCell>

                        <TableCell
                            sx={{ color: '#00000099', cursor: 'pointer', padding: '5px 16px 5px 16px' }}
                            align="left"
                        >
                            {contacto}
                        </TableCell>
                    </TableRow>
                );
            })}
        </TableBody>
    );
};

export default SinAsignarContent;

I’ve used useState in other ocations, where, i pass data as props, and update it whit no problem, why is not working this time ? why am i being forced to re-render component ?

Override Mocha globals with Jest in directory

I have a repo where I am using cypress for E2E tests and Jest for unit/integration tests. The folder structure is similar to:

> src
    > utils
       time.ts
       time.spec.ts
> cypress

I am using jest for the tests in src and cypress is hard coded to use mocha

The current issue is – because cypress is exporting mocha as the default global for describe and expect – i have to explicitly import describe/expect from @jest/globals

Is there a config in either js, mocha or jest where i can specify only use mocha for cypress folder and jesforsrc` folder?

JSON data is not visible on Network while opening React App in mobile [duplicate]

I’m running my react app in PC using npm start

You can now view musical-world in the browser.   

  Local:            http://localhost:3000        
  On Your Network:  http://xxx.xxx.xx.xxx:3000 

I want to see this app on my mobile so, I follow this link http://xxx.xxx.xx.xxx:3000 in mobile and App is visible but my JSON server data is not visible means everything is showing or working fine except JSON data.

My JSON server data is available here http://localhost:3001/songs

So what I need to do here?

Like when i worked on php i used xampp in that case i was able to see my data in mobile even it was on mysql server.

api search bar doesn’t refresh after first search

I created a search bar with vanilla js that loads items from an API array. When I search for the first time, it loads an image, title, and price. but when you type in a second search, the list does not refresh. You also can’t click out of it.

<body>
<input type="text" id="searchBar" onkeyup="getItemList()"   class="blgSearch" name="search bar" placeholder="Type In Item"><button id="searchBtn" onclick="btnFunction" type="submit">search</button> 
<div id="itemsFilter">
   <!-- <div class="item">
       <img src="" alt="image"/> 
       <h2>Item Title</h2>
       <div>cost</div></div> -->

</div>

  <script src="/search.js"></script>

and script

  //connect to API
let path = "<path>"; 
let devKey = "<key>";
let token =  "<token>";

const api = path+ devKey + token;
const url = encodeURI(api) 
let itemsList= [];

window.addEventListener('DOMcontentLoaded', loadContent)

//displays loaded content
function loadContent(){
    getItemList();
    btnfunction();   
}

fetch(url)
    .then (res => res.json()) 
    .then(data => {console.log(data); itemsList= data})

//activate on keyup
const searchBar = document.getElementById('searchBar');
//activate onclick
// const searchBtn = document.getElementById('searchBtn');

//searchBar.addEventListener("keyup", getItemList); 
const itemsFilter = document.getElementById('itemsFilter');


//filter out items by name 
function getItemList(){
    console.log(itemsList);
    let filteredItems= itemsList.rows.filter(item=> item.name.includes(searchBar.value));

    //create the filtered items element
    filteredItems.forEach(filteredItem => {
        let itemDiv = `
        <div class="item">
        <img src="${filteredItem.picture}" class="filteredImg" alt=""/> 
        <h2 class="itemName" >${filteredItem.name}</h2>
        <div class="itemPrice" >$${filteredItem.base_cost}</div>
        </div>
        `
        itemsFilter.insertAdjacentHTML("beforeend", itemDiv);
    });
}

function searchBnt() { 

}
 

any tips?

How to remove black background from this JS coding?

I’m trying to make this particle text be on a transparent background to add onto a slideshow. Can someone assist? I cannot seem to find where it is stated within the code.

Here is the JS code. Sorry I can’t seem to get it to fit properly within the code section of the post.

class Particles { constructor(x, y, texture, size) {
this.x = x;
this.y = y;

this.sprite = new PIXI.Sprite(new PIXI.Texture.from(texture));

this.sprite.texture.frame = new PIXI.Rectangle(x, y, size, size);

this.sprite.x = x;
this.sprite.y = y;

this.speedX = 0;
this.speedY = 0;

this.radius = 100;

this.gravity = 0.1;

this.maxGravity = 0.01 + Math.random() * 0.03;

this.friction = 0.9;

this.dirX = Math.random() - 0.5;
this.dirY = Math.random() - 0.5;   }

update(mouse) {
const distanceX = mouse.x – this.sprite.x;
const distanceY = mouse.y – this.sprite.y;

const distanceSqrd = distanceX * distanceX + distanceY * distanceY;

if (distanceSqrd < this.radius * this.radius && distanceSqrd > 0) {
  const distance = Math.sqrt(distanceSqrd);

  let normalX = distanceX / distance;
  let normalY = distanceY / distance;

  this.speedX -= normalX;
  this.speedY -= normalY;

  this.gravity *= this.friction;
} else {
  this.gravity += 0.1 * (this.maxGravity - this.gravity);
}

let oDistX = this.x - this.sprite.x;
let oDistY = this.y - this.sprite.y;

this.speedX += oDistX * this.gravity;
this.speedY += oDistY * this.gravity;

this.speedX *= this.friction;
this.speedY *= this.friction;

this.sprite.x += this.speedX;
this.sprite.y += this.speedY;   } }

class ParticlesText { constructor({ text, size }) {
this.app = new PIXI.Application({ width: innerWidth, height: innerHeight });

document.querySelector("#content-canvas").append(this.app.view);

this.text = text;
this.size = size;

this.cols = 500;
this.rows = 200;

this.pSize = 2;
this.particles = [];

this.mouse = {x: 0, y: 0}

this.container = new PIXI.particles.ParticleContainer(50000);
this.app.stage.addChild(this.container);

this.onResize = this.onResize.bind(this);   }

init() {
const that = this;
opentype.load(
“https://raw.githack.com/AlainBarrios/Fonts/master/LeagueSpartan-Bold.otf”,
function(err, font) {
if (err) {
alert(“Font could not be loaded: ” + err);
} else {
const canvas = document.createElement(“canvas”);

      // Now let's display it on a canvas with id "canvas"
      const ctx = canvas.getContext("2d");

      // Construct a Path object containing the letter shapes of the given text.
      // The other parameters are x, y and fontSize.
      // Note that y is the position of the baseline.
      const path = font.getPath(that.text, 0, that.size, that.size);
      const width = font.getAdvanceWidth(that.text, that.size);

      that.cols = width;
      that.rows = that.size;

      canvas.width = width;
      canvas.height = that.size;

      path.fill = "rgba(255,255,255,1)";
      // If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize).
      path.draw(ctx);

      that.addObjects(canvas, ctx);
    }
  }
);   }

isEmpty(x, y, ctx) {
const image = ctx.getImageData(x, y, this.pSize, this.pSize);

let emptyCounter = 0;

for (let i = 0; (length = image.data.length), i < length; i += 4) {
  if (image.data[i + 3] !== 0) {
    continue;
  }
  emptyCounter++;
}

return emptyCounter === this.pSize * this.pSize;   }

addObjects(canvas, ctx) {
this.container.x = this.app.renderer.width / 2 – this.cols / 2;
this.container.y = this.app.renderer.height / 2 – this.rows / 2;

for (let i = 0; i < this.cols; i += 1) {
  for (let j = 0; j < this.rows; j += 1) {
    const x = i * this.pSize;
    const y = j * this.pSize;

    if (this.isEmpty(x, y, ctx)) continue;

    const p = new Particles(x, y, canvas, this.pSize);

    this.particles.push(p);
    this.container.addChild(p.sprite);
  }
}

this.container.interactive = true;

this.onResize();
window.addEventListener("resize", this.onResize);

this.container.on("mousemove", e => {
  this.mouse = e.data.getLocalPosition(this.container);
});

this.animate();   }

onResize() {
const { innerWidth, innerHeight } = window;
const size = [innerWidth, innerHeight];
const ratio = size[0] / size[1];

if (innerWidth / innerHeight >= ratio) {
  var w = innerHeight * ratio;
  var h = innerHeight;
} else {
  var w = innerWidth;
  var h = innerWidth / ratio;
}

//this.app.renderer.view.style.width = w + "px";
//this.app.renderer.view.style.height = h + "px";   }

animate() {
this.app.ticker.add(() => {
stats.begin();

  this.particles.forEach(p => {
    p.update(this.mouse);
  });

  stats.end();
});   } }

const particles = new ParticlesText({ text: “KILL THE ROBOTS”, size:
150 }); particles.init();

SwiperJS w/ SyntaxError: Cannot use import statement outside a module error

I can’t seem to figure out what is causing this error, so I will go into more detail below on what I have done and if anyone can spot anything off, let me know.


Here is the error that I am getting:

Uncaught SyntaxError: Cannot use import statement outside a module


Here is everything that I have done:

Here is the package.json:

{
  "scripts": {
    "imagemin": "imagemin src/images/* -p --out-dir=dist/images",
    "start": "gulp style & gulp scripts"
  },
  "devDependencies": {
    "bulma": "^0.9.3",
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "gulp-sass": "^5.1.0",
    "gulp-uglify": "^3.0.2",
    "gulp-uncomment": "^0.3.0",
    "imagemin-cli": "^7.0.0",
    "node-sass": "^7.0.1",
    "rough-notation": "^0.5.1",
    "sass": "^1.47.0",
    "swiper": "^7.4.1",
    "three": "^0.122.0",
    "vanta": "^0.5.21"
  }
}

Here is me enqueuing the node_modules swiperjs:

wp_register_script(
    'Swiper',
    get_template_directory_uri() . '/node_modules/swiper/swiper-bundle.min.js',
    null, null, true
);
wp_enqueue_script('Swiper');

I switched over the script to support the type="module" on SwiperJS:

enter image description here

Here is my swiper.js file that gets compacted into main.min.js:

document.addEventListener('DOMContentLoaded', function() {

    import Swiper, { Navigation, Pagination } from 'swiper';
    import 'swiper/css';
    import 'swiper/css/navigation';
    import 'swiper/css/pagination';

    Swiper.use([Navigation, Pagination]);

    new Swiper(".mySwiper", {
        direction: "vertical",
        slidesPerView: 1,
        spaceBetween: 30,
        mousewheel: true,
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
    });
});

Here is the final output which is enqueued and minified:

document.addEventListener("DOMContentLoaded",()=>{const e=Array.prototype.slice.call(document.querySelectorAll(".navbar-burger"),0);0<e.length&&e.forEach(o=>{o.addEventListener("click",()=>{var e=o.dataset.target;const t=document.getElementById(e);o.classList.toggle("is-active"),t.classList.toggle("is-active")})})}),document.addEventListener("DOMContentLoaded",function(){import e,{Navigation as t,Pagination as o}from"swiper";import"swiper/css";import"swiper/css/navigation";import"swiper/css/pagination";e.use([t,o]),new e(".mySwiper",{direction:"vertical",slidesPerView:1,spaceBetween:30,mousewheel:!0,pagination:{el:".swiper-pagination",clickable:!0}})}),document.addEventListener("DOMContentLoaded",function(){VANTA.BIRDS({el:"#main-hero",mouseControls:!0,touchControls:!0,gyroControls:!1,minHeight:200,minWidth:200,scale:1,scaleMobile:1,colorMode:"lerpGradient",color1:2829099,quantity:3,backgroundColor:16251129,birdSize:1.5})});

Does anyone know what might be happening?

How to add hard coded values into a JSON response

I am trying to use PHP to generate JSON to specifically take a desired shape.
Below is a snippet of my PHP code:

      if($con){
    $sql="select * from people";
    $result=mysqli_query($con,$sql);
    if($result){
          header("Content-Type: JSON");
        $i=0;
        while($row = mysqli_fetch_assoc($result)){
            $response[$i]['gender']=$row['gender'];
            $response[$i]['first']=$row['first'];
            
            $i++;
        }
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
}

Here is my current JSON response

  [
   {
      "gender":"male",
      "first":"Angela"
   },
   {
      "gender":"female",
      "first":"Krista"
   }
]

And here is my desired response:

{
    "inputs": [
      {

        "values": {
          "gender": "male",
          "first": "Angela"
        }
      },
      {
        "values": {
          "gender": "female",
          "first": "Krista"
        }
      }
    ]
  }

Firebase – Create subcollection only if the parent doc exists

In Firestore, when you are deleting a doc, you can specify a condition like { exists: true }, in order to avoid deleting the document if it doesn’t exist.

In a concurrent scenario, it is possible that we would only like to add a doc to a subcollection if the parent document exists.

For example, imagine the following NoSql structure:

   -comment (doc)
       /likes (subcollection created when the first like is given)
          -like1
          -like2
          ...

Is it possible to do something like

likeRef.create(data, { parent_exists: true });

??

Is the only way to handle this situation with Transactions (reading the parent doc, and throwing an error when .exists() is false)?

I am afraid of this type of situation because if the sub-collection is created at the same time as the container document is deleted, there could be orphan “entities” in the database that may even break the UI if it is not prepared for these extreme cases.

Set value and trigger action when dropdown value is changed [duplicate]

I have this React select dropdown:

const handleSyncList = () => {
    ......
};
const [exchangeId, setExchangeId] = useState('');

<select onSelect={e => setExchangeId(e.target.value)} onChange={handleSyncList}>
  <option value="">All Exchanges</option>
  {exchangesList.map(otherEntity => (
        <option value={otherEntity.exchangeId}>
          .......
        </option>
      ))
    : null}
</select>

I need to set the selected value to exchangeId and call handleSyncList.
Is it possible first to set the option value and then call handleSyncList?

React – What is the Best Way to use Multiple createContexts?

I’ve just learned about the createContext hook and I’m wondering what’s the best approach to using multiple contexts globally throughout the project.

From what I’ve seen if you want to create and use multiple contexts it looks kinda messy having multiple nested Context tags and I’m wondering if there is a cleaner looking way of doing this?

(Example of how I think a project using four contexts would look)

import React, { createContext, useState } from "react";

export const OneContext = createContext();
export const TwoContext = createContext();
export const ThreeContext = createContext();
export const FourContext = createContext();

export default function App(){
    const [one, setOne] = useState(null);
    const [two, setTwo] = useState(null);
    const [three, setThree] = useState(null);
    const [four, setFour] = useState(null);

   return(
        <>
            <OneContext.Provider value={one}>
                <TwoContext.Provider value={two}>
                    <ThreeContext.Provider value={three}>
                        <FourContext.Provider value={four}>            
                            "Insert components here"
                        <FourContext.Provider />
                    <ThreeContext.Provider />
                <TwoContext.Provider />
            <OneContext.Provider />
        </>
   )
}