Execute a local python file from a browser

I wrote a website app for my boss and also a Python script to automatically send some documents to printers. the problem is, my boss doesnt want to click the icon to print on Desktop, but wants to have a button in the browser, on website.

So, i need a button on a https website that will execute a local .py file on PC.

Is it possible? I know that security wise its like blowing up your front door, but whatever, he wants it…

Anyone have any ideas?

NextJS/NextUI, initial columns of a table according to screen size

I’m working on my first NextJS project, using NextUI and a MongoDB database. I’ve managed to display a table, with a system for modifying the columns displayed, a search bar, pagination and a system for selecting the rows displayed per page, but I can’t define the variable containing the default columns displayed according to screen size.

Here’s the code concerned (with initial columns that don’t vary according to screen size, and based on the documentation):

const INITIAL_VISIBLE_COLUMNS = ["name", "email", "city", "actions"]

const [visibleColumns, setVisibleColumns] = React.useState(
    new Set(INITIAL_VISIBLE_COLUMNS)
)

const headerColumns = React.useMemo(() => {
    if (visibleColumns === "all") return customersColumns
        return customersColumns.filter((column) =>
        Array.from(visibleColumns).includes(column.key)
    )
}, [visibleColumns])

This code works.

And when I try to condion the display of columns according to screen size, in this way:

const mediaQuery = {
    isSmallScreen: useMediaQuery({ maxWidth: 767 }),
    isMediumScreen: useMediaQuery({ minWidth: 768, maxWidth: 991 }),
    isLargeScreen: useMediaQuery({ minWidth: 992, maxWidth: 1199 }),
    isXLargeScreen: useMediaQuery({ minWidth: 1200 }),
}

const getVisibleColumns = () => {
    if (mediaQuery.isSmallScreen) {
        return ["name", "city", "actions"]
    } else if (mediaQuery.isMediumScreen) {
        return ["name", "city", "email", "phone", "actions"]
    } else {
        return ["name", "email", "phone", "city", "postalCode", "address", "actions"]
    }
}

const INITIAL_VISIBLE_COLUMNS = getVisibleColumns()

const [visibleColumns, setVisibleColumns] = useState(INITIAL_VISIBLE_COLUMNS)

useEffect(() => {
    setVisibleColumns(getVisibleColumns());
}, [mediaQuery.isSmallScreen, mediaQuery.isMediumScreen, mediaQuery.isLargeScreen, mediaQuery.isXLargeScreen]);

const headerColumns = React.useMemo(() => {
    if (visibleColumns === "all") return customersColumns
        return customersColumns.filter((column) =>
        Array.from(visibleColumns).includes(column.key)
    )
}, [visibleColumns])

it works, I do have columns displayed according to screen size, which are always modifiable via select, but I get these two errors:

Error: Text content does not match server-rendered HTML.
See more info here: https://nextjs.org/docs/messages/react-hydration-error

Error: There was an error while hydrating this Suspense boundary. Switched to client rendering.

I don’t know what to try, any help would be appreciated, thank you very much.
if you want to see other parts of my code, don’t hesitate

Node fs.unlink does not delete the files immediatly

I have an issue with node fs.unlink

I have a function that writes files to disk storage extracts data from the these files then deletes the files

const parseShpFile = async ({
    cpgFile,
    dbfFile,
    prjFile,
    qmdFile,
    shpFile,
    shxFile,
}) => {
    // saving binary files to local machine

    const dbfPath = await saveBinaryToLocalMachine(dbfFile);
    const shpPath = await saveBinaryToLocalMachine(shpFile);

    //reading files from local machine using shapefile
    const shpParsedData = await shapefile
        .open(shpPath, dbfPath)
        .then((src) => src.read())
        .then((data) => {
            return data;
        })
        .then(async (data) => {
           // deleting from the local machine
            deleteFilesFromLocal([shpPath, dbfPath]);

            return data;
        })
        .catch((e) => {
            console.log("Error", e);
        });

    return shpParsedData;
};

the delete function is

const deleteFilesFromLocal = async (filePaths) => {
    for (const filePath of filePaths) {
        try {
            fs.unlinkSync(path.resolve(filePath));
        } catch (e) {
            console.log("error in deleting file", filePath);
        }
    }
};

The issue is when I run this code the files are not removed from the desk until the server restarts or shutdowns.

Before server restart or shutdown

enter image description here

After the server restarted.

enter image description here

Alert Component does not show after triggering the same Error twice

I am currently working on a Website using Nuxt.js (Vue.js) and I am having trouble with my custom Alert Component.

