How can I create custom shareable embed links for media like Spotify or SoundCloud?

Some websites and applications, such as Spotify and SoundCloud, generate unique embed links when sharing a song or video. These embeds are more than just static content; they allow users to play the media directly.

For example, here’s an image of Spotify’s embed:
Spotify embed link example

I attempted to create a basic embed using the tag, but I want something more functional and dynamic, like the ability to play the track or video directly from the embed. Does anyone have suggestions for implementing this with custom functionality (e.g., custom player controls)?

Any help or libraries to explore would be appreciated!

First column must be a domain column – Google Line chart

I am trying to draw chart in Google line chart in web app, functionality of the chart is

  • On loading the page Chart should display with data “All”.
  • On drop down selection chart have to be updated with selected values.

After test deployment, I am getting the error in the browser

First column must be a domain column

Not sure where I am messing around 🙁

Here is my App script function

function draw_chart(){
  var ss = SpreadsheetApp.openById('XXXXXXX');
  var metrics_sheet = ss.getSheetByName('sheet1');
  var lastrow = metrics_sheet.getLastRow();
  var lastcolumn = metrics_sheet.getLastColumn();
  var values = metrics_sheet.getRange("A1:X").getValues();
  /* Find Last Index of the Non Blank cells */
  const range = metrics_sheet.getRange("A1:X"+lastrow).getValues();
  var index_values  = lastrow - range.reverse().findIndex(c=>c[0]!='');
  var temp = "A1:X"+index_values;
  var values = metrics_sheet.getRange(temp).getValues();
  var chart_dt = JSON.stringify(values); 
  Logger.log(chart_dt);
  return chart_dt;
}

Above function gives the output like

[["city","date","volume"],
["All","2022-04-30T18:30:00.000Z",492],
["All","2022-05-31T18:30:00.000Z",406],
["All","2022-06-30T18:30:00.000Z",924],
["All","2022-07-31T18:30:00.000Z",902],

["san fran","2023-04-30T18:30:00.000Z",613],
["san fran","2023-05-31T18:30:00.000Z",233],
["san fran","2023-06-30T18:30:00.000Z",593],
["san fran","2023-07-31T18:30:00.000Z",306],

["chicago","2022-04-30T18:30:00.000Z",989],
["chicago","2022-05-31T18:30:00.000Z",735],
["chicago","2022-06-30T18:30:00.000Z",497],
["chicago","2022-07-31T18:30:00.000Z",663]]

My Script for drawing and filtering the charts

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
    <script src="https://www.gstatic.com/charts/loader.js"></script>    
    <script type="text/javascript">    
      google.charts.load('current',{'packages':['corechart']});
      google.charts.setOnLoadCallback(drawchart);
         

      function drawchart(){
        window.alert('Inside Draw Chart func');
        google.script.run.withSuccessHandler(displaychart).chart_draw();        
      }

      function get_filter_city(){                
        google.script.run.withSuccessHandler(filter_data).draw_linechart();             
      }       

      function filter_data(city_data){
        let city_select = document.getElementById("city").value;
    let f_city_data = city_data;        

        //Filter for regions
        if(city_select==""){
          city_select = city_data.slice(0);
        }else{          
          filterbyregion = f_city_data.filter(city_data => city_data.city === city_select);          
        }     
      }

      function displaychart(c_data1){
        var datatable = new google.visualization.DataTable();
        datatable.addColumn('string','date');
        datatable.addColumn({type:'string',role:'annotation'});        
        datatable.addColumn('number',id:'pat');

        var rows = [];

        for(var i=0;i<c_data1.length;i++){          
          var curr_element = c_data1[i];
          var e_date = new Date(curr_element[1]);

          rows.push([curr_element[0],curr_element[1],curr_element[2]]);
        }
        datatable.addRows(rows);                      

      //Setting Chart Options
      var options={
        title: 'Sales Volume'        
      };

      // Draw our chart passing some options
      var chart = new google.visualization.LineChart(document.getElementById('chart_container'));
      chart.draw(datatable,options);
      }
      </script>

HTML code

    <select id="city">
      <option value="All">All</option>
      <option value="san fran">san fran</option>
      <option value="chicago">chicago</option>
     </select>
     <button id="srch_btn" onclick="get_filter_city()"> Search </button> 
     <div id="hell" class="chart_container"></div>

Leaflet custom marker with divIcon crashes on ios

I am working on a website that features a map with different locations to that open additional information on click.

