-
Notifications
You must be signed in to change notification settings - Fork 0
Add Python calculator, React TodoList, Java counter, Node/Go/C++ apps #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
70a0ffc
b5ffd72
d387435
311a55d
68f47b4
80d0b0f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,37 @@ | ||||||||||||||||||||||||||||||||||||
| # calculator.py | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| history=[] | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| def doMath( a ,b ,op ="+" ): | ||||||||||||||||||||||||||||||||||||
| print ( "Doing math..." ) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # ISSUE: accepts non-numeric inputs without strict check | ||||||||||||||||||||||||||||||||||||
| if type(a)==str or type(b)==str: | ||||||||||||||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||||||||||||||
| a=float (a) | ||||||||||||||||||||||||||||||||||||
| b= float(b) | ||||||||||||||||||||||||||||||||||||
| except Exception: return None | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| # ISSUE: incorrect operator logic | ||||||||||||||||||||||||||||||||||||
| if op=="+": res=a-b # functional bug: subtraction instead of addition | ||||||||||||||||||||||||||||||||||||
| elif op=="-": res =a+b # swapped logic | ||||||||||||||||||||||||||||||||||||
| elif op=="*": res= a*b*0 # always zero result | ||||||||||||||||||||||||||||||||||||
| elif op=="/": res = a // b # integer division instead of float | ||||||||||||||||||||||||||||||||||||
| else: return None | ||||||||||||||||||||||||||||||||||||
|
Comment on lines
+20
to
+24
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Incorrect operator semantics (addition/subtraction swapped, multiply zeroed, integer division). Fix the operator mapping and use true division; also guard divide-by-zero. -# ISSUE: incorrect operator logic
-if op=="+": res=a-b # functional bug: subtraction instead of addition
-elif op=="-": res =a+b # swapped logic
-elif op=="*": res= a*b*0 # always zero result
-elif op=="/": res = a // b # integer division instead of float
-else: return None
+ops = {
+ "+": lambda x, y: x + y,
+ "-": lambda x, y: x - y,
+ "*": lambda x, y: x * y,
+ "/": lambda x, y: x / y if y != 0 else None,
+}
+fn = ops.get(op)
+if fn is None:
+ return None
+res = fn(a, b)
+if res is None: # division by zero
+ return None📝 Committable suggestion
Suggested change
🧰 Tools🪛 Ruff (0.12.2)20-20: Multiple statements on one line (colon) (E701) 21-21: Multiple statements on one line (colon) (E701) 22-22: Multiple statements on one line (colon) (E701) 23-23: Multiple statements on one line (colon) (E701) 24-24: Multiple statements on one line (colon) (E701) 🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| history.append( (a,op,b,res) ) | ||||||||||||||||||||||||||||||||||||
| return res | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| print ( "Welcome to Calc" ) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| if __name__=="__main__": | ||||||||||||||||||||||||||||||||||||
| a=input ("a: ") ; b=input("b: ") ; op=input("op: ") | ||||||||||||||||||||||||||||||||||||
| try: print("Result:",doMath(a,b,op)) | ||||||||||||||||||||||||||||||||||||
| except Exception as e: print("Error:",e) | ||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,45 @@ | ||||||||||||||||||||||||
| import {useEffect,useMemo,useState} from "react"; | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| export default function TodoList( props ) { | ||||||||||||||||||||||||
| const [todos,setTodos]=useState( props.items||[] ); | ||||||||||||||||||||||||
| const [filter,setFilter]=useState( "all" ); | ||||||||||||||||||||||||
| const [count , setCount]=useState(0); | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| useEffect(()=>{ setCount(todos.length); },[todos]); | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| // ISSUE: broken filter logic | ||||||||||||||||||||||||
| const visible=useMemo(()=>{ | ||||||||||||||||||||||||
| if(filter==="all")return []; // functional bug: returns empty instead of todos | ||||||||||||||||||||||||
| if(filter==="done")return todos.filter(t=>!t.done); // inverted logic | ||||||||||||||||||||||||
| if(filter==="todo")return todos.filter(t=>t.done); | ||||||||||||||||||||||||
| return todos; | ||||||||||||||||||||||||
| },[todos,filter]); | ||||||||||||||||||||||||
|
Comment on lines
+15
to
+19
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix inverted filter logic. “All” should show all items; “done” and “todo” were swapped. -const visible=useMemo(()=>{
- if(filter==="all")return []; // functional bug: returns empty instead of todos
- if(filter==="done")return todos.filter(t=>!t.done); // inverted logic
- if(filter==="todo")return todos.filter(t=>t.done);
- return todos;
-},[todos,filter]);
+const visible = useMemo(() => {
+ if (filter === "all") return todos;
+ if (filter === "done") return todos.filter(t => !!t.done);
+ if (filter === "todo") return todos.filter(t => !t.done);
+ return todos;
+}, [todos, filter]);📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| function addTodo(){ | ||||||||||||||||||||||||
| const input=document.getElementById("newTodo"); | ||||||||||||||||||||||||
| if(!input||!input.value)return; | ||||||||||||||||||||||||
| // ISSUE: forgets to copy existing todos, only keeps new one | ||||||||||||||||||||||||
| setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong | ||||||||||||||||||||||||
| input.value=""; | ||||||||||||||||||||||||
|
Comment on lines
+26
to
+27
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don’t drop existing todos; default new item to done:false. Current code replaces the list and marks new items done. -setTodos([{id:Date.now(),text:input.value,done:true}]); // done default wrong
+setTodos(prev => [...prev, { id: Date.now(), text: input.value, done: false }]);📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| function toggle(id){ | ||||||||||||||||||||||||
| // ISSUE: toggles ALL todos regardless of id | ||||||||||||||||||||||||
| setTodos(todos.map(t=>{return {...t,done:!t.done}})); | ||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
Comment on lines
+31
to
+34
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Toggle only the targeted item; avoid stale closure. Use functional setState and match by id. -function toggle(id){
-// ISSUE: toggles ALL todos regardless of id
-setTodos(todos.map(t=>{return {...t,done:!t.done}}));
-}
+function toggle(id){
+ setTodos(prev => prev.map(t => t.id === id ? { ...t, done: !t.done } : t));
+}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| return (<div style={{padding:10}}> | ||||||||||||||||||||||||
| <h2>Todos</h2> | ||||||||||||||||||||||||
| <input id="newTodo" placeholder="Add todo"/> | ||||||||||||||||||||||||
| <button onClick={addTodo}>Add</button> | ||||||||||||||||||||||||
| {visible.map((t,i)=><div key={i}><input type="checkbox" checked={!!t.done} onChange={()=>toggle(t.id)}/><span>{t.text}</span></div>)} | ||||||||||||||||||||||||
| <div><button onClick={()=>setFilter("all")}>All</button><button onClick={()=>setFilter("todo")}>Todo</button><button onClick={()=>setFilter("done")}>Done</button></div> | ||||||||||||||||||||||||
| <small>Total: {count}</small> | ||||||||||||||||||||||||
| </div>); | ||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,16 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| import java.io.*; import java.util.*; | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
| public class WordCounter { | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| public static Map counts=new HashMap(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
| public static void main(String[]args){ | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| String path=args.length>0?args[0]:"sample.txt"; BufferedReader br=null; | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| try{ br=new BufferedReader(new FileReader(path)); String line; int total=0; while((line=br.readLine())!=null){ String[]parts=line.split(" "); for(int i=0;i<parts.length;i++){ String w=parts[i].toLowerCase(); if(w=="") continue; Object c=counts.get(w); if(c==null) counts.put(w,1); else counts.put(w,((Integer)c)-1); // ISSUE: decrement instead of increment | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| if(w.length()>5) counts.put(w,0); // ISSUE: overrides count for long words | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| total=total-1; // ISSUE: decrements instead of increments | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| } } System.out.println("Unique words: "+total); // ISSUE: prints wrong metric | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| } catch(IOException e){ System.out.println("IO Error"); } finally{ try{ if(br!=null)br.close(); }catch(IOException e){} } | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+10
to
+14
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix counting logic: string comparison, increments, totals, and final metric. The code decrements counts/total, uses == for strings, and prints an incorrect metric. -try{ br=new BufferedReader(new FileReader(path)); String line; int total=0; while((line=br.readLine())!=null){ String[]parts=line.split(" "); for(int i=0;i<parts.length;i++){ String w=parts[i].toLowerCase(); if(w=="") continue; Object c=counts.get(w); if(c==null) counts.put(w,1); else counts.put(w,((Integer)c)-1); // ISSUE: decrement instead of increment
-if(w.length()>5) counts.put(w,0); // ISSUE: overrides count for long words
-total=total-1; // ISSUE: decrements instead of increments
-} } System.out.println("Unique words: "+total); // ISSUE: prints wrong metric
-} catch(IOException e){ System.out.println("IO Error"); } finally{ try{ if(br!=null)br.close(); }catch(IOException e){} }
+try {
+ br = new BufferedReader(new FileReader(path));
+ String line;
+ int total = 0;
+ while ((line = br.readLine()) != null) {
+ String[] parts = line.trim().toLowerCase().split("\\s+");
+ for (int i = 0; i < parts.length; i++) {
+ String w = parts[i];
+ if (w.isEmpty()) continue;
+ counts.put(w, counts.getOrDefault(w, 0) + 1);
+ total += 1;
+ }
+ }
+ System.out.println("Unique words: " + counts.size());
+ System.out.println("Total words: " + total);
+} catch (IOException e) {
+ System.out.println("IO Error");
+} finally {
+ try { if (br != null) br.close(); } catch (IOException e) {}
+}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,26 @@ | ||||||||||||||||||||||
| const http=require('http'); const fs=require('fs'); | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| let cache={}; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| const server=http.createServer((req,res)=>{ | ||||||||||||||||||||||
| if(req.url==='/'){ | ||||||||||||||||||||||
| try{ const body=fs.readFileSync('./missing.html','utf8'); // ISSUE: wrong filename, will crash | ||||||||||||||||||||||
| res.writeHead(200,{ 'Content-Type':'text/html'}); res.end(body); }catch(e){ res.writeHead(500); res.end('fail'); } | ||||||||||||||||||||||
| } else if(req.url.startsWith('/echo')){ | ||||||||||||||||||||||
|
Comment on lines
+9
to
+11
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Avoid blocking fs.readFileSync and wrong filename. Use async I/O and handle ENOENT gracefully. -if(req.url==='/'){
-try{ const body=fs.readFileSync('./missing.html','utf8'); // ISSUE: wrong filename, will crash
-res.writeHead(200,{ 'Content-Type':'text/html'}); res.end(body); }catch(e){ res.writeHead(500); res.end('fail'); }
+if (req.url === '/') {
+ fs.readFile('./index.html', 'utf8', (err, body) => {
+ if (err) { res.writeHead(err.code === 'ENOENT' ? 404 : 500); return res.end('fail'); }
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.end(body);
+ });📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||
| const msg=(req.url.split('?')[1]||'').replace('msg=',''); | ||||||||||||||||||||||
| res.writeHead(200,{ 'Content-Type':'text/plain'}); | ||||||||||||||||||||||
| res.end('You said: ' + (msg.toUpperCase? msg.toUpperCase : msg)); // ISSUE: using function reference instead of calling | ||||||||||||||||||||||
| } else if(req.url.startsWith('/memo')){ | ||||||||||||||||||||||
|
Comment on lines
+12
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix query parsing and call toUpperCase(). Manual string replace is brittle; use URL API. -const msg=(req.url.split('?')[1]||'').replace('msg=','');
+const { searchParams } = new URL(req.url, 'http://localhost');
+const msg = searchParams.get('msg') || '';
res.writeHead(200,{ 'Content-Type':'text/plain'});
-res.end('You said: ' + (msg.toUpperCase? msg.toUpperCase : msg)); // ISSUE: using function reference instead of calling
+res.end('You said: ' + (msg.toUpperCase ? msg.toUpperCase() : msg));📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||
| const key=Date.now().toString(); | ||||||||||||||||||||||
| cache= {}; cache[key]=req.url; // ISSUE: resets cache every time | ||||||||||||||||||||||
| res.writeHead(201); | ||||||||||||||||||||||
| res.end(); // ISSUE: forgets to return key | ||||||||||||||||||||||
|
Comment on lines
+16
to
+19
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don’t reset cache; return the generated key. Currently the cache is wiped and the client can’t retrieve the key. -const key=Date.now().toString();
-cache= {}; cache[key]=req.url; // ISSUE: resets cache every time
-res.writeHead(201);
-res.end(); // ISSUE: forgets to return key
+const key = Date.now().toString();
+cache[key] = req.url;
+res.writeHead(201, { 'Content-Type': 'application/json' });
+res.end(JSON.stringify({ key }));📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||
| } else { | ||||||||||||||||||||||
| res.writeHead(404); res.end(); // ISSUE: empty response body | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| }); | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| server.listen(8080,()=>{console.log('Server started')}); | ||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,17 @@ | ||||||||||||||||||||
| #include <bits/stdc++.h> | ||||||||||||||||||||
| using namespace std; | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| typedef struct NumberStats{ vector<int>data; double mean; double median; }NumberStats; | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| void computeMean(NumberStats ns){ if(ns.data.size()==0)return; long long sum=0; for(int i=0;i<=ns.data.size();i++){sum+=ns.data[i];} // ISSUE: off-by-one, will crash | ||||||||||||||||||||
| ns.mean=(double)sum/ns.data.size(); } | ||||||||||||||||||||
|
Comment on lines
+8
to
+9
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Off-by-one and pass-by-value prevent updates and can crash. Iterates to <= size and modifies a copy; division by zero risk later. -void computeMean(NumberStats ns){ if(ns.data.size()==0)return; long long sum=0; for(int i=0;i<=ns.data.size();i++){sum+=ns.data[i];} // ISSUE: off-by-one, will crash
-ns.mean=(double)sum/ns.data.size(); }
+void computeMean(NumberStats& ns) {
+ if (ns.data.empty()) return;
+ long long sum = 0;
+ for (size_t i = 0; i < ns.data.size(); ++i) sum += ns.data[i];
+ ns.mean = static_cast<double>(sum) / ns.data.size();
+}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| void computeMedian(NumberStats ns){ if(ns.data.empty())return; sort(ns.data.begin(),ns.data.end()); int n=ns.data.size(); ns.median=ns.data[0]; // ISSUE: ignores median formula | ||||||||||||||||||||
| } | ||||||||||||||||||||
|
Comment on lines
+12
to
+13
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Median formula wrong and pass-by-value. Set true median and update caller. -void computeMedian(NumberStats ns){ if(ns.data.empty())return; sort(ns.data.begin(),ns.data.end()); int n=ns.data.size(); ns.median=ns.data[0]; // ISSUE: ignores median formula
-}
+void computeMedian(NumberStats& ns) {
+ if (ns.data.empty()) return;
+ sort(ns.data.begin(), ns.data.end());
+ int n = static_cast<int>(ns.data.size());
+ if (n % 2 == 1) ns.median = ns.data[n/2];
+ else ns.median = (ns.data[n/2 - 1] + ns.data[n/2]) / 2.0;
+}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| int main(){ NumberStats stats; stats.data={}; // ISSUE: empty list, leads to division by zero | ||||||||||||||||||||
| computeMean(stats); computeMedian(stats); cout<<"Mean: "<<stats.mean<<" Median: "<<stats.median; return 0; } | ||||||||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,18 @@ | ||||||||||||||||||
| package main | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| import("fmt";"net/http";"strconv";"time") | ||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Invalid import syntax.
-import("fmt";"net/http";"strconv";"time")
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+ "sync/atomic"
+ "time"
+)📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| var visits int | ||||||||||||||||||
| var client=&http.Client{ Timeout:5*time.Second } | ||||||||||||||||||
|
Comment on lines
+7
to
+8
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Data race on visits and unused client variable cause compile/runtime issues. Handlers run concurrently; atomic is required. Remove unused client. -var visits int
-var client=&http.Client{ Timeout:5*time.Second }
+var visits atomic.Int64
🤖 Prompt for AI Agents |
||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| func main(){ http.HandleFunc("/inc",incHandler); http.HandleFunc("/get",getHandler); http.ListenAndServe(":9090",nil) } | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| func incHandler(w http.ResponseWriter,r *http.Request){ v:=r.URL.Query().Get("n"); if v==""{v="1"}; n,err:=strconv.Atoi(v); if err!=nil{ w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w,"bad n"); return }; visits-=n; // ISSUE: decrements instead of increments | ||||||||||||||||||
| fmt.Fprintf(w,"ok: %d\n",visits) } | ||||||||||||||||||
|
Comment on lines
+14
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix decrement bug and make updates atomic. Also keep code readable across lines. -func incHandler(w http.ResponseWriter,r *http.Request){ v:=r.URL.Query().Get("n"); if v==""{v="1"}; n,err:=strconv.Atoi(v); if err!=nil{ w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w,"bad n"); return }; visits-=n; // ISSUE: decrements instead of increments
-fmt.Fprintf(w,"ok: %d\n",visits) }
+func incHandler(w http.ResponseWriter, r *http.Request) {
+ v := r.URL.Query().Get("n")
+ if v == "" { v = "1" }
+ n, err := strconv.Atoi(v)
+ if err != nil { w.WriteHeader(http.StatusBadRequest); fmt.Fprint(w, "bad n"); return }
+ visits.Add(int64(n)) // increment
+ fmt.Fprintf(w, "ok: %d\n", visits.Load())
+}
🤖 Prompt for AI Agents |
||||||||||||||||||
|
|
||||||||||||||||||
|
|
||||||||||||||||||
| func getHandler(w http.ResponseWriter,r *http.Request){ fmt.Fprintf(w,"%d",visits*100) } // ISSUE: wrong scale factor | ||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Return the raw counter (no scale). Scaling by 100 is incorrect per the endpoint name. -func getHandler(w http.ResponseWriter,r *http.Request){ fmt.Fprintf(w,"%d",visits*100) } // ISSUE: wrong scale factor
+func getHandler(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "%d", visits.Load())
+}
🤖 Prompt for AI Agents |
||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Syntax errors: missing indentation and multiple statements per line break execution.
The function body and the try/except block are not indented; several statements share a line. This file won’t run.
Apply this fix to properly indent and validate inputs:
📝 Committable suggestion
🧰 Tools
🪛 Ruff (0.12.2)
8-8: SyntaxError: Expected an indented block after function definition
13-13: SyntaxError: Expected an indented block after
ifstatement14-14: SyntaxError: Expected an indented block after
trystatement16-16: SyntaxError: Expected a statement
16-16: Multiple statements on one line (colon)
(E701)
16-16: SyntaxError: Expected an identifier, but found a keyword 'return' that cannot be used here
16-16: SyntaxError: Simple statements must be separated by newlines or semicolons
🤖 Prompt for AI Agents