How to add 20px to a span element’s width

i have a span element inside a container.
when the font weight of the text inside the span is set to 400px , the width of the span is 140px.
But when i change the text fontWeight to bold (700px) , the width of the span changes to 150px and that impacts the UX of the component because all the component change its width.

How to add extra space to a span element without adding margins or paddings so that when setting the text inside this span to bold, the span do not change its width ?

Thank you.

i tryed this css class but it did not work

span {
  display: inline-block;
  width: calc( 100% + 20px );
}

JavaScript, PWA, offline page

In my PWA application, I have an offline page with the following JavaScript listener:

<script>
    window.addEventListener('online', () => window.location.reload());
</script>

The listener works fine when the offline page is directly opened in the browser. However, when this page is opened inside an iframe, the code is unable to reload the page.

Please show how to improve the JavaScript code in order to be able to detect the parent iframe and, in this case, reload the parent page

How to pass an onChange function from a parent to child component in material UI?

I’m new to react and material UI and I’m trying to make a dropdown select component. I want to be able to pass onChange functions to the component from the parent, and I’ve followed the official documentation, but selecting the option doesn’t seem to do anything.

This is the child component:

export default function AutocompleteForm(props) {
  const {label, array, function} = props
  
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={array}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label={label}
      onChange={function} />}
    />
  )
}

I pass it a label, an array of options to display and an onChange function.

In the parent, I have this:

const Form = () => {
    const [value, setValue] = useState('')
    const handleSelect = (event, newvalue) => {
        console.log(newvalue)
        setLabel(newvalue)
      }
    const options = ['Option 1', 'Option 2', 'Option 3']
    
    return (
    <AutocompleteForm array={options} label="Pick an option" function={handleSelect}/>)

}

However, I don’t see the value from my handleSelect function displayed to the console, and the value is not updated either. I’m not sure what I’m doing wrong here, any tips would be appreciated!

How to correctly spy on setInterval using Jest in unit tests?

I am writing a react application, and also its unit test cases. I am facing a very odd scenario, wherein I am trying to spy on the setInterval ( or setTimeout ) which is placed inside a function, but it is not being called in my test

Following is my code :

// useInterval.js – Oversimplified version

export const useInterval = () => {
    setInterval(() => {
        console.log("called");
    }, 1000);
};

// useInterval.test.js

describe("Test Interval", () => {
    let spyOnSetInterval = null;
    
    beforeEach(() => {
        jest.useFakeTimers();
        spyOnSetInterval = jest.spyOn(global, 'setInterval'); 
    });

    afterEach(() => {
        jest.restoreAllMocks();
        jest.useRealTimers();
    });

    it("checking to see if setInterval is called", () => {
        useInterval(); // already imported in the current file.
        jest.advanceTimersByTime(1000);
        expect(spyOnSetInterval).toBeCalled();
    });
});

Output

expect(jest.fn()).toBeCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      18 |         usInterval();
      19 |         jest.advanceTimersByTime(1000);
    > 20 |         expect(spyOnSetInterval).toBeCalled();
         |                                  ^
      21 |     });
      22 | })

What am I doing wrong here ? If I spy on the console.log also which is inside the setInterval, it is never called. However, if I place console.log outside setInterval and spy on console.log, then it is working fine.

At the end, I need to write test cases to check that setInterval is being called.

Tried :

  •     jest.advanceTimersByTime(5000);  // To make sure setInterval is being called multiple times
    
  • jest.runAllTimers() // Even though this should not work since interval is infinite.
  • Tried using simon API but that also didnt work

PowerBI issue with visuals colors matching application

MS Power BI – colors of visuals from JS API does not match colors in application

I have tried applying theme but when I provided with needed colors it is always taking them from the top. I did not find no way to corelate colors with names/filters.
enter image description here
enter image description here

Besides that there is that gray box overlapping the visual. When i am forming a report i add 3 visuals:
a title, chart and border so this gray box is not one of them.

Any ideas what can be done to make colours of visuals always match these in application and where this gray box can come from?

Prisma Client Extensions – computed fields returns promise

The new Prisma client extensions provide a way to compute a custom field in the response.

e.g.

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient().$extends({
  result: {
    user: {
      // Add a computed field called `nameAndAge` to the user
      nameAndAge: {
        needs: {
          name: true,
          age: true,
        },
        compute(user) {
          return `${user.name} (${user.age}y)` + getdata();
        },
      },
    },
  },
});

