How to invoke class-validator on a class itself

Validators are typically invoked on class variables, not on the class itself. Is it possible to apply a validator to a class? I’m trying to use a decorator as a clean solution that can also be used elsewhere. We want to define certain properties that atleast one of them should exist directly on class?

import {
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';

@ValidatorConstraint({ async: false })
export class AtLeastOneOf implements ValidatorConstraintInterface {
  validate(_, args: ValidationArguments) {
    const properties = args.constraints;
    const value = args.object as any;

    return properties.some(property => value[property] !== undefined && value[property] !== null);
  }

  defaultMessage(args: ValidationArguments) {
    const properties = args.constraints;
    return `At least one of the following properties must be provided: ${properties.join(', ')}.`;
  }
}

export function AtLeastOneField(properties: string[], validationOptions?: ValidationOptions) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      name: 'AtLeastOneField',
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: properties,
      validator: AtLeastOneOf,
    });
  };
}


@AtLeastOneField(['photoId', 'userId']) // not work here
export class ListUsers {
  @IsID()
  @IsOptional()
  userId?: string;

  @IsID()
  @IsOptional()
  accountId?: string;

  @IsID()
  @IsOptional()
  photoId?: string; 

}

I want to write a code to create an interactive coffee ratio calculator for a wordpress blog

I am trying to create a coffee ratio calculator. My slider works to select the ratio, but the amount of coffee does not calculate how much water to use or interact with the ratio selected. Here is my broken code:

When I change the amount of coffee in the input field, the recommended water amount does not update to reflect the selected ratio. How can I fix this issue so that the coffee amount interacts properly with the selected ratio to calculate the water amount?

<!DOCTYPE html>
<html>

