Webpack: Dynamically create from images in a directory

My simplified filesystem:

|webpack.config.js
|package.json
|dist
   |-index.html
|src
   |-index.js
   |card
      |-card.js
   |images
      |-imageImporter.js
      |-coffee.jpg
      |-chocolate.jpg
      |-...

I want to write something along the lines of:

imageImporter.js

const images = [];
const imageContext = require.context('./', false, /.(jpg|jpeg|png)$/);

imageContext.keys().forEach((imagePath) => {
  images.push(imagePath);
});

export default images;

Puts all the image paths in an array images

index.js

import images from './images/imageImporter.js';
import {dom_createCard} from './card/card.js';
let dom_contentDiv = document.querySelector('div#content');

const dom_createCardsHolder = () => {

    let dom_cardsHolder = document.createElement('div');

    for (let i=0; i< images.length; i++) {
        let imagePath = "../images/"+images[i].substring(2);
        let dom_card = dom_createCard(imagePath); // THE CALL IS HERE
        dom_cardsHolder.appendChild(dom_card);
    }

    return dom_cardsHolder;
}

dom_contentDiv.appendChild(dom_createCardsHolder());

Puts all image cards in the dom_cardsHolder

card.js

require.context('../images', false, /.(png|jpg|jpeg|gif|svg)$/);

const dom_createCard = (imagePath) => {
    let dom_card = document.createElement('img');
    console.log("image path given to me is:"+ imagePath);
    // Prints: image path given to me is:../images/coffee.jpg

    dom_card.src = imagePath; // WHAT TO DO HERE INSTEAD?

    dom_card.width = 300; 
    return dom_card;
}


export {dom_createCard};

Creates image card

package.json

    module: {
        rules: [
            {
                test: /.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
        ],
    },

Bug

Things don’t work. After printing all the image paths it gives me:
GET http://127.0.0.1:5500/images/<Image Name>.jpg 404 (Not Found)

Note

If in card.js i do instead

import coffeeImage from '../images/coffee.jpg'
// ...
const dom_createCard = (imagePath) => {
    // ...
    dom_card.src = coffeeImage;
    // ...
}
// ...

It works (but it just prints the coffee.jpg and not the other images)

Javascript trying to get the non repeating values from 2 inputs

I am trying to get the non repeating values from the 2 inputs.
Ex: If I type some names in the first input: George, Michael, John and in 2nd input: John, Robert, Michael.
should return in the 3 input: George, Robert.

# const resultElement = document.getElementById('ResultField');
      const text1Element = document.getElementById('old');
      const text2Element = document.getElementById('new');

      function myFunction() {
        const x = text1Element.value;
        const y = text2Element.value;

        //split the textareas by newlines
        const xArr = x.split('n');
        const yArr = y.split('n');

        const result = xArr
          .map((line, index) => {
            return line + ' ' + yArr[index];
          }, '')
          .join('n');

        const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) !== i);

        resultElement.value = removeDuplicates;
      }

using this line I get the duplicates. ex: Michael, John
const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) !== i);

if I change “!” to “=” I get the combine input. ex: George, Michael, John, Robert
const removeDuplicates = result.split(/s/g).filter((word, i, arr) => arr.indexOf(word) === i);

Many thanks.

Why is $ defined, even in about:blank?

I’ve opened a new tab in Firefox and a blank tab in Chrome. When I type $ into the console, the variable is already defined. What is this, why does it exist, and what does it do?

enter image description here

If it is jQuery, it must be a very old/minimal version. $('body') returns the body element, but $('body').text() throws Uncaught TypeError: $(...).text is not a function.

How to make an image input save to files? [closed]

I’m trying to make a program that takes an image as input and that converts it to a list of pixels (like [[0, 255, 230], [283, 58, 86]]). Also, i want it to be in a format of 100×100 px, to not make it crash.

I need to save the image to files as image.png, and, after, make a list of its pixels.

I don’t really know how to do it, i just know how to take an image input: <input type="file" id="imageInput" accept="image/*">

I tried to search in the internet, but i didn’t find how to save it and how to convert it to a list of pixels.

can’t use scss loader to config webpack