I created a contact-form on my website that triggers a custom notification when the user enters wrong data or does not enter all required data. However, if the same error gets triggered twice (e.g. wrong phone number). The alert does not show a second time.

I have now tried to fix this for two days and ChatGPT can’t help me either here. So I really hope that one of you knows why this might be happening.

My custom WarningAlert component:

    <!-- WarningAlert.vue -->
<template>
    <div v-if="show" class="overlay">
      <div class="alert alert-warning" role="alert">
        <div class="container">
          <div class="alert-icon">
            <i class="now-ui-icons ui-1_bell-53"></i>
          </div>
          <strong>{{ strongText }}</strong> {{ message }}
          <button v-if="dismissible" type="button" class="close" @click="hideOverlay" aria-label="Close">
            <span aria-hidden="true">
              <i class="now-ui-icons ui-1_simple-remove"></i>
            </span>
          </button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    props: {
      message: String,
      type: String,
      strongText: String,
      dismissible: Boolean,
    },
    data() {
      return {
        show: false,
      };
    },
    methods: {
      hideOverlay() {
        this.show = false;
      },
      showWarningAlert(message) {
        // Show the warning alert with the provided message
        this.message = message;
        this.show = true;
  
        // Hide the warning alert after 5 seconds (5000 milliseconds)
        setTimeout(() => {
          this.hideOverlay();
        }, 5000);
      },
      hideWarningAlert() {
        // Dismiss the warning alert
        this.show = false;
        this.message = '';
      },
    },
    watch: {
      message() {
        // sets show true, after an update
        this.show = true;
        setTimeout(() => {
          // delayed hiding 5000 Millisekunden (5 Seconds)
          this.hideOverlay();
        }, 5000);
      },
    },
    mounted() {
      this.showWarningAlert(this.message);
    },
  };
  </script>
  
  <style scoped>
  .overlay {
    position: fixed;
    top: 50px;
    left: 0;
    width: 100%;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    padding: 20px;
  }
  
  .alert {
    width: 70%;
  }
  </style>
  

Here is the contact form and the imported component:

 <!-- Alert component -->
        <WarningAlert v-if="showWarningAlert" :message="warningMessage" :type="'warning'" :strongText="'Warning!'"
          :dismissible="true" @dismiss="dismissWarningAlert"></WarningAlert>
    
<!-- Contact Form -->
        <div class="main">
          <div class="contact-content">
            <div class="container">
              <div class="row">
                <div class="col-md-5 ml-auto mr-auto">
                  <h2 class="title">Senden Sie uns eine Nachricht</h2>
                  <p class="description">Wir stehen Ihnen gerne zur Verfügung. Wir werden Ihnen innerhalb eines Werktages
                    antworten.
                    <br>
                    <br>
                  </p>
                  <form role="form" id="contact-form" @submit.prevent="submitForm" method="post">
                    <label>Ihr Name</label>
                    <fg-input required placeholder="Name..." v-model="form.firstName"
                      addon-left-icon="now-ui-icons users_circle-08"></fg-input>
    
                    <label>Email Adresse</label>
                    <fg-input required placeholder="Email..." v-model="form.email"
                      addon-left-icon="now-ui-icons users_circle-08" title="Please enter a valid email address"></fg-input>
    
                    <label>Telefon</label>
                    <fg-input required placeholder="Telefonnummer..." v-model="form.phone"
                      addon-left-icon="now-ui-icons tech_mobile"></fg-input>
    
                    <div class="form-group">
                      <label>Ihre Nachricht</label>
                      <textarea name="message" class="form-control" id="message" placehiolder="Nachricht..." v-model="form.message" rows="6"></textarea>
                    </div>
    
                    <div class="submit text-center">
                      <button class="btn btn-success btn-rounded" type="submit" round>Senden</button>
                    </div>
                  </form>

And finally the CSS of my submitForm() method, where the error probably lies (as the notification gets triggered here).