The site works well on desktop, but on mobile the site refreshes until the following error appears “a problem repeatedly occurred”. I have done several tests and I realized it happens when I use the custom L.divIcon but I don’t see anything wrong there.

const locations = [
              {
          "key" : "aquarium",
          "title" : "aquarium",
          "time" : "present",
          "lat" : "52.4986179",
          "lon" : "13.4165594",
        },
              {
          "key" : "andenbuch",
          "title" : "andenbuch",
          "time" : "present",
          "lat" : "52.4889454",
          "lon" : "13.4029223",
        },
              {
          "key" : "poropati",
          "title" : "Poropati",
          "time" : "present",
          "lat" : "52.4804748",
          "lon" : "13.4464375",
        }];

for (let index = 0; index < locations.length; index++) {
        marker = L.marker([locations[index].lat, locations[index].lon], {
          icon: L.divIcon({
            className: `marker marker-category-${locations[index].time}`,
            html: `
              <div class="pin"></div>
              <div class="title">${locations[index].title}</div>
            `
          }),
        }).addTo(map).on('click', () => { openModal(locations[index].key) });
      }

I have tried reorganizing the code, when I removed the divIcon and used the default marker it worked, but I need a custom marker.

Blank Page when Refreshing create-react-app

Whenever I refresh any page on my create-react-app static build(npm run build), I get a blank page.
When checking source, I can see that I got 200 OK from index.html but the page content is just empty. the HTML contains nothing but imports and etc, no content.

However, a Hard-Refresh (CTRL+SHIFT+F5), everything refreshes and works as expected.
I tried various solutions found on the web, spent over 10 hours on this and I’m just lost. any ideas would be appericiated

Here’s my App.JS

function App() {
    return (
        <>
            <Router>
                <AccessibleNavigationAnnouncer/>
                <Switch>
                    <Route path="/login" component={Login}/>
                    <Route path="/app/*" component={Layout}/>

                    <Redirect exact from="/" to="/login"/>
                </Switch>
            </Router>
        </>
    )
}

package.json

...
  "homepage": "https://blahblah.com/",
...

.htaccess

RewriteEngine On
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Here’s my serving logic (runs on Node)

const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'build')));

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(9000);

P.S: The site is hosted on a shared hosting of Namecheap. if that matters somehow

Merge blocks created by svg path

My react web app has over 2000 blocks that created by svg path.

Users can select the blocks they need and merge them to a large block.

The sides of selected blocks must be adjacent.

The problem is I have no idea how to handle irregular block like A0+A1+A2+A4 in snippet.

const data = Array.from({ length: 9 }).map((_, i) => ({
  id: `A${i}`,
  x: (i % 3) * 300,
  y: Math.floor(i / 3) * 300,
  p: [{ node: "L", x: 300, y: 0 },{ node: "L", x: 300, y: 300 },{ node: "L", x: 0, y: 300 }]
}));
const expectResult = [
  {
    id: "A0", x: 0, y: 0,
    p: [{ node: "L", x: 900, y: 0 },{ node: "L", x: 900, y: 300 },{ node: "L", x: 600, y: 300 },{ node: "L", x: 600, y: 600 },{ node: "L", x: 300, y: 600 },{ node: "L", x: 300, y: 300 },{ node: "L", x: 0, y: 300 }],
  },
  {
    id: "A3", x: 0, y: 300,
    p: [{ node: "L", x: 300, y: 0 },{ node: "L", x: 300, y: 300 },{ node: "L", x: 600, y: 300 },{ node: "L", x: 600, y: 600 },{ node: "L", x: 0, y: 600 }],
  },
  {
    id: "A5", x: 600, y: 300,
    p: [{ node: "L", x: 300, y: 0 },{ node: "L", x: 300, y: 600 },{ node: "L", x: 0, y: 600 }],
  },
];

const App = () => {
  return (
    <div>
      original
      <svg width="100%" viewBox="-100 -100 1200 1200">
        {data.map((d) => (
          <Booth key={d.id} d={d} />
        ))}
      </svg>
      expected result after merge by selected blocks
      <svg width="100%" viewBox="-100 -100 1200 1200">
        {expectResult.map((d) => (
          <Booth key={d.id} d={d} />
        ))}
      </svg>
    </div>
  );
};

const drawPath = (path) => path.map((p) => (p.node === "L" ? `${p.node}${p.x} ${p.y}` : `${p.node}${p.x1} ${p.y1} ${p.x2} ${p.y2} ${p.x} ${p.y}`)).join("") + "Z";