I’m just started using Webpack and it’s quite complicated for me.
After many hours I understood that it just support JS/Json to build but we can handle other types with loader. So far I succeed to load .css files with below config

module: {
        rules: [
            {
                test: /.css$/,
                use: [
                    "style-loader",
                    {
                        loader: "css-loader",
                        options: {
                            importLoaders: 1,
                            modules: true,
                        },
                    },
                ],
                include: /.module.css$/,
            },
            {
                test: /.css$/,
                use: ["style-loader", "css-loader"],
                exclude: /.module.css$/,
            },
        ]
    }

but now i want to make another config to load SCSS but i’m failed with every try.
please guide me.

I also tried to install many packages to load scss such as

npm install sass-loader sass webpack --save-dev

and after that I changed webpackconfig to :

module: {
    rules: [
      {
        test: /.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },

but it still can’t build it and give me the following commend:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

How to handle turn of the year logically with moment.js?

Basically, I’m having a dynamic dropdown with x isoWeeks starting from the current one. A function is called when the isoWeek in the dropdown is selected.

var currentWeek = localStorage.getItem('currentWeek');
var currentYear = localStorage.getItem('currentYear');

var dropdownKalender = document.getElementById('dropdown_kalender');
var newWeek = dropdownKalender.options[dropdownKalender.selectedIndex].value;
localStorage.setItem('currentWeek', newWeek);

The newWeek variable is the selected week in moment().isoWeek() format. Now I’m in need of the logic for checking if the selected week is in the next year (or if it’s back in the current year in case a future week has been selected before). I’m pretty sure it’s about checking if a week is greater than the other, but as said before, I’m stuck at the logic part.

Add delay to promise.resolve [duplicate]

I have the following class which generates Mock data. I would like to add a 2 second delay to simulate slow network. How can I add a timeout before returning the resolved promise?

Thanks,

export class MockGenerator {
    public getMockRecord = async () => {
        return Promise.resolve({id:123});
    };
}

Fullcalendar: How to fix position of events

When creating an event using Ruby on Rails with Fullcalendar.js, they get this strange margin on the top of the slot. On the image below, the event (in red) should start at 11am and finish at 12am, but is not following the grid.

The object sent it’s in the correct time and timezone.

enter image description here

Here is my code:

const calendar = new Calendar(calendarEl, {
        plugins: [interactionPlugin, timeGrid, dayGrid, listView],
        initialView: 'timeGridWeek',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
        },
        select: info => {
            // Remove the previous click handler if it exists
            if (currentSelectHandler) {
                document.getElementById('confirmBookingBtn').removeEventListener('click', currentSelectHandler);
            }

            currentSelectHandler = () => {
                console.log(info);
                addBooking(info.startStr, info.endStr, bookableGroupId, calendar);
                modalInstance.hide();
            };

            // Attach the new click handler
            document.getElementById('confirmBookingBtn').addEventListener('click', currentSelectHandler);

            // Set the confirmation text and show the modal
            createConfirmationText(info.startStr, info.endStr, pricePerHalfHour);
            modalInstance.show();
        },
        selectAllow: function(selectInfo) {
            // Parse the selection start and end times
            const start = new Date(selectInfo.startStr);
            const end = new Date(selectInfo.endStr);

            // Check if the selection is within business hours
            return isSelectionWithinBusinessHours(start, end, availabilities);
        },
        eventClick: info => {
            if (currentCancelHandler) {
                // Remove the previous click handler if it exists
                document.getElementById('confirmCancelBtn').removeEventListener('click', currentCancelHandler);
            }

            currentCancelHandler = () => {
                cancelBooking(info.event.id);
                info.event.remove();
                cancelModalInstance.hide();
            };

            // Attach the new click handler and show modal
            document.getElementById('confirmCancelBtn').addEventListener('click', currentCancelHandler);
            cancelModalInstance.show();
        },
        nowIndicator: true,
        slotMinTime: '06:00',
        slotMaxTime: '22:00',
        slotDuration: '00:30:00',
        slotLabelFormat: {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
        },
        eventTimeFormat: {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
        },
        allDaySlot: false,
        selectable: true,
        selectOverlap: false,
        businessHours: businessHoursConfig,
        events: [...events]
    });

    calendar.render();

Using R shiny, trying to pass reactive value into plotting module applied to different plots

I have written a plotting module in R that allows the user to change axis values based on double click. In the example below, I have shortened the problem to the x-axis title. When the x-axis value is double clicked, a modalDialog will appear allowing the user to change the axis name. However, when I use this module multiple times in an application only one of the plots have the double click effects.

I believe this is a problem with ids, and I should use moduleServer(id, function(input, output, session) {}). However, I can’t seem to pass reactive values in when I try to use the moduleServer function. I get the following error:

Warning: Error in module: unused arguments (childScope, function () 
{
    .dependents$register()
    if (.invalidated || .running) {
        ..stacktraceoff..(self$.updateValue())
    }
    if (.error) {
        stop(.value)
    }
    if (.visible) .value else invisible(.value)
})

Here is the code as condensed as I could make it. The plotUI module uses javascript code to detect the double click but I do not think this is the issue.

plotUI:

plotUI <- function(id) {
  ns <- NS(id)
  
  tagList(
    div(
      style = "position:relative;",
      plotOutput(ns("plot")),
      tags$style(type = "text/css", 
                 paste0("#", ns("plot"), " { cursor: default; }")),
      tags$script(HTML(
        sprintf(
          "$(document).on('shiny:idle', function() { 
      var plotElement = document.getElementById('%s'); 
      if(plotElement) { 
        var threshold = 50; 
        // Remove the existing event listener to avoid accumulation
        plotElement.removeEventListener('dblclick', doubleClickHandler);
        plotElement.onmousemove = function(evt) { 
          var rect = plotElement.getBoundingClientRect(); 
          if (rect.bottom - evt.clientY <= threshold) { 
            plotElement.style.cursor = 'pointer'; 
          } else { 
            plotElement.style.cursor = 'default'; 
          } 
        }; 
        plotElement.addEventListener('dblclick', doubleClickHandler);
      } 
    });

    function doubleClickHandler(evt) {
      console.log('double click event');
      var clickedY = evt.clientY; 
      var clickedX = evt.clientX; 
      var svgBounds = document.getElementById('%s').getBoundingClientRect(); 
      var threshold = 50; 
      if (svgBounds.bottom - clickedY <= threshold) { 
        Shiny.setInputValue('%s', { zone: 'x', ts: new Date().getTime() });
      } 
    }",
    ns("plot"), ns("plot"), ns("label_edit")
        )
      ))
    )
  )
}