<head>
  <title>Coffee Ratio Calculator</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    
    .calculator {
      max-width: 600px;
      margin: auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    
    .result {
      margin-top: 20px;
      font-weight: bold;
    }
    
    .slider {
      width: 100%;
    }
    
    .input-section {
      margin-bottom: 20px;
    }
    
    .slider-labels {
      display: flex;
      justify-content: space-between;
    }
  </style>
</head>

<body>

  <div class="calculator">
    <h2>Coffee Ratio Calculator</h2>
    <p>Adjust the coffee-to-water ratio using the slider and enter the amount of coffee you want to use. The calculator will display the recommended amount of water based on the selected ratio.</p>

    <div class="input-section">
      <label for="ratio">Select Coffee Strength:</label>
      <div class="slider-labels">
        <span>1:12</span>
        <span>1:15</span>
        <span>1:18</span>
      </div>
      <input type="range" id="ratio" name="ratio" min="12" max="18" value="15" step="0.1" class="slider" oninput="updateRatio(this.value)">
      <div id="selectedRatio">Selected Ratio: 1:15</div>
    </div>

    <script>
      function updateRatio(value) {
        document.getElementById('selectedRatio').innerText = 'Selected Ratio: 1:' + parseFloat(value).toFixed(1);
      }
    </script>

    <div class="input-section">
      <label for="coffeeAmount">Amount of Coffee (grams):</label>
      <input type="number" id="coffeeAmount" value="12" min="1" oninput="calculateWater()">
    </div>

    <div class="result">
      <p>Recommended Water Amount: <span id="waterAmount">180</span> grams</p>
    </div>
  </div>

  <script>
    function updateRatio(value) {
      document.getElementById('selectedRatio').innerText = 'Selected Ratio: 1:' + value;
      calculateWater();
    }

    function calculateWater() {
      var ratio = document.getElementById('ratio').value;
      var coffeeAmount = document.getElementById('coffeeAmount').value;
      if (coffeeAmount === '') {
        coffeeAmount = 0;
      }
      var waterAmount = coffeeAmount * ratio;
      document.getElementById('waterAmount').innerText = waterAmount.toFixed(1);
    }

    document.addEventListener('DOMContentLoaded', function() {
      calculateWater(); // Initial calculation on page load
    });
  </script>

</body>

</html>

Change H2’s with a certain class to H3

I don’t understand javascript (or jquery) AT ALL so I’m hoping someone can help. I need to change some h2’s into h3’s. I can’t do it at the source as they’re inside a gallery template and cannot be altered.

I only want to target h2’s within this class ‘.collection-668efa708d9ccb52d149b0b1.view-item’

and the h2’s themselves have a class of ‘list-item-content__title’

I’ve looked online and came up with the code below, but as I said, I don’t know what I’m doing. If someone could let me know the correct code I would be very grateful.

<script>
function changeHTMLTag()
{
    var el = document.querySelector('.collection-668efa708d9ccb52d149b0b1.view-item h2.list-item-content__title');
    el.outerHTML = '<h3>' + el.innerHTML + '</h3>';
}

Setting Cookies for External Website from Angular Application

I want to load a external website and need to set cookies for that in order to pass the context. In my flutter application I am opening a web view and setting cookies for that. Is it possible to do the same in a Angular Application. what are the possible ways?

I did try to load the website usign Iframes but seems like it doesn’t allow to open that specific website due to this error Refused to frame ‘https://example.com/’ (for ex) because an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘self’.

Get the first character making a regular expression test fail [closed]

I use the following function to examine whether an entry contains invalid characters. The regular expression test() function return false when the input string contains excluded character(s). Is there any way to return the first character/character(s) making the test fail?

    function isContainInvalidCharacter(str) {
    //--- Allowable characters in string a-z, A-Z, 0-9, Space @,.$)/(-%:
    if ( /^[A-Za-z0-9p{sc=Hani}s,.@$)/(%:-]+$/u.test(str) == false) {
        return true;
    } else
        return false;
}

Data table not working in jquery ajax response

I want to show data in a pop-up using data-tables. I am building pop-up on click event and when I get success response from AJAX Request then I want to show that data in data-tables format(pagination, search, export).

Here is my AJAX success Code –

success: (response) => {
                if ($.fn.DataTable.isDataTable('#dataTable2')) {
                    $('#dataTable2').DataTable().destroy();
                }
                $('#dataTable2 tbody').empty();

                $('#dataTable2').DataTable({
                    dom: '<"datatable-header"lBfrtip>',
                    lengthMenu: [
                        [10, 25, 50, -1],
                        [10, 25, 50, "All"]
                    ],
                    buttons: [{
                        extend: 'collection',
                        text: 'Export',
                        buttons: ['copy', 'csv', 'print']
                    }],
                    initComplete: function() {
                        $('.dt-buttons').css({
                            'position': 'absolute',
                            'top': '15px',
                            'right': '100px'
                        });
                    }
                });

                document.getElementById('lightbox').style.display = 'block';
                $('#dataTable2').addClass('js-dataTable');
                $('#dataTable2').html(response);
                $('#lightbox').show();

            }

HTML code –

<div id="lightbox">
            <div id="lightbox-content">
                <span class="close" onclick="closeLightbox()">&times;</span>
                <div class="row mt-4">
                    <div class="col-md-12 table-container">
                        <table id="dataTable2" class="table table-hover table-striped no-footer" aria-describedby="dataTable_info">
                        </table>
                    </div>
                </div>
            </div>
        </div>

Error –

Uncaught TypeError: Cannot read properties of undefined (reading 'aDataSort')
    at _fnSortFlatten (backend.js?id=45e6969aba26e99cc456499f7b307f41:193000:35)
    at _fnSortingClasses (backend.js?id=45e6969aba26e99cc456499f7b307f41:193338:13)
    at loadedInit (backend.js?id=45e6969aba26e99cc456499f7b307f41:188170:4)
    at HTMLTableElement.<anonymous> (backend.js?id=45e6969aba26e99cc456499f7b307f41:188269:4)
    at Function.each (backend.js?id=45e6969aba26e99cc456499f7b307f41:127655:19)
    at jQuery.fn.init.each (backend.js?id=45e6969aba26e99cc456499f7b307f41:127477:17)
    at jQuery.fn.init.DataTable [as dataTable] (backend.js?id=45e6969aba26e99cc456499f7b307f41:187821:7)
    at $.fn.DataTable (backend.js?id=45e6969aba26e99cc456499f7b307f41:202685:17)

NgbModal how to make the modal appear from right to left instead of default top to bottom

I’m using NgbModal and there the Modal is opening from Top to Bottom by default when opening. Is it to possible to make it appear from right to left. I have set up the positioning already such that it is at the right corner of the screen. But cannot figure out the direction of opening

I looked at their API but couldn’t find an option for direction.
https://ng-bootstrap.github.io/#/components/modal/examples

Here is stackblitz of their first example which could be a minimum reproducible example

I also found this answer which uses pure bootstrap and not abstraction like ng bootstrap, so not sure how it can be applied to NgbModal

<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Profile update</h4>
    <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Crossclick')"></button>
  </div>
  <div class="modal-body">Modal Content</div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-secondary" (click)="modal.close('Save click')">
      Save
    </button>
  </div>
</ng-template>

<button class="btn btn-lg btn-outline-primary" (click)="open(content)">
  Launch demo modal
</button>

<hr />

<pre>{{ closeResult }}</pre>
  open(content: TemplateRef<any>) {
    this.modalService
      .open(content, {
        ariaLabelledBy: 'modal-basic-title',
        animation: true,
      })
      .result.then(
        (result) => {
          this.closeResult = `Closed with: ${result}`;
        },
        (reason) => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        }
      );
  }

