Content-aware fill with HDR

I’m looking for a way to resize (e.g., landscape to portrait) a .JPG or .HEIC photo that was taken with an iPhone, content-aware fill and blur the newly added space, and retain the HDR on iPhone or a web site.

Thus far, I’ve tried many different apps, but none of them support all 3.

Does anyone know if this is possible? Even if you only know of a JavaScript framework or something that can do so, I will happily create the app myself.

The events in fullcalendar sometimes duplicate on my database when i move them to another date/time. How can i solve this?

I’am using fullcalendar 6.1.14 in django 4.2.11. I have a function defined to update the delivery date of an item where the number of the document of the item is the same as the event id and the year is the year that it is changing it from and i even have a check for it to not add already existing NumDoc + Year combinations, but sometimes, ramdomly, it duplicates the event in the database when i drag them to a new date and i have no idea how to solve this. I’am using Microsoft MySQL Server Mangement as database manager.

Function to Move Events in views.py

@csrf_exempt
def update_delivery_date(request):
    if request.method == 'POST':
        event_id = request.POST.get('id')
        new_start_date = request.POST.get('new_start_date')
        year = request.POST.get('year')
        
        # Check if the user has the allowed groups
        if not (request.user.groups.filter(name__in=['Expedicao', 'Dir Logistica', 'Logistica']).exists() or request.user.is_superuser):
            return JsonResponse({'success': False, 'error': 'User does not have permission to move events'}, status=403)

        try:
            with transaction.atomic():
                # Find the specific event by DocNum and Year
                event = EncomendasCalendar.objects.select_for_update().get(NumDoc=event_id, Ano=year)
                
                # Check if there is already another event with the same DocNum and Year
                if EncomendasCalendar.objects.filter(NumDoc=event_id, Ano=year).exclude(NumDoc=event_id).exists():
                    print("Duplicate")
                    return JsonResponse({'success': False, 'error': 'An event with the same DocNum and Year already exists'}, status=400)
        
                # Check if the new date is the same as the current one
                if event.DataEntrega == new_start_date:
                    print("same")
                    return JsonResponse({'success': False, 'error': 'The delivery date is already the same as the informed date.'}, status=400)
                
                # Update the DeliveryDate with the new date
                event.DataEntrega = new_start_date
                event.UpdatedBy = request.user
                
                # Save the updated event in the database
                event.save()
                
        except EncomendasCalendar.DoesNotExist:
            return JsonResponse({'success': False, 'error': 'Event not found'}, status=404)
        
        except Exception as e:
            print('Error updating the delivery date:', e)
            return JsonResponse({'success': False, 'error': 'Error updating the delivery date'})
        
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)

function in js file where the is the calendar and the events are moved (calendar.js)

