getImageData() does not return correct RGB values

I’ve written a website that extracts pixel colors from an image. I do this by using getImageData on a canvas holding the image. However, I do not manage to get the correct values for this sample image.

When using Pillow to extract, for example, the first pixel color (x=0, y=0) it returns (49, 98, 173, 255) for the RGBA color space.

from PIL import Image 
im = Image.open('image.png').convert('RGBA')
pix = im.load()
print(pix[0, 0])

Also Java gives me the same results:

BufferedImage bufferedImage = ImageIO.read(new File("image.png"));
        int rawRGB = bufferedImage.getRGB(0, 0);
        Color color = new Color(rawRGB);

However when I use an HTML canvas I get the following values by getImageData: (26, 99, 179, 255).

        let image = new Image();
        const reader = new FileReader();

        image.addEventListener('load', function () {
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext("2d");
            canvas.width = this.width;
            canvas.height = this.height;
            ctx.drawImage(this, 0, 0);
            let data = ctx.getImageData(0, 0, 1, 1).data;
            document.getElementById('imageData').innerHTML = data;
        });

        image.addEventListener('load', function () {
            let canvas = document.createElement('canvas');
            let gl = canvas.getContext("webgl2");
            gl.activeTexture(gl.TEXTURE0);
            let texture = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, texture);
            const framebuffer = gl.createFramebuffer();
            gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this);
            gl.drawBuffers([gl.COLOR_ATTACHMENT0]);
            let data = new Uint8Array(1 * 1 * 4);
            gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, data);
            document.getElementById('webGl').innerHTML = data;
        });

        reader.addEventListener('load', (event) => {
            image.src = event.target.result;
        });

        var fileToRead = document.getElementById("yourFile");

        fileToRead.addEventListener("change", function (event) {
            var files = fileToRead.files;
            if (files.length) {
                reader.readAsDataURL(event.target.files[0]);
            }
        }, false);
<pre>Expected:  49,98,173,255<br>
ImageData: <span id="imageData"></span><br>
WebGL:     <span id="webGl"></span><br></pre>
<input type="file" id="yourFile" name="file">

I do not understand why this happens or how the browser comes up with these values. I’ve tried both Chrome and Firefox and they displayed the same incorrect values. I’ve read about premultiplied alphas but I don’t how this should affect my results as the picture does not make use of the alpha channel. Any help would be appreciated!

Next js ; static generation and SWR in single page

I m building a blog website in next js , the API for the blog is from some headless CMS.

