Duplicate identifier ‘LibraryManagedAttributes’ after Storybook gets installed

When I execute

npx storybook@latest init

to set up Storybook (as result it modifies package.json)
then I’m unable to npm run the project because of:

Error: node_modules/@types/react-dom/node_modules/@types/react/index.d.ts:3139:14 - error TS2300: Duplicate identifier 'LibraryManagedAttributes'.

3139         type LibraryManagedAttributes<C, P> = C extends
                  ~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@types/react/ts5.0/index.d.ts:3308:14
    3308         type LibraryManagedAttributes<C, P> = C extends
                      ~~~~~~~~~~~~~~~~~~~~~~~~
    'LibraryManagedAttributes' was also declared here.

enter image description here

Tried several ways with no luck.
The new lines in package.json after executing npx storybook@latest init
are some new devDependencies:

"devDependencies": {
    "@storybook/addon-essentials": "^7.6.3",
    "@storybook/addon-interactions": "^7.6.3",
    "@storybook/addon-links": "^7.6.3",
    "@storybook/angular": "^7.6.3",
    "@storybook/blocks": "^7.6.3",
    "@storybook/test": "^7.6.3",

    "react": "^18.2.0",
    "react-dom": "^18.2.0",

    "storybook": "^7.6.3",
}

Is this a Storybook issue or Typescript and how to resolve it?

I tried to add

"overrides": {
  "react": "^18.2.0"
}

as suggested after removing all node_modules – no luck.
P.S. No Yarn.

Any suggestions how to fix this issue?

How to add custom indicator using trading-vue-js?

Trading-vue-js library doesn’t support Bollinger bands %B indicator, how to create a custom indicator to display it? Currently I think maybe I can use RSI indicator, but do the calculation by myself, change the name to “BB %B”, and change 70 to 1(overbought), 30 to 0(oversold). But I am a newbie, I don’t know how to do it, if anyone knows how to do it, I will be grateful.

Maybe I need to change something in the settings, but I don’t know what to do

offchart: [
    {
        name: "RSI",
        type: "RSI",
        data: [],
        settings: {
            // Any settings for the RSI indicator
        },
    },
    {
        name: "BB %B",
        type: "RSI",
        data: [],
        settings: {
            // Any settings for the RSI indicator
        },
    },
]

Thanks in advance!

Where are standard *.prototype methods implemented in Javascript

I’m going over the documentation of V8 engine, and I try to understand where job of a JavaScript runtime ends, and where job of JavaScript engine starts.

According to the docs in v8 engine:

V8 does however provide all the data types, operators, objects and functions specified in the ECMA standard.

From this I understand that all methods and properties related to, for example String.prototype.* would be implemented on v8 engine. I have spend hours searching v8 source code but this does not seem to be true. More specifically I was looking for the implementation on String.prototype.toUpperCase. Closest thing I’ve found is the cstring implementation.

On the other hand, having all these methods implemented in host (e.g runtime) contradicts what documentation MDN provides, as there for example the String.prototype.toUpperCase is implemented in different versions of browsers. For example I would expect that Edge, Chrome (both using V8) would have String.prototype.toUpperCase implemented in the same version.

So, I would appreciate it if can someone please shade some light on these for me?

Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading ‘getState’) with Next.js

I have a code using nextjs, I can’t solve that error, I’m using Redux Toolkit and I think it’s correct.

erorr is :

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'getState')

Call Stack
eval
node_modulesreact-reduxdistreact-redux.mjs (1045:0)
mountMemo
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (12440:0)
Object.useMemo
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (13138:0)
Object.useMemo
node_modulesnextdistcompiledreactcjsreact.development.js (1771:0)
Provider
node_modulesreact-reduxdistreact-redux.mjs (1045:0)
renderWithHooks
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (11009:0)
mountIndeterminateComponent
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (16761:0)
beginWork$1
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (18345:0)
beginWork
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (26741:0)
performUnitOfWork
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25587:0)
workLoopSync
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25303:0)
renderRootSync
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (25258:0)
recoverFromConcurrentError
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (24475:0)
performConcurrentWorkOnRoot
node_modulesnextdistcompiledreact-domcjsreact-dom.development.js (24420:0)
workLoop
node_modulesnextdistcompiledschedulercjsscheduler.development.js (261:0)
flushWork
node_modulesnextdistcompiledschedulercjsscheduler.development.js (230:0)
MessagePort.performWorkUntilDeadline
node_modulesnextdistcompiledschedulercjsscheduler.development.js (534:0)

