How to prevent the images div from overflowing?

If I select multiple images, the div with class “images” overflows, I want it to be scrollable not to overflow and also want to keep the images aspect ratio, how do I do it?

**** Ignore this text, it’s just filler text because StackOverflow says “It looks like your post is mostly code; please add some more details.” ****
**** Ignore this text, it’s just filler text because StackOverflow says “It looks like your post is mostly code; please add some more details.” ****

function init() {
  let files = document.querySelector("input[name='files']");
  files.onchange = filesChanged;
}

function filesChanged(event) {
  let imagesDiv = document.querySelector(".images");
  while (imagesDiv.firstChild) imagesDiv.firstChild.remove();

  for (let file of this.files) {
    let fr = new FileReader();
    fr.onloadend = () => {
      let img = new Image();
      img.title = file.name;
      img.src = fr.result;
      imagesDiv.appendChild(img);
    };
    fr.readAsDataURL(file);
  }
}

window.addEventListener("load", init);
* {
  font-family: inherit;
  font-size: inherit;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  word-break: break-word;
}

html,
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-size: 1rem;
  width: 100%;
  height: 100%;
  padding: .25rem;
}

.hide {
  display: none !important;
}

.column {
  flex: 1;
  display: flex;
  flex-flow: column;
}

.row {
  flex: 1;
  display: flex;
  flex-flow: row;
}

.gap {
  gap: .25rem;
}

input,
textarea {
  flex: 1;
  border: 1px solid lightgray;
  border-radius: .25rem;
  padding: .5rem;
}

textarea {
  resize: none;
  min-height: 10rem;
}

.form {
  background-color: bisque;
  border: 1px solid lightgray;
  border-radius: .25rem;
  width: 100%;
  max-width: 62.5rem;
}

.form fieldset {
  border: none;
  padding: .5rem;
}

.form label {
  color: gray;
  font-size: small;
}

.images {
  background-color: gray;
  border: 1px solid lightgray;
  display: flex;
  flex-flow: row;
  align-items: start;
  overflow-x: auto;
}

.images:empty {
  display: none;
}

.images img {
  flex: 1;
  max-width: 150px;
  max-height: 150px;
}
<form action="#" class="form">
  <fieldset class="column gap">
    <div class="column">
      <label>Title</label>
      <input type="text" name="title">
    </div>
    <div class="column">
      <label>Details</label>
      <textarea name="details"></textarea>
    </div>
    <div class="column gap">
      <input type="file" name="files" multiple accept="image/png, image/jpeg">
      <div class="row gap images"></div>
    </div>
  </fieldset>
</form>

HTML + java script ! help + web methods , html or java script is not working the way it should

so what i need is when i login i need the web method return a list of patients and the html page display the list under the log in field set
here is the html page

<!DOCTYPE html>

<html>
    <head>
        <title>Doctor page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <fieldset>
            <legend>doctor login</legend>
            <form id="docLOG" onsubmit="Docauth(event)">
            <label for="docuser">Username:</label>
            <input type="text" id="docuser" name="docuser" required><br><br>
            <label for="docpass">Password:</label>
            <input type="text" id="docpass" name="docpass" required><br><br>
            <input type="submit" value="Login">
            </form>
        </fieldset> 
      <div id="patientList" style="display: none;">
        <h2>Patient List</h2>
        <ul id="patientListItems"></ul>
    </div>

    <script>
        function Docauth(event) {
            event.preventDefault(); // Prevent default form submission
            
            var DU = "doc1";
            var DP = "pass1";
            
            var docuser = document.getElementById("docuser").value;
            var docpass = document.getElementById("docpass").value;
            
            // Check if username and password match expected values
            if (docuser === DU && docpass === DP) {
                // If true, make AJAX request to call the web method getPatientList()
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'http://localhost:8080/HHH', true);
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        var patients = JSON.parse(xhr.responseText); // Parse the response
                        displayPatientList(patients); // Display patient list
                        alert("done");
                    } else {
                        alert("Error occurred while calling the web method");
                    }
                };
                xhr.onerror = function () {
                    alert("Error occurred while processing request");
                };
                xhr.send();
            } else {
                alert("Invalid username or password");
            }
        }

        function displayPatientList(patients) {
            var patientListItems = document.getElementById('patientListItems');
            patients.forEach(function (patient) 
            {
                var listItem = document.createElement('li');
                listItem.textContent = 'ID: ' + patient.id + ', Age: ' + patient.age + ', Last Visit: ' + patient.lastVisit;
                patientListItems.appendChild(listItem);
            });
            document.getElementById('patientList').style.display = 'block'; // Show patient list
        }

    </script>
    </body>