methods: {
    async submitForm() {
      // Initialisation
      this.showWarningAlert = false;
      this.warningMessage = '';

      // Check if all relevant fields filled out
      if (!this.form.firstName || !this.form.email || !this.form.phone) {
        this.showWarningAlert = true;
        this.warningMessage = 'Please fill out all required fields (Name, Email, Phone).';
        return;
      }

      const emailRegex = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
      if (!this.form.email.match(emailRegex)) {
        this.showWarningAlert = true;
        this.warningMessage = 'Please enter a valid email address.';
        return;
      }

      const phoneRegex = /^(+d{1,3})?d{1,14}$/;
      if (!this.form.phone.match(phoneRegex)) {
        this.showWarningAlert = true;
        this.warningMessage = 'Please enter a valid phone number.';
        return;
      }

      // Send formulas if everything is validated
      try {
        const response = await axios.post('http://localhost:3005/send-email', this.form);
        if (response.status === 200) {
          console.log('Email sent successfully');
        }
      } catch (error) {
        console.error('Error sending email:', error);
        // Show warning if error
        this.showWarningAlert = true;
        this.warningMessage = 'Something went wrong. Please contact us via email.';
      } finally {
        // Reset Warning properties before leaving the method
        this.showWarningAlert = false;
        this.warningMessage = '';
      }
    },
    dismissWarningAlert() {
      // Dismiss the warning alert
      this.showWarningAlert = false;
      this.warningMessage = '';
    }
  },

How I can change the colour for when the switch is toggled?

I got this code online, I’m confused as to how I can get the background colour to change when the button is toggled. How would I get it to change colour when the html containers are .

:root {
  /*========== Colors ==========*/
  /*Color mode HSL(hue, saturation, lightness)*/
  --line-color: hsl(234, 12%, 35%);
  --active-color: hsl(234, 100%, 98%);
  --inactive-color: hsl(234, 20%, 68%);
  --body-color: hsl(189, 49%, 87%);
  --background-colour: hsl(189, 84%, 14%);
}

* {
  box-sizing: border-box;
}

body {
  height: 100vh;
  margin: 0;
  display: grid;
  place-items: center;
  background-color: var(--body-color);
}

.toggle__content {
  display: grid;
  row-gap: 1.5rem;
}

.toggle__label {
  cursor: pointer;
  padding-block: .5rem;
}

.toggle__check {
  display: none;
}

.toggle__rail {
  position: relative;
  width: 52px;
  height: 4px;
  background-color: var(--line-color);
  border-radius: 2rem;
}

.toggle__circle {
  display: block;
  width: 24px;
  height: 24px;
  background-color: var(--body-color);
  box-shadow: inset 0 0 0 4px var(--inactive-color);
  border-radius: 50%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  margin: auto 0;
  transition: transform .4s, box-shadow .4s;
  z-index: 2;
}

.toggle__border {
  position: absolute;
  width: 32px;
  height: 32px;
  background-color: var(--body-color);
  border-radius: 50%;
  left: -4px;
  top: 0;
  bottom: 0;
  margin: auto 0;
  transition: transform .4s;
}


/* Toggle animation effects */

.toggle__check:checked~.toggle__rail .toggle__circle {
  transform: translateX(28px);
  box-shadow: inset 0 0 0 12px var(--active-color);
}

.toggle__check:checked~.toggle__rail .toggle__border {
  transform: translateX(28px);
}
<div class="toggle__content">
  <label class="toggle__label">
        <input type="checkbox" class="toggle__check">

        <div class="toggle__rail">
            <span class="toggle__circle"></span>
            <span class="toggle__border"></span>
        </div>
    </label>
</div>

I want to change it from –body-color: hsl(189, 84%, 14%) to –background-colour: hsl(189, 84%, 14%) when the switch is toggled

How to underline a word in a JavaScript String? [closed]

let questions = [{
    question: "Good times good actions.",
    options: ["Option 1", "Option 2", "Option 3", "Option 4"],
    correct: "Option 2"
  },
  {
    question: "Question 2",
    options: ["Option 1", "Option 2", "Option 3", "Option 4"],
    correct: "Option 4"
  },
];

This is my code, I made a question game that asks questions to the user, but here in the question game I want to underline some words, for example the word “good”. How can I underline these?

I tried doing “<mark> Good </mark> times good actions.” and “<b> Good </b> times good actions” in the code but it didn’t work. If there is someone who does not know in artificial intelligence, please write.

My current output is:

How to make these containers fit when resizing the window

I’m playing around with a site for a friend, and I’m having issues making things fit when resizing the window.

Normal:
Looks as it should
Smaller window:
Gap under image

A gap appears under the image – ideally I want the image to resize when the window does.

Here’s the HTML and CSS