code :

that the store.js file

'use client';
import { configureStore } from "@reduxjs/toolkit";
import books from './Features/bookSlice'
export const store = configureStore({
  reducer: {
    books,
  },
})

that the provider.jsx file

'use client';
import { Provider } from "react-redux";
import store from './store'
export function Providers({childern}) {
return (
  <Provider store={store}>
    {childern}
  </Provider>
  )
}

that the bookSlice.js file

'use client';
import { createSlice , createAsyncThunk } from "@reduxjs/toolkit";
 export const getBooks = createAsyncThunk('book/getBooks' , async (_,thunkAPI)=>{
  try {
    const res = await fetch('http://localhost:3005/books');
    const data = await res.json();
    return data;
  } catch (error){
    console.log(error);
  }
})
const bookSlice = createSlice({
  name: 'book',
  initialState: { books:null},
  extraReducers: (builder)=> {
    builder.addCase(getBooks.pending, (state , action)=>{
      console.log(action);
    }),
    builder.addCase(getBooks.fulfilled, (state , action)=>{
      console.log(action);
    }),
    builder.addCase(getBooks.rejected, (state , action)=>{
      console.log(action);
    })
  },
});
export default bookSlice.reducer;

that the layout.js file

import { Inter } from 'next/font/google'
import './globals.css'
import Navbar from './components/navbar/navbar'
import Footer from './components/footer/footer'
import { Providers } from './redux/provider'
const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
      <Navbar/>
      <Providers>{children}</Providers>
      
      <Footer/>
      </body>
    </html>
  )
}

How to fix this error i’m a begginer
I am sure the files are arranged correctly in my project

React component react-xarrows

I am using react-xarrows react component and it works good but it shows aero only if it pre defined is it possiable to create that areo dynamically as user wants
code is…

import React from 'react';
import Xarrow, {useXarrow, Xwrapper} from 'react-xarrows';
import Draggable from 'react-draggable';

const boxStyle = {border: 'grey solid 2px', borderRadius: '10px', padding: '5px'};

const DraggableBox = ({id}) => {
    const updateXarrow = useXarrow();
    return (
        <Draggable onDrag={updateXarrow} onStop={updateXarrow}>
            <div id={id} style={boxStyle}>
                {id}
            </div>
        </Draggable>
    );
};

export function V2Example() {
    return (
        <div style={{display: 'flex', justifyContent: 'space-evenly', width: '100%'}}>
            <Xwrapper>
                <DraggableBox id={'elem1'}/>
                <DraggableBox id={'elem2'}/>
                <Xarrow start={'elem1'} end="elem2"/>
            </Xwrapper>
        </div>
    );
}

Is there a way to return to initial scale when fingers released after zooming (pinchEnd) for the whole page

i was trying to update meta viewport tag on fly with touchstart/touchend events, but it doesn’t work properly on Android and not working at all on Iphones.

const handleTouchStart = () => { 
const viewportMeta = document.querySelector('meta[name="viewport"]') as HTMLMetaElement | null;
    if (viewportMeta) {
      viewportMeta.content = 'width=device-width, user-scalable=yes';
    }
  };
  const handleTouchEnd = () => {
    const viewportMeta = document.querySelector('meta[name="viewport"]') as HTMLMetaElement | null;
    if (viewportMeta) {
      viewportMeta.content = `width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0`;
    }
  };

    document.addEventListener('touchstart', handleTouchStart);
    document.addEventListener('touchend', handleTouchEnd);

3rd party libraries seem to have done the trick (react-quick-pinch-zoom/react-zoom-pan-pinch), but somehow form events have been blocked (like focus, blur) for all the forms i’ve got. (i have several pages, with different content type and length)

    const onUpdate = useCallback(({ x, y, scale }: {x: number, y: number, scale: number}) => {
      const { current } = refLayout;
      if (current) {
        const value = make2dTransformValue({ x, y, scale });
        current.style.setProperty('transform', value);
      }
    }, []);
