Gravity Forms Validations using javascript

I am creating a registration form for an event using gravity forms, about 6 000 have to register. The form should not allow the user to register if the number of shirts are not equal to the number of participants. Gravity forms conditional logic doesn’t support this condition currently. So I need help on how I can write a javascript code to validate.

I want to display an error underneath the number of shirts field, which says” the number of participants should be equal to the number of shirts”. Also, you the user should not be allowed to register.

How can I limit the input year on @mui/x-date-pickers to a specific range?

I use @mui/x-date-pickers. Can I limit the input year, for example from 1000 to 2023? Now I can enter years like 0000 or 9999.

enter image description here

My datePicker, I tried to put mask into InputProps, but It doesn't work   

``<DatePicker
      label={label}
      value={value}
      open={isOpen}
      onChange={onChange}
      onOpen={changeIsOpen(true)}
      onClose={changeIsOpen(false)}
      className={styles.box__picker}
      slotProps={{
        popper: { className: styles.box },
        textField: {
          helperText,
          error,
        },
      }}
      minDate={MIN_DATE}
      maxDate={MAX_DATE}
   />``

AmCharts Animate Lines on a Map?

I’ve been looking to put in an animated map for my website. However, I’m struggling to create some effects that look to have been previously possible in AmCharts, or perhaps even possible but I’m not sure where to go with it.

animated map example

Compressing the effect down into a gif along with the design of the website was unfortunately not so good, but hopefully you can see the effect I’m attempting to recreate. I noted that one user had used a method for an older version of AmCharts to animate the CSS of the path, although this wouldn’t exactly accomplish my desired effects.

I just wanted to know if it was at all possible to create this effect in the newer version of AmCharts. I’ve created a codepen to give a base as to what I’ve tried. I’ve had a go at implementing the CSS trick used in prior versions:

#mapdiv path {
    stroke-linejoin: round;
    stroke-linecap: round;
    stroke-dasharray: 500%;
    stroke-dasharray: 0 /; /* fixes IE prob */
    stroke-dashoffset: 0 /; /* fixes IE prob */
    -webkit-animation: am-draw 40s;
    animation: am-draw 40s;
}
@-webkit-keyframes am-draw {
    0% {
        stroke-dashoffset: 500%;
        fill: red;
    }
    100% {
        stroke-dashoffset: 0%;
        fill: blue;
    }
}
@keyframes am-draw {
    0% {
        stroke-dashoffset: 500%;
        fill: red;
    }
    100% {
        stroke-dashoffset: 0%;
        fill: blue;
    }
}

But unfortunately to no avail. It seems to just ignore the CSS code. I did also try adding some of the functions like setting the line id, but that seemed to break the code since it appears to be old syntax. Any help is greatly appreciated.

Is it possible to use the same PostgreSQL database transaction with Knex.js and TypeORM?

Both Knex.js and TypeORM support database transactions with PostgreSQL.

  1. Is it possible to create a PostgreSQL transaction with either Knex.js or TypeORM and use the same transaction with the other db client?
  2. Do “two-phase commit transactions”, “distributed transactions” or “XA transactions” help in this regard?

Get value when click in chart `area` type using ApexChart

Hello i want ask about apexchart.
i want get specific value when i click in chart

i have apexchart like this :

    seriesku = [
                    {
                        name: 'Actual',
                        data: this.data.mystorage.map(data => {
                            return {
                                x: data.year,
                                y: data.actual
                            }
                        }),
                    },
                    {
                        name: 'Target',
                        data: this.data.mystorage.map(data => {
                            return {
                                x: data.year,
                                y: data.budget
                            }
                        }),
                    },
                ]
return {
      chart: {
                    type: 'bar',
                    events: {
dataPointSelection: function (event, chartContext, config) {
var seriesData = chartContext.w.config.series[config.seriesIndex];
var dataPoint = seriesData.data[config.dataPointIndex];
console.log(seriesData.name);
console.log(dataPoint.x);
console.log(dataPoint.y);


                        }
                    }
                },
series =seriesku
}

i want get value using dataPointSelection and it worked in chart type bar.
But what I really want is to use chart area type and using this code not worked, i dont see any error and any event when using the same code in area type.

in the chart area when I click on the actual value it automatically clicks on the target data too because they are in the same year. i think because of that dataPointSelection is not working ?
I don’t have a problem with that condition, instead i want to get both the actual and target data for that year.

Can anyone help me ?

Highlight search query function that works with special characters [duplicate]

