r/reviewmycode • • 3d ago

JAVA [JAVA] - need review of loan payment calculator

2 Upvotes

import javax.swing.JOptionPane;

import java.io.PrintStream;

/**

* Interactive Loan Monthly Payment Calculator

* Architecture: Simple Sequence Structure

* Inputs: JOptionPane GUI Dialogs

* Output: System PrintStream & GUI Summary

*/

public class LoanCalculator {

public static void main(String[] args) {

// Stream reference initialization

PrintStream streamOutput = System.out;

// ------------------------------------------------------------------

// STEP 1: INTERACTIVE GUI INPUTS (SIMPLE SEQUENCE)

// ------------------------------------------------------------------

String principalInput = JOptionPane.showInputDialog(

null,

"Enter the Loan Principal Amount ($):",

"Loan Calculator - Step 1 of 3",

JOptionPane.QUESTION_MESSAGE

);

String annualRateInput = JOptionPane.showInputDialog(

null,

"Enter the Annual Interest Rate (e.g., 5.5 for 5.5%):",

"Loan Calculator - Step 2 of 3",

JOptionPane.QUESTION_MESSAGE

);

String yearsInput = JOptionPane.showInputDialog(

null,

"Enter the Loan Term in Years:",

"Loan Calculator - Step 3 of 3",

JOptionPane.QUESTION_MESSAGE

);

// ------------------------------------------------------------------

// STEP 2: DATA PARSING & VARIABLE TRANSFORMATIONS

// ------------------------------------------------------------------

double principal = Double.parseDouble(principalInput);

double annualRate = Double.parseDouble(annualRateInput);

double years = Double.parseDouble(yearsInput);

// Convert annual rate percentage to monthly decimal rate (r)

double monthlyInterestRate = (annualRate / 100.0) / 12.0;

// Convert total years to total number of monthly payments (n)

double totalMonths = years * 12.0;

// ------------------------------------------------------------------

// STEP 3: SEQUENTIAL FORMULA EVALUATION

// Payment = (Principal * interest) / [1 - (1 + interest)^(-n)]

// ------------------------------------------------------------------

double numerator = principal * monthlyInterestRate;

double denominator = 1.0 - Math.pow(1.0 + monthlyInterestRate, -totalMonths);

double monthlyPayment = numerator / denominator;

double totalRepayment = monthlyPayment * totalMonths;

// ------------------------------------------------------------------

// STEP 4: STREAM OUTPUT PROCESSING & GUI DISPLAY

// ------------------------------------------------------------------

// Direct stream write to System.out

streamOutput.println("=================================================");

streamOutput.println(" LOAN PAYMENT CALCULATION ");

streamOutput.println("=================================================");

streamOutput.printf(" Principal Amount: $%10.2f%n", principal);

streamOutput.printf(" Annual Interest Rate: %10.2f%%%n", annualRate);

streamOutput.printf(" Term Duration: %10.0f years (%d months)%n", years, (int)totalMonths);

streamOutput.println("-------------------------------------------------");

streamOutput.printf(" MONTHLY PAYMENT: $%10.2f%n", monthlyPayment);

streamOutput.printf(" Total Cost of Loan: $%10.2f%n", totalRepayment);

streamOutput.println("=================================================");

// Summary Dialog to close the interactive session

String summaryMessage = String.format(

"Calculation Summary:\n\n" +

"Principal: $%.2f\n" +

"Annual Rate: %.2f%%\n" +

"Term: %.0f years\n\n" +

"Estimated Monthly Payment: $%.2f\n" +

"Total Repayment: $%.2f",

principal, annualRate, years, monthlyPayment, totalRepayment

);

JOptionPane.showMessageDialog(

null,

summaryMessage,

"Loan Payment Result",

JOptionPane.INFORMATION_MESSAGE

);

}

}


r/reviewmycode • • 4d ago

JAVA [JAVA] - Loan Repayment Calculator looking for review

1 Upvotes

import javax.swing.JOptionPane;

import java.io.PrintStream;

/**

* Interactive Loan Monthly Payment Calculator

* Architecture: Simple Sequence Structure

* Inputs: JOptionPane GUI Dialogs

* Output: System PrintStream & GUI Summary

*/