const user = await prisma.user.findFirst();
console.log(user?.nameAndAge);

However, I want to call an async function from within the client like this:

async function getdata(){
  return "external data here!"
}

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient().$extends({
  result: {
    user: {
      // Add a computed field called `nameAndAge` to the user
      nameAndAge: {
        needs: {
          name: true,
          age: true,
        },
        compute(user) {
          return `${user.name} (${user.age}y)` + getdata();
        },
      },
    },
  },
});

const user = await prisma.user.findFirst();
console.log(user?.nameAndAge);

However, this always returns a promise and I can’t await the getdata() function in the return.

Is there a solution to this somehow ?

How to merge encrypted PDF into new one?

I have React app.

I have a feature to merge multiple PDFs into a new one and download it.

The case where one PDF has some kind of encryption (it’s visible in the browser but when try to merge it throws an error)

I am using PDF-merger package to merge pdf’s.

import PDFMerger from 'pdf-merger-js/browser';


 for (const f of dataFiles) {
    await merger.add(f);  // error is thrown if the file is encrypted
 }

Error message:

Error: Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.

Could I somehow merge this PDF and load the content properly? With some npm package or something like that?

Primeng dataView pagination and lazy load

I have an api that uses pagination to get products from a product database page of certain size and I want to implement a way to search trough the data with filters and display it in primeng dataview. Ideally what I would like is to set the products array as the value in dataview and when user searches for data it loads the first page and then when the user presses a new page in the pagination it get’s loaded into the array from the api. if the user moves back the data should already be in the array and retrieved from it instead of the api.

The code bellow is my attempt at getting it to work, but using onPage and LazyLoad at the same time causes 2 requests to be sent to the api and it keeps retrieving the same chunk of data for some reason. I am pretty new to angular so any other tips would also be appreciated.

search component

import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, ParamMap} from '@angular/router';
import {Observable} from 'rxjs';
import {switchMap} from 'rxjs/operators';
import {Title} from '@angular/platform-browser';

import {Product} from '../interface/product/product';
import {CategoryDto} from '../interface/category/category-dto';
import {BrandDto} from '../interface/brand/brand-dto';
import {CategoryService} from '../service/category/category.service';
import {BrandService} from '../service/brand/brand.service';
import {ProductService} from '../service/product/product.service';
import {LazyLoadEvent} from "primeng/api";

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
  @ViewChild('dataView') dataView: any;
  products: Product[] = []; // Array to store the retrieved products
  virtualProducts: Product[] = [];
  selectedSize = 40; // Number of products per page
  totalRecords = 0; // Total number of products
  nextPage = 0; // Current page number
  name?: string; // Name search parameter, adjust the type as per your requirement
  category = ''; // Category search parameter, adjust the type as per your requirement
  subcategory?: string; // Subcategory search parameter, adjust the type as per your requirement
  selectedBrands: string[] = []; // Brands search parameter, initialized as an empty array
  priceRange: number[] = [0, 4000]; // Price range search parameter, adjust the type as per your requirement
  subcategories: string[] = [];
  brands: string[] = [];
  sizeOptions: number[] = [5, 20, 40, 60, 80, 100, 200, 500];
  selectedPriceRange: number[] = [20, 1000];
  first = 0;
  loading: boolean = false;

  constructor(
    private categoryService: CategoryService,
    private brandService: BrandService,
    private productService: ProductService,
    private route: ActivatedRoute,
    private titleService: Title
  ) {
  }

  ngOnInit(): void {
    this.nextPage = 0;
    this.products = []
    this.virtualProducts = []
    console.log("ngOnInit")
    this.updateFilterValues();
    this.titleService.setTitle(this.category);
  }

  search(): void {
    this.productService
      .searchProducts({
        size: this.selectedSize,
        page: this.nextPage,
        category: this.category,
        subcategory: this.subcategory,
        brands: this.selectedBrands,
        priceRange: this.selectedPriceRange,
        name: this.name
      })
      .subscribe((value) => {
        this.products.push(...value.products)
        this.totalRecords = value.total_products;
        this.virtualProducts=[]
      });
  }

  onPageChange(event: any) {
    this.loading = true;
    const rowsPerPage: number = event.rows; // Number of rows per page
    const firstRecordIndex: number = event.first; // Index of the first record on the current page

    this.nextPage = Math.floor(firstRecordIndex / rowsPerPage);
    this.selectedSize = rowsPerPage;
    this.first = firstRecordIndex;

    if (firstRecordIndex === 0) {
      this.products = [];
    }
    this.search()
    setTimeout(() => {
      let loadedProducts = this.products.slice(firstRecordIndex, firstRecordIndex + rowsPerPage);
      this.virtualProducts.splice(this.first,0,...loadedProducts)
      event.forceUpdate;
      this.loading = false;
    }, 1000);
  }

  loadProducts(event: LazyLoadEvent) {
    this.loading = true;
    if (event.rows != null) {
      this.selectedSize = event.rows;
    }
    if (event.first != null) {
      this.first = event.first;
      if (this.first == 0) {
        this.products = [];
      }
    }
    this.nextPage = Math.floor(this.first / this.selectedSize);
    console.log(this.first)
    console.log(this.products.length)
    console.log(this.nextPage)
    this.search()
    setTimeout(() => {
      let loadedProducts = this.products.slice(this.first, this.first + this.selectedSize);
      this.virtualProducts.splice(this.first,0,...loadedProducts);
      event.forceUpdate;
      this.loading = false;
    }, 1000);

    this.loading = false;

  }

  private fetchCategories(category: string) {
    this.categoryService
      .getSubcategoriesByCategoryName(category)
      .subscribe((categories: CategoryDto[]) => {
        this.subcategories = categories.map((category: CategoryDto) => category.name);
      });
  }

  private fetchBrands(category: string) {
    this.brandService.getBrandsByCategoryName(category).subscribe((brands: BrandDto[]) => {
      this.brands = brands.map((brand: BrandDto) => brand.name);
    });
  }

  updateFilterValues(): void {
    this.route.paramMap
      .pipe(
        switchMap((params: ParamMap) => {
          const category = params.get('category');
          if (category) {
            this.category = category;
            this.fetchCategories(category);
            this.fetchBrands(category);
          }
          return new Observable<any>();
        })
      )
      .subscribe();
  }
}