So i am trying to create a function that takes a query and a result, and returns JSX with the result, but the query is highlighted in bold text. It should ignore special characters and capitalisation.

For example if you search for Stack it should return ‘Stäçkoverflow’. It should also ignore special characters such as spaces, dashes, &, @, %, etc.

So Stack as a query should return ‘St-ackoverflow’ or ‘St ack‘overflow.

This is what I have come up so far, it works as long as there are no special characters. But I am having trouble to figure out how to do this with special characters included.


function highlightSearchQuery(searchQuery: string, result: string): JSX.Element {
    const regex = new RegExp(`(${searchQuery})`, 'gi');
    const parts = result.split(regex);
    return (
        <>
            {parts.map((part, index) => {
                const isQueryMatch = part.toLowerCase() === searchQuery.toLowerCase();
                return <Fragment key={index}>{isQueryMatch ? <strong>{part}</strong> : part}</Fragment>;
            })}
        </>
    );
}

Axios API always returns Undefined as response to frontend

I have created an Axios instance which uses the function processResponse for processing the response. Then it sends the appropriate object to the frontend.

The problem is when I try to use the response in the frontend, it always shows that response is undefined. The response gets printed correctly in the processResponse function but it can’t be accessed from the frontend.

The processResponse function is :

const processResponse=(res) => {
    console.log(res.status);
    if (res.status===200) {
        return {isSuccess: true, data: res.data};
    }
    else {
        return {
            isFailure: true,
            status: res?.status,
            msg: res?.msg,
            code: res?.code
        };
    }
};

The Axios response interceptor is:

apiCaller.interceptors.response.use(
    function (res) {
        return processResponse(res);
    },
    function (err) {
        return Promise.reject(processError(err));
    }
);

It returns the rejected Promise properly but not the response.

Finally, the call from the frontend:

const signupUser=async () => {
        const tmp={
            username: username,
            name: name,
            password: password,
        };
        let res=await API.usersignup(tmp);
        console.log(res.response);
        if (res.isSuccess) {
            setName("");
            setUsername("");
            setPassword("");
            changeLogin;
        }
        else {
            setErr("Oops! Something went wrong :(");
        }
    };

This is where it always shows res is not defined.

Sorry for any problems, this is my first time asking a question here.

page not loading after using cy.stub for window.open in cypress, trying to open next tab in same window

I have page where I have to click on edit button, which opens edit page in new tab, as cypress does not support multiple tab testing, I found a way from internet https://glebbahmutov.com/blog/cypress-tips-and-tricks/#deal-with-windowopen using cy.stub method to prevent opening another tab,now it is loading in same tab, but page is blank, on click api is successfully hitting, url redirects to new edit url, I am stuck in this. our developers saying that they are sending some properties in their code which helps to render html body in edit page. I dont know how to pass these same properties in our cy.stub function, also we dont have target attribute in the button. I am sharing our code and that react development piece of code for window.open.

I tried using this, cy stub method to overwrite the original window open method.

cy.window().then(win => {
  cy.stub(win, 'open').callsFake((url) => {
          return win.open.wrappedMethod.call(win, url, '_self')
      }).as('open')
  })
  // cy.wait(10000)
  EditTesting.getEditButton().click({force: true}); // clicking that edit button
  cy.wait(3000)
  cy.get('@open').should('have.been.calledOnceWithExactly', 'http://10.14.46.89:8080/claim/904877316/edit')

our react development code where they are using window.open to open new tab.

NextJS PromptCard component throwing a ‘TypeError: Cannot read properties of undefined (reading ‘image’)’ error – what is the cause?

I am trying to render PromptCard component through my PrompCarList component in my NextJs App. But I am getting the error above. I logged the post to the console but it does not show the user data even I set ref to the ‘User’ in the models. Please can anyone help me to find the problem ?

this the result of console.log(post) in the PromptCard.jsx file

`{_id: '64770098152922e3f36c8414', prompt: 'Test prompt', tag: '#product', __v: 0}
prompt:"Test prompt"
tag:"#product"
__v:0
_id:"64770098152922e3f36c8414"
[[Prototype]]:Object`

I am wondering if it is working ref:’User’ code

//-----This is PromptCard.jsx file

import {useState} from 'react'
import Image from 'next/image'
import { useSession } from 'next-auth/react'
import { usePathname } from 'next/navigation'