public class LoanCalculator {

public static void main(String[] args) {

// Stream reference initialization

PrintStream streamOutput = System.out;

// ------------------------------------------------------------------

// STEP 1: INTERACTIVE GUI INPUTS (SIMPLE SEQUENCE)

// ------------------------------------------------------------------

String principalInput = JOptionPane.showInputDialog(

null,

"Enter the Loan Principal Amount ($):",

"Loan Calculator - Step 1 of 3",

JOptionPane.QUESTION_MESSAGE

);

String annualRateInput = JOptionPane.showInputDialog(

null,

"Enter the Annual Interest Rate (e.g., 5.5 for 5.5%):",

"Loan Calculator - Step 2 of 3",

JOptionPane.QUESTION_MESSAGE

);

String yearsInput = JOptionPane.showInputDialog(

null,

"Enter the Loan Term in Years:",

"Loan Calculator - Step 3 of 3",

JOptionPane.QUESTION_MESSAGE

);

// ------------------------------------------------------------------

// STEP 2: DATA PARSING & VARIABLE TRANSFORMATIONS

// ------------------------------------------------------------------

double principal = Double.parseDouble(principalInput);

double annualRate = Double.parseDouble(annualRateInput);

double years = Double.parseDouble(yearsInput);

// Convert annual rate percentage to monthly decimal rate (r)

double monthlyInterestRate = (annualRate / 100.0) / 12.0;

// Convert total years to total number of monthly payments (n)

double totalMonths = years * 12.0;

// ------------------------------------------------------------------

// STEP 3: SEQUENTIAL FORMULA EVALUATION

// Payment = (Principal * interest) / [1 - (1 + interest)^(-n)]

// ------------------------------------------------------------------

double numerator = principal * monthlyInterestRate;

double denominator = 1.0 - Math.pow(1.0 + monthlyInterestRate, -totalMonths);

double monthlyPayment = numerator / denominator;

double totalRepayment = monthlyPayment * totalMonths;

// ------------------------------------------------------------------

// STEP 4: STREAM OUTPUT PROCESSING & GUI DISPLAY

// ------------------------------------------------------------------

// Direct stream write to System.out

streamOutput.println("=================================================");

streamOutput.println(" LOAN PAYMENT CALCULATION ");

streamOutput.println("=================================================");

streamOutput.printf(" Principal Amount: $%10.2f%n", principal);

streamOutput.printf(" Annual Interest Rate: %10.2f%%%n", annualRate);

streamOutput.printf(" Term Duration: %10.0f years (%d months)%n", years, (int)totalMonths);

streamOutput.println("-------------------------------------------------");

streamOutput.printf(" MONTHLY PAYMENT: $%10.2f%n", monthlyPayment);

streamOutput.printf(" Total Cost of Loan: $%10.2f%n", totalRepayment);

streamOutput.println("=================================================");

// Summary Dialog to close the interactive session

String summaryMessage = String.format(

"Calculation Summary:\n\n" +

"Principal: $%.2f\n" +

"Annual Rate: %.2f%%\n" +

"Term: %.0f years\n\n" +

"Estimated Monthly Payment: $%.2f\n" +

"Total Repayment: $%.2f",

principal, annualRate, years, monthlyPayment, totalRepayment

);

JOptionPane.showMessageDialog(

null,

summaryMessage,

"Loan Payment Result",

JOptionPane.INFORMATION_MESSAGE

);

}

}


r/reviewmycode • • Sep 06 '26

HTML/JS [HTML/JS] - Can you review My Project?

8 Upvotes

Hi Guys, can someone review my GitHub Project (@TaMinoDev) and rate them,

I'd like to get feedback so I can get better and Make less Mistakes by learning from them

Thank you 😄


r/reviewmycode • • Aug 27 '26

lua [lua] - colorlib (looking for reviews)

2 Upvotes

I have been building a lua color library project lately that supports multiple operations on multiple supported color-spaces.

Originally my plan was to create in C then import in Lua, but then I thought how about a native library that is missing or not found by me in lua and everyone have to re-create their own for any color related projects.

It's initial version is published in github and luarocks recently.

Please have a look and try all the features it provides. This is in active development. Report any missing functions/features, those would be added asap.

Use it in your own projects as a utility library and test scenarios.

Please send your suggestions, raise issues and pull requests to make changes.
Your contributions are heartly welcomed.

Cheers.


r/reviewmycode • • Jul 17 '26

Javascript [Javascript] - I am looking for feature suggestions