search component html

<div class="flex-container">
  <div class="flex-item">
    <div class="p-inputgroup">
      <input type="text" class="p-inputtext" placeholder="Search" [(ngModel)]="name">
      <button class="p-button p-ripple" (click)="search()"><i class="pi pi-search"></i></button>
    </div>
  </div>
  <p-divider></p-divider>
  <div class="card flex">
    <span>Price Range: {{selectedPriceRange[0]}} - {{selectedPriceRange[1]}}</span><br><br>
    <p-slider [(ngModel)]="selectedPriceRange" [range]="true" [min]="priceRange[0]" [max]="priceRange[1]"
              aria-label="label_number"></p-slider>
  </div>
  <p-divider></p-divider>
  <div class="flex-item">
    <div>
      <p-dropdown [options]="subcategories" [(ngModel)]="subcategory" placeholder="Choose a Category"></p-dropdown>
    </div>
    <div>
      <p-multiSelect [options]="brands" [(ngModel)]="selectedBrands" placeholder="Choose Brands"></p-multiSelect>
    </div>
  </div>
</div>
<p-divider></p-divider>
<p-dataView #dataView [paginator]="true" [value]="virtualProducts" [lazy]="true"  [first]="first" [rows]="selectedSize" [totalRecords]="totalRecords"
            [pageLinks]="5" [rowsPerPageOptions]="sizeOptions" [loading]="loading" (onPage)="onPageChange($event)" (onLazyLoad)="loadProducts($event)">
  <ng-template let-product pTemplate="listItem">
    <div class="col-12">
      <div class="flex flex-column xl-flex-row xl-align-items-start p-4 gap-4">
        <div
          class="flex flex-column sm-flex-row justify-content-between align-items-center xl-align-items-start flex-1 gap-4">
          <div class="flex flex-column align-items-center sm-align-items-start gap-3">
            <a [routerLink]="['/product', product.id]">
              <div class="text-2xl font-bold text-900">{{ product.name }}</div>
            </a>
            <div class="flex align-items-center gap-3">
              <span class="flex align-items-center gap-2">
                <i class="pi pi-tag"></i>
                <span class="font-semibold">{{ product.subcategory }}</span>
              </span>
            </div>
          </div>
          <div class="flex sm-flex-column align-items-center sm-align-items-end gap-3 sm-gap-2">
            <span class="text-2xl font-semibold">{{ product.price + '€' }}</span>
            <button class="p-button p-button-rounded" [disabled]="product.stock === 0">
              <i class="pi pi-shopping-cart"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </ng-template>
