Symbol.iterator mysteriously changes to null or undefined upon calling

I have a JavaScript class that wraps an array. The class looks something like this.

class Store {
    constructor() {
        this._store = [];
    }
}

I am trying to define a Symbol.iterator, so a class instance can be iterated through with for example a for (... of ...) loop.

The class is designed in such a way, that the _store parameter can be null. My solution for defining Symbol.iterator function in compliance with this is as follows

class Store {
    ...

    [Symbol.iterator]() {
        return (this._store || [])[Symbol.iterator]();
    }
}

The idea behind this is, that if the _store holds an array, this code will return _store[Symbol.iterator], otherwise it will return iterator of an empty array.

If console.log-ged, the following expression appears to be a function, as expected.

console.log( (this._store || [])[Symbol.iterator] )

However, once this function is called, the following error is thrown, which points to the code which called the function.

TypeError: Cannot convert undefined or null to object

Any ideas to why this is happening?

How to update this to work with new MUI v6 Grid2?

I’m trying to update my project to the new Material UI v6 version, but I’m encountering layout issues after upgrading to the new Grid v2. The layout of the chart (and possibly other components) gets compressed and loses its full width. I tried removing the item property from the Grid, but that didn’t fix the issue.

I’m using Vite as the bundler and Material UI v6. Below is the code for my dashboard page:

import React from "react";
import Grid from "@mui/material/Grid";
import { Box, useMediaQuery, useTheme } from "@mui/material";
import PageContainer from "../../components/container/PageContainer";
import StockOverview from "./components/StockOverview";
import StockUnderSafety from "./components/StockUnderSafety";
import SalesOverview from "./components/SalesOverview";

const Dashboard = () => {
  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));

  return (
    <PageContainer title="Dashboard" description="This is Dashboard">
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "100vh",
          padding: isSmallScreen ? theme.spacing(2) : theme.spacing(8),
        }}
      >
        <Grid container spacing={2} maxWidth={"100%"}>
         
          <Grid item xs={12} lg={8}>
            <SalesOverview />
          </Grid>

          
          <Grid item xs={12} lg={4} container direction="column" spacing={2}>
            <Grid item>
              <StockOverview />
            </Grid>
            <Grid item>
              <StockUnderSafety />
            </Grid>
          </Grid>
        </Grid>
      </Box>
    </PageContainer>
  );
};
export default Dashboard;







