accessing objects in new array

const lineExampleOne = [{
    weight:150,
    floor: 2,
    },{
    weight:200,
    floor: 3,
    },{
    weight:120,
    floor: 5,
    },{
    weight:80,
    floor: 2,
    },{
    weight:180,
    floor: 4,
    },{
    weight:170,
    floor: 4,
    }];

let newArray = [];

lineExampleOne.forEach((person)=>{
  newArray.push(person);
})

console.log(newArray);

this returns something like this [object Object],[object Object] etc…

How do I correctly add each object to my empty newArray? How do I properly access each objects properties from my newArray? and is there a way to test how many unique values I have for floors and weight of all the objects in my newArray?

I need to validate an input regardless of font format

I have written a short script that works pretty much as a quiz. It displays a dialogue box making a question and you input the answer. However, my intention is that whether the answers are provided in capital or lowercase text, the app should grant you a point regardless.
My question is, how can I give a point regardless of the font format of the input?
I saw someone using toUpperCase() at some point in the code, but I am not quite sure.

let questions = [
  ["Who created Demon Slayer?", 'Gotouge'],
  ['Who was the first demon that ever existed?', 'Muzan'],
  ['Who was the flame pillar of the Demon Slayer Corps?', 'Rengoku']
];


let item = '';
let score = 0;

function quiz (arr){
  for (let i = 0; i<questions.length; i++){
    let interrogate = prompt(`${arr[i][0]}`);
    if(interrogate === arr[i][1]){
      score++;
    }
  }
}


quiz(questions);
console.log(score);

download multiple images as zip file using javascript in angular

I need to download a list of images using javascript in angular as a zip file..
so my website is an shopping website..if we click on a product it will open allthe images related to it.This is same as we have in amazon and flipkart shopping websites.
i had a button and when i click on the button i need to download all the images that are showing when clicked on the respective product.
The problem I am facing is that there are no images in the downloaded file.
here is the html part

<a class=”download” (click) = “download()” >

below is the .ts part and “this.Images” has all the image urls

download(){
let count = 0;
const zip = new JSZip();

this.Images.forEach((item) =>{
  this.fileName = this.getfileName(item);
  JSZipUtils.getBinaryContent(item, (err,data)=>{
    if(err){
      throw err;
    }
    console.log(data);    
    zip.folder("images").file(this.fileName,data,{base64: true});
    count++

    if(count === this.Images.length){
      zip.generateAsync({type:'blob'}).then((content)=>{
          fileSaver.saveAs(content, this.fileName);
      });
    }
  });
});
}

getfiileName() method is as below

getfileName(str){
return str.substring(str.lastIndexOf('/')+1);

}

Note : I dont want to use JSZipUtils in my code

document.getElementById(“mydiv”) returning null

I am trying to make a div element draggable in react with typescript, following is the code

function dragElement(elmnt:HTMLElement) {
 var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0
 if (document.getElementById(elmnt.id + "header")) {
   document.getElementById(elmnt.id + "header")!.onmousedown = dragMouseDown
 } else {
   elmnt.onmousedown = dragMouseDown;
 }

 function dragMouseDown(e:MouseEvent) {
   e = e || window.event;
   e.preventDefault();
   pos3 = e.clientX;
   pos4 = e.clientY;
   document.onmouseup = closeDragElement;
   document.onmousemove = elementDrag;
 }

function elementDrag(e:MouseEvent) {
  e = e || window.event;
  e.preventDefault();
  pos1 = pos3 - e.clientX;
  pos2 = pos4 - e.clientY;
  pos3 = e.clientX;
  pos4 = e.clientY;
  elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}

function closeDragElement() {
  document.onmouseup = null;
  document.onmousemove = null;
  }
 }

if (document.getElementById("mydiv") != null) {
dragElement(document.getElementById("mydiv")!);
}

  export const PopUpCommon= () =>{ 
    return(
    <div id="mydiv">
    <div id="mydivheader">Click here to move</div>
    <p>Move</p>
    <p>this</p>
    <p>DIV</p>
  </div> 
  )}

Here I am checking document.getElementById(“mydiv”) is null or not to avoid the console error ‘Cannot read properties of null (reading ‘id’)’, since that is returning null dragElement is not getting called. Why is that returning null even if an element with the id “mydiv” is present ?