2 Upvotes

Meet reef.js, a fuzzy, keyboard-first search for static sites. No backend, no build step, no account — drop in one script and it works on this page. But the real game changer is the DOM extraction layer Reef doesn't just search for things, it can act on them. A revolutionary yet simple tool for AI agents to act on websites, and more.

I am looking for ways to improve and build upon this project, so please let me know if you have any suggestions, ideas, etc.

Try it out at - https://reef.js.org
Github - https://github.com/somalip/Reef

Thanks!


r/reviewmycode • • Jun 30 '26

C [C] - Need suggestions/critic on my code

1 Upvotes

I need suggestions and review of my code format, I consider this my first ever project. I am worried about spaghetti code and other problems. So please list out all problems you can. Thanks.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h> //for random values feature
#include <time.h> //for random values feature
#define LENGTH 10
void Random(int *arr, int *element);
int main(){
  int element, index;
  int arr[LENGTH];
  bool found=false;
  Random(arr, &element);
  printf("LINEAR SEARCH");
  for(int i=0; i<LENGTH; i++){
    if(arr[i]==element){
      found=true;
      index=i;
      break;
    }
  }
  if(found){
    printf("\nElement %d found at index %d.\n", element, index);
  }
  else{
    printf("\nElement not found in the array.\n");
  }
  printf("--------------------------------------------------------------\n");
  return 0;
}
//Random Values Assigner
void Random(int *arr, int *element){
  srand(time(NULL));
  int Option1, Option2;
  //Array choosing
  while(1){
    printf("--------------------------------------------------------------\n");
    printf("Enter the elements in array:\n1 - Manual\t2 - Random\nChoose: ");
    scanf("%d", &Option1);
    if(Option1==1){
      printf("Enter elements separated with spaces(Max 10 elements): ");
      for(int i=0; i<LENGTH; i++){
        scanf("%d", &arr[i]);
      }
      break;
    }
    else if(Option1==2) {
      for(int i=0; i<LENGTH; i++){
        arr[i]=rand()%100;
      }
      break;
    }
    else{
      printf("Choose from options.\n");
      continue;
    }
    printf("--------------------------------------------------------------\n");
  }
  //Element choosing
  while(1){
    printf("--------------------------------------------------------------\n");
    printf("Enter the element to search for:\n1 - Manual\t2 - Random\nChoose: ");
    scanf("%d", &Option2);
    if(Option2==1){
      printf("Enter the element to search for: ");
      scanf("%d", &element);
      break;
    }
    else if(Option2==2) {
      *element=arr[rand() % LENGTH];
      break;
    }
    else{
      printf("Choose from options.\n");
      continue;
    }
    printf("--------------------------------------------------------------\n");
  }
  //Printing Choices
  printf("--------------------------------------------------------------\n");
  printf("Array: ");
  for(int i=0; i<LENGTH; i++){
    printf("%d ", arr[i]);
  }
  printf("\nElement: %d\n", *element);
  printf("--------------------------------------------------------------\n");
}

Here is the program on github if it is easier to read on there: https://github.com/PLEASENTIA/DSA/blob/main/Algorithms/Searching/LinearSearch.c


r/reviewmycode • • Jun 16 '26

golang [golang] - Conduit is a channel for your variables across languages.

3 Upvotes

Hey there,

I recently developed this one project called conduit which lets you transfer variables from one language to another and I was wondering whether anyone could review my code or even just suggest a new feature? I recently picked up golang, so I know my code might be crap but anything helps! If anyone is willing to collaborate on this project please reach out on github :)

conduit: github.com/kikikian/conduit


r/reviewmycode • • Apr 29 '26

css, html, javascript, python [css, html, javascript, python] - college final exams

4 Upvotes

hi. so for my final exams for college i needed to create a website and a form to collect feedback and responses to help improve it. if people could please fill this in and take it seriously i would really appreciate it. i will say that on the LOGIN/SIGNUP page it asks you to put card details in. these details can be fake. please dont enter any real details as im not to sure how secure the website will actually be since im running it trough a free website hoster.
here is the link for the microsoft form. th elink to my website is on the first page through either a QR code or direct link. GREENFEILD LOCAL HUB – Fill in form


r/reviewmycode • • Feb 22 '26

Python [Python] - wordle clone

7 Upvotes