...
    <QuickPinchZoom
        onUpdate={onUpdate}
        centerContained
        draggableUnZoomed={false}
        tapZoomFactor={0}
        zoomOutFactor={1000}
      >
       <div ref={refLayout}>
        {content}
       </div>
      </QuickPinchZoom>

trying to find what was blocking form events was no use. may be i’m doing something wrong? is there any ideas?

modify container of event: add HTML after .fc-event-title?

Would like to modify (not: replace) the information displayed in the fullcalendar timegrid week view. So, show time + title, but also show e.g. the attendees and location (available as extendedProps).

In Fullcalendar v6 I can use content injection to completely replace the content.
E.g. eventContent: { html: '<b>hello</b>' }.
Time and title (and their classes) will no longer be shown.

Another answer refers to using eventDidMount.
But this adds HTML outside the existing element.
Would like it to appear after .fc-event-title. E.g.

eventDidMount: function(arg) {
  console.log(arg.el);
  arg.el.innerHTML += "<b>hello</b>";
}

Generates:

<a tabindex="0" class="fc-event fc-event-start fc-event-end fc-event-future fc-timegrid-event fc-v-event">
  <div class="fc-event-main">
    <div class="fc-event-main-frame">
      <div class="fc-event-time">10:00 - 12:00</div>
      <div class="fc-event-title-container">
        <div class="fc-event-title fc-sticky">My title</div>
        <!-- would like the HTML to appear here -->
      </div>
    </div>
  </div>
  <!-- instead of here -->
  <b>hello</b> 
</a>

Suggestions how to add extra HTML after the .fc-event-title div?

How to get ChatGPT API working with backend to frontend when getting CORS Error?

I’m trying to get a final project working with the ChatGPT API working. Just running my the ChatGPT API in Node.js works great, but I need to interact with the front end to get user input where I ask the user what mood they’re in and also ask why they feel the way they do, and relay that to the back end so that the ChatGPT API can respond. I keep getting this error:

“mood-mental-health-git-testconnectapi-savannahcode.vercel.app/:1 Access to fetch at ‘http://localhost:3000/api/completions’ from origin ‘https://mood-mental-health-git-testconnectapi-savannahcode.vercel.app’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: 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.
localhost:3000/api/completions:1
Failed to load resource: net::ERR_FAILED

This is what my code looks like:

server.js:

import express from "express"
import "dotenv/config.js"
import cors from "cors"
const cors = require("cors")
import OpenAI from "openai"

const openai = new OpenAI(process.env.OPENAI_API_KEY)

const corsOptions = {
  origin: "https://localhost:3000", // Allow all origins
  methods: ["GET", "POST"], // Allow GET and POST requests
  allowedHeaders: ["Content-Type", "Authorization"], // Allow Content-Type and Authorization headers
}

app.use(cors(corsOptions))
const app = express()
app.use(express.json())
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  )
  next()
})

app.post("/api/completions", async (req, res) => {
  const userMood = req.body.userMood
  const userMoodReason = req.body.userMoodReason

  const completion = await openai.chat.completions.create({
    messages: [
      {
        role: "system",
        content: `User is feeling ${userMood}. The reason they're feeling this way is ${userMoodReason}. They struggle with their mental health at varying times to varying degrees. Please advise the user with good advice.`,
      },
    ],
    model: "gpt-3.5-turbo",
  })

  res.json(completion.choices[0].message.content)
})

app.listen(3000, () => console.log("Server listening on port 3000"))

app.get("/", (req, res) => {
  res.send("Hello, world!")
})

index.js:

let userMood = ``
    let userMoodReason = ``
    let userMoodAdvice = ``