const Booth = ({ d }) => {
  return (
    <g key={d.id} id={d.id} transform={`translate(${d.x},${d.y})`}>
      <path stroke={"black"} fill="none" strokeWidth={1} d={`M0 0${drawPath(d.p)}`} />
      <text y={150} fontSize={80}>
        {d.id}
      </text>
    </g>
  );
};
ReactDOM.createRoot(document.getElementById("app")).render(<App />);
body {
  margin: 0;
  padding: 0;
}
<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin="true"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin="true"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin="true"></script>
<div id="app"></div>

I tried to use min and max to calculate the new block’s shape, but it can’t handle irregular block.

const data = Array.from({ length: 9 }).map((_, i) => ({
  id: `A${i}`,
  x: (i % 3) * 300,
  y: Math.floor(i / 3) * 300,
  p: [
    { node: "L", x: 300, y: 0 },
    { node: "L", x: 300, y: 300 },
    { node: "L", x: 0, y: 300 },
  ],
}));

const areas = [
  { id: "A0", blocks: ["A0", "A1", "A2", "A4"] },
  { id: "A3", blocks: ["A3", "A6", "A7"] },
  { id: "A5", blocks: ["A5", "A8"] },
];
const mergeBlock = (blocksData) => {
  const filter = [];
  return blocksData
    .map((d1) => {
      const area = areas.find((d2) => d1.id === d2.id);
      const pos = blocksData.filter((d) => area && area.blocks.includes(d.id)).map((d) => ({ x: d.x, y: d.y }));
      const x = pos.length > 0 ? Math.min(...pos.map((d) => d.x)) : d1.x;
      const y = pos.length > 0 ? Math.min(...pos.map((d) => d.y)) : d1.y;
      const w = pos.length > 0 ? Math.max(...pos.map((d) => d.x)) - x + 300 : d1.w;
      const h = pos.length > 0 ? Math.max(...pos.map((d) => d.y)) - y + 300 : d1.h;
      filter.push(...(area ? area.blocks.filter((d) => d !== d1.id) : []));
      return {
        ...d1,
        x,
        y,
        p: [
          { node: "L", x: w, y: 0 },
          { node: "L", x: w, y: h },
          { node: "L", x: 0, y: h },
        ],
      };
    })
    .filter((d) => !filter.includes(d.id));
};

const App = () => {
  return (
    <div>
      <svg width="100%" viewBox="-100 -100 1200 1200">
        {mergeBlock(data).map((d) => (
          <Booth key={d.id} d={d} />
        ))}
      </svg>
    </div>
  );
};

const drawPath = (path) => path.map((p) => (p.node === "L" ? `${p.node}${p.x} ${p.y}` : `${p.node}${p.x1} ${p.y1} ${p.x2} ${p.y2} ${p.x} ${p.y}`)).join("") + "Z";

