How to get inserted model or collection when using fillAndInsert which just returns a boolean?

$transactionsData is an array, and I want the id from transaction id from the transaction model for each item and assign it to the details to insert the id to the transaction item table, how can I achieve it in Laravel 12 fillAndInsert method, I tried tap method to use but it also returns boolen value.

$transactions = Transaction::fillAndInsert($transactionsData);

$transactionDetailsData = array_map(function ($detail, $index) use ($transactions) {
    $detail['transaction_detail_id'] = $transactions[$index]['id'];
    return $detail;
}, $transactionDetailsData, array_keys($transactionDetailsData));

TransactionItem::fillAndInsert($transactionDetailsData);

Nginx location with alias redirect to root [closed]

I need to place a site inside existed project. site.com – this is the main site, site.com/site2/ this is the second one.

  1. When I visite site.com it’s show me /index.php [OK]
  2. When site.com/site2/ it’s show me /site2/web/index.php [OK]
  3. But when site.com/site2/qwe it redirect back to /index.php [FAIL]. I need /site2/web/index.php

The project structure is:

/
/site2/
/site2/web/
/site2/web/index.php
/index.php

Nginx site conf

server {
    root /var/www/site;
    index index.php index.html index.htm;
    ...

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }

    location /site2/ {
        alias /var/www/site/site2/web/;

        add_header X-Location-Visited true always;

        try_files $uri $uri/ /index.php$is_args$args;
        # I'd tried without any result
        # try_files $uri $uri/ /site2/index.php$is_args$args;
        # try_files $uri $uri/ /site2/web/index.php$is_args$args;

        location ~ .php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        }
    }
}

snippets/fastcgi-php.conf

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+?.php)(/.*)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

Json response not rendering to html table, only shows raw json data

I am returning json response from index method of my controller class.

use AppHttpControllersController;
use IlluminateHttpRequest;
use AppModelsAdminServicesFinish;

class FinishController extends Controller
{
    public function index()
    {
        $finishes = Finish::select('id','name')->where('status', 1)->orderBy('id','desc')->get();
        return response()->json(['finishes'=>$finishes]);
    }
}

My route function:

Route::get('admin_finish', [FinishController::class, 'index'])->name('admin_finish.index');

In my blade php file, I am trying to render this json response to html table. But it’s only showing raw json data.

@extends('admin.index')
@section('admin_content')
    <section>
                    <table id="example2" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>S.No.</th>
                                <th>Finish Name</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="i_tbl_finish">
                        </tbody>
                    </table>
    </section>
@endsection

@section('js_scirpts')
    <script>
        $(document).ready(function() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            fetchData();

            function fetchData() {
                    $.ajax({
                        type: "GET",
                        url:  "{{ route('admin_finish.index') }}",
                        dataType: 'json'
                        success: function(data) {
                            let rows = '';
                            $.each(data, function(key, finishes) {
                                rows += `
                                    <tr>
                                        <td>${finishes.id}</td>
                                        <td>${finishes.name}</td>
                                        <td>
                                            <button data-id="${finishes.id}" class="btn btn-primary btn-sm edit-post"><i class="fa fa-edit"></i></button>
                                            <button data-id="${finishes.id}" class="btn btn-danger btn-sm delete-post"><i class="fa fa-trash"></i></button>
                                        </td>
                                    </tr>
                                `;
                            });
                            $('#i_tbl_finish').html(rows);
                        },
                        error: function(error) {
                            console.log(error);
                        }
                    });
            }
        });
    </script>
@endsection

But I am getting only raw json data. It seems the ajax function is not working or may be issues with route. But I can not trace out the reason for this. Why is it so? Please see the attached image of my output.

output as raw json data

How to convert PNG image to JPEG using GD and imagejpeg without displaying in browser or saving to file system? [closed]

There are answers on SO about converting an image to a JPEG using PHP’s imagejpeg and either displaying in browser or saving to disk such as this one but I can’t find way to convert to JPEG without displaying or saving so it merely stays in memory without the extra overhead of saving to disk or displaying.

The use case is that the code is in an API endpoint that receives a request from a mobile device, sends a request to one API that returns a PNG file in the form of a string and then must send a JPEG file to a second API that only accepts JPEG files before returning the final result to the user.

While accomplishing these tasks, time is of the essence. Displaying the image in a background thread would be absurd and a waste of resources as would saving it to disk. All I need to do is convert the PNG file to a JPEG file but imagejpeg seems to have the added behavior of outputting the image or saving it.