[[enter image description here](https://i.sstatic.net/rEbr93ik.png)](https://i.sstatic.net/LML2VBdr.png)

The problem is that after updating to the new Grid v2, the chart layout shrinks, especially in width. I tried removing the item property from the Grid, but nothing changed. Here's an image showing the issue.

Environment:

Material UI v6
Vite
React
Any suggestions on how to resolve this problem are appreciated.

changing scope in npx apps

I want to make a npm package that should be run with npx instead of being installed locally, and I want to readFileSync a file from the folder in node package and writeFileSync to a file inside the end user’s computer

how would I do that

Error importing troika-three-text with importmap

I’m trying to get the troika-three-text into my Three.js script by importing it via the html, as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Three.js OrbitControls Example (r168)</title>
</head>
<body>
    <!-- Set canvas size with width and height attributes -->
    <canvas id="__canvas_id__" width="600" height="400"></canvas>
    <script type="importmap">
        {
            "imports": {
                "three": "https://unpkg.com/[email protected]/build/three.module.js",
                "OrbitControls": "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js",
                "troika-three-text": "https://unpkg.com/[email protected]/dist/troika-three-text.esm.js"
            }
        }
    </script>
    <script type="module" src="4viz3d.js"></script>
</body>
</html>

Yet, when I try to import the package into my 4viz3d.js script using import { Text } from 'troika-three-text'; I get an error and no image is shown anymore.

Any ideas on what might be going wrong?

How to center items in carousel slider?

I am currently working on a country flag slider with around 14 different country flags.

My desired animation is that there is a container/card showing only 3 countries on the card, where it slides after 2 seconds:

Country on the left moves out of the container
Country on the middle moves to the left
Country on the right goes to the middle and scales a little bit (so it pops a bit more out) while moving to it.

And a new country moves to the right side.

The issue I’m encountering is that I can’t figure out how to center the middle image into the middle of the card, since the way I’ve implemented it is that there are 14 images and when I use justify-content: center; the Philippines shows on the card in the middle which is normal but not the desired outcome.

What I have tried so far:

  • Using pixels and calculate the amount it has to move but this doesn’t make it responsive and I would like it to be responsive.
  • Justify-content: center; on the div

What currently happens: [Click]
Desired animation: [Click]

This is my first Stackoverflow post and I hope I explained everything clearly, if not please feel free to give feedback on how I can improve my post.

Code:

const slider = document.querySelector('.flag-slider');
const flags = document.querySelectorAll('.flag');
let currentIndex = 2; // Middle flag

function updateFlags() {
  flags.forEach((flag, index) => {
    flag.classList.remove('active');
    if (index === currentIndex - 1) {
      flag.classList.add('active');
    }
  });
}

function slideFlags() {
  // Slide to the left
  slider.style.transform = `translateX(-${(currentIndex - 1) * (75 / 3)}%)`;

  currentIndex++;

  if (currentIndex > flags.length) {
    console.log('reset');
    currentIndex = 2;
    slider.style.transform = `translateX(0%)`;
  }

  updateFlags();
}

// Initial flag setup
updateFlags();

// Auto-slide every 2 seconds
setInterval(slideFlags, 2000);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
}

.countries {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 300px;
  padding: 20px;
}

.slider-container {
  width: 100%;
  margin: 50px auto;
  overflow: hidden;
  position: relative;
}

.flag-slider {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.flag,
.last_flag {
  width: 33.33%;
  padding: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: transform 0.5s ease-in-out, opacity 0.5s ease-in-out;
}

.flag img {
  width: 100%;
  object-fit: contain;
}

.flag.active {
  transform: scale(1.2);
}
<html class="no-js" lang="">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <link rel="stylesheet" href="css/style.css">
  <meta name="description" content="">
  <meta property="og:title" content="">
  <meta property="og:type" content="">
  <meta property="og:url" content="">
  <meta property="og:image" content="">
  <meta property="og:image:alt" content="">
  <link rel="icon" href="/favicon.ico" sizes="any">
  <link rel="icon" href="/icon.svg" type="image/svg+xml">
  <link rel="apple-touch-icon" href="icon.png">
  <link rel="manifest" href="site.webmanifest">
  <meta name="theme-color" content="#fafafa">
</head>

<body>

  <div class="countries">
    <div class="slider-container">
      <div class="flag-slider">
        <img class="flag" src="https://picsum.photos/200" alt="Australia">
        <img class="flag" src="https://picsum.photos/200" alt="Austria">
        <img class="flag" src="https://picsum.photos/200" alt="Brazil">
        <img class="flag" src="https://picsum.photos/200" alt="Canada">
        <img class="flag" src="https://picsum.photos/200" alt="France">
        <img class="flag" src="https://picsum.photos/200" alt="Germany">
        <img class="flag" src="https://picsum.photos/200" alt="India">
        <img class="flag" src="https://picsum.photos/200" alt="Mexico">
        <img class="flag" src="https://picsum.photos/200" alt="Philippines">
        <img class="flag" src="https://picsum.photos/200" alt="South Africa">
        <img class="flag" src="https://picsum.photos/200" alt="Egypt">
        <img class="flag" src="https://picsum.photos/200" alt="UK">
        <img class="flag" src="https://picsum.photos/200" alt="USA">
        <img class="flag" src="https://picsum.photos/200" alt="Venezuela">
        <img class="flag" src="https://picsum.photos/200" alt="Australia">
        <img class="last_flag" src="https://picsum.photos/200" alt="Austria">
      </div>
    </div>
    <span>Different countries</span>
  </div>
  <script src="js/app.js"></script>
</body>

</html>

I have tried to calculate it and hard code it but it worked for a fixed width, but it didn’t work if the screen was smaller.

Calling ASMX task based method with object parameter results in Unknown web method error

I have an async ASMX web method which works as expected when passing a simple string (I followed the excellent information provided by Stephen Cleary on this question Calling Task-based methods from ASMX

If I post a json object via an XmlHttpRequest to a sync method, this works OK (the object’s underlying type is Dictionary<string,object> but if I try to pass the same js object to the async version, I get the Unknown web method error, even though the WSDL indicates that the method MyDownload exists.

What am I doing wrong/missing?

Javascript:

        let jobUrl = '@Helpers.GetUrl(Request, "SiteService.asmx/MyDownload", false)'; //Fails
        //let jobUrl = '@Helpers.GetUrl(Request, "SiteService.asmx/MyTest", false)'; // Succeeds
        let tmp = {};
        tmp.myDownloadViewModel = @Html.Raw(Json.Encode(Model));
        ajaxQuery(jobUrl, 'POST', 'json', tmp, function (result) {
        ...
        });

SiteService.asmx.cs:

using ...

namespace MyCompany.Namespace
{
    /// <summary>
    /// Summary description for SiteService1
    /// </summary>
    [WebService(Namespace = "http://mycompany.co.uk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class SiteService : System.Web.Services.WebService
    {
        [WebMethod]
        public string MyTest(object myDownloadViewModel)
        {
            var x = 1;

            return "ok";
        }

        // Async webmethod info from Stephen Cleary https://stackoverflow.com/questions/24078621/calling-task-based-methods-from-asmx
        private async Task<string> FooAsync(string patientId)
        {
            ....
        }

        [WebMethod]
        public IAsyncResult BeginMyDownload(object myDownloadViewModel, AsyncCallback cb, object state)
        {
...
        }

        [WebMethod]
        public string EndMyDownload(IAsyncResult res)
        {
            return ((Task<string>)res).GetAwaiter().GetResult();
        }
    }
}

Angular: create a separate bundle file for each library of my workspace

Description of the issue

I have an Angular (version 15.2) workspace, that has an host app, three modules and two libraries.

This structure shows what is being used by what:

host
    moduleA
        library1
    moduleB
        library1
        library2
    moduleC
        library1
        library2

The host lazy-loads the three modules in this way:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';

const routes: Routes = [
  {
    path: "a",
    loadChildren: () => import("a").then(m => m.AModule)
  },
  {
    path: "b",
    loadChildren: () => import("b").then(m => m.BModule)
  },
  {
    path: "c",
    loadChildren: () => import("c").then(m => m.CModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

Each of the three modules use library1 and/or library2, as shown in the structure at the beginning.

The lazy loading works as expected, meaning that when I navigate to “localhost:4200/a” I can see from the network that I only get moduleA.js (of course with the name generated by Angular).

Naturally I also see the file common.js that, as I was expecting, contains all the code from library1 used in moduleA, moduleB, and moduleC.

The problem is that this common.js file also contains the code from library2, that is only shared by moduleB and moduleC. This causes the browser to load code that is useless in that moment and invalidates (although not entirely) the purpose of the lazy-loading system.

Therefore I was wondering if among the angular configurations there is something to add or change in order to obtain a different bundle for each library.

Desired result

The desired result is that when navigating to “localhost:4200/a” the browser would download moduleA.js and an library1.js. Then when navigating to “localhost:4200/b”, the browser would download moduleB.js, library2.js, but not the library1 that has already been downloaded.

What I’ve already tried

I have already explored solutions like the angular options vendorChunk: false, commonChunk: false and then tried to use webpack’s SplitChunkPlugin via the angular json.

With the SplitChunkPlugin method I was able to obtain a common.js file that contained only the code of the library1, that is used by all of the lazy imported modules, but the code of library2 was repeated in moduleB and moduleC.

This is what my custom webpack config looked like:

module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        library1: {
          test: /[\/]projects[\/]library1[\/]/,
          name: 'library1',
          chunks: 'all'
        },
        library2: {
          test: /[\/]projects[\/]library2[\/]/,
          name: 'library2',
          chunks: 'all'
        }
      }
    }
  }
};

Passing a javascript method as an argument

I’ve been around javascript for a long time, but am pretty rusty with javascript Classes. For a particular project I’m working on, things are starting to get unwieldy and I’d like to start cutting up my code into separate files. I don’t want to have to import all my functions explicitly, so I’ve started wrapping them up into a Class (which makes sense for other reasons also). Some of my functions return callbacks (functions). That is:

return functionName;

Which I can use like:

var callBack = functionReturningFunction();
...
callBack();

I cannot find any information about returning and passing methods, rather than functions what is the syntax there? Ideally I’d like to pass in methods as arguments to the constructor so I can say:

const myObject = new MyClass(methodName);

So I don’t have to do:

const myObject = new MyClass();
myObject.methodName();

How can I conditionally load images in Svelte?

I am trying to create a webpage where you get a random image when you open the page. I want svelte to decide on a random image when the page loads and then load that image in the “src” tag. I have a set number of images that I will choose from.

I can do this, however, I don’t want the page to get ALL of the images and then randomly select one. I would like to just randomly select one, then load that image in order to keep requests and data to a minimum.

Here is what I have now:

<script>
    import heroOne from "$lib/hero.webp";
    import heroTwo from "$lib/heroTwo.webp";

    let heroImg;
    const rand = Math.floor(Math.random() * 2);
    switch(rand){
        case 0: heroImg = heroOne; break;
        case 1: heroImg = heroTwo; break;
    }
</script>

<img src={heroImg} alt="Some alt text">

As far as I know, this is still going to load both hero images. Is there some way to only load the image once selected?

The router.push function is not working in the login submit handler

I’m using the Next.js App Router and have implemented middleware to check for the presence of an access token. If a user tries to access any page other than the root (/) or login-related pages without a token, I’m adding the returnURL to the search params so they can be redirected back to that page after logging in. However, this approach hasn’t been working as expected. For handling the login process, I’m using react-hook-form along with tanstack-query’s useMutation.

const returnURL = useSearchParams().get('returnURL') || '/';

//submit handler
const onSubmit: SubmitHandler<FieldValues> = () => {
  postSigninMutate(
    { username: payload.username, password: payload.password },
    {
      onSuccess: async (res) => {
        const { response } = res;
        const authorizationToken = response.headers.get('authorization-token');
        const expiresAt = response.headers.get('authorization-token-expired-at');
        const refreshToken = response.headers.get('refresh-token');

        if (authorizationToken && expiresAt && refreshToken) {
          Cookies.set('authorization-token', authorizationToken, { secure: true });
          Cookies.set('expires-at', expiresAt);
          Cookies.set('refresh-token', refreshToken, { secure: true });
        }

        router.push(returnURL);
      },
      onError: (err) => alert(err)
    }
  );
};

<form onSubmit={handleSubmit(onSubmit)} className="flex-col-start m-0 w-80 gap-6 pt-10">
...

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const url = request.nextUrl.pathname;
  const accessToken = request.cookies.get('authorization-token');

  console.log(accessToken ? 'yes' : 'no');
  console.log(url);

  if (url === '/') {
    const response = NextResponse.next();
    response.headers.set('X-Skip-Icons', 'true');
    return response;
  }

  if (
    accessToken &&
    (url === '/signup' ||
      url === '/login' ||
      url === '/kakaoLogin' ||
      url === '/find-password-email' ||
      url === '/find-password-question' ||
      url === '/find-password-newpassword')
  ) {
    if (request.nextUrl.searchParams.has('returnURL')) {
      return NextResponse.redirect(new URL(request.nextUrl.searchParams.get('returnURL') || '/', request.url));
    }
    console.log('here');
    return NextResponse.redirect(new URL('/', request.url));
  }

  if (
    !accessToken &&
    url !== '/signup' &&
    url !== '/login' &&
    url !== '/kakaoLogin' &&
    url !== '/find-password-email' &&
    url !== '/find-password-question' &&
    url !== '/find-password-newpassword'
  ) {
    const redirectURL = new URL('/login', request.url);
    const returnURL = request.nextUrl.pathname + request.nextUrl.search;
    redirectURL.searchParams.set('returnURL', returnURL);

    const response = NextResponse.redirect(redirectURL);
    return response;
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|icons/favicon.ico|icon).*)']
};

I suspected that the issue was due to page caching and a mismatch between cookie updates on the client and server. After calling router.refresh(), the middleware triggered and the page updated, but the URL in the address bar didn’t change. I then added a setTimeout after router.refresh() to delay the router.push(returnURL), and while this solution worked, it made me question whether this is the right approach.

However, when I press the back button, I can still access the login page, which shouldn’t happen after a successful login.

router.refresh();
setTimeout(() => {
  router.push(returnURL);
}, 1000);

Dynamic display of suggestions in the search bar with Spring Boot [closed]

I have a spring boot project that deals with the management of books and authors, in particular in the form for entering a new book I must also add its author or several authors associated with that book.

To enter an author I use a search bar which checks based on the first letters typed in the bar which author or authors in the db have those characters entered.

So it must be possible to display suggestions when typing letters into the search bar.

I have implemented the search bar, the problem is that no hints are displayed.

What happens instead when I start typing letters is that I get an error message instead of the suggestions.

Here are my codes I wrote:

https://gist.github.com/reginelsunshine/1859953f616275652e36d394ee4698fa#file-gistfile1-txt

“You attempted to use a Firebase module that’s not installed natively on your project by calling firebase.app().” after upgrading React Native

ERROR Error: You attempted to use a Firebase module that’s not installed natively on your project by calling firebase.app().

Ensure you have installed the npm package ‘@react-native-firebase/app’, have imported it in your project, and have rebuilt your native application.

This error is located at:
in app
in RCTView (created by View)
in View (created by AppContainer)
in ChildrenWrapper (created by Root)
in _default (created by Root)
in Root (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in Integrity(RootComponent), js engine: hermesenter image description here

After upgrading React Native from 0.68.4 to 0.73.4, I reinstalled Firebase using Yarn.

I double-checked my Firebase setup in MainApplication.java to ensure the Firebase app module was correctly imported.

I also verified that my Firebase initialization code (firebase.app()) was correctly implemented, and this setup worked perfectly before the upgrade.

I expected the Firebase module to initialize and work as it did before the React Native version upgrade, with no native module errors. I was hoping that after the upgrade, Firebase would continue to integrate smoothly into my project without any issues.

Use Enter key press for focus change and check input before submit form in asp.net

I have a asp.net form content dropdownlist, textbox and button. I want to implement Enter key press to change focus and check input before submit form. I use onkeyup=”EnterPressFocusChange(this, event)” for change focus and OnClientClick=”return CheckInputData(this);” for check input data before submit. When I use button property UseSubmitBehavior=”false” then change focus task working but checking input function always return true and button onCkick function calls. And when I use button property UseSubmitBehavior=”true” then onCkick function calls when I press Enter Key press . How can I complete both task?

<script type="text/javascript">
        function CheckInputData(a) { 
            // If valid input return true
            // else return false
        }
        function EnterPressFocusChange(a, event) {
            if (event.which == 13) {
                // Change focus
            }
        }
    </script>

    <form runat="server">
        <asp:DropDownList ID="DropDownList1" runat="server" onkeyup="EnterPressFocusChange(this, event)" AutoPostBack="true"></asp:DropDownList>
        <asp:TextBox ID="tb1" Text="0" runat="server" onkeyup="EnterPressFocusChange(this, event)"></asp:TextBox><br />
        <asp:Button ID="btnFakeButton" runat="server" Text="Fake Button" OnClientClick="return CheckInputData(this);" UseSubmitBehavior="false" OnClick="btnFakeButton_Click"/>

I want to implement Enter key press to change focus and check input before submit form.

RegisterAsync error Can’t load Login page with Successful message

Can someone help remove this error.

My result.IsSuccess will be false. My register function is broken.

My gihub link is:Thibaut501/Mango (github.com)

How when fix your RegisterAsync code, and then once it’s able to register users, then it will return true.

till same error.I have used the same codes as Mr Patel but no success.

When adding breakpoint

if (result!= null && result.IsSuccess)

result.IsSuccess false

Message "Not Found"

Result null

even I add for ResponseDto:

namespace Mango.Web.Models

{

    public class ResponseDto

    {

        public object? Result { get; set; }

        public bool IsSuccess { get; set; } = true;

        public string Message { get; set; } = "";

    }

}

Still same error.Any help

For ResponseDto result = await _authService.RegisterAsync(obj);

even I put a breakpoint to understand where is the error but I cannot find it.

Its only registering when ResponseDto: is

namespace Mango.Web.Models

{

   

        public class ResponseDto

        {

        public bool IsSuccess { get; set; }

            public object Result { get; set; }

            public string Message { get; set; }

        }



    }



also when change  if (result!= null && result.IsSuccess) to (result!= null && !result.IsSuccess if  only it works.) 

I want when if (result!= null && result.IsSuccess) that it works.

Any help,

Fabrice

Login page loads and Registration Successful message appears only when

(result!= null && !result.IsSuccess)
I want when (result!= null && result.IsSuccess)

blazor after visual studio update throws some strange warnings

after update visual studio to 17.11.3
in almoust evert file that i open vs throw some worning as

Severity    Code    Description Project File    Line    Suppression State
Warning (active)    TS1109  (JS) Expression expected.   Miscellaneous   D:xxxComponentsCoreDialogConfirmComponent.razor__virtual.html__virtual.js   9   

as on screen
enter image description here

is it some .net bug ? or i should do something with it? no idea what it is this _virtual.html_virtual.js ? guess some temp file?

before update there was no such things…?

thanks and regards