Refresh the ag-grid server side table after applying sort or filter to any column using Reactjs

I am using ag-grid for displaying data in Reactjs.

The data are getting sorted and filtered from the backend, I just need to display data in the table.

The problem I am facing is on grid load it loads the data correctly but does not load the data after applying the filter.

function DashboardServerSideTable(props: AgGridTableProps) {
const { columns } = props;

// states
const [gridApi, setGridApi] = React.useState<GridApi>();
const { state, dispatch } = useContext(DashboardContext);

// Query & Mutation
const [getDashboardTableData, { data, refetch, loading }] = useLazyQuery(GET_DASHBOARD_TABLE_DATA, {
    notifyOnNetworkStatusChange: true, // This will send the network status
    fetchPolicy: 'no-cache',
});

const handleGridReady = useCallback((params) => {
let { filterModel}: IServerSideGetRowsRequest = params;
    const dataSource = {
        rowCount: 1000,
        getRows: function (params: IServerSideGetRowsParams) {
            getDashboardTableData({
                variables: {
                    tab: state.tab,
                    headerFilter: state.card,
                    filtergroup: JSON.stringify(filterModel),
                },
            }).then(res => JSON.parse(res.data.lpapqpprojectsumm.body)).then(({ datarows, size, total }) => {
                params.successCallback(datarows, total);
            }).catch(err => params.fail());
        }
    };
    params?.api?.setServerSideDatasource(dataSource);
}, []);


return (
    <div className={clsx(styles.table, 'ag-theme-alpine')}>
        <AgGridReact
            pagination
            paginationAutoPageSize
            onGridReady={handleGridReady}
            defaultColDef={defaultColDef}
            rowModelType="serverSide"
            serverSideStoreType="partial"
            cacheBlockSize={1000}
        >
            {columns.map((col) => (
                <AgGridColumn {...col} key={col.field} />
            ))}
        </AgGridReact>
    </div>
)

}

How can I return two parameters when onfocus?

I have a function that returns the currently focused item’s ID and a random string. I use a different function to parse through that string.

I need to also return the aria-label, which is where I’m having trouble. None of my current attempts have worked.

Button:

<button class="some-class" id="some-id" aria-label="some-label" onfocus="reply_focus(this.id)">Button Text</button>

Javascript:

var global_focused_id = -1;
function GetLastFocusedId() {
  return global_focused_id;
}
function reply_focus(focused_id) {
  global_focused_id = focused_id + ' || ' + Math.random();
}

What returns now is:
some-id || 0.1234567890

What I’d like returned is:
some-id || some-label || 0.1234567890

Redirect automatically all links from one basic-URL to another?

I have the following problem: We have a website that have multiple hrefs for images – They all uses the same domain. Which is something like:

<a href="http://img.example-domain.com">Avatar</a><br/>

But the server this domain is using is currently is inactive, but it’ll come back at some point, i just do not know when.

Now, we have a new image server, that is hosted on AWS.
But since the code have many entries using the old domain, i would like to know how can i redirect ALL requests to that domain to another one, instead of editing the code itself.

For example: Each request from “img.example-domain.com”, shall be redirected to “img.example-domain.com.amazon.etc”

Please, how can i do this?

I am using Apache, and would prefer a solution that envolves using Apache Rewrite module or something like that… But if it is not possible, i will be OK too with a code solution.

Thanks in advance, to everyone.

How to check oldest transaction on Ethereum address?

I have a large amount of Ethereum address that I want to get the oldest transaction on that wallet

If the oldest transaction on that address is more than 10 days then I will keep it, other address will be discard

What is the best way to do this kind of task? checking it one by one is too tedious

Thank you very much for helping me

AJAX loading content into page

Im trying to include a file on my server using AJAX, the only problem is that it stops my php code from working.

the page im using ajax at:

<div id="content">
<!--- HERE GOES CONTENT --->
</div>
<script>
$.ajax({
    url: 'https://mywebsite.com/func/contentpage.php',
    dataType: 'html'
})
.done(function(data) {
    // Assuming the request returns HTML, replace content
    $('#midten').html(data);
});
    </script>

contentpage.php codes

<?php
$g1 = $database->query("SELECT * FROM `users` WHERE `sesid` = '" . $_SESSION["uises"] ."' AND abd='" . $_SESSION["uiabd"] ."'");
$ui2 = $g1->fetch_object();

