Tiled gallery of images without empty spaces

I have a set of images that have different widths and heights, their height to width ratios are not the same. Is it possibly to make a tiled gallery of these images without any space between rows or columns ie. with completely 100% fill a div with images using only CSS? Leaving space on the last row would be fine but it would be better to have none.

Otherwise I have to use Javascript to make some kind of mosaic row column sorter that adjusts image widths and heights to fill rows and columns. I could use equal row heights and multiple spanning containers in some areas.

So my question is, is this layout possible with only CSS or do I have to use JS?

Yup validation of a nested field

Im building validation scheme and need to make one field required dependent on the value of another field, but validation doesnt work

Heres code example

export const schema = yup.object().shape({
    parentField: yup.object().shape({
        field1: yup.number(),
        field2: yup
            .array()
            .nullable()
            .of(
                yup
                    .object()
                    .nullable()
                    .shape({
                        nestedField1: yup
                            .string()
                            .max(64)
                            .default(null)
                            .when('parentField.field2.nestedField2', {
                                is: (val) => val !== null && val !== '',
                                then: yup.string().required("nestedField2 is required"),
                            }),
                        nestedField2: yup
                            .string()
                            .nullable()
                            .default(null)
                            .when('parentField.field2.nestedField1', {
                                is: (val) => val !== null && val !== '',
                                then: yup.string().required("nestedField1 is required"),
                            }),
                    })
            )
}, [['parentField.field2.nestedField1', 'parentField.field2.nestedField2']]);

Its just doesnt trigger validation and i cant find proper explanation on how to validate nested fields like this in yup

Google Tag Manager Tag for custom script is not firing even though trigger has fired

The Problem is pretty much in the title.
I have been trying to do a simple script insertion for a customer of mine for a while now, but the tag is not firing, even though the trigger has been fired, there are not blocking triggers and the firing options are set to once per event.
As far as i can tell from the Google Tag Deployment Rectriction List that’s not the problem either. The website explicitly whitelists “google” and “img” and only blacklists “adm”, “sp”, “gcs” and “opt”, which shouldn’t interfere with my script tag as far as I’m aware.

enter image description here

I have already tried a number of different ways to trigger the tag and also tried switching up the firing options but it still refuses to fire and implement the script.
When I try implementing another tag type it works, so there HAS to be a problem with the script tag and the blacklist, but I can’t figure out what exactly is blocking the script tag.

How to spy on Vue composable inner function that is called inside another function inside composable?

The project is using Vue, Vitest and Vue Test Utils. I am new to UI unit testing and I need to test that when one function from composable is called, then the other function should have been called.

My functions look something like this (details omitted):


export function useHelper() {

  async function wait(milliseconds: number): Promise<void> {
    return await new Promise<void>(resolve => setTimeout(() => resolve(), milliseconds));
  }

  async function executeInBatches(delay = 0) {
    if (delay) {
      await wait(delay);
    }
  }

return {
    executeInBatches,
    wait,
  };
}


My unit test is next:


beforeEach(() => {
  vi.useFakeTimers({shouldAdvanceTime: true});
});

afterEach(() => {
  vi.useRealTimers();
  vi.clearAllMocks();
});


 it('should call function wait when delay is provided', async () => {
      const composable = useHelper();
      const waitSpy = vi.spyOn(composable, 'wait');
      const delay = 100;

      await executeInBatches(delay);
      vi.advanceTimersByTime(delay * 2);

      expect(waitSpy).toHaveBeenCalled();
    });

I do not understand why waitSpy does not work. If i do exactly same thing, but spy on window.setTimeout, which is called inside wait function, then the timeout spy correctly works.

Working example with spying on setTimeout:


 it('should call setTimeout when delay is provided', async () => {
      const composable = useHelper();
      const timeoutSpy = vi.spyOn(window 'setTimeout')
      const delay = 100;

      await executeInBatches(delay);
      vi.advanceTimersByTime(delay * 2);

      expect(timeoutSpy).toHaveBeenCalled();
    });

Could you please help, why does spying on composable does not work?

Thanks in advance

dom-to-image and web share api issue on iOS

This is my source code. I use the dom-to-image plugin to capture images for downloading or sharing. The download functionality works well in all environments. However, the Web Share API works perfectly on Android browsers, such as Chrome and Brave. On iOS browsers, like Safari and even Chrome, the image is incorrect on the first click, and you need to click twice to get the correct result, how to fix it on iOS.

function shareImage(id) {
  const content = document.getElementById(id);

  try {
    domtoimage.toBlob(content).then(blob => {
      const file = new File([blob], 'share.jpg', {
        type: 'image/jpeg'
      });

      if (navigator.share) {
        navigator.share({
            title: 'share test',
            files: [file]
          })
          .then(() => console.log('Successful share'))
          .catch((error) => console.error('Error sharing', error));
      } else {
        alert('not support');
      }
    });
  } catch (error) {
    console.error('convert error', error);
  }
}

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('btn_download').addEventListener('click', function() {
    domtoimage.toJpeg(document.getElementById('capture'), {
        quality: 0.95
      })
      .then(function(dataUrl) {
        const link = document.createElement('a');
        link.download = 'download.jpg';
        link.href = dataUrl;
        link.click();
      });

    return false;
  });

  document.getElementById('btn_share').addEventListener('click', shareImage.bind(null, 'capture'));
});
.canvas {
  background: #000;
  position: relative;
  transform: rotate(3deg);
  height: 400px;
  width: 400px;
}