In a page i want to do the following

  1. List some blogs.
  2. Set of buttons available, based on each button click different set of blogs are loading (should replace the blogs in #1).

Since SEO is needed I m pretty confused to use which approach should i choose.

What i thinking is i can use generate the initial list with
getStaticProps (Static Generation), and after loading i want to replace the blogs based on user action (button click).

But i m confused is it possible to use static generation and SWR in single page.

Can somebody give advise on my problem?.

Thanks in advance

Is it better to have data arranged with an array of objects or an object of objects for use in React? 🎅

I am structuring data to be used later to hydrate a table in react, where the data will change dynamically through WebSocket calls. Currently I have an array of objects:

result1
Array(2) [Object, Object]
    [[Prototype]]: Array(0)
    length: 2
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Array(0)

I can convert the arrays to objects using result = Object.assign({}, result1);:

result
Object {0: Object, 1: Object}
    [[Prototype]]: Object
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Object

With that data, and once I get the React UI setup, I will want to each pools object’s properties to be displayed in its own column:

enter image description here

Which is more convenient and recommended for use in my react application?

Regex match from digit to digit?

Is there a way to regex from digit to digit?
I have this tracklist:
“01. Intro 02. Waage 03. Hyänen (feat. Samra) 04. Ich will es bar (feat. Haftbefehl) 05. Am Boden bleiben (feat. Casper & Montez) 06. Panzerglas (feat. Face) 07. Sobald Du gehst 08. 90’s (feat. Olson) 09. Erzähl‘ mir nix (feat. Nio) 10. Dope & 40s 11. Lila (feat. Bosca) 12. Wo ich wohn‘ 13. Bahnen 14. 200K”

which I tried to split with /dd([^d]*)/g into objects. But I got as a result:

0: ""
1: ". Intro "
2: ""
3: ". Waage "
4: ""
5: ". Hyänen (feat. Samra) "
6: ""
7: ". Ich will es bar (feat. Haftbefehl) "
8: ""
9: ". Am Boden bleiben (feat. Casper & Montez) "
10: ""
11: ". Panzerglas (feat. Face) "
12: ""
13: ". Sobald Du gehst "
14: ""
15: ". "
16: ""
17: "’s (feat. Olson) "
18: ""
19: ". Erzähl‘ mir nix (feat. Nio) "
20: ""
21: ". Dope & "
22: ""
23: "s "
24: ""
25: ". Lila (feat. Bosca) "
26: ""
27: ". Wo ich wohn‘ "
28: ""
29: ". Bahnen "
30: ""
31: ". "
32: ""
33: ""
34: "0K"

How do I include the numbers 01,02,03… and what are the possibilites for cases like track 14 where the title track is “200k”

Text value doesn’t change in React Native app using Class Component

I have this react native app that shows the splash screen first and loads a home screen. The sample home screen shows text as “Demo Display” and I want to change it to “Text Changed!”. I’m using a stateful class component. But everytime I try to restart/reinstall/debug the app the text remains same as “Demo Display”. How can I fix this?

App.js

import React,{ Component } from 'react'
import { View, Text } from 'react-native'
import SplashScreen from 'react-native-splash-screen'

export default class App extends Component {

  componentDidMount() {
      SplashScreen.hide();
  }

  render() {
    return (
      <View>
        <Text>Text Changed!</Text>
      </View>
    );
  }
}

This is a screen shot of the app

Why’s my response being executed more than once with the correct data instead of just only once with useEffect()?

I know having an empty dependency [] executes useEffect() only once but when it does execute only once with an empty dependency [] – it logs an empty array in the console.

When it’s not empty, it just continuously logs with no end in sight. I’m not sure why it won’t log it correctly just one time with the data I need to use.

What am I doing wrong?

Code below:

const [uploadsData, setUploadsData] = useState([]);

const getUploads = async () => {
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    await axios.get('http://localhost:8000/api/get-uploads', {headers})
        .then(resp => {
            console.log(resp);
            setUploadsData([resp.data]);
        }).catch(error => {
        console.log(error);
    });
};

useEffect(() => {
    getUploads();
    // logs empty array in the console if dependency array is empty
    // logs correct data when dependency array isn't empty - i.e. [uploadsData]
    console.log(uploadsData);
}, []);

JavaScript form validation returns Uncaught TypeError regarding value property

I am working on a project website with a registration form in which I want to check if the password is ok, if the email is ok, and etc.
I get no output at all (No alerts) and the page just refreshes itself, when checking the console I see an error that’s described at the end.

That’s the function:

function validationCheck() {
            var name = document.forms["register"]["fName"];
            var email = document.forms["register"]["email"];
            var phone = document.forms["register"]["phonenumber"];
            var password = document.forms["register"]["password"];

            if (name.value == "") {
                window.alert("Please enter your name.");
                name.focus();
                return false;
            }


            if (email.value == "") {
                window.alert(
                    "Please enter a valid e-mail address.");
                email.focus();
                return false;
            }

            if (phone.value == "") {
                window.alert(
                    "Please enter your telephone number.");
                phone.focus();
                return false;
            }

            if (password.value == "") {
                window.alert("Please enter your password");
                password.focus();
                return false;
            }

            return true;
        }

That’s the Form HTML:

 <form id="register" runat="server" method="post" onsubmit="return validationCheck();">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group"><input class="form-control" type="text" name="username" placeholder="Username" runat="server" id="username"/></div> <!-- Username #11 -->
            <div class="form-group"><input class="form-control" type="text" name="email" placeholder="Email" runat="server" id="email"></div> <!-- Email #1 -->
            <div class="form-group"><input class="form-control" type="text" name="password" placeholder="Password" runat="server" id="password"></div> <!-- Password #2 -->
            <div class="form-group"><input class="form-control" type="text" name="fName" placeholder="First Name" runat="server" id="fName" /></div> <!-- First Name #8 -->
            <div class="form-group"><input class="form-control" type="text" name="lName" placeholder="Last Name" runat="server" id="lName"/></div> <!-- Last Name #9 -->
            <div class="form-group"><input class="form-control" type="date" name="birthdate" runat="server" id="birthdate" placeholder="Birthdate"/></div> <!-- Birthdate #3 -->
            <div class="form-group"><input class="form-control" title="Phone Number" name="phonenumber" placeholder="Phone Number" runat="server" id="phonenumber" /></div> <!-- Phone Number #4 -->
            <span></span>
            <div class="form-group"><select id="gender" name="gender" runat="server" class="form-control" style="color:#6c757d">
                                        <option value="Gender" disabled="disabled" selected="selected">Gender</option>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><select id="camera" name="camera-brand" runat="server" class="form-control" style="color:#6c757d">
                                        <option value="Camera Brand" disabled="disabled" selected="selected">Camera Brand</option>
                                        <option value="Nikon">Nikon</option>
                                        <option value="Canon">Canon</option>
                                        <option value="Fuji">Fuji</option>
                                        <option value="Sony">Sony</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><input class="form-control" type="text" name="lens" placeholder="Lens" runat="server" id="lens"/></div> <!-- Lens #10 -->
            <div class="form-group"><select id="genre" name="genre" runat="server" class="form-control" style="color:#6c757d">
                                    <option value="Sport">Sports</option>
                                    <option value="Wildlife">Wildlife</option>
                                    <option value="Landscape">Landscape</option>
                                    <option value="Portrait">Portrait</option>
                                    <option value="Architecture">Architecture</option>
            </select></div>
            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" runat="server" id="submit">Sign up</button></div>
        </form>

The error I am receiving:

Uncaught TypeError: Cannot read properties of undefined (reading 'value')

unit test for a function that returns nothing

I want to write a unit test for the loadingTime function. This function converts timeTable (type map) into a result array which consists of 0 and 1. Index 3-5 (03:00 – 05:00), 12-14 (12:00 – 14:00) are 1, the rest is 0. Then the result array is assigned to the rowTable. How to write a unit test for this?

timeTable: Map<number, Array<from: string to: string>>

0:[{from: "03:00", to: 05:00"}, {from: "12:00", to:"14:00"}]
1:[{from: "00:00", to: "23:00"}]
2:[{from: "00:00", to: "23:00"}]
3:[{from: "00:00", to: "23:00"}]
4:[{from: "00:00", to: "23:00"}]
5:[{from: "00:00", to: "23:00"}]
6:[{from: "00:00", to: "23:00"}]

rowTable:

 rowTable: Row[] = [
    { name: this.allDays.monday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.tuesday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.wednesday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.thursday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.friday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.saturday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.sunday, items: new Array(24).fill(1), active: true }
  ];

loadingTime

loadingTime(): void {
   if (this.timeTable) {
     let result = [...this.timeTable].reduce((r, [key, value], i) => {
       r[i] = Array(24).fill(0);
       value.forEach(o => {
         let start = getHours(o.from);
         const end = getHours(o.to);
         while (start <= end) {
           r[i][start] = 1;
           start++;
         }
       })
       return r;
     }, []);
 
     this.rowTable.forEach((el, i) => {
       el.items = result[i];
       el.active = false;
     })
   }
 }

my attempts, but I don’t know if I’m going in the right direction. Please help

it("should loading Time"), () => {

  const timetableMock = new Map<number, Array<HourScheduleDefinitionModel>>()
      timetableMock.set(0, [{ from: '00:00', to: '23:00' }]);

  component.loadingTime = () => {};

  const onSaveSpy = spyOn(component, "loadingTime")

  component.loadingTime();

  expect(onSaveSpy).toEqual([........I don't know what to enter here]);

}

how to drop submenu one by one?

in the Navbar the submenu’s class name is submenu , we have 7 submenus ‘ im trying to make something like mouse hover but without using mouse event , i want to show them one by one (show the first and hide it, show the second and hide it) , what is the better way to do that with JavaScript

here is the my code but it show them once one on the other :

function changestyle(){
        var els = document.getElementsByClassName("submenu");
        for(var i = 0; i < els.length-1; i++)
        {
           
          els[i].style.display = 'block';
        
        
        }
        }

i tried another code but it doesn’t work :

function changestyle(){
            var els = document.getElementsByClassName("submenu");
            for(var i = 0; i < els.length-1; i++)
            {

                
                const showone = function(){
                    els[i].style.display = 'block';
                    
                  };
            
                  const hideone = function(){
                    els[i].style.display = 'none';
                    
                  };
                  setTimeout(showone, 2000);
                setTimeout(hideone, 2000);
            }
            }

Use api data inside a javascript script

I am rendering an EJS template with an array. But inside the script I can’t access the data. How do I access that data inside a script ?

API CODE

app.get('/', (req, res) => {
    var countries = [
        {
            name: 'america',
            cities: [
                'New york',
                'Los Angeles'
            ]
        },
        {
            name: 'india',
            cities: [
                'Delhi',
                'Mumbai'
            ]
        }
    ]
    res.render('home', {
        countries
    });
});

JS SCRIPT

<script>
        function populate(sel1, sel2) {
            console.log('funcc');
            console.log(countries);
        }
    </script>

The error in chrome console is:
Uncaught ReferenceError: countries is not defined

There is “undefined” in my chart created by chart.js

There is an undefined appearing in the chart created by Chart.js v3.7.0 and v2.9.4 as well ass seen in the figure.

and the function generating the graph, div and canvas is (JS) as follows:

    function arrangeForGraph(counts){
        for(var i =0;i<counts.length;i++){
                var divname = document.createElement("div");
                divname.id="div"+i;
                divname.class="chartAreaWrapper;chart";
        var dataname = document.createElement("data");
                var _canvas = document.createElement("canvas");
                _canvas.id="canvas"+i;
                _canvas.height="400";
                _canvas.width="600";
                _label_list = counts[i][4];
        dataname.id=_label_list;
        dataname.value= counts[i][0];
        dataname.style="display:none;"
        dataname.title="countchart"; 
        dataname.text="countsch";
                var ctx = _canvas.getContext("2d");
        ctx.imageSmoothingEnabled = true;
        Chart.plugins.register({id: 'pan', id:'zoom'});
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: _label_list,
                        datasets: [
                            {
                                label: "Upper Bound",
                                data: counts[i][3],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: 1,
                            },
                            {
                                label: "Lower Bound",
                                data: counts[i][1],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: false,
                            },
                            {
                                label: "Value",
                                order: 1,
                                data: counts[i][0],
                                backgroundColor: 'rgba(75, 192, 192, 0.85)',
                                borderColor: 'rgba(75, 192, 192, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                {
                                label: "Prediction",
                                order: 1,
                                data: counts[i][2],
                                backgroundColor: 'rgba(100, 100, 100, 0.85)',
                                borderColor: 'rgba(100, 100, 100, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                        ]
                    },
                    options: {
            
                                pan: {
                                 enabled: true,
                                 mode: 'xy'
                                 },
                                zoom: {
                                 enabled: true,
                                 drag: true,
                                 speed: 0.1,
                                 threshold: 2,
                                 mode: 'xy'
                                },
            title:{
                  text: "Behaviours",
                  display: true,
                      fontSize: 15
                },
            legend: {
                    display: false},
            elements: {center:{}},
                        responsive: true,
                        scales: {
                            xAxes: [{scaleLabel: {display: true, labelString: 'Date & Time'}}],
                            yAxes: [{scaleLabel: {display: true, labelString: 'Parameter Values'},ticks: {beginAtZero: true}}]
                        }
                    },
                });console.log(myChart);
        document.getElementById("main2").appendChild(divname);
        document.getElementById(divname.id).appendChild(_canvas);
        document.getElementById(_canvas.id).appendChild(dataname);
            };

}

Does anybody point my mistake so I can remove that annoying undefined watermark?

The graph is generated with the array coming from serverside, and if more than 1 array is found in counts then counts.length amounts o graphs are generated without any erorrs except that undefined mark on each graph.

Pan and zoom is not working as well but I think I have to ask another question for that.

Thanks in advance

How to parse redirect URL or the request sent to it by OAuth 2 in react-native, with expo-auth-session

I am trying to implement OAuth 2 with the expo-auth-session module.

My user is able to authenticate and is redirected to my backend web server, which is able to recieve the authentication code from the API provider. I was able to do so without using expo-auth-session package.

What I want now is to fire a callback function that prints the provider’s response (the one that is sent to my redirect uri) or at least the complete url (with get parameters) the response is sent to. From what I understand, expo-auth-session should allow me to do so.

Note : I cannot provide a custom scheme because the provider only allows http and https schemes. Regardless, when the user is redirected, the application should be able to parse the query parameters and to trigger a callback.

Here is my code :

import React, { useState } from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { Button, Platform } from 'react-native';

WebBrowser.maybeCompleteAuthSession(); // useless on native

// Endpoint
const discovery = {
  authorizationEndpoint: 'https://provider.com/oauth/authorize',
  tokenEndpoint: 'http://192.168.1.8:8080/token', // <-- I'm not really sure exactly what this should be? My guess is my own backend should return a token to identify my users who authenticated with the API. At least that's what I would like to do.
};

const useProxy = Platform.select({ web: false, default: true }); // not using this right now

export default function App() {
  const [step, setStep] = useState('start'); // 
  const [request, response, promptAsync] = useAuthRequest(
    {
      ':region': 'eu',
      clientId: 'myClientId',
      scopes: ['wow.profile'],
      responseType: 'code',
      redirectUri: 'http://192.168.1.8:8080/login', // this is my backend's route where I retrieve the user's authentication code,
      // prompt: Prompt.None,
      state: 'someteststate', // yes I know this isn't good practice but this is just for testing.
      extraParams: { 'customProviderKey': 'value' }
    },
    discovery
  );

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { code } = response.params;
      console.log(code);
    } else if (response) {
        console.log(response);
    } else {
      console.log("No response..."); // this fires when the component is loaded, before the user authenticates.
    }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync({ useProxy });
        }}
    />
  );
}