const Booth = ({ d }) => {
  return (
    <g key={d.id} id={d.id} transform={`translate(${d.x},${d.y})`}>
      <path stroke={"black"} fill="none" strokeWidth={1} d={`M0 0${drawPath(d.p)}`} />
      <text y={150} fontSize={80}>
        {d.id}
      </text>
    </g>
  );
};
ReactDOM.createRoot(document.getElementById("app")).render(<App />);
body {
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin="true"></script>
<div id="app"></div>

Audio to 2d lip sync animation in javascript

I researched for a few days how to convert an MP3 voice-over to an animated lip synced character video, like Adobe character animation. I like 2d animations.

I found crazytalk tool to create such animations offline. I am looking for a javascript/python library which can compile an animation and produce a video. Or an easy approach to implement such a library.

Imitate browser event capturing in Javascript

Event capturing as in Event Capturing/Bubbling, not event-handlers.

I have a web-application where the user can create visualization elements within a div.
In one example the user created a div that’s clickable and has a hover-event, but is a sibling to, and displayed on top of, elements that have context-menu events on them.

The user still wants these context-menu events to work, as they open a context-menu that enables value-specific behaviour.

This causes trouble since I can’t seem to find a way to imitate the way the browser fires off events.
What I want to do is handle right-click events in the ‘editor’ and if the cursor position overlaps another of the children of the ‘editor’, recursively re-dispatch the event on all elements directly below the cursor.
Creating events and dispatching them manually only causes them to bubble up, not propagate down.

I also cannot disable pointer-events on the user’s div, as their events would stop working.
Even if I did in the instant the button is clicked, I still need to be able to re-run the browser’s event programmatically so that the elements below are also affected by it.

My application only knows of the editor itself and the elements outside; everything within is dynamically assembled by the user.
This means I cannot find the text-element by id and bubble the events upwards.

The following snippet shows an example of the current state.
Because of the elements in the sibling div being nested, simply dispatching an event on the sibling itself doesn’t work.

let editor = document.getElementById("editor");
editor.oncontextmenu = e => {
  // Skip opening the browser context-menu.
  e.preventDefault();

  for (let i = 0; i < editor.children.length; i++) {
    let currentChild = editor.children[i];
    if (currentChild == e.target) {
      // Avoid executing the event on the element that received it.
      continue;
    }

    let currentRect = currentChild.getBoundingClientRect();
    if (currentRect.left < e.offsetX &&
      currentRect.top < e.offsetY &&
      currentRect.right > e.offsetX &&
      currentRect.bottom > e.offsetY) {

      // Problem here is that the new event is only sent to the sibling, not further down to the texts.
      // Since the text boxes have context menu event, not the sibling, this won't do anything.
      // I would preferrably like to just re-execute the right-click while the browser calculates the destination.
      // The current way requires every layer to have this custom logic in 'oncontextmenu',
      // which is not possible in my scenario.
      let ev = new MouseEvent('contextmenu', {
        screenX: e.screenX,
        screenY: e.screenY,
        clientX: e.clientX,
        clientY: e.clientY,
        ctrlKey: e.ctrlKey,
        shiftKey: e.shiftKey,
        altKey: e.altKey,
        metaKey: e.metaKey,
        button: e.button,
      });
      currentChild.dispatchEvent(ev);
    }
  }
}

let header = document.getElementById("header");
document.onmousemove = e => {
  header.innerHTML = 'Header text<br/>x: ' + e.pageX + '<br/>y: ' + e.pageY;
}
#header {
  padding: 25px;
  border: 1px solid black;
}

#editor {
  position: relative;
}

.sibling {
  position: absolute;
  background-color: red;
  border: 5px solid blue;
  opacity: 0.3;
  width: 250px;
  height: 250px;
  top: 50px;
  left: 75px;
}

.me {
  position: absolute;
  opacity: 0.3;
  width: 300px;
  height: 300px;
  top: 25px;
  left: 50px;
  border: 5px solid black;
}

.me:hover {
  border-color: red;
  background-color: green;
}

.nephew {
  height: calc(100% - 30px);
  width: calc(100% - 30px);
  margin: 9px;
  padding: 5px;
  border: 1px solid white;
}

.cousin {
  color: yellow;
  align-content: center;
  text-align: center;
  margin: auto 0;
  height: 50%;
  width: 100%;
  border: 1px solid blue;
}
<header id="header">Header text<br/> x: ?<br/> y: ?</header>
<div id="editor">
  <div class="sibling">
    <div class="nephew">
      <div class="cousin">
        <div class="text" oncontextmenu="alert('context-menu on 'Value 1'')">Value 1</div>
      </div>
      <div class="cousin">
        <div class="text" oncontextmenu="alert('context-menu on 'Value 2'')">Value 2</div>
      </div>
    </div>
  </div>
  <div class="me" onclick="alert('clicked 'me'')" oncontextmenu="alert('context-menu on 'me'')"></div>
</div>

Same snippet in JSFiddle:
https://jsfiddle.net/7gnqsm51/9/

The project does not currently use JQuery, so I would prefer solutions without it.

13:33:44 [vite] Internal server error: Missing “./dist/entry-preview.mjs.js” specifier in “@storybook/react” package

how to fix this
i using
“@storybook/react”: “^8.2.9”,
“@storybook/react-vite”: “8.2.9”,
“vite”: “^4.4.0”,
“vite-tsconfig-paths”: “^4.3.1”,
“vitest”: “^1.3.1”
in the network tab in developer console I see the call:
GET http://localhost:6007/virtual:/@storybook/builder-vite/vite-app.js net::ERR_ABORTED 404 (Not Found)

-file main.ts

import type { StorybookConfig } from '@storybook/react-vite';

const config: StorybookConfig = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-next',
    '@storybook/addon-essentials',
    '@storybook/preset-create-react-app',
  ],
  framework: {
    name: '@storybook/react-vite',
    options: {},
  },
  
};

export default config;

-file preview.tsx