<section id="home-info" class="bg-light">
        <div class="info-img"></div>
        <div class="info-content">
          <h2>About <span class="text-primary">133</span> Grand Rue</h2>
          <p>
            TEXT
          </p>
          <a href="about.html" class="btn">Read More</a>
        </div>
      </section>
      <section id="features">
        <div class="box bg-light">
        <i class="fas fa-mountain-sun fa-3x"></i>               
        <h3>Great Location</h3>
            <p>Sitting in the centre of St Jean du Gard, with access to the town centre.....</p>
        </div>
        <div class="box bg-primary">
        <i class="fas fa-person-swimming fa-3x"></i>
        <h3>Pool</h3>
        <p>Access to the garden and pool for the downstairs apartment.</p>
        </div>
        <div class="box bg-light">
        <i class="fas fa-question fa-3x"></i>
        <h3>?</h3>
        <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eveniet, officiis.</p>
        </div>
      </section>

CSS:

#home-info {
    height: 400px;
  }
  
  #home-info .info-img {
    float: left;
    width: 50%;
    background: url('../img/archway.jpg') no-repeat;
    min-height: 100%;
    background-size: 100%;
    text-align: center;
    
  }
  
  #home-info .info-content {
    float: right;
    width: 50%;
    height: 100%;
    text-align: center;
    padding: 50px 30px;
    overflow: hidden;
    
  }
  
  #home-info .info-content p {
    padding-bottom: 30px;
  }
/* Features */

.box{
    float:left;
    width: 33.333%;
    padding:60px;
    text-align:center;
}

.box i{
    margin-bottom:10px;
}

tried to play around with widths and heights etc.

I have an issue in my 3rd party advertisement alignment in my webpage

I have an issue in my 3rd party ad alignment in my webpage. And there is an issue when maximize and minimization of the webpage, that the 3rd party ad will be zoom in and zoom out during the maximize and minimization, otherwise noramlly webpage its doesn’t shown an error and its having an proper alignment, During the maximize and minimize of the webpage only its shown a error and that the ad is zoom in ( minimize ) and zoom out ( maximize ) ( the 3rd party ad ). How to resolve this issue ? And how to set a proper (ad) alignment of a 3rd party ad section in our webpage.

I tried a meta tag in css and medaia queries and I am not having the exact correction. And I am expecting the how to solve this issues in a css. (iframe zoom in during the resizing the webpage up and zoom out during the resizing the webpage down).

sorting DataTables from Django

I’m currently working on a Django project where I need to display and sort weather station data in a DataTable. I’m facing an issue when it comes to sorting columns that contain calculated values, such as averages and sums.
this code result in clickhouse error due to a problem with the inner join not working as properly I am out of ideas to sort the values (avg_value, max_value,min_value, sum_value, and count_value) please help