plotServer:

plotServer <- function(input, output, session, plot_obj) {
  # plotServer <- function(id, plot_obj) {
  # moduleServer(id, function(input, output, session) {
  
  # Store x-axis value
  x.val <- reactiveVal("x")
  
  # Render plot from input object
  output$plot <- renderPlot({
    p <- plot_obj()
    p <- p + xlab(x.val())
    return(p)
  })
  
  # Change x label when double click is detected
  observeEvent(input$label_edit, {
    showModal(modalDialog(title = "Edit x",
                          textInput(inputId = session$ns("newLabel"), label = "Label Text", value = x.val()),
                          footer = actionButton(session$ns("update_label"), "Update"),
                          easyClose = TRUE
    ))
  })
  
  # Update x-axis value on button press
  observeEvent(input$update_label, {
    x.val(input$newLabel)
    removeModal()
  })
  # })
}

app:

library(shiny)
library(ggplot2)

data(iris)
ui <- fluidPage(
  selectInput("x_var", "x-var:", choices = names(iris)),
  selectInput("y_var", "y-var:", choices = names(iris), selected = names(iris)[2]),
  plotUI("plot1"),
  plotUI("plot2")
)

server <- function(input, output, session) {
  
  to.plot <- reactive({
    ggplot(iris, aes_string(x = input$x_var, y = input$y_var)) + geom_point()
  })
  
  to.plot2 <- reactive({
    ggplot(iris, aes_string(x = input$x_var)) + geom_histogram(binwidth = 0.2) 
  })
  
  callModule(plotServer, "plot1", to.plot)
  callModule(plotServer, "plot2", to.plot2)
}

shinyApp(ui, server)