echo $ui2->name;
?>

The code above should echo a name from the database but for some reason it does not.

if i use php and include the page like this: include("/func/contentpage.php");
it echo the name whitout any problems

but when trying to load the page whit ajax it does not echo a name or anyhting.
The reason im using AJAX is to load content when buttons is clicked whitout the browser having to reload.

any one know how i can solve this probelm whit AJAX or know another method i could use in php to change the path in include whitout having to reload the webpage/load the whole website again.

How to update firebase without changing syntax

I have no idea how to do this, but unfortunately the project ive been working on is running off of firebase 7.14.0, as a newer developer I have found this to be very tough to work with because there is no documentation. Is there anyway I can move to firebase 9 without having to change all of the syntax?

Supabase .limit prevents row being found

I’m using supabase in a Next.js app.

In my login flow the user submits a form containing their username/password. Within my api route I use .toLowerCase() on the username then pass it to the supabase api to see if a user exists with that username as follows;

let { data: staff, error } = await supabase
    .from('staff')
    .select('*')
    .eq({ username: lowercaseUsername })

This works fine – the user is found, password/password hash is compared and I get logged in.

However when I add a .limit(1) to the query, my row in the database is no longer found.

let { data: staff, error } = await supabase
    .from('staff')
    .select('*')
    .eq({ username: lowercaseUsername })
    .limit(1)

Can anyone shed any light on why this might be?

How to keep socket.io client in frontend code

I am just learning webdev and want to try to make a multiplayer game using Express and socket.io

I can make a server with socket.io in it which listens. That part works fine.

However when I try to connect a client, this only works if I let the HTML file with the following in it be served by the server like follows:

Server code:

const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)

const port = 3000

io.on('connection', (sock) => {
    console.log('client connected')
})

// This seems to be necessary, but I don't want it to be!!!
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html')
})

server.listen(port, () => {
    console.log(`Server listening on port ${port}`)
})

This index.html has the following at the bottom:

<script src="/socket.io/socket.io.js"></script>
<script>const socket = io()</script>

However I want to keep all my frontend code seperate from the server. I made a seperate repository for the frontend and backend. I want the frontend to contain all the UI logic and use only data calls (AJAX) to get Json data from the server. So I want to put this index.html file in my frontend code only.

Yet if I do this the connection doesn’t work.

I can start the server fine.
I open index.html from WebStorm which also creates a server for this which I configured to also listen to port 3000

Yet it cannot find /socket.io/socket.io.js and I get the following error in the console.
It also doesn’t work if WebStorm runs on a different port.

The resource from “http://localhost:3000/socket.io/socket.io.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

How can I keep this html in my client repo only and still work with socket.io, or is this not possible?

Save canvas element as image in static website

I have a static website where users can go through a set of questions. At the end of each round, I want to store the result that is in a div as an image.

I was able to use html2canvas to convert the div into an image. I was also able to show the image in the page. But I would like to store these images. What’s the best way to do it? I tried this approach.

I set up a very simple node.js API server with a POST endpoint. The parameter to this endpoint is the canvas.dataURL() string which I will store as an image file in the server.

The problem I am facing is that this string is very long and I get a 413 error when I test my API. What’s the best way to work around this?

Creating an index signature in Typescript with required AND optional keys

I’m trying to find a more elegant solution for creating a type that allows certain keys of it’s index signature to be optional.

This may be a use case for generics, but I can’t seem to crack it.

Currently constructing it like this:

//  Required and optional keys allowed as indexes on final type
type RequiredKeys = 'name' | 'age' | 'city'
type OptionalKeys = 'food' | 'drink'

//  Index types use to combine for final type
type WithRequiredSignature = {
    [key in RequiredKeys]: string
}
type WithOptionalSignature = {
    [key in OptionalKeys]?: string
}

//  Build type with required and optional properties on index signature
type FinalType = WithRequiredSignature & WithOptionalSignature

//  Test objects with functional autocomplete
const test1: FinalType = {
    name: 'Test',
    age: '34',
    city: 'New York'
}

const test2: FinalType = {
    name: 'Test',
    age: '34',
    city: 'New York',
    drink: 'Beer'
}

const test3: FinalType = {
    name: 'Test',
    age: '34',
    city: 'New York',
    food: 'Pizza'
}