Displaying multiple returns from API JSON response

Attempting to display different API JSON responses on an HTML page instead of only one. The API request comes back with three different responses but the html only will show the first one. How do I get this to display all responses no matter the number of returns?

When requesting the information from API, this is the JSON response I get.

{
  "success":true,
  "error":null,
  "response":[
    {
      "periods":[
        {
          "summary":{
            "temp":{
              "maxC":6,
              "maxF":44,
              "minC":3,
              "minF":37,
              "avgC":3.8,
              "avgF":38.8,
              "count":177,
              "qc":10
            },
            "dewpt":{
              "maxC":4,
              "maxF":39,
              "minC":1,
              "minF":33,
              "avgC":1.6,
              "avgF":34.9,
              "count":177,
              "qc":10
            }
          }
        }
      ],
      "loc":{
        "long":-93.249759078026,
        "lat":44.977344633615
      }
    },
    {
      "periods":[
        {
          "summary":{
            "temp":{
              "maxC":7,
              "maxF":44,
              "minC":3,
              "minF":38,
              "avgC":4.2,
              "avgF":39.5,
              "count":159,
              "qc":10
            },
            "dewpt":{
              "maxC":4,
              "maxF":38,
              "minC":1,
              "minF":33,
              "avgC":1.5,
              "avgF":34.7,
              "count":159,
              "qc":10
            }
          }
        }
      ],
      "loc":{
        "long":-93.248161315918,
        "lat":44.962871551514
      }
    },
    {
      "periods":[
        {
          "summary":{
            "temp":{
              "maxC":7,
              "maxF":44,
              "minC":3,
              "minF":37,
              "avgC":4.2,
              "avgF":39.6,
              "count":828,
              "qc":10
            },
            "dewpt":{
              "maxC":5,
              "maxF":41,
              "minC":2,
              "minF":35,
              "avgC":2.8,
              "avgF":37,
              "count":828,
              "qc":10
            }
          }
        }
      ],
      "loc":{
        "long":-93.328,
        "lat":45.001
      }
    }
  ]
}

I am using this script on an html to show the results.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Weather Alerts</title>
    <script defer src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js"></script>

    <style>
      #alerts .tempicon {
        position: absolute;
        top: 5px;
        left: 10px;
        width: 170px;
        height: 170px;
      }
      #alerts .temptext {
        position: absolute;
        top: 55px;
        left: 30px;
        color: #ffffff;
        font-size: 50px;
        font-family: Arial, Helvetica, sans-serif;
        text-shadow: 2px 2px 5px black;
      }
    </style>
  </head>
  <body topmargin="0" leftmargin="0">
    <div id="alerts"></div>

    <script>
      window.onload = () => {
        const target = document.getElementById("alerts");
        const aeris = new AerisWeather("[CLIENT_ID]", "[CLIENT_SECRET]");
        const request = aeris.api().endpoint("observations/summary").place("minneapolis,mn").from("today");
        request.get().then((result) => {
          const periods = result.data;
          if (periods) {
            console.log(periods);
            const html = `
            <img src="https://dakotaradar.org/newicons/temps/${periods[0].periods[0].summary.temp.maxF}.png" class="tempicon">
            <div class="temptext">${periods[0].periods[0].summary.temp.maxF}&#176;F</div>
            `;
            target.innerHTML = html;
          }
        });
      };
    </script>
  </body>
</html>

Displaying Multi Returns from API Json Responds

Attempting to display different API JSON responses on a html instead of only one. The API request comes back with three different responses but the html only will show the first one. How do I get this to display all responses no matter the number of returns?

When requesting the information from API, this is the JSON response I get.