import '@mantine/core/styles.css';
import React, { useEffect } from 'react';
import { addons } from '@storybook/preview-api';
import { DARK_MODE_EVENT_NAME } from 'storybook-dark-mode';
import { MantineProvider, useMantineColorScheme } from '@mantine/core';
import { theme } from '../src/theme';

const channel = addons.getChannel();

function ColorSchemeWrapper({ children }: { children: React.ReactNode }) {
  const { setColorScheme } = useMantineColorScheme();
  const handleColorScheme = (value: boolean) => setColorScheme(value ? 'dark' : 'light');

  useEffect(() => {
    channel.on(DARK_MODE_EVENT_NAME, handleColorScheme);
    return () => channel.off(DARK_MODE_EVENT_NAME, handleColorScheme);
  }, [channel]);

  return <>{children}</>;
}

export const decorators = [
  (renderStory: any) => <ColorSchemeWrapper>{renderStory()}</ColorSchemeWrapper>,
  (renderStory: any) => <MantineProvider theme={theme}>{renderStory()}</MantineProvider>,
];

“I tried to run Storybook with Vite, but encountered a 404 error for the vite-app.js file, and couldn’t resolve it.”

Google Ad Manager Script not running after deployment, works fine on local environment

I am facing an issue where the Google Ad Manager script provided to me works perfectly in my local development environment, but it does not run after deployment to my server. The browser console shows no errors or warnings in either case, but the ads are not loading on the deployed version.

What I’ve tried:

  1. Verified that the same script works on local but not on production.
  2. Checked the browser console for any errors or warnings—none are shown.
  3. Verified that no ad blockers are interfering.
  4. Ensured that the deployed environment matches the local environment in terms of configuration.
  5. Tried inspecting network requests related to ads, but nothing unusual was found.

Environment Details:

  • Local: [e.g., Windows/Mac, Browser (Chrome/Firefox/etc.)]
  • Server: [e.g., Ubuntu/Debian, Apache/Nginx]

Additional Info:

  • I have Build it using Docker and Tested it is working fine locally but not after deployment
  • The script is included using standard HTML <script> tags.
  • No CORS-related issues are appearing in the console.
  • The website on the server is served over HTTPS, and SSL certificates are correctly installed.

Any insights or ideas on why the script isn’t running in production but works locally would be greatly appreciated!

Here is the Link

dev.startbazaar.pk

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 
    https://support.google.com/admanager/answer/1697712?hl=en&ref_topic=4390040&sjid=4107885407167616336-EU
  -->
  <script src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
  <script>
    window.googletag = window.googletag || { cmd: [] };
    googletag.cmd.push(function () {
      googletag.defineSlot('/28379801/Starbazaar728x90', [728, 90], 'div-gpt-ad-1725272785987-0')
        .addService(googletag.pubads());
      googletag.enableServices();
    });
  </script>
</head>

<body>
  <h1>Hello World</h1>
  <div id='div-gpt-ad-1725272785987-0' style='min-width: 728px; min-height: 90px;'>
    <script>
      googletag.cmd.push(function () { googletag.display('div-gpt-ad-1725272785987-0'); });
    </script>
  </div>
</body>

</html>

The date picker format stopped working after I moved the code from the PHTML file to a separate JavaScript file

I was implementing a date picker on one of my pages, and it was working fine. However, after moving my JavaScript files from the PHTML file to a separate JS file, it stopped working and is now picking the wrong format. Can you help me fix it?

Working file that present in the same phtml file

 $('#imported_from_dated').datepicker({
    format: '<?php echo DATE_PICKER_FORMAT; ?>', // format 'yyyy-mm-dd'
 }).on('changeDate', function (e) {
   $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
   if ($('#imported_to_dated').val() != '') {
     $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
   }
   $('#imported_from_dated').show();   
 });

 $('#imported_to_dated').datepicker({
   format: '<?php echo DATE_PICKER_FORMAT; ?>', // format 'yyyy-mm-dd'
 }).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    $('#imported_to_dated').show();
 });

 $('#searchDataForm').formValidation({
    message: 'list message',
    fields: {
        imported_from_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 1',
                },
                date: {
                    format: '<?php echo DATE_VALIDATION_FORMAT; ?>', // format MM/DD/YYYY
                    message: 'error message 2',
                }
            }
        },
        imported_to_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 3',,
                },
                date: {
                    format: dateValidationFormat,
                    message: 'error message 4',,
                },
                callback: {
                    callback: function (value, validator, $field) {
                        var startDate = $('#imported_from_dated').val();
                        var endDate = $('#imported_to_dated').val();
                        if (startDate !== '' && endDate !== '') {

                            var dateSt = startDate.split('/');
                            var dateEd = endDate.split('/');
                            var StDt = Date.parse(dateSt[2] + '-' + dateSt[0] + '-' + dateSt[1]); //Year, Month, Date
                            var EdDt = Date.parse(dateEd[2] + '-' + dateEd[0] + '-' + dateEd[1]);

                            if (StDt > EdDt) {
                                return {
                                    valid: false,
                                    message: 'error message 5',
                                };
                            }
                        }
                        return true;
                    }
                }
            }
        }
    }
}).on("keyup",'[name="imported_from_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_from_dated');
}).on("keyup",'[name="imported_to_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_to_dated');
});

