ReactNative not rendering spinner and rendering other unwanted loading component

I’m trying to do loading spinner using ActivityIndicator with ReactNative. I’ve mocked rest api to see if spinner works. The problem is, despite that I am using ActivityIndicator, I see component which I have not created, while isLoading is true.

Component I see instead has text ‘Loading…’ in top left corner.

loading component

Function which mocks endpoint with loading time:

async fetchFishDetails(fishId: number): Promise<ApiResponse<any>> {
        let fish: Fish | undefined
        let user: any | undefined

        fish = this.user1.fishes.find(fish => fish.id === fishId)
        user = this.user1
        if (fish === undefined) {
            fish = this.user2.fishes.find(fish => fish.id === fishId);
            user = this.user2
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        
        return {
            status: 200,
            body: {fishDetails: fish, user: user}
        }
    }

Function that handle response from function above:

export const getFishDetails = async (fishId: number): Promise<ServiceResponse<any>> => {
    console.debug('getFishDetails(), fishId=', fishId);

    try {
        const response = await fishRestApi.fetchFishDetails(fishId);
        
        if (response.status === 200) {
            return new ServiceResponse(Type.SUCCESS, response.body);
        } else {
            console.error('Error occurred fetching fish from backend')
            return new ServiceResponse(Type.FAIL, undefined);
        }
    } catch (error) {
        console.error('Error occurred getting fish, err=', error);
        return new ServiceResponse(Type.FAIL, undefined);
    }
};

Fetching data in component

    useEffect(() => {
        setIsLoading(true)
        console.log('start loading')
        getFishDetails(fishId)
            .then(response => {
                if (response.type === Type.SUCCESS) {
                    const {fishDetails, user} = response.body;
                    setFishDetails(fishDetails);
                    setUser(user);
                    setProfilePictureUri(user.picture ? {uri: user.picture} : require('../assets/user-default.png'));
                } else {
                    console.log('Failed to get fish details');
                }
            })
            .catch(err => {
                console.error('Error fetching fish details:', err);
            })
            .finally(() => {
                setIsLoading(false);
                console.log('loading ended')
            })

    }, [fishId]);

View that is returned

return (
        <ScrollView style={styles.container}>
            {isLoading ? (<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator size="large" animating={true}/>
            </View>) : <View style={styles.content}> ....  </View>

Would be grateful for an explanation about this ‘Loading…’ component and for all other advices.

I’ve tried to search google and documentation about the component and couldn’t find anything.

Nightwatch test don’t fail when NoSuchElementError is thrown

I inherited an automation test suite in Nightwatch/Cucumber and encountered an interesting issue. When a step fails due to an element not being found or an assertion error, the scenario continues running and eventually marks as ‘passed’.

I tried adding abortOnAssertionFailure: true and abortOnElementLocateError: true to my config file, but it didn’t make any change to the test run. Ideally, the scenario should abort as soon as anything fails, and the scenario should be marked as ‘failed’. A day of research didn’t give me an answer. I’d appreciate any pointers.

Using ES2021 for Public Angular Libraries instead of Angular Package Format?

I’ve been using the Angular Package Format for publishing public Angular libraries like this one.

I’m considering switching the build to just output ES2021 modules with Typescript Types instead of using the Angular Package Format, and I’m wondering whether there are any versions of Angular 2+ that would not be compatible with this?

I was thinking of using a tsconfig.json like this:

{
  "compilerOptions": {
    "target": "es2021",
    "module": "es2020",
    "lib": ["es2021", "DOM", "DOM.Iterable"],
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitOverride": true,
    "types": ["mocha"]
  },
  "include": ["src/**/*.ts"],
  "exclude": []
}

So the "src/**/*.ts" files would be compiled into the build directory. The src/index.ts would be used to export the public API that same way public-api.ts does in the Angular Packge Format.

And within package.json the resources built would be exposed like this:

"main": "build/index.bundle.js",
"module": "build/index.js",
"type": "module",
"types": "build/index.d.ts",

Are the any Angular 2+ versions that would be incompatible with this approach?

code in script tag of html within a flask app throwing small annoying errors

Home.html file:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" type="text/css" href="{{url_for("static",filename="css/css.css")}}">
</head>
<body>
<h1>Welcome to recipe book</h1>
<p>{{length}}</p>
<script>
const amount = "{{length}}";
let list = {{images , tojson}};
const base_URL = "{{ url_for('static',filename='images') }}"; 
const altText = {0:"Breakfast",1:"Lunch",2:"Dinner",3:"Snacks"};
for(let count=0;count<amount;count++){
    let current_image = document.createElement('img');
    let Cur_URL = base_URL + "/" + list[count];
    console.log(Cur_URL);
    current_image.setAttribute("src",Cur_URL);
    current_image.setAttribute('alt',altText[count]);
    current_image.setAttribute('height','200');
    current_image.setAttribute('width','auto');
    document.body.appendChild(current_image);
}   
</script>
</body>

</html>

main.py Flask python file:

#,redirect,url_for,send_from_directory,
from flask import Flask,render_template
import os
app = Flask(__name__)
@app.route("/")
def home():
    parent  = r"C:UserskhaitDesktopWebsiteRecipe_Bookstaticimages"
    everything = os.listdir(parent)
    images = []
    for i in everything:
        if os.path.isfile(os.path.join(parent,i)):
            images.append(os.path.join(parent,i))
    length = len(images)
    return render_template("Home.html",images=images,length=length)

if __name__ == "__main__":
    app.run(debug=True)`

i was just tryna use the length variable in my html. and it throws these errors in relation to this line: “const amount = {{length}};” and this line “console.log(amount);”:

Error 1:
Property assignment expected.javascript
Error 2:
Declaration or statement expected.javascript

I am aware many similar questions have been asked on this and I asked a similar one about the length variable. But that was a numerical flask variable and this is a list flask variable. I looked through them and couldn’t find an answer to my problem. I’m also interested to know what would the proper syntax be for boolean,char and string variables. I assume dict variables would have the same logic as the list variables. Right?
Any help would be greatly appreciated.

CORS error when sending POST request to google apps script (using client side javascript)

I am trying to send data to google apps script so that it will add that data onto a google slides presentation that will be created in the users google drive. I am using the OAuth2 library.

https://github.com/googleworkspace/apps-script-oauth2

I am sending a fetch request to my web app url (execute as user, accessible to anyone with google account). However I keep on getting a CORS error:

Access to fetch at ‘https://script.google.com/macros/s/AKfycbzCdWHQn3AOxBsICRFxVqJ8DBvNoqUGX47Z1_svLZ-SRWE706WzmcSq3hWFwVzuWCjm/exec’ from origin ‘http://localhost:10003’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

**Here is my code
**

    async function sendData() {
        const jsonData = [{
                "subject": "The girl",
                "predicate": "ran home"
            },
            {
                "subject": "The cat",
                "predicate": "wore a hat"
            },
            {
                "subject": "The tree",
                "predicate": "fell down"
            }
        ];

        try {
            const response = await fetch(
                'https://script.google.com/macros/s/AKfycbxFkvMAEey-UPOWSJSqMMQBqLS0hPcUkYQRLTKAOPLuC4k-DU28sS8pVeRFhyMwzGfs/exec', {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(jsonData),
                    credentials: "include" // Ensure credentials are included for cross-origin requests
                });

            const responseText = await response.text();
            console.log("Data response:", responseText);

            // Check if the response contains an HTML redirection link
            if (responseText.includes('Authorize')) {
                // Redirect to the authentication URL
                const parser = new DOMParser();
                const doc = parser.parseFromString(responseText, "text/html");
                const redirectUrl = doc.querySelector("a").href;
                window.location.href = redirectUrl;
                return;
            }

            const data = JSON.parse(responseText);
            console.log("Success:", data);
            alert("Data sent successfully: " + JSON.stringify(data));
        } catch (error) {
            console.error("Error:", error);
            alert("Error sending data: " + error.message);
        }
    }

**Here is my apps script code:
**

function doPost(e) {
  Logger.log("doPost function ran");
  
  var service = getOAuthService();
  if (service.hasAccess()) {
    Logger.log("User has access");
    var accessToken = service.getAccessToken();
    
    try {
      Logger.log("acess Token: " + accessToken);
      
      var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
        headers: {
          Authorization: 'Bearer ' + accessToken
        }
      });
      Logger.log("Drive API Response: " + response.getContentText());
      
      var jsonData = JSON.parse(e.postData.contents);
      
      var presentation = copyAndModifyPresentation(jsonData);
      var url = presentation.getUrl();
      Logger.log("Presentation URL: " + url);
      
      return ContentService.createTextOutput(JSON.stringify({ message: 'Presentation created with URL: ' + url }))
          .setMimeType(ContentService.MimeType.JSON);
    } catch (err) {
      Logger.log("Error: " + err.message);
      return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid JSON: ' + err.message }))
          .setMimeType(ContentService.MimeType.JSON);
    }
  } else {
    Logger.log("User does not have access. Need to authorize.");
    var authorizationUrl = service.getAuthorizationUrl();
    return ContentService.createTextOutput(JSON.stringify({ status: "unauthenticated", authUrl: authorizationUrl }))
        .setMimeType(ContentService.MimeType.JSON);
  }
}

Thank you

I have tried using no-cors but the data is only posted if the user is already signed into a google account. To prompt the user to sign in, I can’t have the mode set as no-cors, because I need a response which would contain the authorization URL.

I also tried setting up a PHP proxy server but it gives me a 401 error code
POST http://localhost:10003/wp-content/themes/twr/handle-google-auth.php 401 (Unauthorized)

calcAmountOut SOLANA RAYDIUM

Hello how can i calcul amountOut of a swap on solana raydium please ?
This is the code i try :

 const poolInfo = await Liquidity.fetchInfo({
  connection: raydiumSwap.connection,
  poolKeys: poolKeys,
});
const amountOut = Liquidity.computeAmountOut({
          poolKeys,
          poolInfo,
          amountIn: '5000000',
          currencyOut: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
          slippage : '5',
        }).amountOut;
console.log(amountOut);

Virtuoso Grid reverse order

I am writing a frontend in React and have a component that uses VirtuosoGrid() to render a collection of images. As images are uploaded, new images appear at the bottom of the page. I would like to reverse this so that newer images are shown first, and older images are shown last (or, more specifically, images are shown in reverse order of their database ID — I don’t care about the last-modified date of the image, I care about it’s database ID and when it was uploaded).

I found that VirtuosoGrid() has a reversed prop that accepts a boolean, but assigning this a value of “true” does nothing. Am I missing something to make this work?

The images are passed to this component as an array, in order of database IDs; is there a way in JavaScript to quickly reverse this array, and then I can pass that to the VirtuosoGrid() component without having to alter it at all? Or, is there a way to write a map() function that iterates backwards through the array?

My original code for the VirtuosoGrid() (which started from this documentation page):

/**
* This module adapted from react-virtuoso docs
* https://virtuoso.dev/grid-responsive-columns/
*/

import React, { forwardRef, useContext, useEffect, useState } from 'react';
import { VirtuosoGrid } from 'react-virtuoso';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';

import Thumbnail from './Thumbnail';
import AppDataContext from './SupportingModules/AppDataContext';


export default function VirtuosoGridWrapper (props) {
  const theme = useTheme();
  const smallScreen = useMediaQuery(theme.breakpoints.down('sm'));
  const mediumScreen = useMediaQuery(theme.breakpoints.only('md'));
  const largeScreen = useMediaQuery(theme.breakpoints.only('lg'));
  const hugeScreen = useMediaQuery(theme.breakpoints.only('xl'));
  const [itemWidth, setItemWidth] = useState('33%');

  const handleResize = () => {
    if (smallScreen) {
      setItemWidth('33%');  // 100% / 3 columns = 33%
    } else if (mediumScreen) {
      setItemWidth('25%');  // 100% / 4 columns = 25%
    } else if (largeScreen) {
      setItemWidth('20%');  // 100% / 5 columns = 20%
    } else if (hugeScreen) {
      setItemWidth('14.28%'); // 100% / 7 columns = ~14.28%
    } else {
      setItemWidth('33%'); // If unclear, default to small size
    };
  };

  useEffect(() => {handleResize();}, [smallScreen, mediumScreen, largeScreen, hugeScreen])


  // Ensure that this stays out of the component, 
  // Otherwise the grid will remount with each render due to new component instances.
  const gridComponents = {
    List: forwardRef(({ style, children, ...props }, ref) => (
      <div
        ref={ref}
        {...props}
        style={{
          display: "flex",
          flexWrap: "wrap",
          ...style,
        }}
      >
        {children}
      </div>
    )),
    Item: ({ children, ...props }) => (
      <div
        {...props}
        style={{
          padding: "0",
          width: itemWidth,
          display: "flex",
          flex: "none",
          alignContent: "stretch",
          boxSizing: "border-box",
        }}
      >
        {children}
      </div>
    )
  }

  const ItemWrapper = ({ children, ...props }) => (
    <div
      {...props}
      style={{
        display: "flex",
        flex: 1,
        textAlign: "center",
        padding: "0.5rem 0.5rem",
        border: "0px dashed red",
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </div>
  );

  function VirtualizedImageList() {
    const {appData} = useContext(AppDataContext);
    const imageList = appData.imageData;

    return (
        <VirtuosoGrid
          style={{ height: "100vh" }}
          totalCount={imageList.length}
          components={gridComponents}
          itemContent={(index) => 
            <ItemWrapper>
              <Thumbnail src={imageList[index].source} id={imageList[index].id}/>
            </ItemWrapper>
          }
        />
    );
  };

  return <VirtualizedImageList imageList={props.imageList}/>;
};

I have tried this, to no effect:

<VirtuosoGrid
  style={{ height: "100vh" }}
  totalCount={imageList.length}
  components={gridComponents}
  reversed={true}  // "reversed" prop is not working
  itemContent={(index) => 
    <ItemWrapper>
      <Thumbnail src={imageList[index].source} id={imageList[index].id}/>
    </ItemWrapper>
  }
/>

Find case-insensitive substring in array of objects within array of objects in JavaScript

I’m not sure how to deal with nested arrays and objects in JavaScript. I need to check if any of the Titles – whether the main folder Title or the Title within Contents – include a certain case-insensitive word (information in the sample code). It can stop checking as soon as it finds the word in any Title. I need to skip over/ignore the Description.

const data = [{
    "Title": "folder title 1",
    "Id": 857412,
    "Description": { "Text": "description 1" },
    "Contents": [
        { "Title": "contents 1 title 1", "Id": 123456 },
        { "Title": "contents 1 title 2 - Information", "Id": 987654 }
    ]
},{
    "Title": "folder title 2",
    "Id": 895623,
    "Description": { "Text": "description 2" },
    "Contents": [
        { "Title": "contents 2 title 3", "Id": 784512 }
    ]
}];

const contents = data.map(item => ({Contents:item.Contents}));
const folders = data.map(item => ({Title:item.Title}));
const combinedData = contents.concat(folders);
const stringData = JSON.stringify(combinedData);
console.log(stringData.toLowerCase().includes("information"));

My code works but I’m 100% sure that there is a better way to do this and I’m not sure how much data I’ll be dealing with each time. I just cannot wrap my head around the array of objects within an array of objects and I’m still too new to JavaScript to understand many methods. The examples on websites are too simplistic with just a few numbers in an array, which doesn’t help with this data.

What is a better method to use? How can I check the Titles for both folders and contents at the same time, while also ignoring Description, without needing to concatenate and stringify in order to find the word? Thanks for any suggestions!

How to get node.js to wait until pdfkitDocument.on(‘end’) finishes completely

We have an application that uploads a PDF to S3 and returns an object with metadata about the S3 file. This works fine if we want to email the link to the document to someone. The problem comes if we want to download the file from S3 immediately thereafter, for instance, to attach the file to a message vs. a link to the file. What seems to be happening is that the metadata regarding the S3 file is returned to the calling function BEFORE the pdf.on(‘end’) code is executed which triggers the upload to S3. The relevent code snippet is here:

  pdf.on('end', async () => {
    const result = await Buffer.concat(chunks);
    await s3.putObject(
      {
        Bucket: 'corp-attch',
        Key: filePath,
        Body: result,
        ContentType: 'application/pdf',
      }).promise();
    this.logger.log(`S3 Upload Success:  ${filePath}`);
  });

  await pdf.end();
  this.logger.log(`Finished with pdf:  ${filePath}`);
  returnAttach.attachDest = filePath;
  returnAttach.attachName = filePath.split('/').pop();
  const getObjectParams = {
    Bucket: this.configService.awsCorpBucketName,
    Key: filePath, Expires: 900,
  };

  returnAttach.attachUrl = s3.getSignedUrl('getObject', getObjectParams);
  return new Promise(resolve => resolve(returnAttach));

Is there a good way to force the whole thing to wait until the s3.putObject is complete?

In this case, no matter what we try in this code, the ‘S3 Upload Success’ message is logged AFTER the ‘Finished with pdf:’ code and any attempt to access the file via the url returns a 404 when we try to do so from the calling function.

How to Loop through JSON API Data go get specfiic data points using Javascript? [duplicate]

I’m learning how to code with API data, and I’m having difficulty targeting the JSON data from a given endpoint. While the data does return results, I’m struggling to access it correctly and display the “name” and “image_url” fields on the page.

async function fetchData(){
    try {
        const term = document.getElementById("term").value.toLowerCase();
        const response = await fetch (`https://api.vendor.com/v9/lmnop/providers?context=redacted&clinical_keywords=${term}&access_token=abcdefg1234567`)
    
        if(!response.ok){
            throw new Error("It is not working");
        }
    
        const data = await response.json();

        const docs = data._result;
        const docContain = document.getElementById('docContain')

        docs.forEach(doctorData => {
            const doc = doctorData.doc;
            const name = doc.name.first_last;
            const imageUrl = doc.image_url;

            const docElement = document.createElement('div');
            docElement.innerHTML = `
            <h2>${name}</h2>
            <img src="${imageUrl}" alt="${name}">
            `;

            docContain.appendChild(docElement);
        });
        }
        catch(error){
            console.error('Here's what went wrong:', error);
        }
    }

JSON Data Example

   {
    "_metadata": {...
    },
    "_result": [
        {
            "availability": {...
            },
            "customer": "broadway-health-demo",
            "locations": [...
            ],
            "match": {...
            },
            "provider": {
                "accepting_new_patients": true,
                "access_program_status": "Direct Schedule",
                "affiliation": [],
                "age_groups_seen": [...
                ],
                "always_available_provider": false,
                "appointment_ehr_purposes": [...
                ],
                "availability_last_updated": null,
                "board_certifications": [
                    {
                        "board_name": "American Board of Allergy and Immunology",
                        "board_specialty": "BC0000025",
                        "certification_type": "board",
                        "certifying_board": "BC0000001",
                        "rank": 1,
                        "specialty_name": "Allergy and Immunology",
                        "year_certified": 2007
                    }
                ],
                "book_online_url": "https://stg-broadway-health-demo.provider-match.com/book/670015",
                "clinical_contact": null,
                "clinical_keywords": {
                    "promoted": [
                        {
                            "cui": "C3663103",
                            "name": "mast cell activation syndrome"
                        }
                    ],
                    "searchable": [
                        {
                            "cui": "C3665851",
                            "name": "allergic disorders"
                        },
                        ...
                    ]
                },
                "clinical_trials": [],
                "contacts": [
                    {
                        "contact_type": "phone",
                        "extension": null,
                        "subtype": null,
                        "value": "216-555-4321"
                    },
                    ...
                ],
                "current_status": null,
                "default_timezone": "US/Eastern",
                "degrees": [
                    {
                        "name": "MD",
                        "source": "MD",
                        "source_url": null
                    }
                ],
                "direct_book_capable": false,
                "direct_book_pmac": true,
                "direct_book_pmc": false,
                "entity_type": null,
                "external_id": "670015",
                "external_systems": [
                    {
                        "provider_id": "670015",
                        "source_system": "ksched",
                        "system_type": "ksched"
                    }
                ],
                "gender": "Male",
                "graduate_education": [],
                "grants": [],
                "gx": {
                    "max_age": null,
                    "min_age": null
                },
                "hospital_affiliations": [
                    "Broadway Memorial Hospital"
                ],
                "id": 670015,
                "image_url": "https://kyruus-app-static.kyruus.com/providermatch/broadway-health-demo/photos/200/pierce-antonio-6932912268.jpg?1520012496329",
                "insurance_accepted": [...
                ],
                "is_primary_care": false,
                "is_specialty_care": true,
                "ksched_appointment_request_email": null,
                "languages": [...
                ],
                "legal": [],
                "license": [],
                "manually_created": null,
                "media_mentions": [],
                "metadata": {...
                },
                "multi_resource_scheduling": null,
                "name": {
                    "first": "Antonio",
                    "first_last": "Antonio Pierce",
                    "full": "Antonio B Pierce",
                    "last": "Pierce",
                    "middle": "B",
                    "preferred": null
                },
                "network_affiliations": [
                    {
                        "name": "Broadway Memorial Hospital",
                        "type": "Hospital"
                    },
                    ...
                ],
                "networks": [],
                "notes": null,
                "npi": "6932912268",
                "pmc_db_only_provider": null,
                "practice_groups": [
                    {
                        "name": "Broadway Medical Group"
                    }
                ],
                "professional_statement": "...",
                "provider_is_employed": false,
                "provider_type": "Physician",
                "provider_videos": [...
                ],
                "publications": [],
                "rating": {
                    "average": 4.798396,
                    "count": 95
                },
                "ratings": {},
                "request_appointment_url": "https://www.kyruus.com/request-a-demo-of-kyruus-providermatch",
                "reviews": {...
                },
                "sched_interval_duration_days": null,
                "sched_interval_same_day_minute_delay": null,
                "sched_interval_start_days": null,
                "sort_preferences": {},
                "specialties": [
                    {
                        "name": "Endocrinology",
                        "subspecialties": [
                            {
                                "eui": "E0000032",
                                "name": "Diabetes"
                            }
                        ]
                    }
                ],
                "status_transitions": null,
                "telehealth": false,
                "telehealth_badge": null,
                "training": [
                    {
                        "city": null,
                        "country": null,
                        "degree": "MD",
                        "field_of_study": null,
                        "graduation_date": null,
                        "graduation_year": "2001",
                        "name": " Jefferson Medical College",
                        "rank": 1,
                        "state": null,
                        "street1": null,
                        "street2": null,
                        "type": "Medical School",
                        "zip": null
                    },
                    ...
                ],
                "video_url": "https://youtu.be/01cZgUhSZcw",
                "virtual_care_url": null,
                "years_in_practice": 14
            },
            "provider_id": 1430310,
            "sort": [
            ...
            ]
        },
        ...
    ]
    "facets": [],
    "interpretation": [],
    "messages": {...
    },
    "suggestions": {},
    "warnings": []
}

Here is the error I get in console:

TypeError: Cannot read properties of undefined (reading ‘name’)

Uncaught in promise error when importing js file. Using google maps API

import stadiums from "../stadiums";
const ArizonaCoordinates = [
    stadiums.BUF,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.SF,
    stadiums.GB,
    stadiums.ARI,
    stadiums.MIA,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.SEA,
    stadiums.MIN,
    stadiums.ARI,
    stadiums.ARI,
    stadiums.CAR,
    stadiums.LAR,
    stadiums.ARI
];

export default ArizonaCoordinates

Hello all, this is my file Arizona.js which contains an array of all the stadium locations of where the Arizona Cardinals of the NFL play. In the file it imports another file called stadiums.js which contains objects with keys for stadium location and values of latitude and longitude so that it can be interpreted by google maps API. When I try to import Arizona.js to my map.js which displays a map and shows polylines going from stadium to stadium, the map goes full grey and I get this error in the developer javascript console view in chrome browser.

main.js:125 Uncaught (in promise) 
InvalidValueError
    at _.Fj (main.js:125:373)
    at ada (main.js:221:180)
    at main.js:220:230

Snippet of map.js:

import stadiums from './stadiums.js';
import ArizonaCoordinates from './teams/arizona.js';
console.log(ArizonaCoordinates)
console.log(stadiums)

const cardinalsFlightPath = new google.maps.Polyline({
        path: ArizonaCoordinates,
        geodesic: false,
        strokeColor: "#b1063a",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

If anything else is needed to solve, please let me know.

Pieces not visible when using chessboard.js

After following what the documentation says on chessboardjs.com using the unpkg CDN, the chessboard appears without the pieces. I’m assuming that this is because the library scripts don’t know how to find the images, but I don’t know how to reconcile this. Here is my code.

html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Chess</title>
    <link rel="stylesheet" href="../styles/game.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet"
          href="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.css"
          integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU"
          crossorigin="anonymous">
</head>
<body>
    <div id="board1"></div>
    <div class="buttons">
        <a href="lobby.html"><button class="button">Exit</button></a>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2"
            crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.js"
            integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD"
            crossorigin="anonymous"></script>
    <script src="../scripts/chess.js"></script>
</body>
</html>

javascript file

var config = {
    pieceTheme: '/img/chesspieces/wikipedia/{piece}.png',
    position: 'start'
}
var board1 = Chessboard('board1', config);

As you can see, I tried downloading the image files locally, but even this didn’t seem to resolve the issue.

How to create a flex-box container with max of 2 columns that scrolls down upon an items overflow?

I’m trying to build a specific UI that consists of a flexbox container with flex-direction: column and flex-wrap: wrap. For each flex item that is added, the item will take 100% of the container width – and upon an overflow (first items overflow), the container will wrap the items into 2 columns – but the container will not have more then 2 columns – in the next items overflow it should scroll down (overflow-y: auto)?
Is this possible?

I tried a lot of approaches, even using display: grid in a way, but the task i more complicated then it seems.

HTML clustering problem with no “point_count” attribute created despite setting “cluster”: true

I am trying to create an html cluster map using Mapbox, but “cluster”: true is not creating a “point_count” attribute. I can confirm that the geojson is loaded correctly and individual point markers appeared when “cluster”:true was removed.

Current approach

var geoData = {
                "type": 'FeatureCollection',
                "features": [
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [-72.4050504,40.90369252]
                        },
                        "properties": {
                            "title": "title",
                            "description": "description"
                        }
                    },
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [-72.40584471,40.89771544]
                        },
                        "properties": {
                            "title": "title",
                            "description": "description"
                        }
                    }
                ]
            };