{
"success": true,
"error": null,
"response": [
    {
        "periods": [
            {
                "summary": {
                    "temp": {
                        "maxC": 6,
                        "maxF": 44,
                        "minC": 3,
                        "minF": 37,
                        "avgC": 3.8,
                        "avgF": 38.8,
                        "count": 177,
                        "qc": 10
                    },
                    "dewpt": {
                        "maxC": 4,
                        "maxF": 39,
                        "minC": 1,
                        "minF": 33,
                        "avgC": 1.6,
                        "avgF": 34.9,
                        "count": 177,
                        "qc": 10
                    }
                }
            }
        ],
        "loc": {
            "long": -93.249759078026,
            "lat": 44.977344633615
        }
    },
    {
        "periods": [
            {
                "summary": {
                    "temp": {
                        "maxC": 7,
                        "maxF": 44,
                        "minC": 3,
                        "minF": 38,
                        "avgC": 4.2,
                        "avgF": 39.5,
                        "count": 159,
                        "qc": 10
                    },
                    "dewpt": {
                        "maxC": 4,
                        "maxF": 38,
                        "minC": 1,
                        "minF": 33,
                        "avgC": 1.5,
                        "avgF": 34.7,
                        "count": 159,
                        "qc": 10
                    }
                }
            }
        ],
        "loc": {
            "long": -93.248161315918,
            "lat": 44.962871551514
        }
    },
    {
        "periods": [
            {
                "summary": {
                    "temp": {
                        "maxC": 7,
                        "maxF": 44,
                        "minC": 3,
                        "minF": 37,
                        "avgC": 4.2,
                        "avgF": 39.6,
                        "count": 828,
                        "qc": 10
                    },
                    "dewpt": {
                        "maxC": 5,
                        "maxF": 41,
                        "minC": 2,
                        "minF": 35,
                        "avgC": 2.8,
                        "avgF": 37,
                        "count": 828,
                        "qc": 10
                    }
                }
            }
        ],
        "loc": {
            "long": -93.328,
            "lat": 45.001
        }
    }
]

}

I am using this script on an html to show the results.

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Alerts</title>
<script defer src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js"></script>

<style>
#alerts .tempicon {
  position: absolute;
  top: 5px;
  left: 10px;
  width: 170px;
  height: 170px;
}
#alerts .temptext {
  position: absolute;
  top: 55px;
  left: 30px;
  color: #ffffff;
  font-size: 50px;
  font-family: Arial, Helvetica, sans-serif;
  text-shadow: 2px 2px 5px black;
}

</style>

</head>
<body topmargin="0" leftmargin="0">

<div id="alerts"></div>

<script>

window.onload = () => {
const target = document.getElementById('alerts');
const aeris = new AerisWeather('[CLIENT_ID]', '[CLIENT_SECRET]');
const request = aeris.api().endpoint('observations/summary').place('minneapolis,mn').from('today');
request.get().then((result) => {
const periods = result.data;
if (periods) {
console.log(periods);
const html = (`
<img src="https://dakotaradar.org/newicons/temps/${periods[0].periods[0].summary.temp.maxF}.png" class="tempicon">
<div class="temptext">${periods[0].periods[0].summary.temp.maxF}&#176;F</div>
`);
target.innerHTML = html;
}
});
};

</script>

</body>
</html>

Using sprite animation to replace Pacman game

I’m fairly new to HTML/CSS/JS programming and could use some help.

I am trying to reverse engineer a Pacman clone originally built with HTML5/CSS3/JQuery. I have been making headway in getting what I needed to get done: I’ve added a custom overlay, changed some graphics around, etc. The wall I keep hitting is replacing the Pacman character with a custom one. I’m able to add a static PNG file and use that, but I wanted it to be animated. So I learned how to create a spritesheet and animate it using requestAnimationFrame. I added it to the project, but I’m having trouble moving it dynamically using the javascript code.

Here is the code I originally had that replaces the original pacman character (which was created with a canvas arc method) with a static PNG image for each direction:

function drawPacman() { 

var ctx = getPacmanCanevasContext();
  
ctx.beginPath();

if (PACMAN_DIRECTION === 1)  {
    img = document.getElementById("pacmanright");
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
} else if (PACMAN_DIRECTION === 2) { 
    img = document.getElementById("pacmandown");     
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
} else if (PACMAN_DIRECTION === 3 ) {                
    img = document.getElementById("pacmanleft");
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
} else {
    img = document.getElementById("pacmanup");
    ctx.drawImage(img, PACMAN_POSITION_X - (PACMAN_SIZE / 2), PACMAN_POSITION_Y - (PACMAN_SIZE / 2), PACMAN_SIZE, PACMAN_SIZE); 
}

  //ctx.arc(PACMAN_POSITION_X, PACMAN_POSITION_Y, PACMAN_SIZE, startAngle, endAngle, false);
  //ctx.lineTo(lineToX, lineToY);
  //ctx.fill();
  ctx.closePath();
}

