How to customize (adding more features) Angular Material Datepicker Calender efficiently?

I’m currently working Angular 15 with Angular Material’s Datepicker and have encountered a limitation that I would like to address. The default Datepicker provides basic functionality, but I want to enhance it by adding shortcuts for date ranges such as “Past Week,” “Past Month,” and “Past Year.”

Currently, my Datepicker looks like this:
CURRENT

// angular material datepicker
<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker">
    <input matStartDate placeholder="Start date">
    <input matEndDate placeholder="End date">
  </mat-date-range-input>
  <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

I’ve searched through the documentation and various forums, but the solutions I found only discuss changing the format, headers, and styles, without addressing the addition of custom date range shortcuts.

My Question: How can I efficiently customize the Angular Material Datepicker to include these shortcut options? Any guidance or examples would be greatly appreciated!

What I’ve tried so far :

  • Customizing the date format using the matDateFormats configuration.
  • Modifying the header titles with mat-datepicker-header.
  • Implementing a custom input field for quick selection but haven’t integrated it seamlessly with the existing Datepicker.

How I want it to look like:

EXPECTED

How to Limit File Upload Size and Provide Progress Feedback in JavaScript? [closed]

  1. File Size Limitation: Users should not be able to upload files larger than 2 MB. If they attempt to do so, I want to display a warning message.

  2. Upload Progress Feedback: While the file is uploading, I want to show a progress bar that indicates how much of the file has been uploaded.

    Below is the code I have so far

    html

    <!-- The HTML form for file upload -->
    <form id="uploadForm">
        <input type="file" id="fileInput" accept="image/*" required />
        <div id="progressContainer" style="display: none;">
            <progress id="uploadProgress" value="0" max="100"></progress>
            <span id="progressText"></span>
        </div>
        <button type="submit">Upload</button>
    </form>
    
    

    js

    <script>
        // Event listener for the form submission
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault(); // Prevent default form submission
    
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0]; // Get the selected file
            const maxSize = 2 * 1024 * 1024; // Set the maximum file size to 2 MB
    
            // Check if the selected file exceeds the maximum size
            if (file.size > maxSize) {
                alert('File size exceeds 2 MB. Please select a smaller file.');
                return; // Stop the function if the file is too large
            }
    
            // Prepare the form data for upload
            const formData = new FormData();
            formData.append('file', file);
    
            // Show the progress container for upload feedback
            const progressContainer = document.getElementById('progressContainer');
            const uploadProgress = document.getElementById('uploadProgress');
            const progressText = document.getElementById('progressText');
    
            progressContainer.style.display = 'block'; // Show the progress container
    
            // Create a new XMLHttpRequest for file upload
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/upload', true); // Specify the upload endpoint
    
            // Update the progress bar during the upload
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    uploadProgress.value = percentComplete; // Update the progress value
                    progressText.textContent = Math.round(percentComplete) + '% uploaded'; // Update the text
                }
            });
    
            // Handle the response after upload completion
            xhr.onload = function() {
                if (xhr.status === 200) {
                    console.log('Upload complete:', JSON.parse(xhr.responseText)); // Log success
                } else {
                    console.error('Upload failed:', xhr.statusText); // Log error
                }
            };
    
            // Start the upload
            xhr.send(formData);
        });
    </script>
    
    

    I need to ensure that the upload process does not initiate when a large file is selected.

    I want the progress bar to only appear during the upload. How can I manage its visibility effectively?

    Are there any additional features or best practices I should consider for a better user experience regarding file uploads?

How to override component method from angular storybook

In the component I have a method onExample. I am trying to override the functionality of the onExample method from the storybook. As you can see below, I have tried to add the method as argTypes and inside args. But it does not work. I still get the console output From component. How can I override the method?

In the storybook:

import { provideAnimations } from '@angular/platform-browser/animations';
import { applicationConfig, Meta, moduleMetadata, StoryObj } from '@storybook/angular';

