Sync vs Async function execution time confusion [duplicate]

I am struggling to understand why an asynchronous function with some calculations takes such a long time to execute. I have simplified my code like so:

const syncCalc = () => {
    let v = 0;
    for (let i = 1; i < 10000000; i++) {
        //emtpy loop
        v += i
    }
    return v;
}

const asyncCalc = () =>
    new Promise(resolve => {
        let v = 0;
        for (let i = 1; i < 10000000; i++) {
            //emtpy loop
            v += i
        }
        resolve(v);
    })


console.time('syncCalc');
console.log("Result:", syncCalc());
console.timeEnd('syncCalc');

console.log('------------')

console.time('asyncCalc');
asyncCalc().then(v => console.log("Result:", v));
console.timeEnd('asyncCalc');

The result of the above code run in node is:

Result: 49999995000000
syncCalc: 27.659ms
------------
asyncCalc: 14.152ms
Result: 49999995000000

The first part (i.e. 27 ms) makes perfect sense. It takes a while for the calculation to finish in a synchronous environment.

What I don’t get is why it takes 14 ms to get past the asyncCalc function. Shouldn’t the jump from console.time('asyncCalc'); to console.timeEnd('asyncCalc'); be instant as we DO NOT wait for the asyncCalc().then(... to execute?

Why, then, does this take under a millisecond to get from time to timeEnd?

const asyncTimeout = () =>
    new Promise(resolve => {
        setTimeout(() => resolve(49999995000000), 1000)
    })

console.time('asyncCalc');
asyncTimeout().then(v => console.log("Result:", v));
console.timeEnd('asyncCalc');

// asyncCalc: 0.962ms
// Result: 49999995000000


Can someone explain this to me please?

How to synchronize two or more graphics with converFromPixel in same echarts.instance?

I have two dot graphics (scatter) and I need to move the mouse (mousemove) over one of them and pass the tooltip effect to the other. That is, when I move the mouse over series[0], the tooltip must also appear in series[1] and vice versa. I tried synchronizing the charts with chartUSe.getZr().on(...) but I couldn’t get it to work. Also, it wouldn’t be interesting to use echarts.connect to do this, as I need the charts to be in the same instance.

Code:

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

    // system
    const chartSystem = () => {

        const dfInit = () => {
            
            const groups = ['group1', 'group2', 'group3'];

            const data = [];

            for (let i = 0; i < 30; i++) {
                data.push(
                    [
                        (Math.random() * 101) | 0,
                        (Math.random() * 101) | 0,
                        groups[(Math.random() * groups.length) | 0]
                    ]
                )
            }
            return data;
        }

        return {
            "source": {
                "first": dfInit()
            }
        };

    }

    // send
    let pullDataset = [];

    const chartSend = () => {

        const { first } = chartSystem().source;

        pullDataset.push(
            {
                source: [
                    ["x1", "x2", "groups"],
                    ...first
                ]
            }
        )

    }

    chartSend();

    // frames
    const chartUse = echarts.init(document.getElementsByClassName('chart')[0]);

    function chartFrameSwitch0 () {

        const title0 = [
            {
                text: "convertFromPixel in same instance (chartUse)",
                left: 'center',
                textStyle: {
                    fontSize: 30,
                    color: "#242832"
                }
            }
        ];

        const tooltip0 = {
            trigger: "axis"
        };

        const grid0 = [
            {
                left: '5%',
                top: '12%',
                width: '40%',
                height: '35%'
            },
            {
                right: '5%',
                top: '12%',
                width: '40%',
                height: '35%'
            }
        ];

        const xAxis0 = [
            {
                type: 'value',
                gridIndex: 0
            },
            {
                type: 'value',
                gridIndex: 1
            }
        ];

        const yAxis0 = [
            {
                type: 'value',
                gridIndex: 0
            },
            {
                type: 'value',
                gridIndex: 1
            }
        ];

        const series0 = [
            {
                type: 'scatter',
                datasetIndex: 0,
                xAxisIndex: 0,
                yAxisIndex: 0,
                encode: {
                    x: 0,
                    y: 1
                }
            },
            {
                type: 'scatter',
                datasetIndex: 0,
                xAxisIndex: 1,
                yAxisIndex: 1,
                encode: {
                    x: 0,
                    y: 1
                }
            }
        ];

        const option = {
            title: title0,
            tooltip: tooltip0,
            grid: grid0,
            dataset: [pullDataset[0]],
            xAxis: xAxis0,
            yAxis: yAxis0,
            series: series0
        };

        chartUse.setOption(option);

    }

    chartFrameSwitch0();

    // Charts synchronize 
    chartUse.getZr().on('mousemove', function(params) {

        // Catch mousemove event
        let pointInGrid = [params.offsetX, params.offsetY];

        // series 0 interaction
        if (params.seriesIndex === 0) {

            let index = chartUse.convertFromPixel({ seriesIndex: 0 }, pointInGrid)[0];

            // Checks if the index is within the data range
            if (index >= 0 && index < pullDataset[0].source.length) {

                chartUse.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 1,
                    dataIndex: index
                });

            }

        } 
        
        // series 1 interaction
        else if (params.seriesIndex === 1) {

            let index = chartUse.convertFromPixel({ seriesIndex: 1 }, pointInGrid)[0];

            // Checks if the index is within the data range
            if (index >= 0 && index < pullDataset[0].source.length) {

                chartUse.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    dataIndex: index
                });

            }

        }
        
    });


});
<head>
    <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js'></script>