.canvas img {
  max-width: 400px;
}

.canvas div {
  position: absolute
}

.el-p {
  filter: grayscale(100%);
}

.el-f {
  opacity: .5
}

.el-t {
  color: #fff;
  left: 28%;
  top: 70%;
  transform: skew(10deg, 0deg) rotate(10deg);
  font-size: 40px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css">
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-12 text-center">
      <div class="canvas" id="capture">
        <div class="el-p"><img src="https://picsum.photos/id/1/500/300" alt=""></div>
        <div class="el-f"><img src="https://i.imgur.com/bCgZZWA.png" alt=""></div>
        <div class="el-t">Nice!!!!!</div>
      </div>
      <div class="col-md-12 text-center mt-5">
        <button type="button" id="btn_download">download</button>
        <button type="button" id="btn_share">share</button>
      </div>
    </div>
  </div>
</div>

TypeError: Cannot read ‘register’ of undefined

Title:
TypeError: Cannot read ‘register’ of undefined

Description:
I’m developing a React application (kpiApp) using a specific framework. When I try to register my application, I encounter the following error in the browser console:
Uncaught TypeError: Cannot read properties of undefined (reading 'register') at (index):31:14 at Object.execCb (require.js:1696:33) at Module.check (require.js:883:51) at Module.<anonymous> (require.js:1139:34) at require.js:134:23 at require.js:1189:21 at each (require.js:59:31) at Module.emit (require.js:1188:17) at Module.check (require.js:938:30) at Module.<anonymous> (require.js:1139:34)
What I Have Tried:
Verified that applicationManager and other applications (connectApp, configurationApp, kpiApp) are correctly imported and initialized.
Added console logs before calling register to check if modules are loaded correctly.
Ensured require.js is correctly configured to load my modules.
Checked the script tags in index.html to ensure the required scripts are loaded in the correct order.

Code and Configuration:
pluginKpi.tsx:

import React, { useState } from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';
import applicationManager from '../../../framework/src/services/applicationManager';

import LineChart from './components/linechart';
import KpiPage from './components/kpipage';
import Source from './components/source';

const kpiicon = require('./components/assets/kpiicon.svg');

const App: React.FC<RouteComponentProps> = () => {
  const [selectedSource, setSelectedSource] = useState<string | null>(null);
  const [selectedKpi, setSelectedKpi] = useState<string | null>(null);

  return (
    <>
      <Source setSelectedSource={setSelectedSource} selectedSource={selectedSource} />
      <KpiPage selectedSource={selectedSource || ''} selectedKpi={selectedKpi} setSelectedKpi={setSelectedKpi} />
      <LineChart selectedSource={selectedSource} selectedKpi={selectedKpi} selectedTimeRange={'selectedTimeRange'} />
    </>
  );
};

const kpiApp = withRouter(App);

applicationManager.registerApplication({
  name: 'kpiApp',
  icon: kpiicon,
  rootComponent: kpiApp,
  menuEntry: 'kpiApp',
});

export default kpiApp;

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>kpi App</title>
</head>
<body>
  <div id="app"></div>
  <script type="text/javascript" src="./require.js"></script>
  <script type="text/javascript" src="./config.js"></script>
  <script>
    require(["app", "connectApp", "maintenanceApp", "configurationApp", "kpiApp"], function (app, connectApp, maintenanceApp, configurationApp, kpiApp) {
      console.log('connectApp:', connectApp);
      console.log('configurationApp:', configurationApp);
      console.log('kpiApp:', kpiApp);

      connectApp.register();
      configurationApp.register();
      kpiApp.register();

      app("./app.tsx").configureApplication({ authentication: "basic", enablePolicy: false });
      app("./app.tsx").runApplication();
    });
  </script>
</body>
</html>

Documentation or References:
I followed the documentation for creating and configuring a new application in the framework, making sure to adjust the packages.json, webpack.config.js, and index.html files as needed.

How to clone a div with dynamic values [duplicate]

i have a set of li that dynamically adding to page with jQuery draggable
every things work fine, now i added duplicate icon and onclick have clone my div:

   $(document).on('click', '.copy-question', function() {
                var newId = 123;
                var element = $(this).closest('li.FormItem');
                var newElement = element.clone();
                element.after(newElement);
    });

li content is:

<li class="FormItem text-field" data-id="sorting" data-me="1722453902890" type="text">
    <div class="field-actions">
        <a type="edit" class="toggle-form btn formbuilder-icon-pencil copy-question" data-id="1722453902890"
            title="duplicate">duplicate</a>
        <a type="remove" class="del-button btn formbuilder-icon-cancel delete-question" title="x">X</a>
    </div>
    <label class="field-label handle toplabel">(سورتینگ)</label>
    <span class="tooltip-element" style="display: none">?</span>
    <div class="frm-holder">
        <div class="form-elements">
            <input type="hidden" name="question[1722453902890][Qtype]" value="sorting" />
            <div class="form-group placeholder-wrap" style="display: block">
                <label>title</label>
                <div class="input-wrap">
                    <input name="question[1722453902890][label]" class="fld-label form-control" value="title"
                        type="text" />
                </div>
            </div>
            <div class="form-group name-wrap" style="display: block">
                <label>options</label>
                <div class="input-wrap">
                    <div class="sortable-options-wrap" style="height: auto">
                        <ol class="sortable-options">
                            <li class="ui-sortable-handle">
                                <input value="11" type="text" name="question[1722453902890][option][]" data-attr="label"
                                    class="option-label option-attr" />
                            </li>
                            <li class="ui-sortable-handle">
                                <input value="22" type="text" name="question[1722453902890][option][]" data-attr="label"
                                    class="option-label option-attr" />
                            </li>
                            <li>
                                <input value="33" type="text" data-attr="label" name="question[1722453902890][option][]"
                                    class="option-label option-attr" />
                                <a class="remove btn remove-option" style="right: unset; width: unset">X</a>
                            </li>
                        </ol>
                        <div class="option-actions">
                            <a data-count="1722453902890" class="add add-opt">+ </a>
                        </div>
                    </div>
                </div>
            </div>
            <a class="close-field d-none">بستن</a>
        </div>
    </div>
</li>

this li have some input that can dynamically add or remove and a filed with title
when i clone this, new values not clone to new element
and cloned element have old values of inputs
how can duplicate this li with all current dynamic rows and values? (like google form)
thanks all

i tried to get element with

   var element = document.getElementById('id'+oldId);
    var element = $(document).find('#id' + oldId);
    var element = document.querySelector('#id' + oldId);
    var element = $(document.getElementById('#id' + oldId));
    var newElemnt = $(this).closest('li.FormItem').clone(true,true); 
    var newElemnt =  $(this).closest('li.FormItem')[0].outerHTML;
    var str = $(this).closest('li.FormItem').clone().wrap('<div/>').parent().html();
    //console.log(newElemnt.prop('outerHTML'));
    console.log(element.outerHTML());
    console.log(newElemnt.prop('innerHTML'));
    //console.log(element.prop('outerHTML'));
    //console.log(element.prop('innerHTML'));
    //console.log($(this).closest('li.FormItem').html());
    // console.log(oldId);

but all of then return old values (fresh li)
and can not get new value of elements

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”.