const PromptCard = ({post,handleTagClick,handleEdit,handleDelete}) => {
  console.log(post)
  return (
    <div className='prompt_card'>
      <div className='flex justify-between items-start gap-5'>
        <div className='flex-1 flex justify-start items-center gap-3 cursor-pointer'>
          <Image src={post.creator.image} alt='user_image' width={40} height={40} className='rounded-full object-contain'/>
          <div className='flex flex-col'>
            <h3 className='font-satoshi font-semibold text-gray-900'>{post.creator.username}</h3>
            <p>{post.creator.email}</p>
          </div>
        </div>
      </div>
    </div>
  )
}

export default PromptCard;

//----------------------

this is Feed.jsx file

import {useState,useEffect} from 'react'
import PromptCard from './PromptCard'

const PromptCardList=({data,handleTagClick})=>{
  console.log(data)
  return (
    <div className='mt-16 prompt_layout'>
      {data.map((post)=>{
        return (
          <PromptCard key={post._id} post={post} handleTagClick={handleTagClick} />
        )
      })}

    </div>
  )
}

const Feed = () => {
  const [allPosts,setAllPosts]=useState([])
  const [searchText,setSearchText]=useState(''); 
  const handleSearchChange=(e)=>{}

  useEffect(()=>{
    const fetchPosts=async()=>{
      const respone= await fetch('/api/prompt')
      const data= await respone.json()
      setAllPosts(data)      
    }
    fetchPosts()
  },[])
  return (
    <section className='feed'>
      <form className='relative w-full flex-center'>
        <input
          type='text'
          placeholder='Search for a tag or a username'
          value={searchText}
          onChange={handleSearchChange}
          required
          className='search_input peer'
        />

      </form>

      <PromptCardList data={allPosts} handleTagClick={()=>{}}/>

    </section>
  )
}

export default Feed;

--------------------MODELS---------------

`import { Schema, model, models } from 'mongoose';

const PromptSchema = new Schema({
  creator: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
  prompt: {
    type: String,
    required: [true, 'Prompt is required.'],
  },
  tag: {
    type: String,
    required: [true, 'Tag is required.'],
  }
});

const Prompt = models.Prompt || model('Prompt', PromptSchema);

export default Prompt;


import {Schema,model,models} from 'mongoose'


const UserSchema= new Schema({
    email:{
        type:String,
        unique:[true,'Email already exists'],
        required:[true,'Email is required'],
    },
    username:{
        type:String,
        required:[true,'Username is required'],
        match:[/^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, "Username invalid, it should contain 8-20 alphanumeric letters and be unique!"]
    },
    image:{
        type:String,
    }
})

const User=models.User || model('User',UserSchema)
export default User;`

I am trying to replace certain characters with an empty space in javascript

I am writing a javascript function that replaces certain letters in a string. It must only replace the first instance of the letter
for example
software engineering is fun
must become
sftwr engneering is fn
my function however keeps on returning an error

disappearString = (myString, toErase) => {




let newString = myString.split();
let newErase = toErase.split();

for(let i = 0; i < newString.length; i++){
    for(let i = 0; i < newErase.length; i++){
        let blue = newString.replace(newErase[i], "")
        return blue.join()
    }
     
}

return blue
}

Question when fetching data categories from strapi

So i am trying to map some categories from strapi but cant seem to get the code to work. anyone can help i would appreciate it. i think the problem is when mapping subCat but have no idea.

import React from “react”;
import “./List.scss”;
import Card from “../Card/Card”;
import useFetch from “../../hooks/useFetch”;

const List = ({ subCats, maxPrice, sort, catId }) => {
const { data, loading, error } = useFetch(
/products?populate=*&[filters][categories][id]=${catId}${subCats.map( (item) => &[filters][sub_categories][id][$eq]=${item} )}&[filters][price][$lte]=${maxPrice}&sort=price:${sort}
);

return (

{loading
? “loading”
data?.map((item) => )}

);
};

export default List;

i tried changing the code but with no luck

Why does my JavaScript function add extra space at the beginning when taking input as a comma-separated string?

Why this function takes extra space in front while taking an input?

My html.erb file is:

<%= form.text_field :monthly_income, class: 'form-control', required: true, onkeyup: "formatLoanAmount(this)" %>

And my script file is:

function formatLoanAmount(element) {
        const formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'bdt',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0,
        });
        input_value = element.value.toString().replace(/BDT/g, '').replace(/,/g, '');
        formatted_number = formatter.format(input_value);
        formatted_number = formatted_number.toString().replace(/BDT/g, '');
        element.value = formatted_number;
    }