I should mention this code is almost a copy of this guide : https://docs.expo.dev/guides/authentication/#dropbox

Note 2 : I’m at a point of my application where there are not much expo dependencies so I’m not closed to the idea of using libraries that would work on standalone (non-expo) apps. In that case I would need an in-app browser module that exposes functions to retrieve redirect and response parameters, and to trigger callbacks on page load… something like that.

Why application craches when using express-rate-limit?

I’m using express-rate-limit package version 6.0.1 to limit hits of request an I also had used express-rate-limit documentation found on https://www.npmjs.com/package/express-rate-limit

However when I use this in my app, my application crashes.
I”m not understanding what is going on here. I have search allot for a conclusion but without any results.
Can someone give me an idea of what I’m doing wrong???

...

//Load env vars
dotenv.config({ path: "./config/config.env" });

//Connect to database
connectDB();

const app = express();

//Set Static folder
app.use(express.static(path.join(__dirname, "public")));

// Body Parser
app.use(express.json());

// Cookie parser
app.use(cookieParser());

//Dev logging middleware
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

// File uploading
app.use(fileUpload());

// Sanitize data
app.use(mongoSanitize());

// Set security headers
app.use(helmet());

// Prevent XSS attacks
app.use(xss());

//Rate limiting
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 1,
});

app.use(limiter);

// Prevent http param pollution
app.use(hpp());

app.use(errorHandler);

const PORT = process.env.PORT || 5000;

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
  )
);

//Handle unhandled promise rejections
process.on("unhandledRejection", (err, promise) => {
  console.log(`Error: ${err.message}`.red);
  // Close server & exit process
  server.close(() => process.exit(1));
});

Screenshot of error message

Merry Christmas gurus and keep on coding!!!

Determine a prime number function

//could anyone explain to me the 2nd and 3rd statement in the for loop
//what is the 1st and 2nd i in the middle part and the last one (i = i + 6)

function prime(n) {
  if (n<=1) return false;
  if (n<=3) return true;

  if (n%2==0||n%3==0) return false
  for(let i=5;i*i<n; i=i+6) {  
    if (n%1==0||n%(i+2)==0)

    return false;
  }
  return true
}