How do I fix a PostgreSQL 46201 error (for complex queries) once I have seeded the database with data (in JavaScript) (GET Request)

I am trying to some complex queries in my bird database to get all the birds back but I want to be able to use queries in the url to get back by diet and to sort accordingly. See the Insomnia images below:

1st query: GET request: localhost:3000/api/birds?sort_by=weight_g&diet=carnivorous

enter image description here

2nd query: GET request localhost:3000/api/birds?diet=piscivorous&sort_by=wingspan_cm&order=DESC

enter image description here

Now I will show you the Javascript code. Error handling has been left out until I get the basics done. I can successfully seed the database and get nodemon up and running. And when I connect to the database using psql and c and execute the inner join query (scroll down to see query) with the tables I get rows of the results back with not error. The error is coming for the express request/response cycle as you saw in the Insomnia images above.

//app.js
app.use((req, res, next) => {
    console.log('Request method: ', req.method);
    console.log('Request url: ', req.url);
    let currentdate = new Date(); 
    let datetime = `Date and time request method made(format:day/month/year|hours:minutes:seconds): ${currentdate.getDate()}/${(currentdate.getMonth()+1)}/${currentdate.getFullYear()}|${currentdate.getHours()}:${currentdate.getMinutes()}:${currentdate.getSeconds()}`
    console.log(datetime)
    next()
  });

const {getAllBirds} = require('./controllers/birds.controller.js')
const express = require('express');
const app = express();
app.use(express.json())
app.get('/api/birds',getAllBirds)

//birds.controller.js
const {selectAllBirds} = require('../models/birds.models.js')

exports.getAllBirds = (req,res) =>{
 const {order} = req.query
 const {sort_by} = req.query
 const {diet} = req.query
 selectAllBirds(sort_by,order,diet).then((birds)=> res.status(200).send({birds})).catch(err => console.log(err))
}

//bird.models.js

const db = require('../db/index.js')

exports.selectAllBirds = (sort_by,order,diet) =>{
    const sortbyGreenList = ['length_cm,','weight_g','wingspan_cm']
    const orderbyGreenList = ['ASC,DESC']
    let queryValues = [];
    let queryStr = `SELECT bird_id,common_name,species_name,wing_colour,diet,can_Fly
    ,length_cm,weight_g,lay_season,fun_fact,wingspan_cm,f_id FROM birds
     INNER JOIN bird_families ON birds.f_id = bird_families.family_id`;

    if(sort_by && !sortbyGreenList.includes(sort_by)){
        return Promise.reject({status: 400, msg: 'Invalid sort_by query string'})
    }

    if(order && !orderbyGreenList.includes(order.toUpperCase())){
        return Promise.reject({status: 400, msg: 'Invalid order query string'})
    }
   
    if(diet){
        queryValues.push(`%${diet}%`)
        queryStr += `WHERE diet ILIKE $1`;
    }

    if(sort_by){
        if(!queryValues.length){
            queryValues.push(sort_by)
            queryStr += `ORDER BY $1`;
        }else{
        queryValues.push(sort_by)
        queryStr += `ORDER BY $2`;  
        } 
    }

    if(order){
        queryStr += `${order.toUpperCase()}`;
    }

    return db.query(queryStr,queryValues).then((result)=>{
        if(!(result.rows.length)){
            return Promise.reject({status: 404, err: 'No results found for query'})

        }else{
            return result.rows
        }
    })
}

I get these errors in the terminal when I try to the GET requests above that you saw in the Insomnia images

Error with 1st query: GET request: localhost:3000/api/birds?sort_by=weight_g&diet=carnivorous

Request method:  GET
Request url:  /api/birds?sort_by=weight_g&diet=carnivorous
Date and time request method made(format:day/month/year|hours:minutes:seconds): 22/2/2024|11:21:1
/home/mbans8a1/Northcoders/northcoders/projects/bird_rookery_project/node_modules/pg-pool/index.js:45
    Error.captureStackTrace(err);
          ^

error: syntax error at or near "diet"
    at /home/moddy456/Programs/program/projects/bird_rookery_project/node_modules/pg-pool/index.js:45:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  length: 94,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '213',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'scan.l',
  line: '1176',
  routine: 'scanner_yyerror'
}

Error with 2nd query:/api/birds?diet=piscivorous&sort_by=wingspan_cm&order=DESC

Request method:  GET
Request url:  /api/birds?diet=piscivorous&sort_by=wingspan_cm&order=DESC
Date and time request method made(format:day/month/year|hours:minutes:seconds): 22/2/2024|11:49:50
{ status: 400, msg: 'Invalid order query string' }