@cache_page(120)
@api_view(['GET'])
def station_list(request):
    serializer = StationListSerializer(data=request.query_params)
    serializer.is_valid(raise_exception=True)

    # Extracting DataTables parameters
    draw = int(request.GET.get('draw', 1))
    start = int(request.GET.get('start', 0))
    length = int(request.GET.get('length', 10))
    order_column_index = int(request.GET.get('order[0][column]', 0))
    order_direction = request.GET.get('order[0][dir]', 'asc')
    search_value = request.GET.get('search[value]', '')
    selected_region = request.GET.get('region')
    selected_governorate = request.GET.get('governorate')

    # QuerySet for AwsGov
    station_queryset = AwsGov.objects.all()

    if selected_region:
        station_queryset = station_queryset.filter(ADMIN=selected_region)
    if selected_governorate:
        station_queryset = station_queryset.filter(REGION_ID=selected_governorate)
    

    # Define columns for sorting and filtering
    direct_fields = ['station_id', 'Name', 'ADMIN_NA_1', 'REGION_N_1']
    all_fields = direct_fields + ['avg_value', 'max_value', 'min_value', 'sum_value', 'count_value']

    # Adjust for language
    if request.LANGUAGE_CODE == 'ar':
        direct_fields = ['station_id', 'Name', 'ADMIN_Name', 'REGION_NAM']

    if order_column_index < len(all_fields):
        order_column = all_fields[order_column_index]
    else:
        order_column = all_fields[0]
    # else:
    #     order_column = columns[0]  # Default to the first column if out of range

    if order_column in direct_fields:
        if order_direction == 'desc':
            order_column = f'-{order_column}'
        station_queryset = station_queryset.order_by(order_column)

    #station_queryset = station_queryset.order_by(order_column)

    # Fetch paginated station data
    #paged_station_data = list(station_queryset[start:start + length].values(*columns))

    # Fetch and process weather data
    varid = request.GET.get('varid', 3)
    start_time_str = request.GET.get('start_time', None)
    end_time_str = request.GET.get('end_time', None)
    if start_time_str and end_time_str:
        start_time = dateparse.parse_datetime(start_time_str)
        end_time = dateparse.parse_datetime(end_time_str)
    else:
        start_time = timezone.now().replace(microsecond=0) - timedelta(hours=24)
        end_time = timezone.now().replace(microsecond=0)

    weather_data = {}
    

    # Annotate with weather data
    weather_annotations = {
    'avg_value': Coalesce(Avg('value'), 0, output_field=FloatField()),
    'max_value': Coalesce(Max('value'), 0, output_field=FloatField()),
    'min_value': Coalesce(Min('value'), 0, output_field=FloatField()),
    'sum_value': Coalesce(Sum('value'), 0, output_field=FloatField()),
    'count_value': Coalesce(Count('value'), 0, output_field=IntegerField())
    }
    # Begin by annotating the station_queryset with all weather data
    

    avg_subquery = Subquery(
        Aws.objects.filter(
            stationid=OuterRef('id'),  # Assuming 'id' is the field in AwsGov matching Aws.stationid
            varid=varid,
            meastime__range=(start_time, end_time)
        ).annotate(avg=Avg('value')).values('avg')[:1],
        output_field=FloatField()
    )

    max_subquery = Subquery(
        Aws.objects.filter(
            stationid=OuterRef('id'),
            varid=varid,
            meastime__range=(start_time, end_time)
        ).annotate(max=Max('value')).values('max')[:1],
        output_field=FloatField()
    )
    min_subquery = Subquery(
        Aws.objects.filter(
            stationid=OuterRef('id'),
            varid=varid,
            meastime__range=(start_time, end_time)
        ).annotate(min=Min('value')).values('min')[:1],
        output_field=FloatField()
    )
    sum_subquery = Subquery(
        Aws.objects.filter(
            stationid=OuterRef('id'),
            varid=varid,
            meastime__range=(start_time, end_time)
        ).annotate(sum=Sum('value')).values('sum')[:1],
        output_field=FloatField()
    )
    count_subquery = Subquery(
        Aws.objects.filter(
            stationid=OuterRef('id'),
            varid=varid,
            meastime__range=(start_time, end_time)
        ).annotate(count=Count('value')).values('count')[:1],
        output_field=IntegerField()
    )
    station_queryset = AwsGov.objects.annotate(
    avg_value=avg_subquery,
    max_value=max_subquery,
    min_value=min_subquery,
    sum_value=sum_subquery,
    count_value=count_subquery 
    )
    
    print(station_queryset)

    # Determine the field to sort by based on the frontend request
    order_column = all_fields[order_column_index] if order_column_index < len(all_fields) else all_fields[0]
    if order_direction == 'desc':
        order_column = f'-{order_column}'

    # Sort the annotated queryset
    station_queryset = station_queryset.order_by(order_column)

    # Fetch the required page of the station data
    paged_station_data = list(station_queryset[start:start + length].values(*direct_fields))

    # The weather data is already included in the paged_station_data, so you don't need to merge it again
    # Prepare the final response
    response_data = {
        "draw": draw,
        "recordsTotal": AwsGov.objects.count(),
        "recordsFiltered": station_queryset.count(),
        "data": paged_station_data,
    }

    return Response(response_data)


here is the code from the frontend in vue js:

     initTable() {
        const LANGUAGE_CODE = "{{ request.LANGUAGE_CODE }}";
        const vm = this;
          this.dataTable = $('#combined').DataTable({
            responsive: true,
            processing: true,
            serverSide: true,
            searching: false,
            dom: 'Plfrtip',
            ajax: {
              url: 'stations/',
              type: 'GET',
              dataSrc: json => json.data,
              error: (xhr, error, thrown) => {
                console.error('Error occurred:', xhr, error, thrown);
              }
            },
            columns: [
              { data: "station_id" },
              {
                data: "Name",
                render: function (data, type, row) {
                return `<a href="station-details/${row.station_id}/" style="text-decoration: none;">${data} <i class="fas fa-share"></i></a>`;
              
              }
              },
              { data: LANGUAGE_CODE === 'ar' ? "ADMIN_Name" : "ADMIN_NA_1" },
              { data: LANGUAGE_CODE === 'ar' ? "REGION_NAM" : "REGION_N_1" },
              {
                data: "avg_value",
                
                render: function (data, type, row) {
                  if (type === 'display' || type === 'filter') {
                    return parseFloat(data).toFixed(2);
                  }
                  return data;
                }
              },
              {
                data: "max_value",
                

              },
              {
                data: "min_value",
                
              },
              {
                data: "sum_value",
                
              },
              { data: "count_value" },
            ],
        });
      },