const meta: Meta<ExampleComponent> = {
  title: 'Example',
  component: ExampleComponent,
  decorators: [
    applicationConfig({
      providers: [provideAnimations(), importProvidersFrom(ExampleModule)],
    }),
    moduleMetadata({ imports: [ExampleModule] }),
    fullSizeDecorator(),
  ],
    argTypes: {
      onExample: (value: any) => {
        console.log('from story ', value);
      },
  },
};

export default meta;

type Story = StoryObj<ExampleComponent>;

export const example: Story = {
  args: {
    onExample: (value: any) => {
        console.log('from story 2', value);
      },
  },
};

In the component example.component.ts

onExample(value): void {
    console.log("From component ", value)
  }

how can I convert the ‘string’ from arrayBuffer to arrayBuffer again?

const filePath = path.join(pdfFolderPath, file);

// Read the PDF file
const fileData = await fs.readFile(filePath);

// Load the PDF document
const pdfDoc = await PDFDocument.load(fileData);
const arrayBuffer = await pdfDoc.save(); // Save as ArrayBuffer

// Get the file name without extension
const nameWithoutExtension = path.basename(file, path.extname(file));

// Convert to Base64 string for JSON
pdfArray.push({
  name: nameWithoutExtension, // Save without .pdf
  pdf: arrayBuffer.toString("base64"),
});

I have that pdf value as arrayBuffer.toString("base64").

const a = await pdfSearch(`${output[i]["field4"]}`, arrivalPdf);

// const arrayBuffer = await response.arrayBuffer(); // Get the PDF as an ArrayBuffer
const pdfDoc = await PDFDocument.load(a.pdf);

a.pdf is the string value that I get from converted value. I’ve been trying to convert it back to feed it to PDFDocument.load(). Stuck for like 3 days. Tried 10 different things that I could find here.

I know that this is very redundant question but I could not work it out after trying different stackoverflow solutions again and again :/

how can I change it to something that I can load it to PDFDocument.load() from pdf-lib?

I tried with atob but it did not work. Also, I am trying to do this on a browser without fetching anything. No server. Just from a plain html. I think I can use the package but many did not work too.

Repeating song in a playlist coding test in Javascript

I’m doing practice coding interview tests and can’t for the life of me figure out why my solution isn’t passing.

I know this is a dupe of this, and that a python version of it is here, but I’m pretty sure my issue is one of javascript internal workings and less of algorithmic design (or maybe not). Either way, I didn’t want to hijack that dupe (it was unanswered anyway) as my question is more specific.

The prompt:

A playlist is considered a repeating playlist if any of the songs
contain a reference to a previous song in the playlist. Otherwise, the
playlist will end with the last song which points to null. Implement a
function isRepeatingPlaylist that, returns true if a playlist is
repeating or false if it is not. For example, the following code
prints “true” as both songs point to each other:

Code starting template:

class Song {
    name;
    nextSong;
    
    constructor(name) {
      this.name = name;
    }
  
    /**
     * @return {boolean} true if the playlist is repeating, false if not.
     */
    isRepeatingPlaylist() {
      // Your code goes here
    }
  }
  
let first = new Song("Hello");
let second = new Song("Eye of the tiger");
  
first.nextSong = second;
second.nextSong = first;
  
console.log(first.isRepeatingPlaylist());

My solution thus far. Expanded with console.log and additional songs to help me figure out what is going on. I’ve been running it using node in my terminal. It appears that my issue is in the line current = this.nextSong;, it just does not seem to be reassigning to the next object correctly. Thoughts?

class Song {
  name;
  nextSong;
  
  constructor(name) {
    this.name = name;
  }
  
  /**
   * @return {boolean} true if the playlist is repeating, false if not.
   */
  isInRepeatingPlaylist() {
    // Your code goes here
    let playlist = [];
    let current = this;
    while (current.name && current.nextSong) {
      console.log('playlist:', playlist);
      if (playlist.includes(current.name)) {
        console.log('in playlist')
        return true;
      } else {
        console.log('not in playlist')
        playlist.push(current.name)
        console.log('added:', current.name)
        console.log('next up:', current.nextSong)
        current = this.nextSong;
        console.log('next up assigned?:', current)
      }
    }
    return false;
  }
}