Help much appreciated

XHR Data Transfer Between Javascript and PHP

  1. JS dispatch was successful. But it does not enter the if block in PHP. Whereas before I restarted the computer successfully entered the if block in PHP.

  2. When successful, the data received is “1”. Even though I have set the static data sent is “4”.

Javascript code:

                let xhr = new XMLHttpRequest();
                let dataStorage = new FormData();
                dataStorage.append('dataStorage', 4);

                console.log("Data yang dikirim:", dataStorage.get('dataStorage'));

                xhr.open('POST', 'sistemDB.php', true);
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        console.log("AJAX request completed with status: " + xhr.status);
                        // console.log(xhr.responseText);
                    } else {
                        console.log("AJAX request failed with status: " + xhr.status);
                    }
                };
                xhr.onerror = function() {
                    console.log("Request failed");
                };
                xhr.send(dataStorage);
                console.log("Send berhasil");

PHP code:

                                <?php
                                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                                    echo '<pre>';
                                    var_dump($_POST); // Display all POST data
                                    echo '</pre>';

                                    // Alternative way to check raw POST data
                                    echo '<pre>';
                                    echo 'Raw POST data: ' . file_get_contents('php://input');
                                    echo '</pre>';

                                    if (isset($_POST['dataStorage'])) {
                                        $data = $_POST['dataStorage'];
                                        echo htmlspecialchars($data); // Use htmlspecialchars to prevent XSS attacks
                                    } else {
                                        echo 'dataStorage not set';
                                    }
}
?>

Please help me

I am trying to change the static value to send to PHP, to a value of “4”

Notes: php and javascript scripts are located in the same file “systemDB.php”.

Issue with Safari and Service Worker Push Notification Opening Window

I’m adding push notifications to my React Web App and I’m having some issues with Safari. First here is the click event listener in my service worker js file (sw.js):