</p-dataView>

pagable products interface

export interface PageableProducts {
  products:Product[];
  total_pages:number;
  total_products:number;
}

product interface

export interface Product {
  id?:string;
  brand:string;
  name:string;
  price:number
  category:string;
  subcategory:string;
  stock:number;
  description:string;
  image_url:string;
}

product service

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from "@angular/common/http";
import {catchError, Observable, of, tap} from "rxjs";
import {PageableProducts} from "../../interface/product/pagable-products";
import {Product} from "../../interface/product/product";
import {Search} from "../../interface/search/search";

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private productUrl:String = 'http://localhost:8080/product/api';
  httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
  };
  constructor(private http:HttpClient) { }

  searchProducts(searchQuery:Search): Observable<PageableProducts> {
    let queryParams = new HttpParams();
    if(searchQuery){
      if(searchQuery.name != null && searchQuery.name.length > 0) queryParams = queryParams.append("name",searchQuery.name)
      if(searchQuery.category != null && searchQuery.category.length > 0) queryParams = queryParams.append("category",searchQuery.category)
      if(searchQuery.subcategory != null && searchQuery.subcategory.length > 0) queryParams = queryParams.append("subcategory",searchQuery.subcategory)
      if(searchQuery.brands != null && searchQuery.brands.length > 0) queryParams = queryParams.append("brands",searchQuery.brands.toString())
      if(searchQuery.priceRange != null && searchQuery.priceRange.length == 2) {
        queryParams = queryParams.append("pMin",searchQuery.priceRange[0])
        queryParams = queryParams.append("pMax",searchQuery.priceRange[1])
      }

      if(searchQuery.page != null && searchQuery.page >= 0) queryParams = queryParams.append("page",searchQuery.page)
      if(searchQuery.size != null && searchQuery.size > 0) queryParams = queryParams.append("size",searchQuery.size)
    }

    console.log(queryParams.toString())

    return this.http.get<PageableProducts>(`${this.productUrl}/public/search`,{params:queryParams}).pipe(
        tap(_ => {
          console.log(`fetched products`)

        }),
        catchError(this.handleError<PageableProducts>('getProducts', { products:[], total_pages:0,
          total_products:0}))
    );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(operation);
      console.error(error);
      return of(result as T);
    };
  }




}

How can I render a external component by calling a function like Component.show()?

Let’s supose I have a Toast (or Modal, or whateaver) component, and I want to render it doing something like:

return (
  <View>
    <TouchableOpacity onPress={() => Toast.show()}>
      <Text>Press</Text>
    </TouchableOpacity>
  </View>
);