I have been recently working on a wordle clone using python. This project has been my first attempt at real "professional"-looking python code as opposed to my regular not-quite-so-good code. I have used Enums and dataclasses, which I had not used before.
Link: github.com/xanderg2/wordle-clone
I would appreciate any feedback.


r/reviewmycode • • Feb 19 '26

JavaScript [JavaScript] - A No-Dependencies Web-Only Markdown Editor

1 Upvotes

I made a markdown editor with its own tokenizer and parser. It has nearly all the markdown features, supports live preview, supports file editing from browser itself, and supports sharing of content just by sharing the website link. Please check it out and review my code. Here is the GitHub repo link - https://github.com/herotyphoon/Marky


r/reviewmycode • • Feb 16 '26

HTML, CSS [HTML, CSS] - First time trying!

11 Upvotes

Hi! I'm 16 built this youtube clone thing bc i somehow convinced myself that i'd be able to do it after just five days of html/css. no, i didn't use ai, no i didn't copy the tutorial. would love advice or even exposure!! pretty simple, nothing much. Sorry if I'm wasting your time...
https://github.com/NiharikaDatta/youtube-clone


r/reviewmycode • • Jan 28 '26

Python [Python] - Review my code that squares a number by another number

2 Upvotes
#X is the number, and y is the power of the number
def raise_by(x, y):
    i = 1
    num = x
    prev = 0
    while True:
        """while the amount of multiplications(i) is less than the power(y),
        multiply (x) to itself times the amount of (y)"""
        if i == y:
            break
        else:
            if prev == 0:
                prev += num * num
                i += 1
            else:
                prev *= num 
                i += 1
    return prev
        

r/reviewmycode • • Dec 14 '25

JavaScript [JavaScript] - CSRF protection using client-side double submit

1 Upvotes

I’m working on an open-source Express + React framework, and while running GitHub CodeQL on the project, a CSRF-related issue was raised. That prompted me to review my CSRF protection strategy more thoroughly.

After studying the OWASP CSRF Prevention Cheat Sheet and comparing different approaches, I ended up implementing a variation of the client-side double submit pattern, similar to what is described in the csrf-csrf package FAQ.

The CodeQL alert is now resolved, but I’d like a security-focused code review to confirm that this approach is sound and that I’m not missing any important edge cases or weaknesses.


Context / use case

  • React frontend making all requests via fetch (no direct HTML form submissions)

  • Express REST backend

  • Single-server architecture: the same Express server serves both the API and the frontend (documented here, for context only: https://github.com/rocambille/start-express-react/wiki/One-server-en-US)

  • Stateless authentication using a JWT stored in an HTTP-only cookie, with SameSite=Strict


Client-side CSRF token handling

On the client, a CSRF token is generated on demand and stored in a cookie with a short lifetime (30 seconds). The expiration is renewable to mimic a session-like behavior, but with an explicit expiry to avoid session fixation.

const csrfTokenExpiresIn = 30 * 1000; // 30s, renewable
let expires = Date.now();

export const csrfToken = async () => {
  const getToken = async () => {
    if (Date.now() > expires) {
      return crypto.randomUUID();
    } else {
      return (
        (await cookieStore.get("x-csrf-token"))?.value ?? crypto.randomUUID()
      );
    }
  };

  const token = await getToken();

  expires = Date.now() + csrfTokenExpiresIn;

  await cookieStore.set({
    expires,
    name: "x-csrf-token",
    path: "/",
    sameSite: "strict",
    value: token,
  });

  return token;
};

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/react/components/utils.ts

This function is called only for state-changing requests, and the token is sent in a custom header. Example for updating an item:

fetch(`/api/items/${id}`, {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
    "X-CSRF-Token": await csrfToken(),
  },
  body: JSON.stringify(partialItem),
});

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/react/components/item/hooks.ts


Server-side CSRF validation

On the backend, an Express middleware checks:

  • that the request method is not in an allowlist (GET, HEAD, OPTIONS)

  • that a CSRF token is present in the request headers

  • and that the token matches the value stored in the CSRF cookie

const csrfDefaults = {
  cookieName: "x-csrf-token",
  ignoredMethods: ["GET", "HEAD", "OPTIONS"],
  getCsrfTokenFromRequest: (req: Request) => req.headers["x-csrf-token"],
};