So I went about creating an spritesheet animation inside of a canvas element.

window.onload = function() {
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");
 
var myImage = new Image();
myImage.src = "https://i.ibb.co/NrJYyQj/spritesheet2-removebg-preview.png";
myImage.addEventListener("load", loadImage, false);

var shift = 0;
var frameWidth = 133;
var frameHeight = 114;
var totalFrames = 3;
var currentFrame = 0;

function loadImage(e) {
  animate();
}

function animate() {

requestAnimationFrame(animate);

context.clearRect(0, 0, 133, 114);

context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
 
shift += frameWidth + 1;
 
  /*
    Start at the beginning once you've reached the
    end of your sprite!
  */

  if (currentFrame == totalFrames) {
    shift = 0;
    currentFrame = 0;
  }
 
  currentFrame++;

}
}

I only got as far as making it appear in the game, but I can’t figure out how to move it dynamically in JS similar to the drawPacman function above. I made some attempts to no avail:

function positionCanvas(canvasId, x, y) {
  const direction = document.getElementById(canvasId);
  const ctx = canvas.getContext("2d")
  direction.style.position = "absolute";
  direction.style.left = x + "px";
  direction.style.top = y + "px";
}

function drawPacman() { 

var ctx = getPacmanCanevasContext();
  
  ctx.beginPath();

if (PACMAN_DIRECTION === 1)  {
    right = document.getElementById("myCanvas");
    positionCanvas(right, PACMAN_POSITION_X, PACMAN_POSITION_Y); 

It doesn’t position the canvas element where I want it. Just stays at 0,0 unless I hard code a position in a CSS file.

I hope my explanation made enough sense. I can share more code if needed.

Javascript upload from local file to string? [duplicate]

I want to make an HTML form, with a Browse button to choose a file to upload, and a Submit button.

enter image description here

I know how to do that if I was making it submit the file to the server. But what if I want to parse the file in JS? Can I make the submitted file into a Blob or a string somehow?

This must be straightforward, but I’ve searched around and I can’t find the answer!

handleInputChange data input synchronising to all other rows

I have a LWC which diaplays a table of a custom object called ‘Specifications’ which a are grouped by Opportunity line items (parent record of the specifications.

The Opportunity row was read only, but I’ve now added two editable fields (Opp_Delivery_Initial__c and Opp_Sales_Initial__c). They work as they should, except, when adding a value to any one of the new fields in the Opportunity row, it simultaneously populates it into all of the other Opportunity line item rows. I’m not sure if i have variables muddled up, but they seem to be consistent. Ive added a screen shot of LWC in use showing the issue and the handleInputChange below, along with the html. Any help would be appreciated.

JS handleInputChange:

    handleInputChange(event) {
        const fieldName = event.target.dataset.field;
        const recordId = event.target.dataset.id;
        const newValue = event.target.value;
        
        // Clone the opportunityProducts array for immutability
        let updatedProducts = this.opportunityProducts.map(product => {
            // Check if the event's record ID matches the product
            if (product.lineItemId === recordId) {
                // Create a new object for the product with the updated field
                return { 
                    ...product, 
                    [fieldName]: newValue 
                };
            } else if (product.specifications) {
                // Clone the specifications array for immutability
                const updatedSpecifications = product.specifications.map(spec => {
                    if (spec.Id === recordId) {
                        return { ...spec, [fieldName]: newValue };  // Update specific specification
                    }
                    return spec;
                });
                // Return the product with the updated specifications
                return { ...product, specifications: updatedSpecifications };
            }
            return product;
        });
    
        // Update the tracked property
        this.opportunityProducts = updatedProducts;
    }      

html:

                    <template for:each={opportunityProducts} for:item="lineItem">
                        <tr key={lineItem.lineItemId} class="group-header">
                            <template if:true={isEditing}>
                                <td colspan="9">
                                    {lineItem.Opportunity_Type__c} Opportunity: QTY: {lineItem.quantity} - {lineItem.Opportunity_Product_Name_Editible__c}: 
                                    <div class="normal-text"> - {lineItem.description}</div>
                                </td>
                            </template>
                            <template if:false={isEditing}>
                                <td colspan="7">
                                    {lineItem.Opportunity_Type__c} Opportunity: QTY: {lineItem.quantity} - {lineItem.Opportunity_Product_Name_Editible__c}: 
                                    <div class="normal-text"> - {lineItem.description}</div>
                                </td>
                            </template>
                    
                            <!-- Editable Delivery Initial Field in Group Header Row -->
                            <td class="delivery-initial-cell">
                                <template if:true={isEditing}>
                                    <lightning-input
                                        variant="label-hidden"
                                        data-id={lineItem.lineItemId} 
                                        value={lineItem.Opp_Delivery_Initial__c} 
                                        onchange={handleInputChange} 
                                        data-field="Opp_Delivery_Initial__c">
                                    </lightning-input>
                                </template>
                                <template if:false={isEditing}>
                                    {lineItem.Opp_Delivery_Initial__c}
                                </template>
                            </td>
                    
                            <!-- Editable Sales Initial Field in Group Header Row -->
                            <td class="sales-initial-cell">
                                <template if:true={isEditing}>
                                    <lightning-input
                                        variant="label-hidden" 
                                        data-id={lineItem.lineItemId} 
                                        value={lineItem.Opp_Sales_Initial__c}
                                        onchange={handleInputChange} 
                                        data-field="Opp_Sales_Initial__c">
                                    </lightning-input>
                                </template>
                                <template if:false={isEditing}>
                                    {lineItem.Opp_Sales_Initial__c}
                                </template> 
                            </td>
                            <template if:true={isEditing}>
                                <td>                                
                                </td>
                            </template>
                        </tr>

Tried to add new editable fields to the Opportunity line item row and ensure that any changes are logged and updates saved back to Salesforce.

Expected, when inputting a value into one of these new fields, that it only updates the current record, not all the other records.

Loading Audio Text Tracks programmatically

From the WebVTT API docs

A text track and cues can be defined in a file using the WebVTT File
Format, and then associated with a particular <video> element using
the <track> element.

Alternatively you can add a TextTrack to a media element in JavaScript
using HTMLMediaElement.addTextTrack(), and then add individual VTTCue
objects to the track with TextTrack.addCue().

I have a vtt file and I’m using new Audio(src); with no <audio> element in the html. Is it not possible to add a text track with a vtt file without an actual <audio> element or do I have to parse the vtt file myself and call addCue for each cue defined in the file?

I’m not using <audio> elements because I need to load about 20 audio files (with vtt files) and play them in a specific order. Maybe I could have one <audio> element and reuse it?

what is 1′”5000 IP address

I use some capture request for check any attack on my web application or not , today I found this (1′”5000) in my Columns That Store Src IP Send the Request , And Here What it send :


{
    "destinationIP": "MY.IP.IS.HERE",
    "destinationPort": 80,
    "headers": {
        "referer": "1'"3000",
        "accept-language": "1'"6000",
        "client-ip": "1'"4000",
        "host": "mydomain.com",
        "connection": "Keep-alive",
        "x-forwarded-for": "1'"5000",
        "accept-encoding": "gzip,deflate,br",
        "user-agent": "1'"2000",
        "via": "1'"7000",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
    },
    "sourcePort": 60486,
    "sourceIP": "103.161.35.121",
    "requestURI": "/fonts/danapro/index/1'"1000",
    "httpMethod": "GET",
    "queryString": "N/A",
    "parameters": {}
}

it’s The Code for get SRC IP :

    private String getClientIpAddress(HttpServletRequest request) {
        for (String header : TextUtils.HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }

        return request.getRemoteAddr();
    }

And HEADER_TO_TRY :

    public static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    };

And Question is how can getClientIpAddress return 1′”5000 to me? and what it is?

Tailwind custom classes overriding using class-variance-authority

I defined the following classes on the tailwind.config.ts file

const config: Config = {
  content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
  theme: {
    extend: {
      colors: {
        "light-white": "var(--light-white)",
        "light-red": "var(--light-red)",
      },
      borderWidth: {
        lg: "50px",
        "lg-long": "85px",
      },
    },
  },
  plugins: [],
};

And the following variant for a div component

const customVariants = cva("size-0", {
  variants: {
    size: {
      lg: `border-t-lg
           border-l-lg-long
           border-b-lg`,
    },
    color: {
      red: `border-t-white
           border-l-light-red
           border-b-white`,
    },
  },
});
<div className={cn(customVariants ({ color, size }))} />

When applying the variants to my component, the color classes override the size classes

Output:

<div class="size-0 border-t-white border-l-light-red border-b-white"></div>

If I swap the color and size definition positions, the size classes override the color classes

const customVariants = cva("size-0", {
  variants: {
    color: {
      red: `border-t-white
           border-l-light-red
           border-b-white`,
    },
    size: {
      lg: `border-t-lg
           border-l-lg-long
           border-b-lg`,
    },
  },
});

Output:

<div class="size-0 border-t-lg border-l-lg-long border-b-lg"></div>

It works if I apply the tailwind classes directly to the div

<div className="size-0 border-t-lg border-l-lg-long border-b-lg border-t-white border-l-light-red border-b-white" />

It also works if I remove the custom borderWidth classes (border-t-lg, border-l-lg-long and border-b-lg) from size variant

const flagVariants = cva("size-0", {
  variants: {
    color: {
      red: `border-t-white
           border-l-light-red
           border-b-white`,
    },
    size: {
      lg: `border-t-[50px]
           border-l-[85px]
           border-b-[50px]`,
    },
  },
});

Output:

<div class="size-0 border-t-white border-l-light-red border-b-white border-t-[50px] border-l-[85px] border-b-[50px]"></div>

It seem when using class-variance-authority and custom classes, tailwind thinks the border color/width are the same property, it overrides some clases and does not apply both.

In this code snippet you can see how the component should look like.

*, ::before, ::after {
    box-sizing: border-box;
    border-width: 0;
    border-style: solid;
}

.bg {
  background-color: black;
  min-height: 200px;
  min-width: 200px;
  display: grid;
  place-items: center;
}

.size-0 {
  width: 0px;
  height: 0px;
}
.border-t-white {
  border-top-color: white;
}
.border-l-light-red {
  border-left-color: red;
}
.border-b-white {
  border-bottom-color: white;
}
.border-t-lg {
  border-top-width: 50px;
}
.border-l-lg-long {
  border-left-width: 85px;
}
.border-b-lg {
  border-bottom-width: 50px;
}
<div class="bg">  
  <div class="size-0 border-t-lg border-l-lg-long border-b-lg border-t-white border-l-light-red border-b-white" ></div>
</div>

How can I fix this? Thanks in advance.

How to solve a dynamic import in all CommonJS modules. (Electron-Store)

I’m developing a desktop application with Electron, and I have a problem with local data storage. My goal is to check if the user is already logged in using a locally stored token. If the token exists, the application should directly open the main window. Otherwise, it should first display a loading window and a login window (console.log("Token is Null")).

However, when I try to import the electron-store library, I get an error.

const Store = require('electron-store');
const store = new Store();

let mainWindow;

function createMainWindow(alrealdyLogin) {
    mainWindow = new BrowserWindow({
        width: 300,
        height: 400,
        frame: false,
        show: true,
        transparent: false,
        resizable: false,
        fullscreenable: false,
        titleBarStyle: 'customButtonsOnHover',
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            enableRemoteModule: false,
            nodeIntegration: false
        },
        icon: path.join(__dirname, 'icon.png')


    });

    mainWindow.loadFile('html/loading.html');
}

app.on('ready', () => {
    const token = store.get('token');

    if (token) {
        createLoginWindow(false);
        createMainWindow();
    } else {
        createLoadingWindow(true);
        createLoginWindow();
    }
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    const token = localStorage.getItem('token');
    if (BrowserWindow.getAllWindows().length === 0) token == null ? console.log("Token is Null") : createMainWindow();
});

The error:

App threw an error during load Error [ERR_REQUIRE_ESM]: require() of ES Module C:UsersNarzayProjetsMeagan ClientLauncher Electronnode_moduleselectron-storeindex.js from C:UsersNarzayProjetsMeagan ClientLauncher Electronmain.js not supported.
Instead change the require of index.js in C:UsersNarzayProjetsMeagan ClientLauncher Electronmain.js to a dynamic import() which is available in all CommonJS modules.
at c._load (node:electron/js2c/node_init:2:16955)
at Object. (C:UsersNarzayProjetsMeagan ClientLauncher Electronmain.js:3:15)

Alert Pop-Up:

A JavaScript error occurred in the main process

Uncaught Exception:

Error [ERR_REQUIRE_ESM]: require() of ES Module C:UsersNarzayProjetsMeagan ClientLauncher Electronnode_moduleselectron-storeindex.js from
C:UsersNarzayProjetsMeagan ClientLauncher Electronmain.js not supported. Instead change the require of index.js in C:UsersNarzayProjetsMeagan ClientLauncher Electronmain.js to a dynamic import() which is available in all CommonJS modules.
at c._load (node:electron/js2c/node_init:2:16955)
at Object. (C:UsersNarzayProjetsMeagan ClientLauncher
Electronmain.js:3:15)

I would like to recover the “token” value in the “localStorage”:

localStorage.setItem('token', data.token);

React component will not update when using redux and createSelector, not detecting UI changes

I created a selector of users in a group in my immutable redux state:

import { useStore } from 'react-redux';
import { createSelector } from '@reduxjs/toolkit'

const selectGroup = (state) => state.group;

const memoizedUsers = createSelector([selectGroup], (group) => {
    return group.get('users').toJS();
})

const useMemoizedUsers = () => {
    const store = useStore();
    return memoizedUsers(store.getState());
}

and then in my component I am displaying a list of the users with the option to delete a user:

const DeleteButton = ({ rowIndex )} => {
    const dispatch = useDispatch();
    return (
     <Button onClick={() => {
        dispatch({
          type: '@@group/removeUser',
          payload: { rowIndex }
        })
      }}>
       Delete
     </Button
    )
}

const columnDefs = [
    {
      headerName: 'Name',
      field: 'name',
    },
    {
      headerName: 'Age',
      field: 'age',
    },
    {
      headerName: '',
      field: 'onDelete',
      cellRenderer: ({ node: { rowIndex } )} => {
        return (
          <DeleteButton rowIndex={rowIndex} />
        )
      }
    }
];

const UserList = () => {
    const users = useMemoizedUsers();

    return {
        <Grid 
          rowData={users}
          columnDefs={columnDefs}
        />
    }
}

When I click delete, I see the redux store being updated ==> from 10 users down to 9 users.
However, my UserList component is not rerendering and the UI still displays all 10 Users.

Anyone know how to force the component to update or am I using the createSelector incorrectly?

If I change const users:

const users = useSelector((state) =>
  state.group.get('users')?.toJS()
}

The component rerenders and the user list updates, but I get that redux warning that Selector unknown returned a different result when called with the same parameters. This can lead to unnecessary rerenders.

Further, I can rewrite the UserList like this:

const UserList = () => {
    const users = useSelector((state) =>
      state.group.get('users');
    }

    return {
        <Grid 
          rowData={users.toJS()}
          columnDefs={columnDefs}
        />
    }
}

Writing the component this way rerenders the UI and the redux warning goes away, but this defeats the purpose of using the createSelectors

I want the modal window to display an error message before closing

router.post("/login", async (req, res) => {
const { username, password } = req.body; // Formdan gelen veriyi al

try {
const request = new sql.Request();
const result = await request
  .input("username", sql.VarChar, username) // Kullanıcı adını parametre olarak ver
  .input("password", sql.VarChar, password) // Şifreyi parametre olarak ver
  .query(
    "SELECT * FROM Kullanicilar WHERE kullaniciAdi = @username AND kullaniciSifre = @password"
  ); // Sorgu

if (result.recordset.length > 0) {
  // Kullanıcı bulunduysa giriş başarılı
  console.log("giriş başarılı");
  res.render("user-page");
} else {
  // Kullanıcı bulunamadıysa hata mesajı
  console.log("Geçersiz kullanıcı adı veya şifre");
  res.render("index", {
    errorMessage: "Hatalı kullanıcı adı veya şifre girdiniz.",
  });
}
} catch (err) {
console.error("Giriş işlemi sırasında hata oluştu:", err);
res.status(500).send("Giriş sırasında bir hata oluştu.");
}});
 

<div class="giris gizle">
  <button class="giris-kapat">&times;</button>
  <h1 class="giris-name">Giriş</h1>
  <div>
    <form action="/login" method="POST">
      <ul class="giris-list">
        <li class="giris-item">
          <p class="giris-text">Kullanıcı Adı:</p>
          <input type="text" name="username" />
        </li>
        <li class="giris-item">
          <p class="giris-text">Şifre:</p>
          <input type="password" name="password" />
        </li>
      </ul>
      <% if (typeof errorMessage !== 'undefined') { %>
      <p id="error-message" style="color: red; margin-top: 10px">
        <%= errorMessage %>
      </p>
      <% } %>
      <button type="submit" class="giris-btn">Giriş</button>
    </form>
  </div>
</div>

In this code, if the user information is entered incorrectly on the login page in the modal window, I want an error to be returned with red text on the login button before the modal window closes. But now, this code returns an error, but it redirects to the /login page and closes the modal window. I would be happy if you help.

canvas.toDataURL with webp not working on iPad Chrome and Safari

I am trying to manipulate images via javascript using canvas.toDataURL('image/webp', 0.8); but although it works on Android and Windows it does not work on IOS (iPad) which returns a png instead.

Same goes for canvas.toBlob()

I am using Safari 16.6 and Chrome 130.0 on the ipad

https://jsfiddle.net/gdp70xsf/

function doConvert() {
  const fileInput = document.querySelector("input[type='file']");
  const img = document.querySelector("img");
  const canvas = document.querySelector("canvas");
  const p = document.querySelector("p");
  const ctx = canvas.getContext("2d");

  const file = fileInput.files[0];

  if (file) {
    const reader = new FileReader();

    reader.onload = function (e) {
      const imgElement = new Image();
      imgElement.src = e.target.result;

      imgElement.onload = function() {
        // Set up the canvas size
        const width = imgElement.width;
        const height = imgElement.height;
        const dpr = window.devicePixelRatio || 1;

        canvas.width = width * dpr;
        canvas.height = height * dpr;

        // Apply scaling and draw image onto canvas
        ctx.scale(dpr, dpr);
        ctx.drawImage(imgElement, 0, 0, width, height);

        // Convert to WebP and display in the img element
        let dataUrl = canvas.toDataURL("image/webp", 0.8);
        img.src = dataUrl;

        p.innerHTML = navigator.userAgent+'<HR>'+dataUrl.substring(0,30)+'...'; // Logging the base64 string for reference
      };
    };

    reader.readAsDataURL(file);
  }
}
</script>
img, canvas {
  width:auto;
  height:50vh;
  vertical-align:top;  
}
canvas {
  border:solid 1px orange;
}
img {
  border:solid 1px red;  
}
div {
  margin:10px;
}
<input type="file" onChange="doConvert()" />
<div>canvas:<canvas></canvas> img:<img /></div>
<div>
  <p></p>
</div>

Is there a way around this (I need to place a canvas manipulated image back into an <img> as a webp on any device type – including the Apple ones)?

Check If Equal Value in Multiple Arrays [duplicate]

I have 3 arrays named “localCodes”, “standardCodes”, and “specialCodes”. I am trying to confirm if there are any distinct values that appear in all 3 arrays.

What is the most efficient way of going about this?

EDIT:

Below is the code I was playing with, I just feel like there is a simpler way here that I am not getting

Example data set:

localCodes = [1,2,3,4]
standardCodes = [10,2,11,44]
specialCodes = [99,98,89,2]

With that set I would want to return true because 2 is found in each of the 3 arrays.

var longest = localCodes
var longFlag = 'local'
if(standardCodes.length > longest.length){
    longest = standardCodes
    longFlag = 'standard'
}
if(specialCodes.length > longest.length){
    longest = specialCodes
    longFlag = 'special'
}

for(l=0; l<longest.length; l++){
    if(longFlag == 'local'){
        //code here
    }
    if(longFlag == 'standard'){
        //code here
    }
    if(longFlag == 'special'){
        //code here
    }
}

Run javascript function using symfony form and twig

I’m trying to execute a function when the user press a key on a form input. To do so, I’m using Symfony with Twig and webpack. Now, when I pass the attribute onkeydown to call the function test(), in the browser I always get the error:

Uncaught ReferenceError: test is not defined onkeydown http://localhost/register:1

Here’s an excerpt of the code

My form: RegistrationFormType.php

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('username', TextType::class, [
            'attr' => ['onkeydown' => 'test()']
        ])
}