map.addSource('crash', {
                        type: 'geojson',
                        data: geoData,
                        cluster: true,
                        clusterMaxZoom: 10, // Max zoom to cluster points on
                        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
                    });

                map.addLayer({
                        id: 'clusters',
                        type: 'circle',
                        source: 'crash',
                        filter: ['has', 'point_count'],
                        paint: {
                            'circle-color': "#f1f075",
                            'circle-radius': 40
                        }
                    });
                    map.addLayer({
                        id: 'cluster-count',
                        type: 'symbol',
                        source: 'crash',
                        filter: ['has', 'point_count'],
                        layout: {
                            'text-field': '{point_count_abbreviated}',
                            'text-font': ['Arial Unicode MS Bold'],
                            'text-size': 12
                        }
                    });
                    map.addLayer({
                        id: 'unclustered-point',
                        type: 'circle',
                        source: 'crash',
                        filter: ['!', ['has', 'point_count']],
                        paint: {
                            'circle-color': '#11b4da',
                            'circle-radius': 5,
                            'circle-stroke-width': 0.8,
                            'circle-stroke-color': '#fff'
                        }
                    });

Desired approach

I was expecting hoping to recreate the styles in this mapbox example: https://docs.mapbox.com/mapbox-gl-js/example/cluster/

Mapbox example of HTML cluster map