let first = new Song("Hello");
let second = new Song("Eye of the tiger");
let third = new Song("Third");
let fourth = new Song("Fourth");

first.nextSong = second;
second.nextSong = third;
third.nextSong = fourth; //not a repeating playlist, should return false
// fourth.nextSong = first;

console.log(first.isInRepeatingPlaylist());
// true

and my output:

playlist: []
not in playlist
added: Hello
next up: Song {
  name: 'Eye of the tiger',
  nextSong: Song {
    name: 'Third',
    nextSong: Song { name: 'Fourth', nextSong: undefined }
  }
}
next up assigned?: Song {
  name: 'Eye of the tiger',
  nextSong: Song {
    name: 'Third',
    nextSong: Song { name: 'Fourth', nextSong: undefined }
  }
}
playlist: [ 'Hello' ]
not in playlist
added: Eye of the tiger
next up: Song {
  name: 'Third',
  nextSong: Song { name: 'Fourth', nextSong: undefined }
}
next up assigned?: Song {
  name: 'Eye of the tiger',
  nextSong: Song {
    name: 'Third',
    nextSong: Song { name: 'Fourth', nextSong: undefined }
  }
}
playlist: [ 'Hello', 'Eye of the tiger' ]
in playlist
true

‘import type’ in JSX file not accepted

I inherited a React Webpack app that I’m trying to recreate using Vite. I started with a bare Vite/React app and then slowly added the legacy code to it. The problem I’m having is that the source has this weird introduction of TypeScript features in .jsx files – mainly import type and typing of parameters. For example:

X [ERROR] Expected "from" but found "{"

src/components/index.jsx:36:12:
  36 │ import type { IAppProps, IProtectedRouteProps } from './types';
     │             ^
     ╵             from

X [ERROR] Expected "{" but found ":"