from the above code while i am selecting any date it will update in to MM/DD/YYYY format.
example : 09/05/2024

But i have move the js file in to seperate file and the code looks like this
PHTML file

 <script type="text/javascript">
    var dateFormat = '<?php echo DATE_PICKER_FORMAT; ?>';
    var dateValidationFormat = <?php echo DATE_VALIDATION_FORMAT; ?>;
 </script>

 JS file

 $('#imported_from_dated').datepicker({
   format: dateFormat,
}).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    if ($('#imported_to_dated').val() != '') {
        $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    }
    $('#imported_from_dated').show();
});

$('#imported_to_dated').datepicker({
   format: dateFormat,
}).on('changeDate', function (e) {
    $('#searchDataForm').formValidation('revalidateField', 'imported_from_dated');
    $('#searchDataForm').formValidation('revalidateField', 'imported_to_dated');
    $('#imported_to_dated').show();
});


$('#searchDataForm').formValidation({
    message: 'list message',
    fields: {
        imported_from_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 1',
                },
                date: {
                    format: dateValidationFormat, // format MM/DD/YYYY
                    message: 'error message 2',
                }
            }
        },
        imported_to_dated: {
            validators: {
                notEmpty: {
                    message: 'error message 3',,
                },
                date: {
                    format: dateValidationFormat,
                    message: 'error message 4',,
                },
                callback: {
                    callback: function (value, validator, $field) {
                        var startDate = $('#imported_from_dated').val();
                        var endDate = $('#imported_to_dated').val();
                        if (startDate !== '' && endDate !== '') {

                            var dateSt = startDate.split('/');
                            var dateEd = endDate.split('/');
                            var StDt = Date.parse(dateSt[2] + '-' + dateSt[0] + '-' + dateSt[1]); //Year, Month, Date
                            var EdDt = Date.parse(dateEd[2] + '-' + dateEd[0] + '-' + dateEd[1]);

                            if (StDt > EdDt) {
                                return {
                                    valid: false,
                                    message: 'error message 5',
                                };
                            }
                        }
                        return true;
                    }
                }
            }
        }
    }
}).on("keyup",'[name="imported_from_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_from_dated');
}).on("keyup",'[name="imported_to_dated"]',function() {
    $("#searchDataForm").formValidation('revalidateField', 'imported_to_dated');
});

I have verified that the values are being passed to the JS file correctly, but I’m still getting the date in the ‘2024-09-05’ format (not converting to MM/DD/YYYY format). I can’t figure out what’s causing the issue, even though the code inside the JS file is written within the document.ready function.

Why this Factory function is not working?

I am writing this factory function in the index.js file. But it is not working. In the console it is showing that the ‘rectangle1’ is undefined. Please find the error.
console error

function createRectangle(len,bre) {
    let rectangle = {
        length: len,
        breadth: bre,
   
        draw: function() {
            console.log('drawing rectangle');
        }
    };
    return rectangle;
}

let rectangleObj1 = createRectangle(5,4);

Refactor the Parser [closed]

-Refactor the code in index.ts and fix potential bugs and concurrency issues.
-Although the working code is required, you aren’t required to write production-level code or handle all edge cases. Do not add new features, keep crucial functionality and refactor.
-Make your code as extensible and flexible as possible. Your main goal is to demonstrate the skill of writing extensible and flexible code.
-You may add comments explaining your refactoring decisions to avoid misunderstandings

Crucial functional requirements

  1. Read several files from API(create a mock), each containing string like:
    “Hello world! : 2024-02-22 14:35:30 UTC”
    “Goodbye world! : 2024-02-22 16:35:30 UTC”
    “Hello? : 2024-02-22 08:35:30 UTC”
    “Hi : 2024-02-22 12:35:30 UTC”

  2. Parse each line, wait for a random number of seconds <5, write a message to the console, and send to the API(create a mock) with the corresponding filename

  3. If parsing or writing fails – resolve gracefully, without error

  4. Read and process each file and its lines concurrently
    Fail criteria
    Violation of any criterion would lead to submission failure