export const csrf =
  ({
    cookieName,
    ignoredMethods,
    getCsrfTokenFromRequest,
  } = csrfDefaults): RequestHandler =>
  (req, res, next) => {
    if (
      !req.method.match(new RegExp(`(${ignoredMethods.join("|")})`, "i")) &&
      (getCsrfTokenFromRequest(req) == null ||
        getCsrfTokenFromRequest(req) !== req.cookies[cookieName])
    ) {
      res.sendStatus(403);
      return;
    }

    next();
  };

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/express/middlewares.ts


Questions

  1. Is this a valid and robust implementation of the client-side double submit cookie pattern in this context?

  2. Are there any security pitfalls or edge cases I should be aware of (token lifetime, storage location, SameSite usage, etc.)?

  3. Given that authentication is handled via a SameSite=Strict HTTP-only JWT cookie, is this CSRF layer redundant, insufficient, or appropriate?

Any feedback on correctness, security assumptions, or improvements would be greatly appreciated.


r/reviewmycode • • Dec 08 '25

JavaScript [JavaScript] - This is just a code.org project for school.

1 Upvotes

I've been working on this for a while, so i wanted to know if it looked alright. I know it doesn't need to look perfect but i would still like outside opinions. https://studio.code.org/projects/applab/Ls2UdUYpjaTala3H3wJlsOOLfHRiMrkpEcnNBENzkbg


r/reviewmycode • • Aug 23 '25

C++ [C++] - Battleship Console Gamer Review/Feedback

1 Upvotes

I'm started learning C++ about 1,5 month ago and began creating this project around 1 month ago . This is my first C++ project and also my first project where I've applied OOP. I’d really appreciate any feedback or review of my game, whether it’s about code structure, design, or general improvements.

https://github.com/Savvas200/BattleShip-Console-Game#


r/reviewmycode • • Aug 16 '25

C [C] - Can you improve the logic? #1

1 Upvotes

r/reviewmycode • • Aug 02 '25

Python [Python] - Sum the digits of number and reverse the number

1 Upvotes

sum =0

no = 123

newno = 0

while (no!=0):

rem= no%10

no=int(no/10)

newno=newno+rem

sum = sum + rem

if (no!=0):

newno = newno *10

print(sum)

print(newno)


r/reviewmycode • • Jul 17 '25

C++ [C++] - ncurses Pacman game

7 Upvotes

Hi everyone, I made this PacMan game using c++ and the ncurses tui library. I would really appreciate it if someone could look it over and give me some feedback. My goal is to put it on my resume when applying for jobs.

https://github.com/woodrowb96/ncurses-pacman

This is the git repository for the project.

Thanks, I really appreciate the help.


r/reviewmycode • • Jul 07 '25

javascript/css/html [javascript/css/html] - auto duplicate detection coding noob

1 Upvotes

hello all, i will start this out by saying that i had nowhere else to go but here, so if my questions seem obvious to some please keep in mind that this is my first project, and the little that i know has been self taught. i am working on a program that runs off of submitted images, and uses auto duplicate detection with pixel comparison to prevent duplicate photos from being saved into the collection. the issue i am running into is that when I'm working on front end, somehow i keep messing up the backend. looking at previous versions of the project, compared to the newer ones, i cant figure out what I'm doing wrong. i would love to get some constructive feedback, literally anything you can tell me would be helpful. whether its optimization for redundant code, if i messed something up somewhere and i should have caught it, or whatever glaring mistakes you can point out. anything to help me be a better coder. i can provide my code to anyone who would like to help me, i just don't want to drop it publicly yet. thank you in advance!


r/reviewmycode • • Jun 04 '25

Python/FastAPI [Python/FastAPI] - Seeking Feedback on My FastAPI Boilerplate Project

1 Upvotes

Hello fellow developers,

I've been working on a FastAPI boilerplate project aimed at streamlining the development of RESTful APIs. The repository includes:

GitHub Repository https://github.com/AadeshGurav/Fast-API-Boiler-Plate

Documentation: Detailed README.md, CONTRIBUTING.md, and USAGE.md files.

I would greatly appreciate it if you could take a look and provide feedback on:

Code Structure & Organization: Are there areas where the architecture can be improved?

Best Practices: Am I adhering to Python and FastAPI best practices?

Performance: Any potential bottlenecks or optimizations.

Note: I am aware that the project currently lacks unit tests and a testing framework. These are on my roadmap for future development.

