schedule name conflict

This commit is contained in:
phowell 2024-08-27 13:36:26 -07:00
parent c9cc3cffcd
commit 20ee2240f0
2 changed files with 175 additions and 125 deletions

View File

@ -1,125 +0,0 @@
# schedule.py
#
# experimenting with manipulating and querying the schedule of courses
import json, re
from datetime import datetime
course_types = {'in-person':'IP','hybrid':'H','online':'O','online live':'OL'}
def course_to_string(crs):
# crn type days start end cred code name teacher
lengths = [5, 3, 5, 6, 6, 4, 4, 13, 35, 25]
items = [ crs[x] for x in 'crn,type,days,time_start,time_end,cred,act,code,name,teacher'.split(',')]
items[1] = course_types[ items[1] ]
items[5] = items[5][0:3]
result = " ".join(f"{str(val):{width}}" for val, width in zip(items, lengths))
return result
def parse_days(str_days):
# return a list with actual day of week names
days = []
if 'M' in str_days:
days.append('monday')
if 'T' in str_days:
days.append('tuesday')
if 'W' in str_days:
days.append('wednesday')
if 'R' in str_days:
days.append('thursday')
if 'F' in str_days:
days.append('friday')
if 'S' in str_days:
days.append('saturday')
return days
def parse_courses(filename):
with open(filename) as f:
courses = json.load(f)
locations, teachers, days, now = {}, {}, {}, datetime.now()
weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
for course in courses:
#print(course)
# Add course to teachers dict
course['teacher'] = re.sub(r'\s+', ' ', course['teacher'])
teachers.setdefault(course['teacher'], []).append(course)
if course['type'] != 'in-person': continue
# Add course to locations dict
locations.setdefault(course['loc'], []).append(course)
# Add course to days dict
for day in parse_days(course['days']):
days.setdefault(day, []).append(course)
# Check if course is happening now
if course['time_start'] == '': continue
if course['time_end'] == '': continue
start_time = datetime.strptime(course['time_start'], '%H:%M')
end_time = datetime.strptime(course['time_end'], '%H:%M')
#if start_time.time() <= now.time() <= end_time.time():
# print(f"{course['code']} is happening now in {course['loc']}")
return locations, teachers, days
# Example usage
locations, teachers, days = parse_courses('cache/sample_semester.json')
#print(json.dumps(locations,indent=2))
#print(json.dumps(teachers,indent=2))
#print(json.dumps(days,indent=2))
dump = 0
if dump:
for L,C in locations.items():
print(f"\n{L}")
for crs in C:
print(" " + course_to_string(crs))
for T,C in teachers.items():
print(f"\n{T}")
for crs in C:
print(" " + course_to_string(crs))
# EXAMPLES
#
print("\n\n")
# Get schedule for a specific room on a specific day
room = 'HU 104'
day = 'monday'
print(f"\nSchedule for {room} on {day}:")
for course in locations[room]:
if day in parse_days(course['days']):
print(" " + course_to_string(course))
# Get weekly schedule for a specific teacher
teacher = 'Kimberly J Smith'
print(f"\nWeekly schedule for {teacher}:")
for course in teachers[teacher]:
print(" " + course_to_string(course))
import sys
import os
columns, rows = os.get_terminal_size()
print(f"Terminal size: {columns} columns x {rows} rows")
def write_at(row, col, text):
sys.stdout.write(f"\033[{row};{col}H{text}")
sys.stdout.flush()
#
lines = [1,2,3,4,5]
for L in lines:
myline = rows - L
write_at(myline, 1, f"This is line {myline}")
write_at(rows,0,'')

175
schedules.py Normal file
View File