self.addEventListener('notificationclick', (event) => {
  const data = event.notification.data;
  const url = data.url || 'http://localhost:3356';

  console.log({ data, url });

  event.notification.close();

  event.waitUntil(
    self.clients
      .matchAll({
        type: 'window',
        includeUncontrolled: true,
      })
      .then((clientList) => {
        console.log('total clients: ', clientList.length);
        for (const client of clientList) {
          console.log({ clientUrl: client.url });
          if (client.url === url + '/' && 'focus' in client)
            return client.focus();
        }
        if (self.clients.openWindow) {
          console.log('Opening a new window', url);
          return self.clients.openWindow(url);
        }
        console.log('No clients to focus');
        return;
      })
      .catch((error) => console.log({ error }))
  );

This is mostly working fine specially in chrome. However the issue I’m having in Safari is that if the web app is not open in any window and/or tab when I click on the notification, safari does not open the web app I’m taken to the last active tab/window. If I have multiple tabs open and one of the tabs is the WebApp then Safari switches and focuses to the correct tab. But it seems that clients.openWindow is not working. the Log Message ‘Opening New Window’ does show up and no error logs shows up.

Any help would be greatly appreciated. Thanks

html2canvas 1.4.1 screenshot error element using background-image:data:image/svg+xml;base64,

I use the html2canvas library to capture screenshots by passing in a className and save the image file as a blob. However, when the image is saved or downloaded, there is an issue with elements that have background-image: url(data:image/svg+xml;base64,…) (SVG image), but PNG images are not affected. I am using html2canvas version 1.4.1.

  function captureImg(className) {
        const bannerElement = document.querySelector('.' + className);
        return html2canvas(bannerElement, {
            scale: 2,
            backgroundColor: null,
        }).then(canvas => {
            return new Promise((resolve, reject) => {
                canvas.toBlob(blob => {
                    if (blob) {
                        const file = new File([blob], 'banner-screenshot.png', {
                            type: 'image/png'
                        });
                        resolve(file);
                    } else {
                        reject(new Error('Failed to convert canvas to blob'));
                    }
                }, 'image/png');
            });
        }).finally(() => {

        }).catch(error => {
            console.error('Error capturing the banner:', error);
        });
    }

    function captureImgNow() {
        captureImg('basic-box').then(file => {
            const formData = new FormData();
            formData.append('file_img', file);
            formData.append('error_now', error_now);
            formData.append('user_learn_id', user_learn_id);
            formData.append('lesson_id', lesson_id);
            formData.append('detail_id', detail_id);
            formData.append('type', 'wrong');
            formData.append('max_error', max_error);
            $.ajax({
                url: '/save-user-note-exam-failed',
                method: 'POST',
                contentType: 'application/json',
                data: formData,
                contentType: false,
                processData: false,
                cache: false,
                success: function (response) {
                    console.log('captureImgNow');
                },
                error: function (xhr) {
                }
            });
        })
    }

This is the image I want
Desired image
This is result
Result image
This this CSS
CSS image

I tried dom-to-image, but the speed is quite slow and not suitable for my project.

 <img width="200px" height="200px" style="z-index: 1000; position: absolute; top: 50%; left: 50%;" src="<%= item.image_background_gray == null ? item.image_background : item.image_background_gray%>" alt="test">

This is image test
test img
This is result test
Result test

Update the array based on Checkbox status in ReactJs

I want to update the filterCandidates array based on the total experience of the candidate when the selected checkbox is checked and remove the candidate data from the array when unchecked, below is the code snippet

import { useState } from "react";

function ExperienceFilter({ candidates }) {
  const [filteredCandidates, setFilteredCandidates] = useState([]);
  const experienceOptions = [
    { value: "1-2", label: "1-2 Years" },
    { value: "3-4", label: "3-4 Years" },
    { value: "5-6", label: "5-6 Years" },
    { value: "7-8", label: "7-8 Years" },
    { value: "9-10", label: "9-10 Years" },
  ];

  function handleChange(e) {
    const { value, checked } = e.target;
    const experiencedCandidates = candidates.filter(
      (candidate) => candidate.totalExperience == value
    );

    if (checked) {
      setFilteredCandidates([...filteredCandidates, experiencedCandidates]);
    }

    if (!checked) {
      setFilteredCandidates((prev) => prev.totalExperience != value);
    }
  }
  return (
    <div>
      <div class="flex flex-col space-y-3 bg-green-600  px-5 pr-20 py-10">
        <div>Years of Experience</div>
        {experienceOptions.map((option, index) => (
          <label key={index}>
            <input
              type="checkbox"
              value={option.value}
              name={option.label}
              onChange={handleChange}
            />
            {option.label}
          </label>
        ))}
      </div>
    </div>
  );
}

export default ExperienceFilter;

How use 3rd party plugins with standalone Prettier API?

I’m writing a web extension to use at work that converts text into formatted code blocks using Prism and Prettier. We primarily use TypeScript and Java. Since the TypeScript plugin is included in Prettier, implementing that was easy enough. However, the Java plugin is 3rd-party and I cannot find any instructions on how to implement it with standalone Prettier.

No matter what I try, the farthest I’ve gotten is seeing ConfigError: Couldn't resolve parser "java". Plugins must be explicitly added to the standalone bundle. in the browser console.

The included plugins can be simply imported with a require() statement. However, trying this with the java plugin throws Error: Can't walk dependency graph: Cannot find module 'prettier-plugin-java' from 'C:UserschrisWebstormProjectsagility-code-chunksformat.js' during the build. I have tried both require("prettier-plugin-java") and require(./node_modules/prettier-plugin-java).

From there, I pivoted to trying a .prettierrc.json/.prettierrc.js, but it doesn’t seem to register either, I assume because I am using the API and not the CLI.

Here is my current state (testing in a dummy HTMl before implementing in the extension):

codeblock.html

<html style="background-color: #fff">
<head>
    <link href="themes/prism.css" rel="stylesheet"/>
    <title>Code Block</title>
    <header></header>
    <script src="bundle.js"></script>
</head>
<body>
<header data-plugin-header="show-language"></header>
<pre><code class="language-java">
<!--  Purposefully formatted poorly to ensure Prettier is working  -->
      package com.example;

    public class Main {

        public static void main(String[] args) {
                        System.out.println("Hello World!");

                }
    }
</code></pre>
<script src="prism.js"></script>
</body>
</html>

format.js

const prettier = require("prettier");
const typescript = require("./node_modules/prettier/plugins/typescript");
const babel = require("./node_modules/prettier/plugins/babel");
const estree = require("./node_modules/prettier/plugins/estree");
const html = require("./node_modules/prettier/plugins/html");
const markdown = require("./node_modules/prettier/plugins/markdown");
const postcss = require("./node_modules/prettier/plugins/postcss");
const yaml = require("./node_modules/prettier/plugins/yaml");

/* Takes in code string and language and attempts to reformat using Prettier API */
async function formatCode(code, language) {
    try {
        let parser = language;

        return await prettier.format(code, {
            organizeImportsSkipDestructiveCodeActions: true,
            parser: parser,
            plugins: [typescript, babel, estree, html, markdown, postcss, yaml],
            tabWidth: 2,
            useTabs: true,
            semi: true,
            singleQuote: false,
            trailingComma: "none",
            bracketSpacing: true,
            arrowParens: "always",
        });
    } catch (error) {
        console.error("Error formatting code:", error);
        return code;
    }
}

/* Grabs the code chunk from the HTML, parses the code (text) and language from it, and calls formatCode() */
setTimeout(async () => {
    for (const code of document.querySelectorAll("code")) {
        const language = code.className.replace("language-", "");
        if(language != null && language.trim() !== "") {
            code.parentElement.style.setProperty("--before-content", `'${language.toUpperCase()}'`);
            code.innerText = await formatCode(code.innerText, language);
        }
    }

    Prism.highlightAll();
}, 1000)

build.js

const browserify = require('browserify');
const fs = require('fs');

browserify(['format.js'])
    .transform('babelify', { presets: ['@babel/preset-env'] })
    .bundle((err, buf) => {
        if (err) {
            console.error(err);
        } else {
            fs.writeFileSync('bundle.js', buf);
        }
    });

package.json

{
  "name": "agility-code-chunks",
  "version": "1.0.0",
  "description": "web extension to format code chunks in agility",
  "main": "popup.js",
  "scripts": {
    "build": "node build.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "nop990",
  "license": "MIT",
  "devDependencies": {
    "@babel/preset-env": "^7.25.2",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0",
    "google-java-format": "^1.3.2",
    "prettier": "3.2.5",
    "prettier-plugin-java": "2.6.4",
    "prettier-plugin-organize-imports": "4.0.0"
  },
  "dependencies": {
    "java-parser": "^2.3.2"
  }
}

Change style on MouseOver event in reactJS

I’ve just started learinng react and i dont get that why setHeadingText changes the color onMouseOver event but setColor doesn’t

import React from "react";

function App() {
  const [headingText, setHeadingText] = React.useState("Hello");
  const [color, setColor] = React.useState("white");
  function mouseOver() {
    setColor("black");
    setHeadingText("Yo");
  }
  function mouseOut() {
    setColor("white");
    setHeadingText("Bye");
  }
  return (
    <div className="container">
      <h1>{headingText}</h1>
      <input type="text" placeholder="What's your name?" />
      <button
        style={{ backgroundColor: { color } }}
        onMouseOver={mouseOver}
        onMouseOut={mouseOut}
      >
        Submit
      </button>
    </div>
  );
}

It works if i use conditional like

const [mouseOver, setMouseOver]=useState(false);
function MouseOver(){
setMouseOver(true);
}

and then

style={{backgroundColor: MouseOver ? "black":"white"}}

but why it doesnt work like that what am i doing wrong??

await Promise.all is not working as expect in a for-loop in nodejs [duplicate]

I got the correct print result, but the print time was not as expected, and my expected result was about one log every second in nodejs

const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 1'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 2'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 3'));
const promise4 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 4'));
const promise5 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 5'));
const promise6 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 5'));
const promise7 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 7'));
const promise8 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 8'));
const promise9 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 9'));
const promise10 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 10'));

const promiseArrays = [
    [promise1, promise2],
    [promise3, promise4],
    [promise5, promise6],
    [promise7, promise8],
    [promise3, promise4],
    [promise9],
    [promise10]
];

async function inOrder() {
    
    for (const promiseArray of promiseArrays) {
        const res = await Promise.all(promiseArray)
        console.log(res.join(""))

        if (res.join("") === 'Promise 9') {
            break
        }
    }
}

inOrder()

I got the correct print result, but the print time was not as expected, and my expected result was about one log every second in nodejs

await Promise.all is not working as expect in a for-loop [duplicate]

const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 1'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 2'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 3'));
const promise4 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 4'));
const promise5 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 5'));
const promise6 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 5'));
const promise7 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 7'));
const promise8 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 8'));
const promise9 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 9'));
const promise10 = new Promise((resolve) => setTimeout(resolve, 1000, 'Promise 10'));

const promiseArrays = [
    [promise1, promise2],
    [promise3, promise4],
    [promise5, promise6],
    [promise7, promise8],
    [promise3, promise4],
    [promise9],
    [promise10]
];

async function inOrder() {
    
    for (const promiseArray of promiseArrays) {
        const res = await Promise.all(promiseArray)
        console.log(res.join(""))

        if (res.join("") === 'Promise 9') {
            break
        }
    }
}

inOrder()

I got the correct print result, but the print time was not as expected, and my expected result was about one log every second

I got the correct print result, but the print time was not as expected, and my expected result was about one log every second