def token(): if request.method == 'GET': return render_template("index.html") elif request.method == 'POST': if request.form['token'] != "": if current_user.is_authenticated: user_id = current_user.get_id() user = db.session.query(models.User).get(user_id) user.token = request.form['token'] db.session.merge(user) db.session.commit() uw_api = UWaterlooAPI(api_key=request.form['token']) courses = getCourses.generateCourses(uw_api) if 'temperature_24hr_min_c' in uw_api.current_weather( ) and not len(courses) == 0: return render_template("select.html", token=request.form['token'], courses=courses) else: return render_template("error.html", errormsg="Invalid API Token") else: return render_template("index.html")
def getschedule(courses: list): UW_API_KEY = os.environ.get('UW_API_KEY', None) if UW_API_KEY is None: raise APIKeyMissingError("Missing: UW_API_KEY" "All methods require an API Key. " "Refer to https://uwaterloo.ca/api/ " "For how to register for an API key.") fetcher = UWaterlooAPI(api_key=UW_API_KEY) schedule = [] for cur_course in courses: course_id = cur_course.split(' ') course_sections = fetcher.course_schedule(course_id[0], course_id[1]) for section in course_sections: if int(section['enrollment_capacity']) - int(section[ 'enrollment_total']) > 0 and 'LEC' in section['section']: starttime = timetoint( section['classes'][0]['date']['start_time']) endtime = timetoint(section['classes'][0]['date']['end_time']) course = uwcourse(cur_course, section['section'], section['classes'][0]['date']['weekdays'], starttime, endtime, {}) schedule.append(course) return schedule
def __init__(self, bot_name, api_key): print("Logging in to reddit as " + bot_name + "...") self.bot = praw.Reddit(bot_name) print("Logged in as " + bot_name + "!") self.uw_key = api_key self.uw_api = UWaterlooAPI(api_key) self.sub_reply_txt = f'./modules/submission_replies_u_{bot_name}.txt'
from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key="ec16c4c498c87b043a33e9903a61c51d") print uw.schedule_by_class_number("007407")
#!/bin/python from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key="db2f06438ed0d3131473a3fef959b190") import datetime import json class course: __subject = "" __catalog = "" __section = "" __startTime = "" __endTime = "" __weekdays = "" def __init__(self, subject, catalog, section): self.__subject = subject self.__catalog = catalog self.__section = section self.__startTime = find_start_time(subject, catalog, section) self.__endTime = find_end_time(subject, catalog, section) self.__weekdays = find_weekdays(subject, catalog, section) def get_subject(self): return self.__subject def get_catalog(self): return self.__catalog def get_section(self): return self.__section
import os import json import time from slackclient import SlackClient from uwaterlooapi import UWaterlooAPI BOT_ID = os.environ.get("BOT_ID") BOT_NAME = "cb" AT_BOT_NAME = "*@" + BOT_NAME + "*" AT_BOT = "<@" + BOT_ID + ">" EXAMPLE_COMMAND = "do" SLACK_CLIENT = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) UW_CLIENT = UWaterlooAPI(api_key=os.environ.get('UW_TOKEN')) def parse_course_command(s): string_length = len(s) alpha_pos = 1 while alpha_pos < string_length and s[alpha_pos].isalpha(): alpha_pos += 1 numer_pos = alpha_pos while numer_pos < string_length and not s[numer_pos].isdigit(): numer_pos += 1 return (s[:alpha_pos], s[numer_pos:])
'last_updated': '2019-08-02T15:07:30-04:00' }] ##One class ends here, and next one starts below it #Useful info: prof name, timing, tutorial timing, enrolment capacity and enrolment total. Prequisites can be seen later or mentioned in side. # Need prof rating but later. #First just make a schedule. #Ask for courses from the user, do not limit the user on the number of courses, make a timetable. # Monday # (8:30 AM to 9:20AM) # PHYS 122 # ................... # ..... from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key="120f4c218136a91d9f0f83d0ce79cca7") def conv( obj ): ##Solves the problem of error of start-time and end-time being unavailable for any class try: return int(obj.replace(':', '')) except Exception: return "N/A" def oneinother(s1, s2): #Returns True if s1 in s2 or s2 in s1 else false #Also deals with the problem of section name being not available try: if len(s1) >= len(s2) and s2 in s1:
import collections from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key="938d42adae6cc93ed580450aef4cdbba") # TAKES ABOUT 10 MINUTES TO RUN # .txt files must be changed into appropriate .json files big_list = uw.courses() course_titles = {} big_dict = {} big_dict2 = {} # A Course is a String # A Prereq is one of: # * list (Course) # * listof (1, listof(Course)) # e.g. : ['MATH 106'] # [1, 'CS115', 'CS135'] # [[1, 'MATH235', 'MATH245'], [1, 'MATH237', 'MATH247']] # Takes a list of prereqs and turns it into a listof (Course) def filter_prereqs(lst): re = [] if len(lst) > 0 and (lst[0] == 1 or lst[0] == 2 or lst[0] == 3): del lst[0]
import requests import sys from apikeys import getUWApiKey from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key=getUWApiKey()) #classes = uw.courses("MAdsfdsfsTH") #print(classes) def getCourse(): #get input currentCourse = raw_input() # error check while not currentCourse or len(currentCourse.split(' ')) != 2: print "Please enter a valid course name" currentCourse = raw_input() return currentCourse.upper() #assuming 5 courses, loops 0-4 i = 1 enteredCourses = [] finalDates = [[] for x in range(5)] while i <= 5: print "Enter name for Course #%d (e.g CS 350)" % (i)
def generateSchedules(request): uw = UWaterlooAPI(api_key=request.form['token']) #TODO: ENSURE INPUTS ARE PUT IN VALID FORMAT (USE REGEX) try: no_classes_before = request.form['before_filter'] no_classes_before_time = datetime.datetime.strptime( no_classes_before, '%H:%M') except: no_classes_before = None try: no_classes_after = request.form['after_filter'] no_classes_after_time = datetime.datetime.strptime( no_classes_after, '%H:%M') except: no_classes_after = None try: if request.form['tutorials']: tutorials_active = False else: tutorials_active = True except: tutorials_active = True num_courses = 0 for num in range(1, 8): if request.form['course' + str(num)]: num_courses = num master_list = [] for course in range(1, num_courses + 1): course_name = request.form['course' + str(course)] course_number = request.form['course' + str(course) + 'num'] course_title = course_name + " " + course_number if not checkValidCourse.course_exists(course_name, course_number, uw): error_message = ''.join( [course_name, course_number, " is not a valid course."]) return [False, error_message] courses_list = uw.course_schedule(course_name, course_number) num_sections = len(courses_list) course_list = [] lecture_list = [] tutorial_list = [] lab_list = [] for section in range(0, num_sections): class_type = courses_list[section]['section'] if class_type.find("LEC") == 0 or class_type.find( "TUT") == 0 or class_type.find("LAB") == 0: days = courses_list[section]['classes'][0]['date']['weekdays'] start_time = courses_list[section]['classes'][0]['date'][ 'start_time'] section_number = courses_list[section]['section'] if no_classes_before: start_time_datetime = datetime.datetime.strptime( start_time, '%H:%M') if start_time_datetime < no_classes_before_time: continue end_time = courses_list[section]['classes'][0]['date'][ 'end_time'] if no_classes_after: end_time_datetime = datetime.datetime.strptime( end_time, '%H:%M') if end_time_datetime > no_classes_after_time: continue course_type = courses_list[section][ 'section'] #either LEC, LAB, or TUT instructor = courses_list[section]['classes'][0]['instructors'] if instructor: instructor = str(instructor[0].encode('ascii', 'ignore')) else: instructor = 'None' if class_type.find("LEC") == 0: lec_section = [ days, start_time, end_time, course_type, instructor, course_title, section_number ] lecture_list.append(lec_section) if class_type.find("TUT") == 0 and tutorials_active: tut_section = [ days, start_time, end_time, course_type, instructor, course_title, section_number ] tutorial_list.append(tut_section) if class_type.find("LAB") == 0: lab_section = [ days, start_time, end_time, course_type, instructor, course_title, section_number ] lab_list.append(lab_section) if lecture_list: course_list.append(lecture_list) if tutorial_list: course_list.append(tutorial_list) if lab_list: course_list.append(lab_list) if master_list: course_list.append(master_list) master_list = list(itertools.product(*course_list)) for schedule in range(0, len(master_list)): try: flattened_list = list(flatten(master_list[schedule])) except: return False if (not checkValidSchedule.is_valid_schedule(flattened_list)): master_list[schedule] = [] else: master_list[schedule] = flattened_list final_list = filter(None, master_list) return final_list
def test_validCourse(): uw_api = UWaterlooAPI(uw_api_key) assert app.checkValidCourse.course_exists('CS', '135', uw_api) == True
def test_invalidCourse(): uw_api = UWaterlooAPI(uw_api_key) assert app.checkValidCourse.course_exists('DOESNT', '135', uw_api) == False
import json import os.path import re from bson import ObjectId from flask import Flask, render_template, send_from_directory from pymongo import MongoClient from uwaterlooapi import UWaterlooAPI with open('key.json') as f: key = json.load(f)['key'] uw = UWaterlooAPI(api_key=key) course_code_r = re.compile(r"([A-Z]+)([0-9]+)") client = MongoClient('localhost', 27017) collection = client.courses.prereqs app = Flask(__name__) DEBUG = False class Encoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, ObjectId): return str(obj) else: return obj
import pprint # pretty printing from flask import Flask # flask app from flask import request # flask app from uwaterlooapi import UWaterlooAPI # UWaterloo Open Data API import json import requests import sys sys.path.append( '/Users/daltyboy11/School/3b/se390/internal_mini_project/flask_app/flaskr') import scheduler pp = pprint.PrettyPrinter(indent=4) uw = UWaterlooAPI(api_key="234279968e219cf1f180a48bf217c318") COURSE_BASE_URL = "https://api.uwaterloo.ca/v2/courses/" KEY = "?key=234279968e219cf1f180a48bf217c318" URL = "https://api.uwaterloo.ca/v2/courses/{}/{}.json?key=234279968e219cf1f180a48bf217c318" def get_course_url(dcode, cnum): return COURSE_BASE_URL + dcode + "/" + cnum + ".json" + KEY def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(SECRET_KEY='dev', ) if test_config is None: app.config.from_pyfile('config.py', silent=True) else: app.config.from_mapping(test_config)
#!/usr/bin/python from uwaterlooapi import UWaterlooAPI import MySQLdb # UW API setup uw = UWaterlooAPI(api_key="013cadb105a7dc1943443cb5ebf7edde") # Open database connection db = MySQLdb.connect("localhost","SE464","SE464project","classroomfinder" ) try: cursorTruncate = db.cursor() cursorTruncate.execute("TRUNCATE TABLE classroomfinder.courses") cursor = db.cursor() cursor.execute("SELECT * FROM classroomfinder.building_rooms") result = cursor.fetchall() for row in result: print "processing room..." building = row[0] room = row[1] try: UWresult = uw.course_by_building_room(building, room) for c in UWresult: sub = c['subject'] catalog_number = c['catalog_number'] title = c['title'] weekdays = c['weekdays'] start_time = c['start_time'] end_time = c['end_time'] cursorInsert = db.cursor(); cursorInsert.execute('''INSERT INTO classroomfinder.courses VALUES (%s, %s, %s, %s, %s, %s, %s, %s)''', (sub, catalog_number, title, weekdays, start_time, end_time, building, room)) cursorInsert.execute('COMMIT')
from uwaterlooapi import UWaterlooAPI uw = UWaterlooAPI(api_key="a07ba3fa921ba4e468a0ed2ad0e0c062") error = "Course Information Not Found" def find_course(subject, number): subject = subject.upper() number = str(number) for course in uw.courses(): if course['subject'] == subject: if course['catalog_number'] == number: return course['title'] return error
# Just barely tests things to make sure they work import datetime from uwaterlooapi import UWaterlooAPI api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288') exclude = ['api_key', 'base_url'] dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1]) args_map = { 'announcements_by_week': dates, 'menu_by_week': dates, 'notes_by_week': dates, 'course': ('CS', '486'), 'course_examschedule': ('CS', '486'), 'course_prerequistes': ('CS', '486'), 'course_schedule': ('CS', '486'), 'course_by_building_room': ('MC', '2038'), 'term_course_schedule': ('1141', 'CS', '486'), 'term_subject_schedule': ('1141', 'CS'), } for attr in dir(api): if attr.startswith("_"): continue if attr in exclude: continue f = getattr(api, attr) print(attr) try: f()
from uwaterlooapi import UWaterlooAPI from pprint import pprint import xlsxwriter if __name__ == '__main__': wb = xlsxwriter.Workbook('test.xlsx') sheet = wb.add_worksheet() uw = UWaterlooAPI(api_key="7d0e829ff82a1aa902f44d6609a1cbb2") courses = uw.courses() count = 0 for course in courses: sheet.write('A%d' % count, course['subject']) sheet.write('B%d' % count, course['catalog_number']) sheet.write('C%d' % count, course['title']) count += 1 wb.close()
api.PostUpdates(message) except Exception as e: print("EXCEPTION:") print(e) else: bot.sendMessage(chat_id=telegramChatId, text="No sessions today") try: api.PostUpdate("No sessions today") except Exception as e: print("EXCEPTION") print(e) return update_id API_KEY = apikeys.UWApiKey uw = UWaterlooAPI(api_key=API_KEY) todays_sessions = [] day = int(time.strftime("%d")) todaysDate = time.strftime("%Y") + time.strftime("-%m-") + str(day) #get all sessions for today for event in uw.infosessions(): if "CANCELLED" in event["employer"].upper(): continue if event["date"] == todaysDate: todays_sessions.append(
""" Pull data from uwaterlooapi - residence Created by: Shijin (Kevin) Yang """ from uwaterlooapi import UWaterlooAPI # connect with api_ley uw = UWaterlooAPI(api_key="c6fe03239babd8c06f887524fa0aeb12") def filter_buildings(buildings, whole_buildings): out = [] for required_building in buildings: for item in whole_buildings: if item['building_code'] == required_building: out.append(item) return out
def test_validCourse(): uw_api = UWaterlooAPI(uw_api_key) courses = app.getCourses.generateCourses(uw_api) assert len(courses) > 0