@ -0,0 +1,175 @@
# schedule.py
#
# experimenting with manipulating and querying the schedule of courses
import json, re, sys, os
from datetime import datetime
from fast_autocomplete import AutoComplete
columns, rows = os.get_terminal_size()
course_types = {'in-person':'IP','hybrid':'H','online':'O','online live':'OL'}
def course_to_string(crs):
# crn type days start end cred code name teacher
lengths = [5, 3, 5, 6, 6, 4, 4, 13, 35, 25]
items = [ crs[x] for x in 'crn,type,days,time_start,time_end,cred,act,code,name,teacher'.split(',')]
items[1] = course_types[ items[1] ]
items[5] = items[5][0:3]
result = " ".join(f"{str(val):{width}}" for val, width in zip(items, lengths))
return result
def parse_days(str_days):
# return a list with actual day of week names
days = []
if 'M' in str_days:
days.append('monday')
if 'T' in str_days:
days.append('tuesday')
if 'W' in str_days:
days.append('wednesday')
if 'R' in str_days:
days.append('thursday')
if 'F' in str_days:
days.append('friday')
if 'S' in str_days:
days.append('saturday')
return days
def parse_courses(filename):
with open(filename) as f:
courses = json.load(f)
locations, teachers, days, now = {}, {}, {}, datetime.now()
weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
for course in courses:
#print(course)
# Add course to teachers dict
course['teacher'] = re.sub(r'\s+', ' ', course['teacher'])
teachers.setdefault(course['teacher'], []).append(course)
if course['type'] != 'in-person': continue
# Add course to locations dict
locations.setdefault(course['loc'], []).append(course)
# Add course to days dict
for day in parse_days(course['days']):
days.setdefault(day, []).append(course)
# Check if course is happening now
if course['time_start'] == '': continue
if course['time_end'] == '': continue
start_time = datetime.strptime(course['time_start'], '%H:%M')
end_time = datetime.strptime(course['time_end'], '%H:%M')
#if start_time.time() <= now.time() <= end_time.time():
# print(f"{course['code']} is happening now in {course['loc']}")
return locations, teachers, days
def write_at(row, col, text):
sys.stdout.write(f"\033[{row};{col}H{text}")
sys.stdout.flush()
def write_search_results(res,maximum=8):
height = max(len(res),maximum)
while len(res)<height:
res.append('')
for i,L in enumerate(res):
write_at(rows - i-1, 1, f"{L} ")
write_at(rows,0,'')
def write_cleared_search_results(maximum=8):
for i in range(maximum):
write_at(rows - i, 1, f" ")
write_at(rows,0,'')
examples = 0
if examples:
# Get schedule for a specific room on a specific day
room = 'HU 104'
day = 'monday'
print(f"\nSchedule for {room} on {day}:")
for course in locations[room]:
if day in parse_days(course['days']):
print(" " + course_to_string(course))
# Get weekly schedule for a specific teacher
teacher = 'Kimberly J Smith'
print(f"\nWeekly schedule for {teacher}:")
for course in teachers[teacher]:
print(" " + course_to_string(course))
def interactive():
import sys
def getch():
# Unix
if sys.platform != 'win32':
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
# Windows
else:
import msvcrt
return msvcrt.getch().decode('utf-8')
words = { x:{} for x in teacherkeys.keys() }
autocomplete = AutoComplete(words=words)
# get search term
query = ''
results = []
while True:
char = getch()
#print(repr(char))
#print("\n\n\n\n\n\n\n\n")
if char == '\x08':
query = query[:-1]
elif char == '\r':
break
else:
query += char
results = [x[0] for x in autocomplete.search(word=query, max_cost=3, size=5)]
print(query+" ",end='',flush=True)
write_search_results(results)
write_cleared_search_results()
print()
print()
if results[0] in teacherkeys:
teacher = teacherkeys[results[0]]
if teacher in teachers.keys():
print(f"\nWeekly schedule for {teacher}:")
for course in teachers[teacher]:
print(" " + course_to_string(course))
else:
print("wasn't found.")
# Read in schedule
locations, teachers, days = parse_courses('cache/sample_semester.json')
teacherkeys = { x.lower():x for x in teachers.keys() }
lname_first = [x.split() for x in teachers.keys() ]
d_lnf = { x[-1].lower() + ", " + ' '.join(x[:-1]).lower(): ' '.join(x) for x in lname_first }
teacherkeys.update(d_lnf)
print(json.dumps(teacherkeys, indent=2))
print("\nEnter your answer")
interactive()