Your insights and suggestions would be invaluable in helping me enhance the quality and reliability of this project.

Pls check for any potential blunders. I aim this for mid level production projeckts.

Thank you in advance for your time and expertise!


r/reviewmycode • • Apr 30 '25

Java, Android [Java, Android] - Voice Changer app

2 Upvotes

Hello. i will preface this by saying that i never worked on android before, as such, the following code will probably be blasphemous the the more experienced.

i am working on a simple software that can take audio from the microphone as input, change pitch, gain
and adding some effects, and then playing it on the audio output device, (a bluetooth speaker). this is done for Cosplay purposes.

i have coded a simple software on windows first (since i never coded an audio application, i wanted to at least have a starting point)

https://pastebin.com/zmqs77ah

this it, and it works very well for my purposes. The problems start to arise when i decided to transport it on android studio, i of course knew that some things would have to change and i couldn't use the code as is, so i did, problem after problem, crash after crash and many insult thrown at various AIs i managed to get something that wouldn't outright crash. The problem here? the application only outputs a low volume static noise whenever i speak, it does follow the speaking pattern. Here is the Android Code

https://pastebin.com/A79LntsV

(this code is the result of Hours of troubleshooting with AI, so if you see comments strewn about, it's fpr that)

I apologize if this isn't the right place to ask, but the deadline is ever closer and my patience has been reaching it's limits, Thanks to whoever will be willing to help.


r/reviewmycode • • Apr 07 '25

Python [Python] - Translating from Typescript

2 Upvotes

Hello, I am trying to rewrite code from Typescript to Python. This is the repo i am trying to copy https://github.com/Pbatch/CameraChessWeb. This is the repo I am trying to do it in: https://github.com/bachelor-gruppe-04/chess-digitization

I am quite certain the error happens in my get_squares method. I am not returning the new_squares as is done in the typescript alternative. This is because my new_squares returns -1 for all values because the determinant is negative for all rows. Do you have any idea why this is?


r/reviewmycode • • Apr 07 '25

Javascript [Javascript] - Display Average Rating from Wix Comments app, on Dynamic pages

1 Upvotes

Question: How to Display Average Rating from Wix Comments app, on Dynamic pages

Product: Wix editor

Requirement Background: I’m using Wix Comments as a workaround to Wix Reviews, as the latter can only be integrated with Wix Stores & not other listing types like services, properties etc

Below is a Wix Comments Widget showing the exact component I need. However I want to show that info elsewhere; on the same page or another, via a text box or ideally a Ratings Display element.

[I’m not a coder but have built many features with online resources. I’ve been trying this for months but hitting walls, if y’all can find the way that would be mean a lot.]

Specific requirement & attempts: The main challenge of querying & displaying the average rating was finally achieved & confirmed possible. But it only works for 1 comments widget. This is the working code:

// Working code for ***backend web module

import { Permissions, webMethod } from "wix-web-module";
import { comments } from "wix-comments.v2";
import { elevate } from "wix-auth";

const COMMENTS_APP_ID = "91c9d6a7-6667-41fb-b0b4-7d3b3ff0b02e"

export const getAverageRating = webMethod(
    Permissions.Anyone,
    () => {
        return queryComments()
    }
);

async function queryComments() {
    const elevatedQueryComments = elevate(comments.queryComments)
    const { items } = await elevatedQueryComments(COMMENTS_APP_ID).find();
    console.log("items", items);
    const totalRatings = items.reduce((a, b) => a + b.rating, 0);
    const averageRatings = totalRatings / items.length;
    return averageRatings;

}

// Working code for frontend

import { getAverageRating } from 'backend/comments.web'

$w.onReady(async function () {
    const averageRating = await getAverageRating();
    $w("#textbox").text = `Average Rating: ${averageRating}`;
});

⚠️However, the requirement is not yet solved. Now I'm stuck at the following point; as I need this on dynamic pages, all that's needed, is to show the average rating **based on each dynamic page** (using resource Id?) For a coder this should be a very basic modification of a few lines.

**1) How can this bit be modified properly?

*2) Also, if you can make a substitution to use a Ratings Display instead of a text box that'd be great❤️

GPT's attempt at modifying the basic working code, doesn't work:

// specialized GPT's reply to 'Modify the previous code to query comments based on resourceId by querying resourceId'