My js test file:

function test(){
    console.log("test");
}

App.js:

import './bootstrap.js';
import './styles/new-account.css';
import './controllers/test.js'

On my browser:
enter image description here

How to ensure file integrity when using pre-signed URLs for S3 uploads in Node.js?

I’m working on an application that allows users to upload files directly to AWS S3 using pre-signed URLs. I’m using the AWS SDK for JavaScript and the getSignedUrl() function to generate the pre-signed URLs.

My current implementation is as follows:
userRouter.js

userRoutes.post("/get-presigned-upload-url", validateJwtToken,
    validateRequest(userValidators.uploadFileSchema),
    awsS3Controller.getPresignedDownloadUrl);

awsS3Controller.js

const awsS3Service = new AWSS3Service();

export const getPresignedDownloadUrl = async (req, res) => {
    try {
        const { folderPath, fileMetadata } = req.body;
        const { contentType, originalFileName, size, ChecksumSHA256 } = fileMetadata;
        const uniqueFileName = awsS3Service.generateUniqueFileName(originalFileName);
        const key = `users/${req.user.id}/${!folderPath ? "" : folderPath}${uniqueFileName}`;
        const presignedUrl = await awsS3Service.generatePresignedUploadUrl(
            key,
            contentType,
            { 
                metadata: { originalFileName, size, ChecksumSHA256 },
                checksumSHA256: ChecksumSHA256
            }
        );
        res.status(HttpStatus.OK).json({ message: "File uploaded successfully", presignedUrl: presignedUrl });
    } catch (error) {
        res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: error.message });
    }   
}