I’m tryig to take input as a comma sepetated string and expection an integer as output.

React; jszip not a constructor

In my project I work to export to excel my data. But i gave “jszip is not a constructor” error.
I tried npm install jsizip but it doesnt work
I try to configure webpack.config.js but this is very complextive for me.

it is my excel codes. I used here ExcelSheet I think problem is here bu i can not understand it.

import React, { useEffect, useState } from 'react'
import { Card, Form, Table } from 'react-bootstrap'
import { getData, getPosts } from '../data/apiData';
import { ScaleLoader } from 'react-spinners';

import ReactExport from 'react-data-export';

const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;

const HomeScreen = () => {

  const [posts, setPosts] = useState([]);
  const [exportData, setExportData] = useState([]);
  const [loading, setLoading] = useState(false);

  const override = `
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: red
  `;

  const DataSet = [
    {
      columns: [
        { title: "Title", style: { font: { sz: "18", bold: true } }, width: { wpx: 125 } }, // width in pixels
        { title: "Body", style: { font: { sz: "18", bold: true } }, width: { wch: 30 } }, // width in characters
      ],
      data: exportData.map((data) => [
        { value: data.title, style: { font: { sz: "14" } } },
        { value: data.body, style: { font: { sz: "14" } } },
      ])
    }
  ]

  const getAllPosts = async () => {
    const data = await getPosts();
    setPosts(data);
  }

  const postChangeHandler = async (e) => {
    setExportData([]);
    setLoading(true);
    const data = await getData(e.target.value);
    console.log(data);
    setExportData([data]);
    setLoading(false);
  }

  useEffect(() => {
    getAllPosts();
  }, [])
  return (
    <div className="container">
      <Card>
        <Card.Body>
          <Card.Title>Excel Export</Card.Title>
          <Form>
            <Form.Control as="select" onChange={(e) => postChangeHandler(e)} defaultValue="Choose....">
              {posts.map(
                (post, i) =>
                  <option key={i} value={post.id}>{post.id}</option>
              )}
            </Form.Control>
          </Form>
          {exportData.length !== 0 ? (
            <ExcelFile
              filename="Covid-19 Data"
              element={<button type="button" className="btn btn-success float-right m-3">Export Data</button>}>
              <ExcelSheet dataSet={DataSet} name="Covid-19 Country Report" />
            </ExcelFile>
          ) : null}
          <Table responsive>
            <thead>
              <tr>
                <th>id</th>
                <th>title</th>
                <th>body</th>
              </tr>
            </thead>
            <tbody>
              {exportData.length === 0 ? (
                <tr>
                  <td colSpan="3">
                    <ScaleLoader
                      css={override}
                      size={150}
                      color={"#eb4034"}
                      loading={loading}
                    />
                  </td>
                </tr>
              ) : (
                <>
                  {exportData.map((data) => (
                    <tr key={data.id}>
                      <td>{data.id}</td>
                      <td>{data.title}</td>
                      <td>{data.body}</td>
                    </tr>
                  ))}
                </>
              )}
            </tbody>
          </Table>
        </Card.Body>
      </Card>
    </div>
  )
}

export default HomeScreen

Have an a tag with a link to another website inside my data.jsx array but it says link not found when I try to visit it on my local dev

I have a data.jsx page with multiple data arrays which I then map out on my component jsx file. one of the array entries is a link in an a tag but when I try to visit the link on my localdev it presents me with an error; problem is clearer below

here is part of my code for my data.jsx file:

id: 1, /* RESILIENT FITNESS */
    img: Work1,
    modalImg: WorkModal1,
    title: 'Website Build',
    details: [
      {
        icon: <FiFileText />,
        title: 'Project : ',
        desc: 'Website',
      },
      {
        icon: <FiUser />,
        title: 'Client : ',
        desc: 'Resilient Fitness',
      },
      {
        icon: <FaCode />,
        title: 'Language : ',
        desc: 'HTML, CSS, JavaScript',
      },
      {
        icon: <FiExternalLink />,
        title: 'Preview : ',
        desc: <a href="www.resilientfitnesshk.com">Click Here</a>,
      },

the last part has a desc with a preview so viewers can visit the website by ‘clicking here’; however Im not sure if the issue is the code itself or its because Im working on my local dev (localhost:5173); this is the error when I actually try to click on ‘Click Here’ in the desc

enter image description here

I’m not sure if this is only happening as Im on a localhost; will the issue resolve itself once I deploy the website?