Skip to content

adding definitions #3

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
272 changes: 272 additions & 0 deletions 508d1fcc-60e0-40e3-a30c-408d0ffa1de9_Data.csv

Large diffs are not rendered by default.

108 changes: 108 additions & 0 deletions lab7_new.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# $pip install Flask
from flask import Flask, jsonify, request, render_template, redirect
import pandas as pd
import duckdb

app = Flask(__name__)

with duckdb.connect("nypd_date.db") as con:
df = con.table("felony").to_df()
print(df)

@app.route("/register", methods=["GET", "POST"])
def register_user():
if request.method == "POST":
username = request.form['username']
age = request.form['age']
country = request.form['country']

with get_db() as con:
con.execute("INSERT INTO users (username, age, country) VALUES (?, ?, ?)",
(username, int(age), country))

return redirect("/user_stats")

return '''
<h2>Register User</h2>
<form method="POST">
Username: <input type="text" name="username"><br><br>
Age: <input type="number" name="age"><br><br>
Country: <input type="text" name="country"><br><br>
<input type="submit" value="Register">
</form>
'''

@app.route("/user_stats", methods=["GET"])
def user_stats():
with duckdb.connect("nypd_date.db") as con:
total_users = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
avg_age = con.execute("SELECT AVG(age) FROM users").fetchone()[0]
countries = con.execute("""
SELECT country, COUNT(*) AS count
FROM users
GROUP BY country
ORDER BY count DESC
LIMIT 3
""").fetchall()

return jsonify({
"Total Users": total_users,
"Average Age": round(avg_age,0),
"Top Countries": [{"Country": row[0], "Number": row[1]} for row in countries]
})

@app.route("/")
def hello_world():
"""Return a friendly HTTP greeting."""

return "<p>Hello, World!</p>"

@app.route("/sum", methods=["GET"])
def sum():
"""Return the sum of two numbers."""
a = request.args.get("a")
b = request.args.get("b")

return jsonify({"sum": int(a) + int(b)})

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

@app.route("/factorial", methods=["GET"])
def factorial_route():
"""Return the factorial of a number."""

n = request.args.get("n",10)
r = factorial(int(n))
response = f'{n}! equals {r}'
return response

@app.route("/whole_data", methods=["GET"])
def whole_data():
"""Return the whole dataset."""
df = pd.read_csv('NYPD_Hate_Crimes_20250131.csv')
df = df.to_csv()
return jsonify(df)

@app.route("/year_data", methods=["GET"])
def year_data():
df = pd.read_csv('NYPD_Hate_Crimes_20250131.csv')
return jsonify(df["Complaint Year Number"].tolist())

@app.route("/alexa_mean_function", methods=["GET"])
def alexa_mean_function():
df = pd.read_csv('NYPD_Hate_Crimes_20250131.csv')
df["Month Number"] = df["Month Number"].astype(float)
return calc_mean(df)

def calc_mean(df):
mean = df["Month Number"].mean()
return mean.astype(str)

if __name__ == "__main__":
app.run(debug=True)

#disclaimer: used ChatGPT to figure out how to receive user information on website (via HTML)
44 changes: 44 additions & 0 deletions lab7_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from flask import Flask, jsonify, request
import duckdb

app = Flask(__name__)

# Database helper function
def get_db():
return duckdb.connect('nypd_date.db')

# POST method to register a new user
@app.route("/register", methods=["POST"])
def register_user():
username = request.json.get('username')
age = request.json.get('age')
country = request.json.get('country')

with get_db() as con:
con.execute("INSERT INTO users (username, age, country) VALUES (?, ?, ?)",
(username, age, country))

return jsonify({"message": "User added successfully"}), 201

# GET method to fetch user statistics
@app.route("/user_stats", methods=["GET"])
def user_stats():
with get_db() as con:
total_users = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
avg_age = con.execute("SELECT AVG(age) FROM users").fetchone()[0]
top_countries = con.execute("""
SELECT country, COUNT(*) AS count
FROM users
GROUP BY country
ORDER BY count DESC
LIMIT 3
""").fetchall()

return jsonify({
"total_users": total_users,
"avg_age": avg_age,
"top_countries": [{"country": row[0], "count": row[1]} for row in top_countries]
})

if __name__ == "__main__":
app.run(debug=True)
25 changes: 25 additions & 0 deletions make_database.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
ATTACH DATABASE 'nypd_date.db' AS mydb2;

CREATE TABLE mydb2.felony AS SELECT * FROM read_csv('NYPD_Hate_Crimes_20250131.csv');

SELECT* FROM mydb2.felony;

CREATE TABLE mydb2.users (
username TEXT,
age INTEGER,
country TEXT
);

INSERT INTO mydb2.users (username, age, country) VALUES
('Alexa', 23, 'USA'),
('Ijaz', 28, 'Bangladesh'),
('Ana', 15, 'Italy'),
('Sarah', 35, 'Canada'),
('James', 21, 'USA'),
('Jack', 29, 'USA'),
('Owen', 45, 'USA'),
('Madison', 33, 'Canada'),
('Ryan', 23, 'Bangladesh'),
('Jean', 13, 'Canada');

SELECT* FROM mydb2.users;
Binary file added nypd_date.db
Binary file not shown.
2 changes: 1 addition & 1 deletion lab4.py → old_lab4.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from flask import Flask, jsonify, request
import pandas as pd
import csv

#import duckdb
#print(df)

app = Flask(__name__)
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ flask
requests
json
csv
ydata-profiling
ydata-profiling
duckdb
Binary file added world_bank.db
Binary file not shown.
Binary file added world_bank.db.wal
Binary file not shown.