awsS3Service.js

class AWSS3Service {
    async generatePresignedUploadUrl(key, contentType, options = {}) {
        try {
            const command = new PutObjectCommand({
                Bucket: this.bucketName,
                Key: key,
                ContentType: contentType,
                Metadata: options.metadata,
                ACL: options.acl || 'private',
                ChecksumAlgorithm: options.checksumAlgorithm || "SHA256",
                ChecksumSHA256: options.checksumSHA256,                
            });
            return await getSignedUrl(this.s3Client, command, { 
                expiresIn: options.expiresIn || this.defaultExpiry,
                signableHeaders: new Set(['host', 'x-amz-sdk-checksum-algorithm', 'x-amz-checksum-sha256', 'content-type'])
            });
        } catch (error) {
            console.error('Presigned URL Generation Error:', error);
            throw new Error(`Failed to generate presigned URL: ${error.message}`);
        }
    }
}

The issue I’m facing is that I want to ensure the file being uploaded to the pre-signed URL is the same as the one used to generate the pre-signed URL. In other words, I want to verify the file integrity between the pre-signed URL generation and the actual file upload.

I’ve tried using the ChecksumSHA256 option in the PutObjectCommand and the signableHeaders option in the getSignedUrl() function, but I’m still not sure if this is the correct approach. For example, I’ve also read that I have to turn on checksums in S3.

AWS S3 Checksum setting

What is the correct/complete way to achieve this verification?