jquery animation – shapes moving in linear motion

I want the shapes to reappear from the right as soon as they start to disappear on the left. For example, if I have square1, circle1, and star1 in a row moving from right to left, as soon as square1 begins to disappear on the left, it should immediately reappear on the right, without waiting for circle1 or star1 to disappear. I want to implement this using jquery.

function startAutoScroll() {
        const $track = $('.track');
        const $shapes = $('.shapes');
        const trackWidth = $track.width();
        const containerWidth = $('.track-container').width();
        const shapeWidth = $shapes.first().outerWidth(true); // Width including margin
    
        // Speed of scrolling based on slider value
        const scrollSpeed = 1; // Adjust as necessary for smoother scrolling
    
        // Continuous scrolling of the track
        autoScrollInterval = setInterval(function() {
            if (!isHovering) {
                let currentLeft = parseInt($track.css('left'), 10);
                let newLeft = currentLeft - scrollSpeed;
    
                // Reset track position to create a continuous effect
                if (Math.abs(newLeft) >= trackWidth) {
                    newLeft = 0;
                }
    
                $track.css('left', `${newLeft}px`);
            }
        }, 100 / autoScrollSpeed); // Interval time for smooth scrolling
    
        // Animate shapes with seamless looping
        function animateShapes() {
            const totalShapesWidth = $shapes.length * shapeWidth;
    
            // Position shapes outside the container initially
            $shapes.each(function(index) {
                $(this).css('left', containerWidth + index * shapeWidth + 'px');
            });
    
            // Animate shapes
            $({ offset: containerWidth }).animate(
                { offset: -totalShapesWidth },
                {
                    duration: 10000 / autoScrollSpeed, // Adjust duration based on speed
                    easing: 'linear',
                    step: function(now) {
                        $shapes.each(function(index) {
                            let offset = now + index * shapeWidth;
                            // Ensure the shapes wrap around seamlessly
                            if (offset <= -shapeWidth) {
                                offset += totalShapesWidth;
                            }
                            $(this).css('left', offset + 'px');
                        });
                    },
                    complete: function() {
                        // Ensure the animation loops correctly
                        animateShapes(); // Loop animation
                    }
                }
            );
        }
    
        animateShapes(); // Start shape animation
    }