The code where I receive the image as a PNG string and then must convert it into a JPEG image is;

$response = "xxx"; //png image from an API in the form of string
$image = imagecreatefromstring($response);//convert to in memory image. this line of code works perfectly

imagejpeg($image);//This converts to jpeg and displays file in browser--this displays to browser. I don't want to display it
imagejpeg($image, 'output.jpg', 100); // variation of imagejpeg that saves the file to disk same as imagejpeg($image)--I don't want to save it to disk
imagejpeg($image, NULL,100);//displays to browser. This is the top-voted but not accepted answer in question linked to.

Does imagejpeg have an option to simply change png to jpeg without displaying in a browser or saving to disk?

Note this has nothing to do with compressing files or with converting the image file into a string as in the question referenced. That question is about turning an image into a string. My situation is the exact opposite; I receive the image as a string from the first API and convert it to a file in memory without a problem using imagecreatefromstring($response).

My question is how to convert the PNG image to JPEG efficiently within my API. I don’t want the script to time out or waste resources or possibly crash due to unnecessary activity such as displaying or saving to disk.

How can I prevent the entire React app from crashing when an invalid component is rendered?

I have a React app where I have a main component EntireApp, which renders a child component Foo. The Foo component conditionally renders either Bar or Baz based on its iconId prop. However, when the iconId passed to Foo is invalid (for example, something like “foz” sent from the server), the entire application crashes, showing the “Application error: a client-side exception has occurred” error in the browser with a blank screen.

Here’s an MRE

const Bar = () => <div>Bar</div>;
const Baz = () => <div>Baz</div>;

const Foo = ({ iconId }) => {
  const components = [
    { icon: 'Bar', iconId: 'bar', component: Bar },
    { icon: 'Baz', iconId: 'baz', component: Baz },
  ];

  const iconData = components.find(c => c.iconId === iconId);

  /// @ts-ignore // intentionally ignore type to illustrate the issue
  const ComponentToRender:(() => React.JSX.Element) = iconData?.component;
  return <ComponentToRender />;
};

const EntireApp = () => {
  return (
    <div>
      <div>Something more important and healthy component</div>
      <Foo iconId="baz" /> {/* Invalid iconId that should not crash the entire app */}
    </div>
  );
};

How can I prevent the entire React app from crashing when an invalid component is rendered ?

I get

Application error: a client-side exception has occurred while loading
localhost (see the browser console for more information).

And a blank page in prod. I don’t really care about the icon breaking. How to tell React:

Hey, if one component is invalid, do not destroy my entire app. Just don’t render that broken component ?

I tried reactStrictMode: false, in next.config.js but this does nothing.

I also looked all of these, but they talk about the reason of the error, nothing about preventing an entire app crash. Next.js Application error: a client-side exception has occurred (see the browser console for more information)

Card Carousel Slider Scrolling

I have created a carousel slider with swipe function and also with side navigation. But with the side navigation I need to scroll 2 cards per click. And also with the pagination, even though I am with the last slide, the pagination is still on the second last active dot.

Carousel Slider Script