</head>
    
<div class='chart' style='width: 100%; height: 100vh;'></div>

SvelteKit + MySQL + Drizzle: Cannot read properties of undefined (reading ‘promise’)

I’m setting up a test project with SvelteKit, using MySQL for the DB and Drizzle as an ORM. It’s using TypeScript.

This is the db/index.ts file:

import { drizzle } from 'drizzle-orm/mysql2';
import { DB_URL } from '$env/dynamic/private';

export const db = drizzle(DB_URL);

Then I import the db file into +page.server.ts:

import { db } from '$lib/db';

and I get the below error

TypeError: Cannot read properties of undefined (reading 'promise')
    at isCallbackClient (file:///home/user/x/node_modules/drizzle-orm/mysql2/driver.js:62:24)
    at construct (file:///home/user/x/node_modules/drizzle-orm/mysql2/driver.js:36:29)
    at drizzle (file:///home/user/x/node_modules/drizzle-orm/mysql2/driver.js:82:10)
    at /home/user/x/src/lib/db/index.ts:4:19

I’m not sure what I’m missing. This is entirety of the two files. I commented out and removed everything else from the +page.server.ts file, there was nothing else in the db module (db/index.ts)

What am I missing?

Storybook – Element type is invalid: Expected a string

I have check my imports and component name but while running below code in Storybook, getting below error

Element type is invalid: Expected a string ( for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your componetn from the file it’s defined in, or you might have mixed up default and named imports.
Check the render method of ‘MDXContent’

or can you please guide me how to write same thing in typescript for storybook

Exisiting code for Storybook base on this https://storybook.js.org/docs/api/doc-blocks/doc-block-typeset

import { Meta, Story, ArgsTable, Preview } from '@storybook/blocks';
import { ThemeProvider } from '@emotion/react';
import MyTypography from '../src/Typography';
import customTheme from '../src/themes/customTheme';

<Meta 
  title="MyTypography" 
  component={MyTypography} 
  parameters={{ layout: "centered" }} 
  tags={['autodocs']} 
/>

# MyTypography

The `MyTypography` component renders typography elements with various styles. You can customize the variant and children to render different typography elements.

## Variants

### Example Usage

<Preview>
  <Story 
    name="Default Typography"
    args={{
      variant: "h1",
      children: "Hello World",
    }}
  >
    {({ args }) => (
      <ThemeProvider theme={customTheme}>
        <MyTypography variant={args.variant}>{args.children}</MyTypography>
      </ThemeProvider>
    )}
  </Story>
</Preview>

### Different Variants

<Preview>
  <Story 
    name="All Typography Variants"
    args={{
      children: "Typography Example",
    }}
  >
    {({ args }) => (
      <ThemeProvider theme={customTheme}>
        {["h1", "h2", "h3", "h4", "h5", "h6"].map((variant) => (
          <MyTypography key={variant} variant={variant}>
            {`${variant.toUpperCase()}: ${args.children}`}
          </MyTypography>
        ))}
      </ThemeProvider>
    )}
  </Story>
</Preview>

## Props

<ArgsTable of={MyTypography} />

How do I format the string to POST data through XMLHttpRequest in Laravel?

I’m trying to send my data through XMLHttpRequest but don’t know how to format the string with all the data

My JS Code:

function savePhotos() {
    var csrf = document.querySelector('meta[name="_token"]').content;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", saveRoute, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xhr.setRequestHeader("X-CSRF-TOKEN", csrf); 
    xhr.send("name='test'"); //What do I put here
}

My Controller create function:

 public function create(Request $request)
 {
     $data = $request->all();
     $model = Photo::create([
            'categoryId' => $data['categoryId'],
            'collectionId' => $data['collectionId'],
            'categoryId' => $data['categoryId'],
            'name' => $data['name'],
            'views' => $data['views'],
            'likes' => $data['likes'],
            'dateUploaded' => $data['dateUploaded'],
            'altText' => $data['altText'],
            'url' => $data['url'],
            'private' => $data['private'],
         ]);
       return redirect()->route("photoIndex");
    }

Deployed React App not loading on Laptop Browsers

I have deployed a React Web App on Azure Static Web App using the free tier with my custom domain. I am able to react the site perfectly fine from mobile devices which includes safari and google chrome phone.
However, when I try to load the site from my laptop edge browser or chrome browser it does not load. Just says this site cannot be reached. When I was developing locally, I was able to view the changes on the chrome browser fine from my laptop, but after deploying the site, it is not available from browsers.

and the site I am trying to reach is https://thephysioai.com/

For ref, here the index.html from the React App that is used for settings

<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
  name="description"
  content="Physio-AI"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo.png"/>
<!-- Open Graph Meta Tags -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta property="og:title" content="PhysioAI" />
<meta property="og:description" content="Your personalized physiotherapy companion powered by AI." />
<meta property="og:image" content="%PUBLIC_URL%/logo.png" />
<meta property="og:url" content="https://thephysioai.com" />
<meta property="og:type" content="website" />

<!--
  manifest.json provides metadata used when your web app is installed on a
  user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
  Notice the use of %PUBLIC_URL% in the tags above.
  It will be replaced with the URL of the `public` folder during the build.
  Only files inside the `public` folder can be referenced from the HTML.

  Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
  work correctly both with client-side routing and a non-root public URL.
  Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>PhysioAI</title>

Why does php built-in server works, but Apache doesn’t

As a question says, when I run command php -S localhost:8000 in terminal(after positioning in project root), and after that, I try testing out the URL http://localhost:8000/app.php, (app.php is my backend file used for route handling and processing fetch requests) and everything works fine, app.php content is shown. However, when I start Apache via Laragon,without running php built-in server, it runs on port 80, and I try testing that aswell with http://localhost/app.php, but the error I recieve is 404:Not found. This isn’t happening only to app.php, but to all backend files I want to reach.

Although I think this isn’t much code-related, since I tried mostly with direct URL submit, I will show my fetch request

    fetch('/back-end/app.php',{
                    method:'POST',
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body:JSON.stringify({
                        firstName:firstName,
                        lastName:lastName,
                        username:username,
                        email:email,
                        password:password
                    })
                })
                .then((response)=>{
                    if(response.ok){ 
                        return response.json();
                    }
                })
                .then((data)=>{
                    console.log('Response:'+data);
                })
                .catch((err)=>{
                    console.error('Error is this:'+err.message, err);
                })

My .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /back-end/app.php [QSA,L]

Why is this happening, that backend files are accessible with php built-in server running, but not with Apache?

How to store and manage user generated javascript code on website

I am currently working on a website where people can upload their pictures, put them in frames, add certian already coded effects. But, i know that there are some more invested users that would be interested in creating their own “templates” and share them with other users. I would like to give them an option to create their own method that outputs a ready “frame”, which will just return <div> element.

Is there any way that i can do this efficiently and with some security?

  • If i will execute just plain javascript code from a user, it may be a
    huge security risk.
  • If i will setup a moderation step, i will be forever busy with checking thousands of mediocre, tiny edits with a lot of delay on user side.
  • If i wont give this option, overall quality of service may suffer, because it wont harness creative potential of its community.

What should i do? Stick just to CSS and HTML so users can upload only those? Restrict certain words that appear in user defined functions? Moderate content? Or rather setup a testing environment and then be in contant with the community?

What do you propose?

Ideas for Javascript libraries and tools [closed]

I am trying to improve my coding skills and to have a better portfolio, and I thought it’d be a great idea to create a library or a tool that could also be useful to others. Unfortunately, I don’t have any ideas in mind.

Do anyone have any idea of a library that would be useful or used any tool that could be improved or fixed? I’m open to ideas. The languages that I’m trying to improve are Javascript and Typescript.

Thank you!

Show two dimensons in a wms layer with leaflet

I have a map and a WMS layer with two dimensions (time and height). I have used leaflet timedimension to show time, but I can not to display the second dimension (height) in the map. Is it possible to do it?

let timeDimension = new L.TimeDimension({
    period: "PT3H",
    timeInterval: "2024-12-22T15:00:00.000Z" + "/PT36H" 
});
    
map.timeDimension = timeDimension; 

let player        = new L.TimeDimension.Player({
    transitionTime: 1500,
}, timeDimension);

let timeDimensionControlOptions = {
    player:        player,
    timeDimension: timeDimension,
    position:      'bottomleft',
    autoPlay: false,
    loopButton: true,
    timeSteps: 1,
    playReverseButton: false,
    limitSliders: true,
};
let timeDimensionControl = new L.Control.TimeDimension(timeDimensionControlOptions);
map.addControl(timeDimensionControl);
let turbTimeLayer = L.timeDimension.layer.wms(turb, {
    updateTimeDimension: true,
});
turbTimeLayer.addTo(map);

I have tried to add a second timeDimensionControl, and I also used the pluging leaflet slidercontrol.

Console.log HTML elements

Starting out in JavaScript with VScode and Chrome on PC
this line of code
console.log(document.getElementById(app-title’));
puts this on the console

(solid triagle)h1#iapp-title

but the tutorial I’m using Modern JavaScript from the Beginning – Second Edition Brad Traversy shows this

<h1 id="app-title">Shopping List</h1>

What am I doing wrong? Is there something in the console settings I’m missing?

Encountering issue in reusable components with react-multi-carousel

I’m developing a reusable component using react-multi-carousel for a React app. However, when I try to integrate it into a different React application, I encounter an error. Could there be issues with dependencies, version compatibility, or incorrect configuration causing this problem?

This is my re-usable component

import React from 'react';
import Carousel from 'react-multi-carousel';
import 'react-multi-carousel/lib/styles.css';

const Widget1 = () => {
  const items = [
    <div style={{ background: 'red', height: 200 }}>Item 1</div>,
    <div style={{ background: 'blue', height: 200 }}>Item 2</div>,
    <div style={{ background: 'green', height: 200 }}>Item 3</div>,
  ];

  const responsive = {
    superLargeDesktop: { breakpoint: { max: 4000, min: 1024 }, items: 5 },
    desktop: { breakpoint: { max: 1024, min: 768 }, items: 3 },
    tablet: { breakpoint: { max: 768, min: 464 }, items: 2 },
    mobile: { breakpoint: { max: 464, min: 0 }, items: 1 },
  };

  return (
    <Carousel responsive={responsive}>
      <div style={{ background: 'red', height: 200 }}>Item 1</div>
      <div style={{ background: 'blue', height: 200 }}>Item 2</div>
      <div style={{ background: 'green', height: 200 }}>Item 3</div>
    </Carousel>
  );
};

export default Widget1;




// webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/Widget1.js',  // Entry point: main JS file of the component
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'Widget1.js',  // Output the bundled JS file in the dist/ folder
    library: 'Widget1',      // Expose it as a global library
    libraryTarget: 'umd',        // Universal module definition (works for CommonJS, AMD, and as a global)
  },
  module: {
    rules: [
      {
        test: /.jsx?$/,           // Match all JS/JSX files
        exclude: /node_modules/,   // Exclude node_modules
        use: {
          loader: 'babel-loader',  // Use Babel to transpile JavaScript
          options: {
            presets: [
                [
                    '@babel/preset-react',
                    {
                      runtime: 'automatic', // Enable the automatic runtime
                      importSource: '@emotion/react', // Optional: use Emotion for JSX pragmas
                    },
                ], 
                '@babel/preset-env'
            ],
          },
        },
      },
      {
        test: /.css$/,            // Match CSS files
        use: ['style-loader', 'css-loader'],  // Use these loaders to handle CSS
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],  // Allow importing without specifying extensions
  },
  externals: {
    react: 'react',
    'react-dom': 'react-dom'
  },
  devtool: 'source-map',
  mode: 'production',             // Set mode to production for minification and optimization
};

this is my react app where I am consuming the widget1

<Widget1 />

The following error messages I am getting,

Cannot read properties of undefined (reading 'validated')
TypeError: Cannot read properties of undefined (reading 'validated')
    at cloneAndReplaceKey (http://localhost:3000/static/js/bundle.js:21406:49)
    at mapIntoArray (http://localhost:3000/static/js/bundle.js:21499:200)
    at mapIntoArray (http://localhost:3000/static/js/bundle.js:21504:164)
    at mapChildren (http://localhost:3000/static/js/bundle.js:21515:5)
    at Object.toArray (http://localhost:3000/static/js/bundle.js:21731:14)
    at t.default (http://localhost:3000/static/js/bundle.js:23108:218)
    at react-stack-bottom-frame (http://localhost:3000/static/js/bundle.js:17901:18)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:9218:20)
    at updateFunctionComponent (http://localhost:3000/static/js/bundle.js:10487:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:11105:16)

in power automate variable produced by java script is visible as [object Object]

function ExecuteScript() {
return (async function () {
    const CHECK_INTERVAL = 500; // Sprawdzenie co 500 ms
    const TIMEOUT = 45000; // Maksymalny czas oczekiwania w milisekundach
    const startTime = new Date().getTime(); // Czas rozpoczęcia

    while (new Date().getTime() - startTime < TIMEOUT) {
        // Pobierz element <div> o id="basicUdiDanger"
        const targetDiv = document.getElementById("basicUdiDanger");
        console.log("Result basicUdiDanger:", targetDiv);

        if (targetDiv) {
            console.log("targetDiv true");
            return "success"; // Zwróć "success" jako czysty tekst
        } else {
            console.log("targetDiv false");
        }

        // Czekaj przed następnym sprawdzeniem
        await new Promise(resolve => setTimeout(resolve, CHECK_INTERVAL));
    }

    // Czas oczekiwania - zwróć "2ndstep"
    console.log("Nie znaleziono tekstu 'Wprowadź dane ręcznie' w <div> w ciągu 45 sekund.");
    return "2ndstep"; // Czas oczekiwania - zwróć "2ndstep"
})()
   .then(result => {
      console.log("Script result:", result);
        return String(result); // Zwróć wynik jako czysty tekst
   })
    .catch(error => {
       console.error("Error during execution:", error);
        return "error"; // Zwróć "error" jako czysty tekst w przypadku błędu
    });

}

in above code variable produced is not recognized by power automate. Is recognized as [object Object] I’ve tried to change it to string but doesn’t help still not reconsided by power automate,

Is it possible to have a FullCalendar dayGridYear to span across the year break

For example, if I have the following:

visibleRange: {
        start: '2024-12-23',
        end: '2025-01-19'
        },   
validRange: {
        start: '2024-12-23',
        end: '2025-01-19'
        }

Then the dayGridYear only shows Dec 23 – Jan 5. For other times of the year, this kind of range of dates is not an issue, it appears to be a problem because it is spanning across the year.

I did a search, and couldn’t find this documented as an issue anywhere.

How to add additionalProperties in nested schema in typebox ajv which has common schema import?

I tried to add the { additionalProperties : false} to one of my typebox schema

schema.ts


export const numericString = (options: { default: string }) =>
  Type.String({
    ...options,
    pattern: '^[0-9]+$'
  });

export const commonQueryParamsWithPagination = Type.Object({
  sort: Type.Optional(Type.String()),
  page: numericString({ default: '1' }),
  size: numericString({ default: '100' })
});

export const getUserRequestQuerySchema = Type.Intersect(
  [
    Type.Object({
      status: Type.String()
    }),
    commonQueryParamsWithPagination
  ]
);

export const getUserRequestSchema = Type.Object({
  query: getAllOrganizationRequestQuerySchema,
  body: Type.Any(),
  headers : Type.Any(),
  params: Type.Any()
} ,   { additionalProperties: false });


This works if any other property is passed to the the top level,

In case we need to add this property to the query schema along with request schema

Option 1:

  [
    Type.Object({
      status: Type.String()
    }),
    commonQueryParamsWithPagination
  ],
  { additionalProperties: false }
);

This approach make the all the property as additional property and is not allowed at all

In order make it work we need to make the query schema without Type.Intersect and commonQueryParamsWithPagination


export const getUserRequestQuerySchema = Type.Object({
      status: Type.String(),
      sort: Type.Optional(Type.String()),
      page: numericString({ default: '1' }),
       size: numericString({ default: '100' })
    }),

As there can be multiple conditions where I have reuse the existing schema so how would I make it work for { additionalProperties : false } for neseted schema whihc need to reuse the existing schema ?