Any ideas of how I can fix these problems?

Next.js Forms Work Locally but Fail on cPanel Deployment

If both forms in my Next.js application are functioning properly with Nodemailer locally, but upon deployment to cPanel, I encounter an “Internal Server Error” when attempting to submit the forms, how can I resolve this issue? Despite attempting various solutions, the problem persists. As a newcomer to Next.js, I’m struggling to find helpful resources.

The error message I receive is:

POST https://mydomain/api/sendContact 500 (Internal Server Error)

Could someone provide guidance on how to troubleshoot and fix this issue? Any insights or suggestions would be greatly appreciated.

Jest with Node.js : “TypeError: Cannot assign to read only property ‘getCustomerSync’ of object ‘[object Module]'”

I aimed to conduct a unit test for a function, applyDiscount(), while avoiding reliance on external sources. To achieve this, I employed a mock function. Please help me to find out this error : “TypeError: Cannot assign to read only property ‘getCustomerSync’ of object ‘[object Module]'”. Here’s my code :

db.js file:
----------
const getCustomerSync = (id) => { // synchronous function
    console.log('Reading a customer from MongoDB...');
    return { id: id, points: 11 };
}
const getCustomer = (id) => { // asynchronous function
    return new Promise((resolve, reject) => {
      console.log('Reading a customer from MongoDB...');
      resolve({ id: id, points: 11 });
    });
}
export { getCustomer, getCustomerSync };

lib.js file:
---------
import * as db from "./db.js";
const applyDiscount = (order) => {
  const customer = db.getCustomerSync(order.customerId); // fake external ressource

  if (customer.points > 10)
    order.totalPrice *= 0.9; // 10% discount
}

lib.test.js file:
---------------
describe("applyDiscount", () => {
    it("should apply 10% discount if customer has more than 10 points", () => {
        const mockFunction = jest.fn();
        db.getCustomerSync = mockFunction.mockReturnValue({ id: 1, points: 20 });

        const order = { customerId: 1, totalPrice: 10 };
       applyDiscount(order);
       expect(order.totalPrice).toBe(9)
    });
});

package.json file :
-------------------
{
  "name": "testing-demo",
  "version": "1.0.0",
  "description": "Automates unit test",
  "main": "db.js",
  "type": "module",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^29.7.0"
  }
}

how can i set a marker tool as default selected in markerjs library