What I want is that both the plots are able to create modalDialogs independent from each other that can change their x-axis titles, while keeping the reactivity to be changed in the app (in this case with the selectInputs).

How can I get a fully working ‘echo’ command in a Jquery terminal?

Im trying to get a echo command to echo what the user types in a JQuery termial.

This is the code I have

  echo: function(...args) {
      this.echo(args)
  },

I tried to use the …args method but when I do that, it will display what I typed, but add a bunch of spaces between them. For example, if i type: “echo hi bro how are you :)” it will return what I said in a this.echo saying the same thing but with 4 spaces between each word.

How can I remove those spaces so that it will directly show what the user typed.

Creating a temporary image when a key is pressed in Javascript

I’m working on a personal website for fun, and I want to add an easter egg where if you press “e” anywhere while on the site, a little image of a speech balloon will appear for a bit and then disappear. It’d be fun if it could make a noise or appear randomly on the page as well but really I just want to get it working at all. I’m not very familiar at Javascript sadly.

So far I’ve looked around and I found things showing an image on a click, and translating a key press into triggering a click event, but I can’t seem to string them together right… I feel like I’ve gone through a bunch of methods and ended up scrapping all of them. I’ve looked into scripts that create images on a click but I don’t know how to translate that into a keypress.

This is what I currently have. As far as I understand it, I set up a listener event to look for when the key is pressed, and then it runs the function showImage that changes the display for the div from none to block. But when I press E nothing happens.

<script>
var addEvent = document.addEventListener ? function(target,type,action){
    if(target){
        target.addEventListener(type,action,false);
    }
} : function(target,type,action){
    if(target){
        target.attachEvent('on' + type,action,false);
    }
}

addEvent(document,'keydown',function(e){
    e = e || window.event;
    var key = e.which || e.keyCode;
    if(key===101){
        showImage();
    }
});

const showImage = () => {
        document.getElementById("first").style.display ='block';
    }
</script>

<body>
<div id="first" style="height:400px; width:400px; display:none;">
    <img src="test.png"> 
</div>
</body>

Sveltekit – loading spinner for multiple load-sources with auto-retry

I’m trying to make a spinner for sveltekit pages that is not too complex, but not sure what would be the simplest way to do it.

When page loads, it load maplibre map. It can fail during that process – so I need to show a spinner and if request fails – I retry the request after 5 seconds. After maplibre map has been loaded, I still do not hide the spinner since I need to load additional data with fetch. This time also I have to retry if request fails (and keep retrying until loaded). Only when everything is loaded I should hide the spinner.

This is the sample code:

onMount(() => {
    let map = new Map({}); //maplibre map
    map.on('load', function(){
        let data = fetch('url').catch((e)=>{
            //means additional load failed - retry in 5 sec.
        });
    });
    map.on('error', function(){
        //means map load failed - retry in 5 sec.
    });
});

I think that retrying logic makes everything much more complex, since I need to keep reference to each loading function and call it again. Not sure if there is already some best-practice solution for this use-case.

creating a discord text channel js

is it possible to create with javascript not node js a text channel on discord so that I can still add headers to bypass the CORS blocker

chatgpt: it is true?>
I’m afraid creating a text channel on Discord directly from client-side JavaScript in a web browser isn’t possible due to security restrictions, specifically CORS (Cross-Origin Resource Sharing) policies.

CORS policies prevent web browsers from making requests to different domains unless the server explicitly allows it. Discord’s API doesn’t support direct requests from client-side JavaScript in a browser due to these security concerns. Even if you try to add headers to bypass the CORS blocker, the Discord API itself doesn’t permit requests from frontend JavaScript due to the potential security risks involved in exposing tokens and sensitive data.

For interactions with Discord’s API that involve creating or modifying server resources (such as channels), you need to do it through a backend server that communicates with the Discord API. This way, you can securely handle authentication and make requests to Discord’s API without CORS restrictions. The backend server can handle the bot token and perform the necessary actions on the Discord server.

In short, to create a text channel on Discord, you’ll need a backend server using a language like Node.js, Python, or any other server-side language that can communicate securely with the Discord API. This way, you can ensure the security of your bot token and perform actions on Discord without running into CORS issues.