Is there an alternative to useEffect with empty array to run on render only once in React Strict Mode for development?

Short long story: my component is messed up when React Strict Mode runs twice useEffect, and hate to get into bad practices so just don’t want to diasable it but don’t know how to get over it. I know that is expected behavior, so I’m looking for a solution or alternative.

Long story:

I am trying to adapt a vanilla JS code I found in codepen to make a typing effect on a p tag, it was quite easy, but then noticed my code was being buggy due to React Strict Mode because the expected behavior of useEffect since it worked very well on deployment.

I know there are libraries like TypeIt that already solved this problem, even in development mode, but I really adapt this one, and now I’m hitting this wall.

Since others already solved this in development mode, there must be a way to do it, but I can’t find it, probably I need to rewrite my functions someway.

Here is the code (this component is very simple so you just import it everywhere):

import React, { useEffect, useState } from 'react'

function TestComponent(
    { 
        words,
        typeDelay, 
        eraseDelay,
        nextWordDelay,
    } 
    :
    { 
        words: (string)[],
        typeDelay: number,
        eraseDelay: number,
        nextWordDelay: number,

    }
) 
{
    const [text, setText] = useState("");
    
    let wordIndex = 0;
    let letterIndex = 0;

    const sleep = (delay: number) => new Promise((resolve) => setTimeout(resolve, delay));

    const type = async () => 
    {  
        console.log(letterIndex, wordIndex);

        if(letterIndex < words[wordIndex].length)
        {
            const newLetter = words[wordIndex].charAt(letterIndex);

            setText(prev => prev + newLetter);

            letterIndex++;
            
            await sleep(typeDelay);

            type();

            return;
        }

        await sleep(nextWordDelay);

        erase();
    }

    const erase = async () =>
    {
        if(letterIndex > 0)
        {
            const newText = words[wordIndex].substring(0, letterIndex - 1);

            setText(prev => newText);

            letterIndex--;

            await sleep(eraseDelay);

            erase();

            return;
        }

        wordIndex++;

        if(wordIndex >= words.length) wordIndex = 0;

        await sleep(nextWordDelay);

        type();
    }

    useEffect(() =>
    {
        type();
    }, [])

    return (
        <p>
            <span className='typed-text'>
                {text}
            </span>
        </p>
    )
}

export default TestComponent

I also know there is a thousand posts about useEffect but found none to ask on how to solve this in development or an alternative to achieve this.

Console not showing “Server Start” after node app.js with Express

I didn’t get start server : 3001 message on console when I bush node app.js on terminal.

My app.js file content:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const cors = require('cors');
var fs = require('fs');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server, {
  cors: {
    origin: "http://localhost:4200",
    methods: ["GET", "POST"]
  }
})