function moveEvents() {
    // Logic to move all events with status_id equal to 2
    var startDate = $('#start_date').val();
    var endDate = $('#end_date').val();
    var csrftoken = Cookies.get('csrftoken');

    $.ajax({
        type: 'POST',
        url: '/move_events/',  // Replace with the correct URL
        data: {
            start_date: startDate,
            end_date: endDate
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function (response) {
            $('#MoveModal').find('input[type="date"]').val('');

            // Close the modal after the move and reload the events
            $('#MoveModal').modal('hide');
            calendar.refetchEvents();
        },
        error: function (xhr, status, error) {
            console.error('Error moving events:', error);
        }
    });
}

Design of the table where Encomendas are inserted, updated etc

I tried many things that i no longer remember, but the last was a check in the views.py code that was supposed to not add a event if the numdoc + year already existed, but it didnt work.

Linkedin API video split upload

I’m working on Linkedin api integration in next.js app. Short videos I upload successfully, the problem is with video splitting. My finction split video if necessary and upload it to temp folder. I use ffmpeg from ‘fluent-ffmpeg’;

export async function splitVideoToTemp(fileName: string): Promise<boolean> {

const inputPath = path.join(process.cwd(), 'tmp', 'input', fileName);
ensureFolderExists('chunks');
const outputDir = path.join(process.cwd() + '/tmp/chunks');
const bytes = 4194303;
await splitVideo(inputPath as string, bytes, outputDir);
await deleteFileFromTemp(inputPath);

return true;
}

export async function splitVideo(inputPath: string, chunkSize: number, outputDir: 
string): Promise<void> {
 try {
    await fs.mkdir(outputDir, { recursive: true });

    const metadata: FFmpegMetadata = await new Promise((resolve, reject) => {
        ffmpeg.ffprobe(inputPath, (err, metadata) => {
            if (err) reject(err);
            else resolve(metadata as FFmpegMetadata);
        });
    });

    const duration = metadata.format.duration;
    const chunkDuration = chunkSize / (metadata.format.size / duration);
    const promises = [];

    for (let startTime = 0, chunkIndex = 0; startTime < duration; startTime += 
 chunkDuration, chunkIndex++) {
        const outputPath = path.join(outputDir, `chunk_${chunkIndex}.mp4`);
        promises.push(processChunk(inputPath, startTime, chunkDuration, outputPath));
    }

    await Promise.all(promises);
    console.log('Video split successfully');
} catch (error) {
    console.error('Error splitting video:', error);
}
}

 function processChunk(inputPath: string, startTime: number, chunkDuration: number, 
 outputPath: string): Promise<void> {
 return new Promise((resolve, reject) => {
    ffmpeg(inputPath)
        .setStartTime(startTime)
        .setDuration(chunkDuration)
        .output(outputPath)
        .on('end', () => resolve())
        .on('error', reject)
        .run();
 });
 }

calling this functions nicely split my video to chuks, they are not corrupted, I can play them one by one.

then I call

const response = await fetch(
        `${LN_API_BASE_URL}/${LN_API_VERSION}/videos?action=initializeUpload`,
        requestOptions
    );
    const result = await response.json();

I receive upload isntructions.

            await splitVideoToTemp(fileName);
            await Promise.all(
                instructions?.map(async (instruction, index) => {
                    const chunkName = `chunk_${index}.mp4`;
                    const outputPath = path.join(
                        process.cwd() + '/tmp/chunks',
                        chunkName
                    );
                    const blob = await getFileAsBlob(outputPath);
                    const result = uploadVideo(
                        instruction.uploadUrl,
                        blob,
                        params.pageAccessToken
                    );
                    const uploadedChunkId = await result;
                    if (uploadedChunkId) {
                        uploadedChunksIds.push(uploadedChunkId);
                        // delete file
                       await deleteFileFromTemp(outputPath);
                    }
                })
            );

all nice and well, when I upload, i receive bunch of chunk ids with each call, I put them in array, call finalize upload with obj

 finalizeUploadRequest: {
   video: 'urn:li:video:videoId',
    uploadToken: '',
   uploadedPartIds: [ .. 'ids i received', '', '', '']
  }

then I poll result, its available, then I post. it success. But on the page I get one random chank from all of them.

Any Idea why? I dont get any error. Upload process is smooth. All videos go through this logic, if video short and dont need to be splitted, it uploads perfectly, but whats wrong with partial uploading? Why it post only one of the chunks and random one?

I’ll appreciate any tips

Javascript: within a document that’s been opened by another document, script within script

I am learning javascript on my own (I’ve been programming in python and C/C++ for a while).
I am building a project that displays family photos stored on a local server. The homepage has a search bar, which opens a new page with thumbnails returned with the results of the search. I want a user to click on the thumbnail, which opens a new page with the image in full, displays the tags, and then has a form which allows a user to submit a possible correction for the tags.

I am unable to get the script that submits the correction for the tags to work properly – I expect it has to do with a document.write() containing another document.write() – the second of which has a script within a script.

my openTabWithThumbnails function is like this:
(setup and check for new tab opening omitted)

    newTab.document.write(`
    <html>
        <head>...</head>
        <body>
        <script>
        document.querySelectorAll('.thumbnail.img'.forEach( => {
            (setup some vars)
            const imageTab=window.open('','_blank');
            if (imageTab) {
                imageTab.document.write(`
                    <html>
                    <head>...</head>
                    <body>
                        (display image)
                        (build suggestion form)
                        !!problem starts here
                        '<scr' + 'ipt>'
                            (get data and send to server)
                        '<scr' + 'ipt>'
                   </body>
                   </html>
                `);
                imageTab.document.close();
              }
        });
        </script>
        </body>
        </html>
     `); 
     newTab.document.close();`

I have also tried for the inner script:

    document.write('<scr' + 'ipt>');
        (get data and send to server)
    document.write('<scr' + 'ipt>');

Also tried:

    var newscr = document.createElement('script');
    newscr.src='otherscriptfile.js';
    document.write('newscr.outerHTML');

In all cases I get the suggestion form up, but then the rest until is displayed at the bottom of the second page.

I am sure I am missing something simple. I also understand that there is likely a much better way to do what I want to do – I’ve searched but likely am asking the question improperly

DataTables Pagination Issue: Header hides with scrollX Option

I’m using DataTables, and everything works well, but I’ve encountered an issue when clicking on pagination: the table header hides, leaving only the table body visible. After some debugging, I discovered that the scrollX: true option is causing this problem. I attempted to remove the scrollX: true option and instead wrapped the parent element in a div with overflow enabled. However, this change resulted in scrollbar appearing below the pagination numbers, separate from the table itself.

<script>
$(document).ready(function() {
    // Initialize DataTables for all elements with the class 'example-table'
    var table = $('.example-table').DataTable({
         paging: true,
        
          fixedHeader: true,
          "scrollX": true, 
        searching: true,
        info: true,
        ordering: true,
        order: [],
        "scrollCollapse": true,
        dom: 'ifrtBp', // Add the buttons control element
        buttons: [
            {
                extend: 'excelHtml5',
                text: 'Export to Excel',
                titleAttr: 'Export as Excel'
             }
        ]
    });



    // Add event listener for print
    window.onbeforeprint = function() {
        // Disable horizontal scrolling and paging temporarily before printing
        table
            .columns.adjust()
            .draw(false); // Redraw table without changing page
        table.page.len(-1).draw(); // Show all entries

        // Disable overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'visible'); 
        $('.dataTables_scrollHead').css('overflow', 'visible');
    };

    window.onafterprint = function() {
        // Re-enable horizontal scrolling and restore paging after printing
        table.page.len(10).draw();

        // Restore overflow and scrolling for both header and body
        $('.dataTables_scrollBody').css('overflow', 'auto'); 
        $('.dataTables_scrollHead').css('overflow', 'auto');
    };
});
</script>

Why It doesn’t show this to the screen

Basically I want show less description and when I press “Read More” I wanna show the full description

The code:

import { useState } from "react";

const JobsListing = ({ job }) => {
  const [showFullDescription, setShowFullDescription] = useState(false);

  let description = job.description;

  if (!showFullDescription) {
    description = description.setstring(0, 90) + "...";
  }

  return (
    <div>
      <div className="bg-white rounded-xl shadow-md relative">
        <div className="p-4">
          <div className="mb-6">
            <div className="text-gray-600 my-2">{job.type}</div>
            <h3 className="text-xl font-bold">{job.title}</h3>
          </div>

          <div className="mb-5">{description}</div>

          <h3 className="text-indigo-500 mb-2">{job.salary}</h3>

          <div className="border border-gray-100 mb-5"></div>

          <div className="flex flex-col lg:flex-row justify-between mb-4">
            <div className="text-orange-700 mb-3">
              <i className="fa-solid fa-location-dot text-lg"></i>
              {job.location}
            </div>
            <a
              href={`/job/${job.id}`}
              className="h-[36px] bg-indigo-500 hover:bg-indigo-600 text-white px-4 py-2 rounded-lg text-center text-sm"
            >
              Read More
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

export default JobsListing;

I expected to show the description from 0, 90 using setstring to show less description also when I click “Read More” I expect to show the full description

Javascript Function using a parameter defined in the future

I’m doing a question that appears in 10:10:02 of this video https://youtu.be/EerdGm-ehJQ?t=36602 (Challenge exercise 12f)

The question is as follows:

  • Click a button in HTML
  • Add a message on the screen
  • Start a ‘setTimeout’ for 2 seconds, at the end of the 2 seconds, remove the message
  • But within that 2 second timeout, press the button again
  • The timeout has to refresh (using clearTimeout) so the timer will continue on for more than the original 2 seconds.

I figured out the solution but I don’t understand how it works.
my code is as follows:

let timeoutID;

function updateMessage() {
  const message = document.querySelector('.js-message')

  message.innerHTML = 'Added'

  clearTimeout(timeoutID)

  timeoutID = setTimeout(function() {
    message.innerHTML = ''
  }, 2000)

}
<button onclick="
  updateMessage();
  ">Add to cart</button>


<p class="js-message"></p>

When the clearTimeout(timeoutID) line is ran, it seems to me that the parameter that is being inputted into clearTimeout is defined on the next bit of code below. how is clearTimeout reaching onto the 2 lines of code below and then going back and running itself?

I see that I’ve put ‘let timeoutID’ in the first line of the script, but I’m not assigning anything to it. I dont understand this part.

Keyboard focus and VoiceOver focus behaves differently when shift + tab (both safari and Chrome)

I have a parent div element (that has a aria label for the screenreader to announce), it contains a link element.I need the screenreader to focus and read div element first, and then when you tab into the child link, to focus and read the child link. This forward tabbing is done as expected since both parent and child element are having tab index of 0.
However, when you shift tab backwards from the child back to the parent element, the tab keyboard focus (the keyboard tab wrapper) moves to the parent, but VO focus wrapper stays at the child component, and VO doesn’t announce anything.

I have tried these following methods in the JS file already:

  1. change the parent’s tabIndex to 1 dynamically when the child element is on focus, and when parent element receives focus, change it back to 0.
  2. When child element gets focus, set its aria-hidden attribute to true, and when focus leaves child element, it changes back to false.
  3. Use a onKeyDown event handler to capture a shiftKey and a eventKey of “tab”, then parentElement.focus()
  4. ChatGPT also recommends to do a setTimeOut to let focus to respond, which i tried and failed, doesn’t make any sense to me either.

Expected: The VO focus should follow the shift + Tab focus to the parent element and announce the aria-label of the parent element.

None of these worked and I’m out of ideas, any input would be super helpful!

Missing few changes returned by ‘onCellsChanged’ function in ReactGrid component

Description:

I am using ReactGrid component from https://reactgrid.com/support. It is accepting onCellsChanged prop that supposed to return all the changes of the cells with CellChange imterface .
However, when I am copying data from one row to another, it is not returning all the necessary changes especially custom-checkbox cells (we have used the same code that is mentioned in the library’s github repo for checkbox – https://github.com/silevis/reactgrid/blob/develop/src/lib/CellTemplates/CheckboxCellTemplate.tsx).
But when we paste the same copied data to the same row for the second time, then it is returning all the data. Please check the attached screenshot for more clarity.

Current behaviour:
When we copied one row and try to paste it to another row, then onCellsChanged function is not returning all the data, but on second time paste, it is returning. Please check the screenshot attached. When I tried to paste the data for the first time, library is returning changes that is print in the console using ‘changes’ keyword. And notice the second time ‘changes’ printed in the console for the second time paste.

Console of the changes for the first and second time

Expected:
onCellsChanged function should return all the cell changes for the first time.

How Monaco Editor completion items provider can be triggered when accessing a string literal property?

In this MonacoEdtior using code, I’ve created a javascript editor instance, and add a piece of typescript code as an extra lib to monaco:

var libSource = `
type State = {
    'address-audited_val': string;
    address: string;
};
const s: State = {
    'address-audited_val': '...',
    address: '...'
};
`
monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, "ts:filename/test.ts");
monaco.editor.createModel(libSource, "typescript", monaco.Uri.parse("ts:filename/test.ts"));
monaco.editor.create(document.getElementById("container"), {
    value: '',
    language: "javascript",
});

Run the code in playground

Unexpected/Current Behavior

When I input s. in monca editor, I can only get a completion item for address, not including one for address-audited_val. screenshot

Expected Behavior

When I input s. in monca editor, I can get the completion items for address and address-audited_val, just like the performance of vscode in this regard.

Question

As we know, the address-audited_val is the string literal property of State. My question is there any way to configure monca so that I can get the completion items for these string literal properties?

cypress with cucumber package.json step_definitions not being found with subfolders

I apologise if this question has been answered elsewhere or is incomplete but I couldn’t find an answer to my issue, as simple as it may seem.

I have made a new cypress project using cucumber feature files and been able to get my tests working if I place it all in to the e2e folder (with step_definitions = “cypress/e2e/*”), but when I put my specs in to subfolders to split out my tests (i.e. e2e/account/… and e2e/booking/…), it doesn’t seem to find my spec files no matter what I put in step_definitions.

I’ve tried "cypress/e2e/*/*", "cypress/e2e/**/*", "cypress/e2e/**" etc. in the step_definitions value in package.json but not sure if I’m just getting it wrong and misunderstanding… Is it possible to split this out or not?

For reference, This is my folder structure

My package.json looks like this ;

{
  "name": "Cypress.Tests",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "cypress": "^13.15.1",
    "cypress-cucumber-preprocessor": "^4.3.1"
  },
  "cypress-cucumber-preprocessor":{
    "nonGlobalStepDefinitions": true,
    "step_definitions": "cypress/e2e/*" <-- My issue 
  }
}

and my cypress.config.js if relevant looks like this ;

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
      on('file:preprocessor', cucumber())
    },
    specPattern: "cypress/e2e/*.feature",
  },
});

How to Animate Expanding Content Height without a Fixed Value in CSS? [duplicate]

I have a button that toggles the height of an element between 0 and 200px. However, I want the height to expand fully to reveal all the content, rather than setting a fixed height of 200px. Using height: max-content displays the full content, but it doesn’t animate.

function toggle() {
  var element = document.getElementsByClassName("content")[0];

  element.classList.toggle("toggle");
}
.content {
  height: 0;
  overflow: hidden;
  transition: height 0.3s ease-in-out;
}

.content.toggle {
  height: 200px;
  overflow: scroll;
}
<button onclick="toggle()">Toggle</button>
<div class="content toggle">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pretium eu arcu non pulvinar. Pellentesque mattis elit posuere leo tristique volutpat. Aenean velit magna, lacinia ac ipsum at, commodo ultricies lacus. Nullam pulvinar ipsum tellus, sed ullamcorper
    justo rhoncus sed. Maecenas facilisis nibh at ante vehicula sodales. Proin pharetra vulputate risus, eget fringilla nulla. Nullam finibus commodo velit quis dignissim.
  </p>
  <p>
    Aenean in ultricies ex. Donec sodales eleifend quam vel placerat. Vestibulum quis tristique felis, in rhoncus ex. Proin tortor quam, viverra ac justo eget, consequat sollicitudin turpis. Aliquam in metus non leo vulputate dapibus. Pellentesque convallis
    scelerisque justo, sit amet rutrum mauris. Quisque pulvinar tellus eget orci blandit viverra. Mauris pharetra, erat non tempor convallis, nulla odio pulvinar elit, a convallis ligula lacus eu augue. Nullam id eros eget mauris semper condimentum. Suspendisse
    commodo mauris orci. Praesent pharetra, massa vestibulum semper gravida, mi sem placerat massa, nec rutrum erat lacus a neque. Etiam ac convallis diam, sit amet tempus lorem. Ut vestibulum lacus fringilla ante hendrerit, a pulvinar magna rhoncus.
    Nulla vel condimentum lacus.
  </p>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae feugiat libero. Sed sed augue sit amet tellus rhoncus volutpat. Sed quis est eu diam mollis tempus. In tristique sem enim, faucibus vestibulum neque consequat sed. Etiam id lacus eu sem
    porta eleifend. Nam iaculis nisl nec ex mattis, a dictum mi auctor. Proin aliquet efficitur sapien, eget faucibus eros vulputate nec. Mauris at tristique mi. Duis pellentesque sed lectus non lacinia. Vivamus tristique rutrum ipsum, in pellentesque
    velit iaculis id. Ut aliquet mauris ut libero gravida, quis mollis nisl pretium. Nam in nisl mauris. Nam rutrum eros ut leo aliquam condimentum. Suspendisse dapibus sed tortor quis accumsan. Maecenas ut diam vel tortor sollicitudin scelerisque sed
    sagittis neque. Nulla sit amet ultricies elit, at tempor ligula.
  </p>
</div>

<div>This is additional content.</div>

Is there a way to animate the height expansion without using a fixed height value in CSS?

Scrollbar issue and automatic time selection issue in Antd Datepicker(showTime)

I have added datepicker of antd in antd form and added disabledTime props and added props value to disabled the future time from current when today’s date is selected, but because i think it checking time at every second my scrollbar resetting automatically but in 5.0.0 and older version of antd is it working fine, and one more thing when I select today’s date it is automatically selecting the current time but in the new version it is not selecting, it is showing 00:00

This is my code in react project with antd form field

            <FormItem
              name={"incident_time_1"}
              rules={[
                {
                  required: true,
                  message: "Please enter incident time",
                },
              ]}
              {...formItemLayout}
              label='Incident Date Time'
            >
              <DatePicker
                format={"YYYY/MM/DD HH:mm"}
                showTime
                disabledTime={(current) => {
                  if (!current) return {};
                  const now = dayjs();
                  if (current.isSame(now, "day")) {
                    return {
                      disabledHours: () =>
                        Array.from({ length: 24 }, (_, i) => i).filter(
                          (hour) => hour > now.hour()
                        ),
                    };
                  }
                  return {};
                }}
                disabledDate={(current) =>
                  current && current > dayjs().endOf("day")
                }
                onChange={(value) =>
                  form.setFieldsValue({ incident_time_2: value })
                }
              />
            </FormItem>

Executing Stringified JavaScript Code from a Content Script

I’m developing a browser extension that enables users to run custom JavaScript code, i.e., code submitted by them, on webpages they specify. I’m developing this extension on Manifest V3. Since Manifest V3 prohibits methods that evaluate a string as code, I can’t use eval() or Function for that purpose. What is the standard approach to take user-submitted code and evaluate it from a content script on pages that they specify?

So far, I have been using setTimeout(my_code, 0) to evaluate user-submitted code, where my_code is a string containing the code to be evaluated. The first argument of this method is supposed to be a function, but when a string is submitted, it evaluates that string as JavaScript code for backward compatibility. This works well on most websites but fails on some websites due to strict CSP policies. I would like a method that is guaranteed to work safely on all websites regardless of their CSP policies.

Return sub array whose element has max value in a nested array [duplicate]

In an array I can find the max value like this

const Arr = [4,7,8,3,6];
const max = 
Math.max(...Arr);
console.log(max) // 8

Now I have a nested array like this,

const mainArr = [
{id:1, sub: "eng", no:3},
{id:2, sub: "kis", no:4},
{id:3, sub: "mat", no:5},
{id:4, sub: "sci", no:1},
{id:5, sub: "agr", no:4},
];

I want to return the sub array the highest no value

//{id:3, sub: "mat", no:5}

Kindly help