Procedural code is not considered a successful solution
The code fails to run
Crucial functionality missing
Fewer than 5 classes and 5 interfaces
Classes with public fields, getters and setters
SOLID, DRY principles violated
Program is not smoothly made up by composing components
(components must compose like in index.ts file in the example)

const mockResponses: Record<string, string> = {
  "file1.txt": `Hello world! : 2024-02-22 14:35:30 UTC
  Goodbye world! : 2024-02-22 16:35:30 UTC
  Hello? : 2024-02-22 08:35:30 UTC
 Hi : 2024-02-22 12:35:30 UTC`,
  "file2.txt": `How are you doing ? : 2024-02-22 13:59:30 UTC
  Fine : 2024-02-22 12:44:30 UTC
  How about you ? : 2024-02-22 22:35:30 UTC
  Same : 2024-02-22 07:39:30 UTC`,
  "file3.txt": `Have you seen high elves ? : 2022-02-22 14:35:30 UTC
  HESOYAM : 2023-02-22 14:35:30 UTC
  BAGUVIX : 2021-02-22 14:35:30 UTC
  THERE IS NO SPOON : 2020-02-22 14:35:30 UTC`,
};

const mockFetch = async (
  filePath: string,
  params?: { body: string; method: string }
): Promise<string> => {
  if (params?.method === "POST") return "";
  return mockResponses[filePath] ?? "";
};

class Parser {
  constructor() {}
  async getContent(file: string): Promise<
    {
      message: string;
      timestamp: string;
    }[]
  > {
    const res = await mockFetch(file);
    const messages = res.split("n");
    const content: { message: string; timestamp: string }[] = [];
    for (let i = 0; i < messages.length; i++) {
      const [message, timestamp] = messages[i].split(":");
      content.push({ message, timestamp });
    }
    return content;
  }
  async saveContent(
    messages: { message: string; timestamp: string }[],
    file: string
  ) {
    const waitGroup: Promise<any>[] = [];
    for (let i = 0; i < messages.length; i++) {
      const promise = new Promise<void>(async (resolve) => {
        await new Promise<void>((resolve) =>
          setTimeout(() => resolve(), Math.random() * 5 * 1000)
        );
        await mockFetch(file, {
          body: JSON.stringify({
            ...messages[i],
            type: messages[i].message.length > 8 ? "long" : "short",
          }),
          method: "POST",
        });
        console.log(
          `Saved message - ${messages[i].message} to ${file} as ${
            messages[i].message.length > 8 ? "long" : "short"
          }`
        );
      });
      waitGroup.push(promise);
    }
    await Promise.all(waitGroup);
  }
}

const main = async () => {
  const files = {
    "file1.txt": "out1.txt",
    "file2.txt": "out2.txt",
    "file3.txt": "out3.txt",
  };
  const parser = new Parser();
  const waitGroup: Promise<any>[] = [];

  for (const [input, output] of Object.entries(files)) {
    const promise = new Promise<void>((resolve) => {
      parser
        .getContent(input)
        .catch((error) => {
          console.error(`Error while getting file ${input} - ${error}`);
          return [];
        })
        .then((messages) => parser.saveContent(messages, output))
        .catch((error) => {
          console.error(`Error while reading file ${input} - ${error}`);
        })
        .then(resolve);
    });
    waitGroup.push(promise);
  }
  await Promise.all(waitGroup);
};

main();

This is how I decided, please tell me if there are any mistakes here and how it can be improved

const mockResponses: Record<string, string> = {
  "file1.txt": `Hello world! : 2024-02-22 14:35:30 UTC
      Goodbye world! : 2024-02-22 16:35:30 UTC
      Hello? : 2024-02-22 08:35:30 UTC
     Hi : 2024-02-22 12:35:30 UTC`,
  "file2.txt": `How are you doing ? : 2024-02-22 13:59:30 UTC
      Fine : 2024-02-22 12:44:30 UTC
      How about you ? : 2024-02-22 22:35:30 UTC
      Same : 2024-02-22 07:39:30 UTC`,
  "file3.txt": `Have you seen high elves ? : 2022-02-22 14:35:30 UTC
      HESOYAM : 2023-02-22 14:35:30 UTC
      BAGUVIX : 2021-02-22 14:35:30 UTC
      THERE IS NO SPOON : 2020-02-22 14:35:30 UTC`,
};