var user_socket_connect_list = [];

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json({limit: '100'}));
app.use(express.urlencoded({ extended: true, limit: '100' }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

const corsOptions = {
  origin: "http://localhost:4200",
}

app.use(cors(corsOptions));

// import express inside dynamic add.
fs.readdirSync('./controllers').forEach((file) => {
  if(file.substr(-3) == ".js") {
    route = require('./controllers' + file);
    route.controller(app, io, user_socket_connect_list);
  }
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

server.listen(3001);

console.log("Server Start: 3001");

Array.prototype.swap = (x,y) => {
  var b = this[x];
  this[x] = this[y];
  this[y] = b;
  return this;
}

Array.prototype.insert = (index, item) => {
  this.splice(index,0, item);
}

Array.prototype.replace_null = (replace = '""') => {
  return JSON.parse(JSON.stringify(this).replace(/mull/g, replace));
}

String.prototype.replaceAll = (search, replacement) => {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
}

default.json file content:

{
"dbConfig": {
    "host":"localhost",
    "user":"root",
    "password":"",
    "database":"online_groceries",
    "timezone":"utc+5:30",
    "charset":"utf8mb4"
}
}

login_controller and socket_controller js files content:

module.exports.controller = (app, io, socket_list) => {
    
}

I following this tutorial YouTube

How to solve that?

note: I don’t have experience with JavaScript programming language, I use it for iOS app.

React hook from not capturing Actuall file (working with File type)

i’m working my side project where i’m building the marketing platfrom for local organization.

i’m using mui tailwind and react hook form to controll forms.

The problem is that when i submit the data react hook form isn’t capturing the actual image or the FileList object it usually returns .

eg: yesterday when i submit my form it’ll give me
enter image description here
fieldName:[FileList] object which is returned by the files Api since FileList is a array like Object it'd get file by FileList[o] where the actuall file is present

but now that whenever i click instead of giving the actual image so that i can interact with image name or other usefull info it’ll only give the file path from my local pc>.

this is the data i’m having after submit the form

brand: "Sameeer ijaz"
category: "salon"
countInStock: "2"
description: "asdasd"
details: "sdasd"
gstPercentage: "2"
image: "C:\fakepath\What is network infrastructure management.png"
price: "3"
sidePicture1: "C:\fakepath\waefdrf.png"
sidePicture2:"C:\fakepath\waefdrf.png"
sidePicture3: "C:\fakepath\What is network infrastructure management.png"
title: "sjdasd"

This is my logic for integrating react hook form with file type

  <div className='mt-10  gap-x-6 gap-y-8 grid grid-cols-12 gap-4 w-full'>
                {[1, 2, 3].map((index) => (
                  <div
                    key={index}
                    className='md:col-span-4 sm:col-span-6 col-span-12 text-sm text-black'
                  >
                    <InputLabel htmlFor={`sidePicture${index}`}>
                      Side Picture {index}
                    </InputLabel>
                    <Controller
                      name={`sidePicture${index}`}
                      control={control}
                      defaultValue=''
                      rules={{ required: `Side Picture ${index} is required` }}
                      render={({ field }) => (
                        <input
                          {...field}
                          type='file'
                          accept='image/*'
                          className='mt-1'
                        />
                      )}
                    />

                    {errors[`sidePicture${index}`] && (
                      <p className='text-red-500 text-xs italic'>
                        {errors[`sidePicture${index}`].message}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            </div>{' '}

i Searched it and didn’t find anything usefull and in some article they’re saying is that it browser feature for the security but the thing is on my backend it’d still give the just the path string not the actual file and multer.js wouldn’t be able to access the image.

Convert to base64 image using observable not working

I have a page which require user to upload attachment in my Ionic app. But the attachment seems like not being send to the API properly. I have used Observable, so I’m not sure why it’s not working as expected. The name is being sent to the API, but it seems error when user submit with an attachment. Already tried to troubleshoot the API, but API is working as expected when using Postman.

selectFileToUpload() function will trigger when upload button is clicked.
postinsertdata() function will trigger when submit button is clicked.

This is my code in filename.page.ts:

selectFileToUpload(event): void {
    this.myService
      .handleImageSelection(event)
      .subscribe({
        next: (res) => {

          // Retrieve the file type from the base64 data URI string
          this._SUFFIX = res.split(':')[1].split('/')[1].split(";")[0];

          // Do we have correct file type?
          if (this.myService.isCorrectFileType(this._SUFFIX)) {

            // Hide the file input field, display the image in the component template
            // and display an upload button
            this.image = res;
          } else {
            console.log('You need to select an image file with one of the following types: jpg, gif or png');
          }
        },
        error: (error) => {
          console.dir(error);
        }
      });
  }

postinsertdata() {
    this.loadingController.create({
        message: "loading..."
    }).then((async (loadingElement) => {
      loadingElement.present();

    return new Promise(resolve => {
          let body = {
            
            name: this.name,
            file: this.image,
            mimeType: this._SUFFIX,
          };

          this.myService.postData(body, "postinserttest").subscribe({
            next: async (data) => {
              this.image = null;
              this._SUFFIX = null;

              await this.loadingController.dismiss();
              alert('Your application has been submitted.');
              this.router.navigate(['/page/al/view']);
            },
            error: async (err) => {console.log(err);
              await this.loadingController.dismiss();
              this.displayAlert("Error in submitting. Please contact your administrator for assistance. Thank you.");
            }
          });
        });
}

And this one is my code in myService.service.ts:

handleImageSelection(event: any): Observable<any> {
    let file: any = event.target.files[0];

    this._READER.readAsDataURL(file);
    return new Observable<void>((observer) => {
      this._READER.onloadend = () => {
        observer.next(this._READER.result);
        observer.complete();
      }
    });
  }

  isCorrectFileType(file) {
    return (/^(gif|jpg|jpeg|png)$/i).test(file);
  }

postData(body, keyword) {

    let type = "application/json";
    const headers = new HttpHeaders({ 'Content-Type': type });
    const options = {
      headers: headers
    };

    let apiUrl = this.serviceBaseUrl + 'api/user/' + keyword;

    return this.http.post(apiUrl, JSON.stringify(body), options).pipe(map(res => res));
  }

Ps: I tried to convert the image to base64 before sending to the API.

Peach Payment Getaway – Authentication Token Issue

I’m currently encountering difficulties obtaining an authentication token through the provided endpoint

Here are the details of the issue:

Endpoint for Authentication Token:
https://testsecure.peachpayments.com/checkout/api/oauth/token

Request:

{
    "clientId": "{{cliendId}}",
    "clientSecret": "{{clientSecret}}",
    "merchantId": "{{merchantId}}"
}

Response:

{"message":"Missing Authentication Token"}

Despite providing the necessary parameters, the response indicates a “Missing Authentication Token” error. I have double-checked the provided credentials, but the issue persists.

Problem while sign > serialize > deserialize > verify using web crypto

As a part of my JS code, using web crypto, I wanted to sign a string, serialize it and later deserialize it and verify it.
For this I created these custom functions createHexTokenFromStrClaim and verifyHexTokenAndGetStrClaim. However my code is not behaving as expected.

Minimal working code:

const keyUsages = ["sign","verify"];
const algo = {
    name: "HMAC",
    hash: {name: "SHA-512"}
};

class Util{
    static text_encoder=new TextEncoder();
    static text_decoder=new TextDecoder();
    static characters  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    static hexEncode(str) {
        let hex = '';
        for (let i = 0; i < str.length; i++) {
            let charCode = str.charCodeAt(i);
            if (charCode < 128) {
            hex += charCode.toString(16).padStart(2, '0');
            } else if (charCode < 2048) {
            hex += ((charCode >> 6) | 0xC0).toString(16).padStart(2, '0');
            hex += ((charCode & 0x3F) | 0x80).toString(16).padStart(2, '0');
            } else {
            hex += ((charCode >> 12) | 0xE0).toString(16).padStart(2, '0');
            hex += (((charCode >> 6) & 0x3F) | 0x80).toString(16).padStart(2, '0');
            hex += ((charCode & 0x3F) | 0x80).toString(16).padStart(2, '0');
            }
        }
        return hex;
    }

    static hexDecode(hex) {
        let str = '';
        for (let i = 0; i < hex.length; i += 2) {
            const byte = parseInt(hex.substr(i, 2), 16);
            str += String.fromCharCode(byte);
        }
        return decodeURIComponent(escape(str)); // Handle UTF-8 encoding
    }
    
    static async createHexTokenFromStrClaim(algo,str_claim,crypto_key){
        const hex_str_claim= Util.hexEncode(str_claim);
        const uint = Util.text_encoder.encode(hex_str_claim);
        const ab = uint.buffer;

        const sign = await crypto.subtle.sign(algo,crypto_key,ab);
        const des = Util.text_decoder.decode(sign);
        console.log(new Uint8Array(sign));
        
        const hex_sign=Util.hexEncode(des);

        return hex_str_claim+"."+hex_sign;
      }
    
    static async verifyHexTokenAndGetStrClaim(algo,hex_token,crypto_key){
        let hex_str_claim,hex_sign;
        [hex_str_claim,hex_sign]=hex_token.split(".");
        
        if(hex_str_claim && hex_sign){
            const uint = Util.text_encoder.encode(hex_str_claim);
            const ab = uint.buffer;

            const des = Util.hexDecode(hex_sign);
            const sign = Util.text_encoder.encode(des);
            console.log(sign);

            const r = await crypto.subtle.verify(algo,crypto_key,sign.buffer,ab);
            if(r){
                return Util.hexDecode(hex_str_claim);
            }
        }

        return;
    }
}

(async()=>{
    const crypto_key = await crypto.subtle.generateKey(algo,true,keyUsages);
    const message = "Hello world こんにちは、元気ですか ईश्वरेण सह एकतां प्राप्तुं एषः महान् दिवसः अस्ति";
    const token  = await Util.createHexTokenFromStrClaim(algo,message,crypto_key);
    console.log(token);

    const claim = await Util.verifyHexTokenAndGetStrClaim(algo,token,crypto_key);
    console.log(claim);
})();

Hex Encoder is used as encoding like base64 introduces special characters , which causes issues with other part of the code.

Problem:
Verification seems to be failing. Specifically in verifyHexTokenAndGetStrClaim the sign is coming completely different after encoding it using const sign = Util.text_encoder.encode(des);

Can’t figure out what I am doing wrong.
Have checked most of the resources about encoding and decoding.
Have checked most of the resource for signing and verifying.