</html>

and here is the Web services that i use this web method (getpatientlist) in the glassfish tester works fine like here

Method returned
java.util.List : “[services.Patient@2d29960b, services.Patient@7609b141, services.Patient@6b708324]”

but in the html page nothing is working except the login part works when entering the wrong password or username an alert shows that something is wrong

package services;

import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

@WebService
public class Docservices 
{
    
    @WebMethod
    public List<Patient> getpatientslist() 
    {
        List<Patient> patients = new ArrayList<>();
        patients.add(new Patient(1, 30, "2023-12-20"));
        patients.add(new Patient(2, 45, "2024-02-10"));
        patients.add(new Patient(3, 25, "2024-01-15"));
             return patients;
    
    }
    
}

it should normally says Done and display the list but nothing is showing not even the Done alert

Why is an empty string in JavaScript equals to zero?

I understand the concepts of type coercion and type conversion, but they don’t clarify why an empty string is zero. Not NaN, but zero.

console.log(Number('')) // 0

The only explanation I was able to found is that an empty string is a part of falsy values, but it covers only a boolean context.

This MDN docs page states “an empty string is zero” as a fact, as well as Language Specification (if I get it right).

Is there a rationale or deeper meaning for such behavior?

How to dependent dropdown with Laravel Inertia Vue?

I have AddressController, and inside that controller, i have function loadCity with other CRUD function like this:

public function loadCities(Request $request)
    {
            $provinceId = $request->province_id;
            $cities = Province::where('province_id', $provinceId)->get();

            return response()->json($cities);
    }

And my create.vue script:

<Multiselect v-model="form.province_id" :options="provinces" valueProp="id" label="name" trackBy="name" :searchable="true" placeholder="Select:" @change="loadCities" />

const cities = ref([]); 

const loadCities = async () => {
    try {
        const response = await router.get(`/apps/address/load-cities/${form.province_id}`);
        cities.value = response.data;
    } catch (error) {
        console.error(error);
    }
}

and this is my route web.id:

Route::resource('/address', AddressController::class, ['as' => 'apps'])
    ->middleware('permission:address.index|address.create|address.edit|address.delete')
    ->except(['show']);

        Route::get('/address/load-cities/{province_id}', [AddressController::class, 'loadCities'], ['as' => 'apps'])
        ->name('apps.address.loadCities');

But the problem now is error:

The GET method is not supported for this route. Supported methods: PUT, PATCH, DELETE.

Can i create dependent dropdown using intertia router like this? Or i have something missing with my code? Thanks before.

Tring to render label on nodes and edges in a d3 force graph, but they are not visible although available under dom tree

To render label on nodes, i have tried various method like this:

    var labels = node.append("text")
        .text(function (d) { return d.label; })
        .attr('x', 6)
        .attr('y', 3);

    node.append("title")
        .text(function (d) { return d.label; });

Or something like this:

 node.append("text")
        // .attr("text-anchor", "middle")
        // .attr("alignment-baseline", "middle")
        .text(d => d.label)
        .attr('x', 6)
        .attr('y', 3);

Here is my complete code:

<svg id="chart">
</svg>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
    let drag = simulation => {

        function dragstarted(event) {
            if (!event.active) simulation.alphaTarget(0.3).restart()
            event.subject.fx = event.subject.x
            event.subject.fy = event.subject.y
        }

        function dragged(event) {
            event.subject.fx = event.x
            event.subject.fy = event.y
        }

        function dragended(event) {
            if (!event.active) simulation.alphaTarget(0)
            event.subject.fx = null;
            event.subject.fy = null;
        }

        return d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended)
    }


    let height = 600
    let width = 600

    let data = {
        "nodes": [{
            "id": "Myriel",
            "label": "Myriel name"
        },
        {
            "id": "Napoleon",
            "label": "Napoleon name"
        }
        ],
        "links": [{
            "source": "Myriel",
            "target": "Napoleon",
            "label": "hit me baby one more time"
        },
        {
            "source": "Napoleon",
            "target": "Myriel",
            "label": "meaw"
        }
        ]
    }

    const links = data.links.map(d => Object.create(d))
    const nodes = data.nodes.map(d => Object.create(d))

    const simulation = d3.forceSimulation(nodes)
        .force("link", d3.forceLink(links).id(d => d.id))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2))

    const svg = d3.select("#chart")
        .attr("viewBox", [0, 0, width, height])

    // Define the arrowhead marker
    svg.append("defs").selectAll("marker")
        .data(["end"])      // Different link/path types can be defined here
        .enter().append("svg:marker")    // This section adds in the arrows
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 15)
        .attr("refY", -1.5)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5");


    // Add the links with arrowheads
    const link = svg.append("g")
        .attr("stroke", "#999")
        .attr("stroke-opacity", 0.6)
        .selectAll("line")
        .data(links)
        .join("line")
        .attr("stroke-width", 1)
        .attr("marker-end", "url(#end)");  // Add the marker-end attribute to link

    link.append("text")
        .attr("text-anchor", "middle")
        .attr("alignment-baseline", "middle")
        .text(d => d.label);

    const node = svg.append("g")
        .attr("stroke", "#fff")
        .attr("stroke-width", 1.5)
        .selectAll("circle")
        .data(nodes)
        .join("circle")
        .attr("r", 5)
        .attr("fill", () => "#" + Math.floor(Math.random() * 16777215).toString(16))
        .call(drag(simulation))

    // node.append("text")
    //     // .attr("text-anchor", "middle")
    //     // .attr("alignment-baseline", "middle")
    //     .text(d => d.label)
    //     .attr('x', 6)
    //     .attr('y', 3);

    var labels = node.append("text")
        .text(function (d) { return d.label; })
        .attr('x', 6)
        .attr('y', 3);

    node.append("title")
        .text(function (d) { return d.label; });


    simulation.on("tick", () => {
        link
            .attr("x1", d => d.source.x)
            .attr("y1", d => d.source.y)
            .attr("x2", d => d.target.x)
            .attr("y2", d => d.target.y)

        node
            .attr("cx", d => d.x)
            .attr("cy", d => d.y)
    })

</script>

I wanted to create a graph like this:
cant visualize label on nodes using d3@v7

How can I do so?

Right now, it looks something like this:
enter image description here

Although it is available under dom, but it’s not visible. I have tried setting their position for quite a while.

Is Deno’s dynamic import() implementation conformant with ECMA-262?

Specification:

When using dynamic import() in Deno there is a strange behaviour that is exclusive to Deno: bare string specifiers don’t dynamically import the module and can be fashioned to consistently throw, see Deno dynamic import(“./exports”) throws module not found for “exports.js” dynamically created in the script.

After some research I located this Dynamic import module is not found when created after the application started. #20945 which while still open is marked as working as designed per Do not permission prompt for statically analyzable dynamic imports.

In the linked blog post https://deno.com/blog/v1.33#fewer-permission-checks-for-dynamic-imports we read

Keep in mind that permissions will still be checked for dynamic imports that are not statically analyzable (ie. don’t use string literals for the specifier):

import("" + "https://deno.land/std/version.ts");

import(`https://deno.land/std@${STD_VERSION}/version.ts`);

const someVariable = "./my_mod.ts";
import(someVariable);

This means we have to employ special treatment for ECMA-262 dynamic import() in Deno.

So, let’s test with a variable that is not a raw string that satisfies that Deno-specific special treatment of specifiers when using import() and see what happens