interface IMessage {
  send: (message: IParserMessage, filepath: string) => Promise<void>;
}

interface IParser {
  parse: (content: string) => IParserMessage[];
}

interface IFileFetcher {
  fetch: (filepath: string) => Promise<string>;
}

interface IFileWriter {
  write: (filepath: string, content: string) => Promise<void>;
}

interface IParserMessage {
  message: string;
  timestamp: string;
}

const mockFetch = async (
  filePath: string,
  params?: { body: string; method: string }
): Promise<string> => {
  if (params?.method === "POST") return "";
  return mockResponses[filePath] ?? "";
};

const LONG_MESSAGE = "long";
const SHORT_MESSAGE = "short";
const POST_METHOD = "POST";

class FileFetch implements IFileFetcher {
  async fetch(filepath: string): Promise<string> {
    return mockFetch(filepath);
  }
}

class FileWriter implements IFileWriter {
  async write(filepath: string, content: string): Promise<void> {
    await mockFetch(filepath, { body: content, method: POST_METHOD });
  }
}

class Parser implements IParser {
  parse(content: string): IParserMessage[] {
    return content.split("n").map((line) => {
      const [message, timestamp] = line.trim().split(" : ");
      return { message, timestamp };
    });
  }
}

class ParserMessage implements IMessage {
  private writer: IFileWriter;

  constructor(writer: IFileWriter) {
    this.writer = writer;
  }

  async send(message: IParserMessage, filepath: string): Promise<void> {
    const delay = Math.random() * 5000;
    await new Promise<void>((resolve) => setTimeout(resolve, delay));
    const content = JSON.stringify({
      ...message,
      type: message.message.length > 8 ? LONG_MESSAGE : SHORT_MESSAGE,
    });
    await this.writer.write(filepath, content);
    console.log(`${message.message} : ${message.timestamp} `);
  }
}

class FileHandler {
  private fetcher: IFileFetcher;
  private parser: IParser;
  private processor: IMessage;

  constructor(fetcher: IFileFetcher, parser: IParser, processor: IMessage) {
    this.fetcher = fetcher;
    this.parser = parser;
    this.processor = processor;
  }

  async handle(inputFile: string, outputFile: string): Promise<void> {
    try {
      const content = await this.fetcher.fetch(inputFile);
      const messages = this.parser.parse(content);
      const waitGroup = messages.map((message) =>
        this.processor.send(message, outputFile)
      );
      await Promise.all(waitGroup);
    } catch (error) {
      console.error(`Error processing file ${inputFile}: ${error}`);
    }
  }
}

const main = async () => {
  const files = {
    "file1.txt": "out1.txt",
    "file2.txt": "out2.txt",
    "file3.txt": "out3.txt",
  };

  const fetcher = new FileFetch();
  const writer = new FileWriter();
  const parser = new Parser();
  const processor = new ParserMessage(writer);
  const handler = new FileHandler(fetcher, parser, processor);

  const waitGroup = Object.entries(files).map(([input, output]) =>
    handler.handle(input, output)
  );
  await Promise.all(waitGroup);
};

main();

When I try to login admin its says Connection Refuse and Post request error [closed]

I have a University Dashboard and in that I have some logins such as Admin Login, student login etc. But when I try to put username and passward then its says in inspect POST net::ERR_CONNECTION_REFUSED and message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’..
And in the backend side I use MySql and I also provide the database connection but this error happens.

I expecting it will give me login successfully or login.

Aligning Buttons at the Same Line with Tabs in React using Ant Design

I am designing a website, and I need to align buttons and tabs at the same line. When I implement following structure, it does work, but when I add the <Table/> component as children, it does not work.

My first code and its output:

     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Tabs defaultActiveKey="1" items={[{ label: 'test', key: 'test', children: 'test' }]} />

        <div>
          <Button type="primary" style={{ marginRight: '8px' }}>Add New</Button>
          <Button>Another Button</Button>
        </div>
      </div>

tabs and buttons are at the same line

But when I add a table, it is like that:

     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <Tabs defaultActiveKey="1" items={[{ label: 'test', key: 'test', children: <Table/> }]} />

        <div>
          <Button type="primary" style={{ marginRight: '8px' }}>Add New</Button>
          <Button>Another Button</Button>
        </div>
      </div>

table ruins the structure

How can I fix that problem?