How to fix “Uncaught TypeError: Cannot read properties of undefined” [duplicate]

What I understood from that error is that a var that I am trying to use is undefine. But even when I’ve defined it, the error remains.

Error code: JavaScript.js:125 Uncaught TypeError: Cannot read properties of undefined (reading ‘lat’)
Here’s the code:

let city_name;
// city_name = document.getElementById("user_city").value = city_name; // stores the textbox input here
console.log(city_name)

// displaying the current location of the user
if (!navigator.geolocation) {
    throw new Error("No geolocation available!");
}

function CityName(lat, lng){
    var url = `https://api.openweathermap.org/geo/1.0/reverse?lat=${lat}&lon=${lng}&appid=ece4c4a2a34f182d239e3e769f6b2801`
    fetch(url)
        .then(response => response.json())
        .then(response => {
            console.log(response);
            city_name = response[0].name;
            console.log(city_name)
            document.getElementById("city").innerHTML = city_name; // displays the city name on the page
        })
}

function Direct_Geocoding(city){ // converts the city input to lat and long 
    city_name = city;
    fetch(`https://api.openweathermap.org/geo/1.0/direct?q=${city_name}&limit=2&appid=ece4c4a2a34f182d239e3e769f6b2801`)
        .then(response => response.json())
        .then(response => {
            console.log(response)
            document.getElementById("city").innerHTML = city_name;
            //const lat = response[0].lat;
            //const lon = response[0].lon;
            
            //console.log(lat, lon);
            // const values = [lat, lon];
            
            return{
                lat: response[0].lat,
                lon: response[0].lon
            };
        })
}

function LocationInformation(lat, lng){
    //Fetch weather data from api
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=ece4c4a2a34f182d239e3e769f6b2801&units=Metric`)

        //converts response into json object
        .then(response => response.json())
        .then(response => {

            //Display whole api in browser console
            console.log(response);

            //Copy one element of response to the HTML paragraph
            document.getElementById("weather_").innerHTML =
                response.weather[0].description;

            let icon_ = response.weather[0].icon;
            document.getElementById("icon").src =
                `https://openweathermap.org/img/wn/${icon_}@2x.png`;

            //copy wind speed element
            document.getElementById("windSpeed").innerHTML =
                "Wind Speed: " + response.wind.speed + "mph";

            //copy temp element
            document.getElementById("temp").innerHTML = Math.round(response.main.temp) + "° C";

            //copy feels like temp element
            document.getElementById("feels_like").innerHTML =
                "Feels like " + Math.round(response.main.feels_like) + "° C";

        })

        .catch(err => {
            //Display error in console log
            console.log(err);
        })
}

function success(pos) {
    console.log(pos);
    const lat = pos.coords.latitude;
    const lng = pos.coords.longitude;

    CityName(lat, lng);

    LocationInformation(lat, lng);
    
}

function error() {

}

const options = {};


function My_Currentlocation(){
    console.log("Button has been clicked!!")

    navigator.geolocation.getCurrentPosition(success, error, options);
}

var submitButton = document.getElementById("city_search");
let buttonClicked = false;
submitButton.addEventListener("click", function handleClicked(){
    if(buttonClicked){
        buttonClicked = true;
        // City_Location(city_name);
    }
})

function City_Location(city){  // gets location of city in search bar
    city_name = city;
    console.log(city_name);
    if(buttonClicked = true){
        city_name = document.getElementById("user_city").value;
        const loc = Direct_Geocoding(city_name);
        let lat = loc.lat; // this is where the error points at. It says lat is not defined.
        let lng = loc.lon;
        // const[lat, lon] = Direct_Geocoding(city_name);
        LocationInformation(lat, lng);
    }   
}

//displays date and time
let time = document.getElementById("current_time");

setInterval(() => {
    let d = new Date();  // 2009-11-10
    const day = d.toLocaleString('default', {day: "numeric"})
    const month = d.toLocaleString('default', { month: 'long' });
    time.innerHTML = day + " " + month + ", " + d.toLocaleTimeString();
}, 1000)

Apologised if this is a bit messy. I feel I couldn’t just post the function alone as everything is interconnected.

Here is the link to the url to see everything fully.