// test_dynamic_module.js

import { exists } from "https://deno.land/std/fs/mod.ts";

const [...modules] = Deno.args;

console.log({ modules });

if (await exists("node_modules")) {
  await Deno.remove("node_modules", {recursive: true});
}

for (const module of modules) {
  try {
    await import(module);
  } catch (e) {
    console.log(e);
  }
}
deno run -A test_dynamic_import.js npm:zod
{ modules: [ "npm:zod" ] }
TypeError: Loading unprepared module: npm:zod, imported from: file:///home/user/test_dynamic_import.js
    at async file:///home/user/test_dynamic_import.js:15:5 {
  code: "ERR_MODULE_NOT_FOUND"
}

We get TypeError: Loading unprepared module.

But why should a dynamic import() have to be prepared?

If we use static import things work as intended.

To me this is a bug that is asserted to be working as designed though effectively means dynamic import() in Deno is not dynamic at all.

Is Deno’s dynamic import() implementation conformant with ECMA-262?

How to intercept all network requests in a web page

I have a situation in which I need to monitor all network requests made by a web page. When I mean all network requests, I really mean absolutely all of them, that is:

  • all requests made from my web page (script or image downloads, XMLHttpRequest requests and so on…)
  • all requests made from scripts that have been downloaded from my web page, including scripts from other domains

In this latter case, if I am talking about the following scenario:

<!-- Let's say my web page is hosted at https://example.com/ -->
<html>
...
<script src="https://otherdomain.com/somescript.js"></script>
...
</html>

If somescript.js downloads stuff from the web, from its own domain or any other domain, I need to monitor that, too.

Is that at all possible?

So far, I tried with a service worker, and it does work, at least to some extent. Surprinsgly, some requests are not actually seen by my service worker. Its registration scope is /.

Next.js import bundle size

I am trying to import components based on variable. My point is to import just the one I want to reduce bundle size.

First Case:

 const componentMapONE = {
  'customers': dynamic(() => import('../../../pages/customers'), {
              loading: () => <FallbackSpinner />,
              ssr: false
            }),
 'brands': dynamic(() => import('../../../pages/brands'), {
              loading: () => <FallbackSpinner />,
              ssr: false
            }),  
// .... others hardcoded manually, or generated with logic doesn't matter same result
};

const importPromises = (componentNames: string[]) => {
  return componentNames.map(name => {
    const loadComponent = componentMap[name];
    if (!loadComponent) {
      throw new Error(`Component ${name} not found`);
    }
    return loadComponent;
  });
};

In this case I import from a map, that generated from logic or hardcoded.

Result: its importing all the hardcoded imports(6gb ram usage). Even when I don’t call importPromises function. At the end of the day application runs without error.

Second Case:

 // with variable... even when child is null

const importPromises = (componentUrls: string[]) => {
  return componentUrls.map((child: string) => {
    return dynamic(() => import(`../../../pages/${child}`), {
      loading: () => <FallbackSpinner />,
      ssr: false
    })
  })
}

// without variable...

const importPromises = (componentUrls: string[]) => {
  return componentUrls.map((child: string) => {
    return dynamic(() => import(`../../../pages`), {
      loading: () => <FallbackSpinner />,
      ssr: false
    })
  })
}

In this case I import with changing path with variable.
Result: Even when child is null, it imports all the pages(6.5gb ram usage). At the end of the day application runs without error.

Third Case:

 // with just string
 
 const importPromises = (componentUrls: string[]) => {
      return componentUrls.map((child: string) => {
        return dynamic(() => import(`../../../pages/customers`), {
          loading: () => <FallbackSpinner />,
          ssr: false
        })
      })
    }

In this case I import with just string without variable.
Result: Only customers page can be run, but ram usage is: 3.2gb which is lower.

Conculsion:

I know that next/dynamic doesn’t work with variabled paths, thats why I also tried First Case. Here I got confused, I cannot see a valuable use case for using next/dynamic. Or I am using it wrong. Either when I import normal without next/dynamic or with next/dynamic, I got same result.