document.addEventListener('DOMContentLoaded', () => {
            const carousel = document.getElementById('promoCarousel');
            if (!carousel) return;

            const viewport = carousel.querySelector('.carousel-viewport');
            const nextButton = carousel.querySelector('.carousel-nav.next');
            const prevButton = carousel.querySelector('.carousel-nav.prev');
            const cards = viewport.querySelectorAll('.card');

            // --- JS-Powered Navigation for CSS Scroll Snap ---
            function updateNavButtons() {
                // Hide/show buttons based on scroll position
                // A small tolerance is added to account for subpixel rendering
                const tolerance = 2;
                prevButton.style.display = viewport.scrollLeft <= tolerance ? 'none' : 'flex';
                const isAtEnd = viewport.scrollLeft + viewport.clientWidth >= viewport.scrollWidth - tolerance;
                nextButton.style.display = isAtEnd ? 'none' : 'flex';
            }

            function scrollCarousel(direction) {
                // Find the width of the first card to determine the scroll amount
                const cardWidth = cards.length > 0 ? cards[0].offsetWidth : 0;
                const scrollAmount = (cardWidth + 12) * direction; // card width + margin
                viewport.scrollBy({ left: scrollAmount, behavior: 'smooth' });
            }

            nextButton.addEventListener('click', () => scrollCarousel(1));
            prevButton.addEventListener('click', () => scrollCarousel(-1));
            
            // Update nav buttons on scroll, load, and resize
            viewport.addEventListener('scroll', updateNavButtons);
            window.addEventListener('resize', updateNavButtons);
            updateNavButtons();

Pagination Script

const paginationContainer = document.getElementById('carouselPagination');
const cardsPerPage = () => {
    const width = window.innerWidth;
    if (width >= 992) return 3;
    if (width >= 768) return 2;
    return 1;
};

function createPagination() {
    paginationContainer.innerHTML = ''; // Clear previous dots

    cards.forEach((card, index) => {
        const dot = document.createElement('div');
        dot.classList.add('dot');
        if (index === 0) dot.classList.add('active');
        dot.dataset.index = index;
        paginationContainer.appendChild(dot);

        dot.addEventListener('click', () => {
            const cardWidth = card.offsetWidth + 0; // card width + margin
            const scrollAmount = cardWidth * index;
            viewport.scrollTo({ left: scrollAmount, behavior: 'smooth' });
        });
    });
}

function updateActiveDot() {
    const scrollLeft = viewport.scrollLeft;
    const cardWidth = cards[0].offsetWidth + 12;

    const index = Math.round(scrollLeft / cardWidth);
    const dots = paginationContainer.querySelectorAll('.dot');

    dots.forEach(dot => dot.classList.remove('active'));
    if (dots[index]) dots[index].classList.add('active');
}

// Recreate pagination on load and resize
createPagination();
window.addEventListener('resize', () => {
    createPagination();
    updateActiveDot();
});

viewport.addEventListener('scroll', updateActiveDot);

Tooltip from @radix-ui/react-tooltip not unmounting when using tailwind-animate

I am using @radix-ui/react-tooltip library in react to create a tooltip component. When I use tailwind-animate library, the tooltip popup does not disappear after the cursor moves away from the trigger button (the popup does not seem to get unmounted). If I translate the same animation code to raw css, it works fine. What could be the issue with tailwind-animate? The tailwind-animate version is 0.2.10 and tailwindcss version is 4.1.11.

Here is the wrapper that I am using as Tooltip content (appears as popup when the cursor hovers over the trigger button:

import * as React from 'react';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { twMerge } from 'tailwind-merge';
import { Caption, SmallerText } from '../Typography';
import { TooltipProps } from './types';
import { tooltipContentBaseStyles } from './styles';
import { FontWeight } from '../../../constants/stringConstants';

const Tooltip = TooltipPrimitive.Root;
const TooltipProvider = TooltipPrimitive.Provider;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipArrow = TooltipPrimitive.Arrow;

type TooltipContentProps = React.ComponentPropsWithoutRef<
  typeof TooltipPrimitive.Content
> &
  Omit<TooltipProps, 'supportingContent' | 'children'>;

const TooltipContent = React.forwardRef<
  React.ElementRef<typeof TooltipPrimitive.Content>,
  TooltipContentProps
>((props, ref) => {
  const {
    className,
    title,
    description,
    side,
    align,
    children,
    hasPointer,
    sideOffset = 4,
    alignOffset = -20,
    ...restProps
  } = props;

  const tooltipContentClassNames = twMerge(
    tooltipContentBaseStyles,
    'rounded-[8px] shadow-lg',
    'bg-white dark:bg-primary-gray-900',
    'text-black dark:text-white',
    className,
  );

  const tooltipContentContainerClassNames = twMerge(
    'max-w-[320px] flex flex-col plr-[2px] ptb-[8px]',
    'rounded-[8px]',
    'gap-[4px]',
  );

  const tooltipArrowClassNames = twMerge(
    'text z-20 fill-gray-700 text-gray-700',
    'fill-white dark:fill-primary-gray-900',
  );

  return (
    <TooltipPrimitive.Content
      ref={ref}
      sideOffset={sideOffset}
      alignOffset={alignOffset}
      className={tooltipContentClassNames}
      side={side}
      align={align}
      {...restProps}
    >
      <section className={tooltipContentContainerClassNames}>
        <article className="mt-2 w-full space-y-1">
          <Caption text={title} weight={FontWeight.SEMI_BOLD} />
          <SmallerText text={description} />
        </article>
        {children}
      </section>
      {hasPointer && (
        <TooltipArrow
          className={tooltipArrowClassNames}
          height={6}
          width={12}
        />
      )}
    </TooltipPrimitive.Content>
  );
});

TooltipContent.displayName = TooltipPrimitive.Content.displayName;

export {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
  TooltipProvider,
  TooltipArrow,
};

the code for tooltipContentBaseStyles (the animation classes below are causing the issue, when i translate them to raw css and apply that css to tooltip content, it works fine):

export const tooltipContentBaseStyles = twMerge(
  'z-50 overflow-hidden',
  'px-3 py-1.5 text-sm',
  'animate-in fade-in-0 zoom-in-95',
  'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',
  'data-[side=bottom]:slide-in-from-top-2',
  'data-[side=left]:slide-in-from-right-2',
  'data-[side=right]:slide-in-from-left-2',
  'data-[side=top]:slide-in-from-bottom-2',
);

Best practices for communicating between components in the same VS Code extension

I’m writing a VS Code extension that has several UI and non-UI components like tree view providers, status bar items, registries of internal state etc. All of them are created in the extension’s activate() function. Some of them need to communicate between themselves, getting some data, modifying state etc. It would be pretty straightforward if all of these components had a reference to each other but there seems to be no clear way to organize this:

  • exporting instances from activate() seems to be more suitable for inter-extension communication;
  • singleton instances (which I’m currently doing) are somewhat smelly and also are single per process, while in the future if I want to support multiple open workspaces I wil need one instance per workspace;
  • I could pass instances of components to constructors of other components in activate() which is probably the cleanest way to code this but cumbersome to extend, especially if two components need to call each other;
  • ExtensionContext.workspaceState and ExtensionContext.globalState are for persistence and likely don’t even support instances of arbitrary classes;
  • rummaging through ExtensionContext.subscriptions is very smelly to me.

So what are best practices of keeping some globally accessible class instances available to all code of an extension?

browser sequentially sending data to server with sleep

having large amount of browser data – json sent to the server side, so wanna to chunk the data and send to the server sequentially with sleep 1 seconds between each sending.

have tried two ways:
way 1:

  let url = "http://localhost:3000/api/v1/test";
  let chunkSize = 100;
  const chunks = data.reduce((acc, _, i) => {
    if (i % chunkSize === 0) acc.push([]);
    acc[acc.length - 1].push(array[i]);
    return acc;
  }, [] as T[][]);

  console.log('chunks',chunks);

  for (const chunk of chunks) {
    console.log( 'chunk',chunk.length);
     await fetch( url , {
                  method: 'POST',
                  body:  JSON.stringify( chunk ) ,
                  "Content-type": "application/json; charset=UTF-8"
                  }
    });
    await setTimeout(function(){},1000);    
    console.log( 'chunk',chunk.length);

however when testing, the process gets stuck when sending the first chunk, no error showing up, just stuck.

second way:

    let url = "http://localhost:3000/api/v1/test";
    let chunkSize = 100;
    const chunks = data.reduce((acc, _, i) => {
        if (i % chunkSize === 0) acc.push([]);
        acc[acc.length - 1].push(array[i]);
        return acc;
      }, [] as T[][]);

  return Promise.all(chunks.map(async chunk => {
     console.log( 'chunk',chunk.length);
     await setTimeout(function(){},1000);  // not working at all
     return await fetch( url , {
                  method: 'POST',
                  body:  JSON.stringify( chunk ) ,
                  headers: {
                  "Content-type": "application/json; charset=UTF-8"
                  }
    });

  }));

the problem with this above is await setTimeout(function(){},1000); never sleeps.

Multiple Attendees for Automated Calendar Invite via Sheets

I hitting an error when I try to add multiple attendees via my spreadsheet. It works with one but when I try comma-separate to include multiple attendees it throws an error:

Error GoogleJsonResponseException: API call to calendar.events.insert failed with error: Invalid attendee email.
createNewEventWithMeet @ Code.gs:34

Link

function createNewEventWithMeet() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Calendar_Events");
  var last_row = sheet.getLastRow();
  var data = sheet.getRange("A2:E" + last_row).getValues();
  var cal = CalendarApp.getCalendarById("[email protected]");

  for(var i = 0;i< data.length;i++){

    var event_name = data[i][0];
    var start_time = data[i][1];
    var end_time = data[i][2];
    var event_description = data[i][3];
    var attendees_event = data[i][4];

//.setVisibility(CalendarApp.Visibility.PRIVATE);

  const mst = "-06:00";
  const calendarId = "[email protected]";
  const resource = {
    start: { dateTime: start_time+mst },
    end: { dateTime: end_time+mst },
    attendees: [{ email: attendees_event }],
    conferenceData: {
      createRequest: {
        requestId: "[email protected]",
        conferenceSolutionKey: { type: "hangoutsMeet" },
      },
    },
    summary: event_name,
    description: event_description,
  };
  const res = Calendar.Events.insert(resource, calendarId, {
    
    conferenceDataVersion: 1,
  });

  
  var googleMeet_Link = res.hangoutLink;
  
  console.log(res);
  }
}

I’ve tried to create multiple columns to split it out but I cannot seem to make it work.

Ammo.js body of the character-controller undesirable penetrate deep into static and dynamic objects

The problem is that the character’s controller does not stand on the surface of a static object, but rather sinks into it. This has undesirable side effects. But at the same time, going up the steps works!

enter image description here

I noticed that if I set upAxis == -1, then the element appears on the surface, and it looks like it should, but the climbing the stairs stops working…

enter image description here

Code clippings:

Character controller set:
CC riggid body:

let body = new AMMO.btPairCachingGhostObject();
body.setWorldTransform(transform);
body.setCollisionShape(colShape);
//  DISABLE_DEACTIVATION == 4
body.setActivationState(4);
body.activate(true);
this.world.getBroadphase().getOverlappingPairCache().setInternalGhostPairCallback(new AMMO.btGhostPairCallback());  
body.setCollisionFlags(body.getCollisionFlags() | btCollisionObjectCollisionFlags.CF_CHARACTER_OBJECT); // 16
this.world.addCollisionObject(body);

CC collider:

let collider = new AMMO.btCylinderShape ( new AMMO.btVector3(metadata.params.radius, metadata.params.halfHeight, metadata.params.radius) );

CC btKinematicCharacterController:

let characterController = new AMMO.btKinematicCharacterController(
    body, 
    collider, 
    0.35, //stepHeight
    1 //upAxis
);
characterController .setUseGhostSweepTest(true);
characterController .setGravity(9.8 * 3); // default 9.8*3
characterController .setMaxSlope(Math.PI / 3); // default Math.PI / 4

this.world.addAction(characterController );

Floor set:
Floor riggid body:

let mass = 0;
let motionState = new AMMO.btDefaultMotionState( transform );
let rbInfo = new AMMO.btRigidBodyConstructionInfo( mass, motionState, colShape, localInertia );
body = new AMMO.btRigidBody( rbInfo);
this.world.addRigidBody(body);
body.setCollisionFlags(body.getCollisionFlags() | btCollisionObjectCollisionFlags.CF_STATIC_OBJECT); // 1

Moreover, this penetration occurs precisely in the lower part of the character’s controller. From the side, everything touches as it should.

In this example, dynamic bodies are scattered. They can be pushed by pressing on them from the side. But if you stand on top of them, penetration occurs..
enter image description here

P.S. If my question seemed inappropriate or bad, please do not immediately put a negative in my reputation, it is better to write, and I will correct, clarify the statement.

On appel devices when playing a sound while on zoom call the bilateral sound is gone (bad sound quality) [closed]

I have a web app that plays sounds for some special purposes.
The issue occurs when playing a sound that plays tons on left and right speakers and when on a zoom meet the effect of left and right sound is gone and the sound becomes bad quality.

Is there a solution on the web platform ?

If no then can we implement a solution on android and ios platforms that overrides zoom phone mode and plays the sound with the bilateral quality sound.

SVG rewind works in Firefox, not in Chrome

Here’s a snippet where the user controls the progress of SVG <animate> using a slider. It works in Firefox. But in Chrome, after sliding it to the very end, it stops working.

const input = document.querySelector('input');
const animate = document.querySelector('animate');
const svg = document.querySelector('svg');

animate.beginElement();
svg.pauseAnimations();
const duration = animate.getSimpleDuration();

input.addEventListener('input', function() {
  svg.setCurrentTime(this.value / 100 * duration);
});
<svg>
  <rect x="50" y="50" width="100" height="100" fill="blue">
    <animate id="anim" attributeName="x" from="50" to="200" dur="5s" begin="indefinite" fill="freeze"/>
  </rect>
</svg>

<input type="range" value="0">

The problem can be solved by removing begin="indefinite". But that may limit other use cases or require hacky workarounds.

What are other solutions?
And what’s causing the problem, is it in accordance to spec or likely a bug in Chrome?

Refused to frame ‘https://localhost:5001/’ an ancestor violates Content Security Policy directive: “frame-ancestors ‘self’ https://localhost:5001/”

I set the following CSP: frame-ancestors 'self' https://localhost:5001/

I get an error:

Refused to frame 'https://localhost:5001/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' https://localhost:5001/".

I’ve tried with and without the / and it has not helped.