i am using the library markerjs (https://markerjs.com/docs/events/) for doing annotation over an image and i am not sure how to make the freehand drawing tool as default selected because right now the select mode tool comes as autoselected does anyone have any idea about it?

I have gone through the documentation and i found the below given constructor but i am not sure how to use it tried it like markerArea.setActiveMarkerButton(“FreeHandMarker”) but this doesn’t work
setActiveMarkerButton
setActiveMarkerButton(typeName: string): void
Selects toolbar button for a specified marker type.

since
2.17.0

Parameters
typeName: string
Marker type name

Returns void
i found the above constructor in the document below
https://markerjs.com/reference/classes/toolbar#setactivemarkerbutton

Which documents or algorithms can I use to solve the problem of presenting possible product placement positions when dragging and dropping?

Here is my design (image below), each object will have coordinates (x, y) as well as dimensions (width, height).

enter image description here

I need more information on how to determine possible product placement positions as well as the interaction between the products and those positions.

Please provide me with some directions to solve this issue.

Installtrigger is deprecated and will be removed in the future

L’impression ne passe pas sur mon système, En analysant la console je trouve qu’il y a un problème qui se déclenche lors du click, c’est lié à Install Trigger (Capture ci-joint) qui existe dans print.js j’ai même un warning qui s’affiche pour m’informer que Install Trigger n’est plus utilisé,
Comment faire pour résoudre ce problème? Est qu’il me faut une MAJ au niveau du Crystal Report et ça va être réglé automatiquement ? ou bien est ce qu’on peut changer ça directement en code du JS, sachant que c’est fichier du Crystal Report ? si Oui c’est quoi l’équivalent de Install Trigger et qui soit compatible avec les browsers?
Ouverte pour toute propositions et merci d’avance.

enter image description here

how to make an anonymous chat tab in a website like NGL

I am currently working on a website for my class project, and I need assistance with a specific feature that I want to include. This feature is called ‘Gossip Chat’, and it is essentially a tab where students and teachers can anonymously post anything they want to share with the community.

To elaborate further, I want to ensure that this feature has a user-friendly interface that allows for easy posting, browsing, and commenting. I also want to ensure that the anonymity of the users is maintained at all times.

As I am not very experienced in website development, I am looking for a step-by-step guide on how to create this feature. Any resources or suggestions that you can provide would be greatly appreciated. Thank you for your help.

i searched a lot but i don’t find anything like i want.

why i cant remove value of to empty string once i have entered any value

problem lies in this code:

whenever i ented any value into my added input, for exmaple like 15 or any number. im able to remove 5 but not 1, or any first number.

here i will link demo. test acc is autofilled if need.

https://wemove-ochre.vercel.app/gym/chest/Bench_press_a7864ba8-fe09-4605-b9a3-9e4ea9d3ddfc

thank you for your time and help in advance.

const set = {
  id: uuidv4(),
  weight: 0,
  rep: 0,
};
const defaultSets = [
 set,set,set
];

const defaultCardioSets = [set];


  const [sets, setSets] = useState<Set[]>(
    type === "cardio" ? defaultCardioSets : defaultSets
  );
  const [allWeights, setAllWeights] = useState(0);


 function handleAddSet(e: React.MouseEvent<HTMLButtonElement>) {
    e.preventDefault();
    setSets([...sets, set]);
  }

  function handleUpdatePerformance(
    e: React.ChangeEvent<HTMLInputElement>,
    id: string
  ) {
    e.preventDefault();

    const newValue = parseFloat(e.target.value);
    if (isNaN(newValue)) return;

    const updatedValue = newValue === 0 ? 0 : newValue;
    const updatedSets = sets.map((set) => {
      if (set.id === id) {
        return { ...set, weight: updatedValue };
      }
      return set;
    });

    setSets(updatedSets);
  }


{sets.map((set, i) => (
          <div key={set.id} className="flex gap-2 items-center justify-between">
            <label className="w-1/4" htmlFor={`set_${i}_metric`}>
              {`Set ${i + 1}`}:{" "}
            </label>
            <input
              id={`set_${i}_metric`}
              type="number"
              className="px-2 py-1 w-1/4 my-2"
              placeholder={exercise.metric}
              value={set.weight === 0 ? "" : set.weight}
              required
              onChange={(e) => handleUpdatePerformance(e, set.id)}
            /> ))}

i have tried using input as text and pass default as string. but it wont let me go back to empty string.

How to render react component at php server

Background

  • I am a WordPress developer.
  • React is very effective for creating complex UIs on WordPress sites.
  • I developed a small WordPress plugin that connects WordPress shortcodes with React components. This allows me to use React with WordPress.

Problem

  • I need to implement Search Engine Optimization. However, React components are rendered on the client-side. I heard that this is not good at SEO.
  • How can I render React components on the server-side? I do not want to use NextJS or Remix because I only need server-side rendering and do not require a full-site SPA and Router.

What I Found

  • PHP supports the V8 JavaScript Engine.
  • Vite offers support for SSR (Server-Side Rendering).

How to remove spaces between bar in d3.js grouped bar chart

I have following d3.js code which helps to create grouped bar chart. My data consist of different states and its population by age categories. In this data few age categories(14 to 17 Years, 18 to 24 Years, 25 to 44 Years) are missing in ‘TX’ and ‘NY’ states. So when we create grouped bar chart using this data, its creating empty space in between the bars for missing data. How can we get rid off this empty space for missing data in between the bars in d3.js.
I found a same question in github, but nobody given solution for that.

@mbostock @jasondavies @gordonwoodhull @esjewett @vogievetsky @jheer @connorgr @Fil @petulla @tmcw
@shikhaagrawal23 @gkumar100


<!DOCTYPE html>
<style>

.axis .domain {
 display: none;
}

</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
   margin = {top: 20, right: 20, bottom: 30, left: 40},
   width = +svg.attr("width") - margin.left - margin.right,
   height = +svg.attr("height") - margin.top - margin.bottom,
   g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x0 = d3.scaleBand()
   .rangeRound([0, width])
   .paddingInner(0.1);

var x1 = d3.scaleBand()
   .padding(0.05);

var y = d3.scaleLinear()
   .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
   .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
   
   
var data = [
 {
   "State": "CA",
   "Under 5 Years": 2704659,
   "5 to 13 Years": 4499890,
   "14 to 17 Years": 2159981,
   "18 to 24 Years": 3853788,
   "25 to 44 Years": 10604510,
   "45 to 64 Years": 8819342,
   "65 Years and Over": 4114496
 },
 {
   "State": "TX",
   "Under 5 Years": 2027307,
   "5 to 13 Years": 3277946,   
   "45 to 64 Years": 5656528,
   "65 Years and Over": 2472223
 },
 {
   "State": "NY",
   "Under 5 Years": 1208495,
   "5 to 13 Years": 2141490,    
   "25 to 44 Years": 5355235,
   "45 to 64 Years": 5120254,
   "65 Years and Over": 2607672
 },
 {
   "State": "FL",
   "Under 5 Years": 1140516,
   "5 to 13 Years": 1938695,
   "14 to 17 Years": 925060,
   "18 to 24 Years": 1607297,
   "25 to 44 Years": 4782119,
   "45 to 64 Years": 4746856,
   "65 Years and Over": 3187797
 },
 {
   "State": "IL",
   "Under 5 Years": 894368,
   "5 to 13 Years": 1558919,
   "14 to 17 Years": 725973,
   "18 to 24 Years": 1311479,
   "25 to 44 Years": 3596343,
   "45 to 64 Years": 3239173,
   "65 Years and Over": 1575308
 },
 {
   "State": "PA",
   "Under 5 Years": 737462,
   "5 to 13 Years": 1345341,
   "14 to 17 Years": 679201,
   "18 to 24 Years": 1203944,
   "25 to 44 Years": 3157759,
   "45 to 64 Years": 3414001,
   "65 Years and Over": 1910571
 }
];

 var keys  = Object.keys(data[0]);
  keys = keys.slice(1);

 x0.domain(data.map(function(d) { return d.State; }));
 x1.domain(keys).rangeRound([0, x0.bandwidth()]);
 y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

 g.append("g")
   .selectAll("g")
   .data(data)
   .enter().append("g")
     .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
   .selectAll("rect")
   .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
   .enter().append("rect")
     .attr("x", function(d) { return x1(d.key); })
     .attr("y", function(d) { return y(d.value); })
     .attr("width", x1.bandwidth())
     .attr("height", function(d) { return height - y(d.value); })
     .attr("fill", function(d) { return z(d.key); });

 g.append("g")
     .attr("class", "axis")
     .attr("transform", "translate(0," + height + ")")
     .call(d3.axisBottom(x0));

 g.append("g")
     .attr("class", "axis")
     .call(d3.axisLeft(y).ticks(null, "s"))
   .append("text")
     .attr("x", 2)
     .attr("y", y(y.ticks().pop()) + 0.5)
     .attr("dy", "0.32em")
     .attr("fill", "#000")
     .attr("font-weight", "bold")
     .attr("text-anchor", "start")
     .text("Population");

 var legend = g.append("g")
     .attr("font-family", "sans-serif")
     .attr("font-size", 10)
     .attr("text-anchor", "end")
   .selectAll("g")
   .data(keys.slice().reverse())
   .enter().append("g")
     .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

 legend.append("rect")
     .attr("x", width - 19)
     .attr("width", 19)
     .attr("height", 19)
     .attr("fill", z);

 legend.append("text")
     .attr("x", width - 24)
     .attr("y", 9.5)
     .attr("dy", "0.32em")
     .text(function(d) { return d; });
</script>
</html>


How to remove trailing slash from URL in HTML file?

I want to remove any trailing slash from URL that can be found on HTML files with Node.js.

I know that there are rewrite or redirect rule for NGINX that I use for serving my site, but I really want to do this too. I want to remove those pesky trailing slash from my site, once and for all. Those rewrite or redirect is not enough.

I can’t configure Hugo that I use for generating my site to not add trailing slash to URL. I have to either use https://example.com/b/content/article-01.html or https://example.com/b/content/article-01/ and I don’t like both. I want https://example.com/b/content/article-01.

If Hugo won’t allow me to use clean URL, I’ll just post-process the generated site myself.


Here are what I’ve found to define URL in the content of HTML files.

  • The URL is after either href=, href=", content=, content=".
  • The URL is before " (only if it is after href=" or content=") or (space) or >.
  • The URL starts with either http or /.
  • Do not remove slash if the URL is exactly /.

So, these are URLs that I have to process.

  • http://example.com/ -> http://example.com
  • https://example.com/ -> https://example.com
  • /b/content/article-01/ -> /b/content/article-01
  • https://example.com/b/content/article-01/ -> https://example.com/b/content/article-01
  • / -> /

I’ve managed to code this for removing trailing slash from content of files, but I don’t know what to use for HTML file.

function removeTrailingSlash(dirPath) {
  const files = glob.sync(`${dirPath}/**/*.+(html|xml)`)
  const regexHTML = // How?
  const regexXML = /<(?:link|guid|loc)>(https?://[^<]+)</(?:link|guid|loc)>/g // XML part is fine

  function rts(url) {
    if (url.length > 1 && url.endsWith('/')) {
      return url.slice(0, -1)
    }
    return url
  }

  files.forEach(file => {
    console.log(file)
    let content = readFileSync(file, 'utf8')
    if (file.endsWith('.html')) {
      content = content.replace(regexHTML, (match, url) => {
        return match.replace(url, rts(url))
      })
    } else if (file.endsWith('.xml')) {
      content = content.replace(regexXML, (match, url) => {
        return match.replace(url, rts(url))
      })
    }
    writeFileSync(file, content)
  })
}

How can I remove trailing slash from the content of the HTML file?

Customise the FlareClient.ts

I am currently trying to implement Flare in our Laravel and Vue project. So far everything works. Now I’m implementing a bypass to send Flare error reports to Flare even if an adblocker is active. I solve the whole thing with a proxy, in which I set the reportingURL from Flare to my API endpoint. But now I have the problem that the sendReport method of Flare does not send a scrfToken, which leads to a 419 status code. So far I have solved the problem with a global error handler:

    import { flare } from "@flareapp/flare-client";
    
    export const initializeErrorHandling = (app) => {
        app.config.errorHandler = (err, vm, info) => {
            flare.beforeSubmit = (report) => {
                window.axios.post('/api/report-error', report)
                    .then(response => {
                        console.log('Report successfully sent to the controller', report);
                        console.log('Response from the server:', response);
                    })
                    .catch(error => {
                        console.error('Error when sending the report to the controller:', error);
                    });
                return report;
            };
        };
    };

This sends the error report to my controller. However, I would like to do the whole thing without this error handler and instead somehow intercept the sendreport method and set a token. However, as I’m still new to the world of programming, I can’t think of a way to solve the problem straight away. I thought of the proxy pattern or a similar mechanism to change the behaviour of the FlareClient without changing the class definition. Do you have any other ideas?
The sendReport method of Flare looks like this:

 private sendReport(report: Flare.ErrorReport): void {
        if (
            !assert(
                this.config.key,
                'The client was not yet initialised with an API key. ' +
                    "Run client.light('<flare-project-key>') when you initialise your app. " +
                    "If you are running in dev mode and didn't run the light command on purpose, you can ignore this error.",
                this.debug
            )
        ) {
            return;
        }

        if (this.maxReportsPerMinuteReached()) {
            return;
        }

        Promise.resolve(this.beforeSubmit(report)).then(reportReadyForSubmit => {
            if (!reportReadyForSubmit) {
                return;
            }

            const xhr = new XMLHttpRequest();
            xhr.open('POST', this.config.reportingUrl);

            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('x-api-token', this.config.key);

            xhr.send(flatJsonStringify({ ...reportReadyForSubmit, key: this.config.key }));

            this.reportedErrorsTimestamps.push(Date.now());
        });
    }

You can find the FlareClient.ts here: https://github.com/spatie/flare-client-js/blob/main/packages/js/src/FlareClient.ts#L165

Get product name at thank you page in woocommerce

We are doing a WooCommerce Conversion Tracking Custom Integration.

Following this guide (but using custom pixel instead of Facebook’s):

https://wedevs.com/docs/woocommerce-conversion-tracking/custom/?utm_source=wporg&utm_medium=Readme&utm_campaign=wcct-lite&utm_content=custom

We would like to pass purchased product’s name against our adv_sub5 parameter. Our script looks like this:

<script>
(...)
        conversionData: {
            event: '', 
            payout: '', 
            sale: ' { order_total } ', 
            currency: '  { currency }   ',
            adv_sub1: ' { order_subtotal } ',
            adv_sub2: '  { customer_email }   ',
            adv_sub3: '  { order_discount }   ',
            adv_sub4: '  { order_number }   ',
            adv_sub5: '',
        }
    })
</script>

We could find the corresponding dynamic variables for all the other parameters, but not for product’s name.

We could not find a documentation for the complete list of variables mentioned in the description above.

I wonder if we can just use { product_name } or do something like this:

Get products names in an array in Woocommerce thankyou page

How do we pass this parameter correctly?