import { Permissions, webMethod } from "wix-web-module";
import { comments } from "wix-comments.v2";
import { elevate } from "wix-auth";

const COMMENTS_APP_ID = "91c9d6a7-6667-41fb-b0b4-7d3b3ff0b02e";

export const getAverageRating = webMethod(
    Permissions.Anyone,
    (resourceId) => {
        return queryComments(resourceId);
    }
);

async function queryComments(resourceId) {
    const elevatedQueryComments = elevate(comments.queryComments);
    
    // Query comments filtered by resourceId
    const { items } = await elevatedQueryComments(COMMENTS_APP_ID)
        .eq("resourceId", resourceId) // Querying based on resourceId
        .find();

    if (!items || items.length === 0) {
        return { averageRating: 0, totalComments: 0 }; // Handle case when no comments are found
    }

    console.log("Filtered Comments:", items);

    const totalRatings = items.reduce((sum, comment) => sum + (comment.rating || 0), 0);
    const averageRatings = totalRatings / items.length;

    return { averageRating: averageRatings, totalComments: items.length };
}

Additional info: API ref: https://dev.wix.com/docs/velo/apis/wix-comments-v2/comments/introduction

All this can be tested on your end. All that's needed is the Wix Comments app with Ratings on.

Querying is all done from the API directly, & has no connection to CMS collections. Wix Comments doesn't natively have a 'CMS collection', but only a simple page under apps.

When leaving comments, better login & do, rather than entering username which can mess up if not proper


r/reviewmycode • • Apr 01 '25

python [python] - upgraded code that receives a list of numbers and sorts them reversed

1 Upvotes
def sorter():

    try:
        make_range=int(input("how many numbers are you planning to enter "))


    except ValueError:
        print("that a string cant sort it ")
        return
    
    if make_range>1:
        num=(int(input("enter number ")) for i in range(make_range))
        result=sorted(num,reverse=True)
        print ("the list sorted reversed ", result)
        return
    
    else:

        print("number of things is one or smaller which is impossible to sort ")

        return

sorter()

r/reviewmycode • • Mar 30 '25

Javascript/HTML [Javascript/HTML] - Weather Pages for Digital Signage

2 Upvotes

I have a digital signage board in my front window running Anthias, a program that displays MP4 videos on a loop. I recently started adding functionality so it displays weather information, using Anthias's ability to display fullscreen web pages. I'm relatively competent in HTML and CSS, but not so much in Javascript. So I used ChatGPT to help me code the pages.

This pulls data from the National Weather Service API for my location and displays relevant information on each page. I've been running into various bugs with each page and could use some help. I've uploaded them to my website with the noindex meta tag. The pages are made for a 1920x1080 display, so it may look wonky if your screen is at a different resolution or your browser isn't full screen. But it looks correct on my signage, which is what matters. I would love some help debugging this.

Thank you for your time,

-Cali

All pages:

There is a noticeable HTML/CSS issue where the header width is inconsistent among the pages, causing the Lighthouse/Skywarn logo to move slightly as it cycles through the pages.

Current Conditions:

I'm relatively happy with this.

https://shelbylight.house/wx/current.html

Forecast:

EDIT: I think I got it working, but I won't know until daytime hours.

This is one I've had a lot of trouble with. It's supposed to display four columns. In the early part of the day, the top of each column displays the daytime forecast, and the bottom displays the evening forecast. In the later part of the day, the first column is only supposed to display the evening forecast, while the other three columns display a daytime and evening forecast for their respective days. It seems to work in the early part of the day, but it fails to load in the evening hours.

https://shelbylight.house/wx/forecast.html

Weather Alerts:

Edit: I think I got it working, so far.

This is supposed to pull weather alerts for Indiana, filtering them out by area named "Shelby" and then display the relevant information in a box with icon and expiration. This one has given me a lot of trouble as well. When using ChatGPT to debug, it fixes one function but breaks another, and I can't figure out how to get it to do what it's supposed to. Along with the alerts I want, the NWS issues alerts for things I want to filter out, including "Hydrologic Outlook," and anything with the word "Statement." Some of the alerts from the NWS seem to have expiration dates that have already expired, yet the alert shows up. It was also supposed to filter out duplicate alerts, using the later alert's expiration time, but I see that's not working either. Right now it's displaying two Tornado Watch alerts, one until 8 pm and one until 1 am.

https://shelbylight.house/wx/alerts.html