src/store/rootSaga.js:18:35:
  18 │ export default function* rootSaga(): Generator<any, void, void> {
     │                                    ^
     ╵                                    {

I tried removing the ‘type’ from the import statements, but there are hundreds of them. Then I got hung up on the more complex statements, like the second one above.

I’d like to avoid changing any code, if I can avoid it. The original code worked built and ran, in whatever environment it had, but I cannot figure out how to get the code working in this clean Vite environment.

Using DELETE cause 405 error while POST works in S3

I am trying to implement a image hosting function using AWS S3 and Hono for API endpoints with NextJS on top.
When I building a delete function, if I define the API on server as delete, it won’t work and produces 405 error. In contrast, using post won’t cause any issue and it works. But in my understanding, defining post, delete or put is required for semantic purposes.
Below is my implementation:
Server-side (Hono):

const mediaS3App = new Hono()
.delete('/delete', async (c) => {
        try {
            const fileName = c.req.query('fileName');

            if (!fileName) {
                return c.json({error: 'File name required.'}, 400)
            }

            const result = await getSignedURL(fileName, 'DELETE')

            if (result.failure) {
                return c.json({error: result.failure}, 401)
            }
            return c.json({url: result.success?.url})
        } catch (error) {
            console.error('Server error:', error);
            return c.json({error: 'An unexpected error occurred.'}, 500)
        }
    })

Client-side:

await Promise.all(fileSelected.map(async (fileName, i) => {
            try {
                const DELURLResponse = await fetch(`/api/images/delete?fileName=${encodeURIComponent(fileName)}`, {
                    method: 'DELETE',
                });

                const DELSignedURL = await DELURLResponse.json();
                if (DELURLResponse.ok && DELSignedURL.url) {
                    const deleteResponse = await fetch(DELSignedURL.url, {
                        method: 'DELETE',
                    });
                    if (deleteResponse.ok) {
                        console.log('delete successful')
                    } else {
                        console.log('error on deletetion')
                    }
                } else {
                    console.error('Failed to delete, something wrong with delete presigned URL', DELSignedURL.error);
                }
            } catch (error) {
                console.error('An error occurred during the deletion:', error);
            }
        }))

It would work If I change to route to post

.post('/delete', async (c) => {
....
await Promise.all(fileSelected.map(async (fileName, i) => {
            try {
                const DELURLResponse = await fetch(`/api/upload/delete?fileName=${encodeURIComponent(fileName)}`, {
                method: 'POST',
            });

Hiding the submenus after the checkbox I clicked with JS

I have a result filtering form as you can see in the attached pictures.
My problem is this:

When I uncheck checkbox number 1, I was able to uncheck the other checkboxes in the sub menu lists that follow. But:

When I uncheck checkbox 1, I want all subsequent html lists with the .sub class to change to ‘display none’. In this way, we hide the sub-location lists.

Filter Bar Preview
Filter Bar Preview

HTML source codes

<div class="section">
  <div class="subhead">Locations</div>
      <ul class="list">
        <li>
            <label>
            <input type="checkbox" name="city" value="2" class="">
            <i class="fas fa-check"></i>
            <span>Antalya</span>
            </label>
            <ul class="sub" style="display: block;">
                <li class="sub-head">Regions</li>
                <li>
                    <label>
                    <input type="checkbox" name="region" value="3" class="">
                    <i class="fas fa-check"></i>
                    <span>Alanya</span>
                    </label>
                    <ul class="sub" style="display: block;">
                        <li class="sub-head">Neighborhoods</li>
                        <li>
                            <label>
                            <input type="checkbox" name="nhood" value="5" class="">
                            <i class="fas fa-check"></i>
                            <span>Avsallar</span>
                            </label>    
                        </li>
                        <li>
                            <label>
                            <input type="checkbox" name="nhood" value="6">
                            <i class="fas fa-check"></i>
                            <span>Bektas</span>
                            </label>    
                        </li>
                        <li>
                            <label>
                            <input type="checkbox" name="nhood" value="7">
                            <i class="fas fa-check"></i>
                            <span>Buyukhasbahce</span>
                            </label>    
                        </li>
                        <li>
                            <label>
                            <input type="checkbox" name="nhood" value="28">
                            <i class="fas fa-check"></i>
                            <span>Pazarci</span>
                            </label>    
                        </li>
                    </ul>      
                </li>
            </ul>
        </li>
    </ul>
</div>

Please help me.

/* accordion for filter */
$(".section [type='checkbox']").on("change", function(e) {
e.preventDefault();
var $this = $(this);

if(!$this.hasClass("accordion-active")) {
  $($this).closest('label').next().show();
}else{
  $($this).closest('label').nextAll().has(":checkbox").first().find(":checkbox").prop('checked', false);
$($this).closest('label').nextAll().has(":checkbox").first().find(":checkbox").removeClass("accordion-active");

   // I tried this code but failed
  // $($this).closest('li').nextAll().find(".sub").hide();
}

With these codes, I can make the checkboxes that come after the checkbox I clicked unchecked or delete some classes.

But what I want is to hide the lists with the .sub class that come after the checkbox I clicked.

frontend (vite) is not making api call to server properlly

i am using vite react,
From frontend which is running on localhost:3000, if i make a api call to backend which on localhost:5000, frontend always make a api call at port 3000 insted of 5000.enter image description here

below is how my code looks

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,  // Frontend runs on port 3000
    proxy: {
      '/api': {
        target: 'http://localhost:5000/',  // Backend running on port 5000
        changeOrigin: true,
        secure: false,
      },
    },
  },
});

Login.jsx

const LoginAdmin = () => {
  const formik = useFormik({
    initialValues: {
      email: '',
      password: '',
    },
    validationSchema: Yup.object({
      email: Yup.string().email('Invalid email address').required('Email is required'),
      password: Yup.string().required('Password is required'),
    }),
    onSubmit: async (values) => {
      try {
        const response = await axios.post('/api/admin/login', values);
        alert('Login successful!');
        console.log(response.data);
        localStorage.setItem('token', response.data.token);
      } catch (error) {
        console.error('Login error:', error);
        alert('Invalid credentials or account not active/approved.');
      }
    },
  });

  return ()
};


server.js

const app = express();

// Middleware
app.use(cors({
    origin: 'http://localhost:3000', // Allow requests from frontend
    credentials: true,  // Allow sending cookies or authentication tokens
  }));
app.use(express.json());

// Connect to MongoDB
connectDB();
// Use admin routes
app.use('/api/admin', adminRoutes);

// Basic route
app.get('/', (req, res) => {
    res.send('Hello from the ES6 backend, DB connected');
});

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

i checked form and Axios request are set up correctly.
also Ensured the backend endpoint exists and is correctly handling the request.
also Verified the proxy configuration in vite.config.js.

thinking it may be some silly error, even restart servers and system.

How to speed up program execution JS [closed]

I have this code:

module.exports = function (N, staff, K) {
    staff.sort((a, b) => b - a);
    let sliced = staff.slice(0, K);

    return sliced.slice(0, K).reduce((a, b)=>{
        return a+b
    }, 0);
}

I would like to hear your suggestions on how to speed up its execution as much as possible

Full screen videos/images with “scrollbar-gutter: stable both-edges” – CSS, HTML

I set “scrollbar-gutter: stable both-edges” for my website for a symmetric look (“scrollbar-gutter: stable” seems to create a slightly skewed look to me) but now I need to display a video that covers the whole screen including the space on the left created by “both-edges” – the scrollbar itself on the right is fine. What would be the best way to do this?

I thought of just using “scrollbar-gutter: stable” instead and then manually adding the scrollbar width on the left for each element, but it seems that the only way to get the actual width of the scrollbar would be to use JavaScript (How can I get browser scrollbar width?). This seems to me like it might not be the best practice – adjusting a very basic property of the whole page, moving all the content with JS. But this is just a sort of a feeling not based on anything rational and I am very new to web development so is probably completely wrong. Would be grateful for any advice.

How to bypass a non official API blockage?

This governmental bank offers free exchange rate API access. But while their specs mention neither limitations nor any requirements, in effect they seem to block:

  1. Server-side fetching from shared hosting – it gets a 404 error. But the PHP code below does work for me from a dedicated server and also from localhost server.
  2. Client-side fetching – it gets a CORS error, which I assume is due to not having a Access-Control-Allow-Origin header.

I’ve tried asking them about limitations which they might not have bothered to document, but they’re unresponsive. So is there any modification to the codes below (e.g. adding certain headers to stream_context_create and fetch) that might bypass either of this?

P.S.
Don’t be tempted to refer to
scraping from in between specific identifiable tags from xml as it discusses their previous (now obsolete) API.

The codes below try to retrieve JSON data from that API.

Server-side fetching

<?php
    $url = "https://edge.boi.org.il/FusionEdgeServer/sdmx/v2/data/dataflow/BOI.STATISTICS/EXR/1.0/?c%5BDATA_TYPE%5D=OF00&startperiod=2024-09-20&endperiod=2024-09-20&format=sdmx-json";
    $cparams = array(
      'http' => array(
      'ignore_errors' => true,
      )
    );

    $context=stream_context_create($cparams);
    $content = file_get_contents($url, context: $context);
    echo '<a href="' . $url . '" target="_blank">' . $url . '</a>';
    echo '<hr>';
    echo '<pre>' . print_r($http_response_header, true) . '</pre>';
    echo '<hr>';
    if (function_exists('json_validate'))
    echo "It's " . (json_validate($content) ? '' : 'NOT') . ' JSON';
    else {
    $json_data_formatted = json_decode($content);
    echo "It's " . ((json_last_error() === JSON_ERROR_NONE) ? '' : 'NOT') . ' JSON';
    }
    echo '<hr>';
    echo '<textarea rows=30 cols=150>' . $content . '</textarea>';
?>

Client-side fetching
(don’t try to run it here since this site blocks fetch in general)

    const url = "https://edge.boi.org.il/FusionEdgeServer/sdmx/v2/data/dataflow/BOI.STATISTICS/EXR/1.0/?c%5BDATA_TYPE%5D=OF00&startperiod=2024-09-20&endperiod=2024-09-20&format=sdmx-json";

    // Update the link element
    document.getElementById('link').href = url;
    document.getElementById('link').textContent = url;

    // Fetch the content
    fetch(url)
      .then(response => {
        // Save the headers to display later
        let headers = '';
        for (let [key, value] of response.headers.entries()) {
          headers += `${key}: ${value}n`;
        }
        document.getElementById('headers').textContent = headers;

        // Check if the response is valid JSON
        return response.text().then(text => {
          try {
            const jsonData = JSON.parse(text);
            document.getElementById('json-status').textContent = "It's valid JSON";
            document.getElementById('content').value = JSON.stringify(jsonData, null, 2); // Pretty print JSON
          } catch (error) {
            document.getElementById('json-status').textContent = "It's NOT JSON";
            document.getElementById('content').value = text; // Show raw content if not JSON
          }
        });
      })
      .catch(error => {
        document.getElementById('json-status').textContent = "Failed due to " + error;
      });
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fetch API Example</title>
</head>
<body>
  <a id="link" href="#" target="_blank">Link</a>
  <hr>
  <pre id="headers"></pre>
  <hr>
  <p id="json-status"></p>
  <hr>
  <textarea id="content" rows="30" cols="150"></textarea>
</body>
</html>

Algorithmic Color Palette with chroma.js and Hue Shifting

I’m using chroma.js to generate color palettes for a specific hue and saturation value. i.e. it vaires lightness according to the number passed in the colors(10) chained function call and travels through the color space as specified by the mode() chained function call.

In my research, it’s important to hue shift colors as they approach different lightness levels.

Where my knowledge falls short is how to determine in which direction the hue should shift? Does it depend on the original hue, or is there some procedure to always add/subtract hue value as lightness goes up and likewise subtract/add as lightness goes down?

I’d like to add another parameter here hueShiftAmount or even startingHue and endingHue but I’m not sure what logical defaults might be for those.

  function generateColorPalette(hue: number, saturation: number) {
    const colors = chroma
      .scale([
        chroma.hsl(hue, saturation / 100, 0.9), // lighter
        chroma.hsl(hue, saturation / 100, 0.1), // darker
      ])
      // .padding([0.1, 0.1])
      .correctLightness()
      .mode(colorSpaceStore.value)
      .colors(10);

    return colors.map((hex) => {
      const hslColor = chroma(hex).hsl();

      // round
      hslColor[0] = Math.round(hslColor[0]);
      hslColor[1] = Math.round(hslColor[1] * 100);
      hslColor[2] = Math.round(hslColor[2] * 100);

      return {
        hex,
        hsl: hslColor,
      };
    });
  }

Here’s one idea that I had:

  function generateColorPalette(hue: number, saturation: number) {
    const HUE_SHIFT = 10; // example of hue shifting.
    const colors = chroma
      .scale([
        chroma.hsl(hue + HUE_SHIFT, saturation / 100, 0.9), // lighter
        chroma.hsl(hue - HUE_SHIFT, saturation / 100, 0.1), // darker
      ])
      // .padding([0.1, 0.1])
      .correctLightness()
      .mode(colorSpaceStore.value)
      .colors(10);

    return colors.map((hex) => {
      const hslColor = chroma(hex).hsl();

      // round
      hslColor[0] = Math.round(hslColor[0]);
      hslColor[1] = Math.round(hslColor[1] * 100);
      hslColor[2] = Math.round(hslColor[2] * 100);

      return {
        hex,
        hsl: hslColor,
      };
    });
  }

Any body with a strong background in color theory can advise me?

I have been enjoying this article about algorithmic color palette generation at stripe but not sure exactly how I should implement the hue shifting.