.....
    submitBtnHolder.addEventListener("click", function (event) {
      if (event.target.classList.contains("submitBtn2")) {
        fetch("http://localhost:3000/api/completions", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            userMood: userMood,
            userMoodReason: userMoodReason,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            console.log("Success:", data)
          })
          .catch((error) => {
            console.error("Error:", error)
          })

        userMoodReason = document.querySelector(".textarea").value
        console.log(userMoodReason)
        submitBtnHolder.innerHTML = ``
        moodBtnGroup.innerHTML = ``
        questionAsker.innerHTML = `Your Caring AI Recommendation:`
        hiddenAdvice.style.display = "block"
        hiddenAdvice.firstChild.innerText = `${userMoodAdvice}`
      }
    })`


I’ve installed CORS and tried all sorts of variations to get it work, including a serverless function, installing vercel’s CLI, and more. I’ve included importing cors. I also read over these resources: https://platform.openai.com/docs/guides/text-generation. I’m expecting the response to be console logged

How to prevent YouTube redirecting to the wrong page?

Whenever I input this YouTube URL in the browser (Chrome, Firefox; both latest versions) and hit Enter or by straight up clicking the link:

https://www.youtube.com/@SPEAKofficial/

(it should look like this)
enter image description here

I get redirected to this instead:

https://www.youtube.com/speak

(it ends up looking like this)
enter image description here

The same happens if a browser is freshly installed, with no extensions / addons / flags whatsoever.

Is there a way I could force the redirect to:
https://www.youtube.com/@SPEAKofficial/

by using JavaScript and without using YouTube API? Some ideas will suffice.

Thanks!

How can I improve the speed of this code in nodejs project

Using Node.js, I have got a task to improve the code I have it. This code takes 10 seconds to do all requests.

how can possible to do those requests in 1~2 seconds:

//Listener on "StartRound" event from {@PredictionGameSmartContract}
getSmartContract().on(EVENTS.START_ROUND_EVENT, async (epoch) => {
  console.log('START_ROUND_EVENT IS TRIGGHERED!');

  //Wait EndRoundEvent processed
  await sleep(START_ROUND_WAITING_TIME);
  //Create and print StartRoundEvent
  const startRoundEvent = await createStartRoundEvent(epoch, pendingRoundEventStack.size);
  printStartRoundEvent(startRoundEvent, pendingRoundEventStack);
  //Check if the bot should stop
  if (startRoundEvent.stopBot) {
    stopBotCommand();
  }
  //Check if the bot should skip the round
  if (!startRoundEvent.skipRound) {
    //Round registered
    pendingRoundEventStack.set(startRoundEvent.id, startRoundEvent);
    if (!isCopyTradingStrategy()) {
      //Wait some time, before closing the round in which bets can be placed, at least 10/20 seconds before closing.
      await sleep(GLOBAL_CONFIG.STRATEGY_CONFIGURATION.WAITING_TIME - START_ROUND_WAITING_TIME);
      //Execute BET strategy
      const betRoundEvent = executeBetStrategy(epoch)
      printBetRoundEvent(betRoundEvent);
      if (betRoundEvent.skipRound) {
        //Round Skipped
        pendingRoundEventStack.delete(betRoundEvent.id);
      } else {
        //Update Round Event
        pendingRoundEventStack.set(betRoundEvent.id, betRoundEvent);
      }
    }
  }

                
});

I am not sure where to begin to actually be able to come down to 3 seconds. How can it be possible to improve the speed of this code?

Putting values of JSON object in an array and displaying it in a table Vue.js

I have some problems with putting the values of a JSON object into a list and displaying them in a table using Vue.js.

Here you are the code I use for getting the document and for displaying it on the console:

await fetch("/api/budget").then(response => response.json())
      .then(response => {
          console.log(response);
      });

I declared a list variable in the data() method provided by Vue in order to store the values:

const app = Vue.createApp({
  data() {
    return {
      //some other variables
      expenses: []
    };
  },
  //some other stuff
});

Here you are the response document:

[
    {
        "_id": "6571eb70320499f416931fd8",
        "id": 2,
        "date": "2021-09-06T00:00:00.000Z",
        "description": "boringday",
        "category": "transport",
        "buyer": "giacomo",
        "cost": 49,
        "users": [
            {
                "username": "paolo",
                "amount": 16.333333333333332
            },
            {
                "username": "giacomo",
                "amount": 16.333333333333332
            },
            {
                "username": "giacomo",
                "amount": 16.333333333333332
            }
        ]
    },
    {
        "_id": "6571eb70320499f416931fe8",
        "id": 18,
        "date": "2019-04-10T00:00:00.000Z",
        "description": "badday",
        "category": "school",
        "buyer": "giacomo",
        "cost": 329,
        "users": [
            {
                "username": "luca",
                "amount": 109.66666666666667
            },
            {
                "username": "luca",
                "amount": 109.66666666666667
            },
            {
                "username": "giacomo",
                "amount": 109.66666666666667
            }
        ]
    },
    {
        "_id": "6571eb70320499f416931feb",
        "id": 21,
        "date": "2021-11-14T00:00:00.000Z",
        "description": "boringexperience",
        "category": "school",
        "buyer": "giacomo",
        "cost": 299,
        "users": [
            {
                "username": "giorgia",
                "amount": 99.66666666666667
            },
            {
                "username": "giacomo",
                "amount": 99.66666666666667
            },
            {
                "username": "giacomo",
                "amount": 99.66666666666667
            }
        ]
    },
    {
        "_id": "6571eb70320499f416931fff",
        "id": 41,
        "date": "2020-04-09T00:00:00.000Z",
        "description": "badtool",
        "category": "sport",
        "buyer": "giacomo",
        "cost": 349,
        "users": [
            {
                "username": "franco",
                "amount": 116.33333333333333
            },
            {
                "username": "franco",
                "amount": 116.33333333333333
            },
            {
                "username": "giacomo",
                "amount": 116.33333333333333
            }
        ]
    }
]

As a final step I want to get each item in the list in a separate row of a HTML table.

How can I do it?

Thank you in advance for your patience.

What is difference between keyboard navigation in mac with Enable Full Keyboard Access

I am trying to develop a custom UI which is keyboard accessible but noticed there difference in Tab key navigation

In the following jsfiddle example:

let div1 = document.getElementById('1');
let div2 = document.getElementById('2');
let div3= document.getElementById('3');
let div4= document.getElementById('4');
let div5= document.getElementById('5');

div5.addEventListener('keydown', (evt)  => {
    console.log("keydown callback");
    evt.preventDefault();
    div1.focus();
});
<div tabindex="0" id="1">Hello 1</div>
<div tabindex="0" id="2">Hello 2</div>
<div tabindex="0" id="3">Hello 3</div>
<div tabindex="0" id="4">Hello 4</div>
<div tabindex="0" id="5">Hello 5</div>

https://jsfiddle.net/zp65h7j3
I am trying to move the focus back to div 1 when there is keydown on the div 5 and logging the event.

This is working as expected in mac.
But when enable full keyboard access the navigation is messed up. The keydown listener is also not executed.

Is this issue with mac when Full Keyboard Access is enabled

Invalid character in charter class error in regex [duplicate]

I am having regex pattern: (?!.+[-]$)[A-Za-z][A-Za-zd-]{0,45}[A-Za-zd]?

I get error when enter input box value which matches with above regex patter in javascript file.

Error

   Pattern attribute value (?!.+[-_]$)[A-Za-z][A-Za-z\d_-]{0,45}[A-Za-z\d]? is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: (?!.+[-_]$)[A-Za-z][A-Za-z\d_-]{0,45}[A-Za-z\d]?: Invalid character in character class

How to handle Thrown error in Promise.all

I have a piece of code in which multiple promises are being handled using Promise.all, but one of the promise isn’t resolving or rejecting but throwing error. Now my question is how to handle this error inside promise.all.

Please note, promises are coming from 3rd party module (node_modules) so i cannot change the code inside the promises, but can only handle the error.

a implementation of above question is

try {
  const a = await Promise.all([
    Promise.resolve(1),
    func1()
    // Promise.reject(4),
  ]);

  console.log(a);
} catch (e) {
  console.log("caught", e); // no error caught
}

// suppose func1 is some function exported by 3rd party package
async function func1() {
  return await new Promise((rs, rj) => {
    return setTimeout(() => {
      throw new Error("error");
    }, 1000);
  });
}

Tried many ways like

func1().catch(e => e)
func2(){
  try{ func1() }catch(err){ throw err }
}