I don’t want nothing else in my App component, just the import of the Toast, and the return with the button that calls the Toast rendering. Without, any conditional or state on my App component function, or any {Toast} (or {isVisible && } inside its return.

I know that is possible, because I already seen libraries like AntDesign (for React JS), which has the message component, that works like a function, you just calls message.success() in whateaver part of the code, and a Message is displayed in your screen, what should I do in my Toast component to get a similar result?

embedding SCORM inside your site security wise

I want to embed a SCORM site in my application. Users can upload any SCORM content they have created, which will be stored in an S3 bucket and served through a CDN (CloudFront).

From a security perspective, I need the CDN alias to be a subdomain of the main site. This allows me to sign cookies for CDN authentication while blocking access to the main API cookies that are signed for the main domain. This precaution is necessary to prevent any malicious code that may be uploaded.

For example, let’s consider the following scenario: the main site is located at app.site.com, and it has cookies signed for domain=app.site.com to communicate with the inner API. The SCORM content is served from cdn.app.site.com, and the cookies for this subdomain are signed for domain=.app.site.com (note the dot at the start).

This setup works well, but it poses a challenge when trying to communicate with the SCORM API since the iframe that contains the SCORM is considered cross-origin with the main domain.

How can I communicate with the SCORM API on one hand and block access to the main API cookies on the other hand, without proxying the requests to a server (in order to leverage the CDN)?

i would apreciate ifi could get some help for my website

hello i would like to know where could be a mistake in this is the code i get a error saying /home/runner/work/_temp/f7610f6f-2495-4196-8736-156d1c0a06ea.sh: line 1: syntax error near unexpected token `(‘
Error: Process completed with exit code 2.
im trying to get a mail when somebody presses a button on my website i have connected it with sendgrid but i still get the error please help thanks
this is the code
name: Email Notification

on:
push:
branches:
– main

jobs:
sendEmail:
runs-on: ubuntu-latest

steps:
  - name: Checkout repository
    uses: actions/checkout@v2

  - name: Set up Node.js
    uses: actions/setup-node@v2
    with:
      node-version: '16'

  - name: Install dependencies
    run: npm install

  - name: Install PowerShell
    run: |

      sudo apt-get update
      sudo apt-get install -y powershell
      pwsh --version  # Verify the installation

  - name: Capture form data
    id: capture-form-data
    run: |
      echo "::set-output name=data::$(echo '{"name": "'${{ env.INPUT_NAME }}'", "email": "'${{ env.INPUT_EMAIL }}'", "message": "'${{ env.INPUT_MESSAGE }}'"}')"

  - name: Send email
    env:
      TO_EMAIL: ${{ secrets.TO_EMAIL }}
      FROM_EMAIL: ${{ secrets.FROM_EMAIL }}
      SENDGRID_API_KEY: ${{ secrets.SENDGRID_API_KEY }}
    run: |
      const sgMail = require('@sendgrid/mail');

      sgMail.setApiKey(process.env.SENDGRID_API_KEY);

      const formData = JSON.parse(process.env.CAPTURE_FORM_DATA);

      const message = {
        to: '[email protected]',  // Replace with your email address
        from: '[email protected]',   // Replace with the sender email address
        subject: 'Form Submission',
        text: `A form submission was received:nnName: ${formData.name}nEmail: ${formData.email}nMessage: ${formData.message}`
      };

      sgMail.send(message)
        .then(() => {
          console.log('Email sent successfully');
        })
        .catch((error) => {
          console.error('Error sending email:', error);
        });

i cannot understand for the life of me why the loop is not running

my loop doesn’t run, but the rest of the code runs.

const cards = document.getElementsByClassName("floating-cards");

console.log(randomcolor());

for (let i = 0; i < cards.length; i++) { 
    console.log(2);
    cards.style.backgroundColor = "rgb("+randomcolor()+","+randomcolor()+","+randomcolor()+")";
}

function randomcolor() {
    return Math.floor(Math.random() * 255);
}

I have generate the following the code where i am login with paypal but i got an error.Please let me known any help what’s wrong with my code

I have generate the following the code where i am login with paypal but i got an error.Please let me known any help what’s wrong with my code.

  paypal.use( ['login'], function (login) {
      login.render ({
        "appid":"Here-i-put-my-client-from-get-paypal",
        "authend":"sandbox",
        "scopes":"openid",
        "containerid":"paypalLoginBtn",
        "responseType":"code id_Token",
        "locale":"en-us",
        "theme":"neutral",
        "buttonType":"LWP",
        "buttonShape":"pill",
        "buttonSize":"lg",
        "fullPage":"false",
        "returnurl":"https://russell-bike-adobe-collins.trycloudflare.com/admin/tracking"
      });
    });

I got an following error

Missing host query argument
Your app can only load if the URL has a host argument. Please ensure that it is set, or access your app using the Partners Dashboard Test your app feature

but i have check that i got correct parameters from login function like: code and id_token
then why it is get missing host query argument.

https://russell-bike-adobe-collins.trycloudflare.com/admin/tracking?code=&id_token=&scope=openid

convert persian input to gregorian in blade laravel

hi Iam not good at javascript and have problem. I hope enyone can help me.
I want to get date from one input and change it to georgian and put it in another input.
and mix some code but didnt work

<input type="date" id="one" oninput="myFunction()">
<input  id="two">

<script>
window.onload = function() {
    var src = document.getElementById("one"),
        dst = document.getElementById("two");
        let text = src.toLocaleDateString('en-Us');
    src.addEventListener('input', function() {
        dst.value = text.value;
    });
};
</script>

thanks anyway