So I want to ask what next/dynamic actually does ?

Thanks.

This asked many where but still I couldn’t find a solution for me.

Edit: With bundle size I mean the RAM usage at next dev. Which is next-server

Ram Usage:

How to have a modal popped up after a post controller has submitted, should I create a new controller for it? Im new to asp.net

here i have my LogIn Controller where if the log in is successful then a modal should pop up which will prompt the user to select mood:

[HttpPost]
public ActionResult LogIn(User u)
{
    var user = _userRepo.Table.Where(model => model.Username == u.Username && model.Password == u.Password).FirstOrDefault();
    try
    {
        if (_userRepo.Table.Where(model => model.Username == u.Username).FirstOrDefault().Password != u.Password)
        {
            ModelState.AddModelError("", "Invalid password");
            ViewBag.LoginSuccess = false;
            return View();
                }
        }
        catch (NullReferenceException)
        {
        ModelState.AddModelError("", "User not exist");
                ViewBag.LoginSuccess = false;
                return View();
        }
        catch (TargetException)
        {
        ModelState.AddModelError("", "User not exist");
                ViewBag.LoginSuccess = false;
                return View();
        }

    FormsAuthentication.SetAuthCookie(u.Username, false);
    ViewBag.LoginSuccess = true;
    Session["User"] = user;

    //return RedirectToAction("Register");
    return RedirectToAction("../UsersPage/ChooseMood");

again if log in was succssful, a modal should pop up instanly which will prompt user to select mood before proceeding to this controller:

public ActionResult UsersHome(string mood)
{
    if (User.Identity.IsAuthenticated)
    {
        return PartialView((User)Session["User"]);
        } else
        {
        return View("../Home/Index");
        }
}

what should be my approach? should I create new controller for the choose mood(modal pop up) then redirect to that UserHome controller?

Discord api fetch request authorization error

When i run this it always return 401 not authorized i have tried the channel id and token witch are redaced and it works it also works in python yet here it just refuses to.
Please help guys

          fetch(`https://discord.com/api/v9/channels/redacted/messages`, {
            mode: "no-cors",
            method: "POST",
            headers: {
              'Authorization' : `Bot redacted`,
              'Content-Type' : 'application/json',
            },
            body: JSON.stringify({
              content: message,
            })})

I have tried changing it and using axios but that runs into a dificult to solve cors issue.

Eleventy site builder: Make JavaScript function available for Nunjucks templates

How can I provide JavaScript functions for my Nunjucks templates when building websites with Eleventy?

Let’s suppose I have a Nunjucks layout file my_layout.njk in the folder _includes:

<!doctype html>
{% set targetItem = findItemById(items, itemId) %}
<p>The value of the item with id {{ itemId }} is {{ targetItem.val }}.</p>

The called function findItemById(items, id) is defined in the config file .eleventy.js in the project’s root folder:

module.exports = function(eleventyConfig) {
    eleventyConfig.addJavaScriptFunction("findItemById", function(items, id) {
        return items.find(item => item.id === id);
    });
};

The array of items to process is stored in the file items.json in the folder _data:

[
    {
        "id": "a",
        "val": "foo"
    },
    {
        "id": "b",
        "val": "bar"
    }
]

Finally, I have a liquid template file item_b.liquid in the project’s root folder to build a static html page with data from items array. When building the site, I know an item’s id and need to get it’s value.

---
layout: my_layout.njk
itemId: b
---

The desired output in the ‘_site’ folder would a html file item_b/index.html with the content

<!doctype html>
<p>The value of item with id b is bar.</p>

However, Eleventy cannot find the function findItemById. When running npx @11ty/eleventy I get the error message:

[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] 1. Having trouble writing to "_site/item_b/index.html" from "./item_b.liquid" (via EleventyTemplateError)
[11ty] 2. (./_includes/my_layout.njk) [Line 1, Column 32]
[11ty]   Error: Unable to call `findItemById`, which is undefined or falsey (via Template render error)

I am using Eleventy version 2.0.1 on Fedora 38 Linux.